Testsuite: munge GnuTLS and OpenSSL ciphersuite strings to be more similar
[exim.git] / src / src / tls-openssl.c
CommitLineData
059ec3d9
PH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
f9ba5e22 5/* Copyright (c) University of Cambridge 1995 - 2018 */
059ec3d9
PH
6/* See the file NOTICE for conditions of use and distribution. */
7
f5d78688
JH
8/* Portions Copyright (c) The OpenSSL Project 1999 */
9
059ec3d9
PH
10/* This module provides the TLS (aka SSL) support for Exim using the OpenSSL
11library. It is #included into the tls.c file when that library is used. The
12code herein is based on a patch that was originally contributed by Steve
13Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
14
15No cryptographic code is included in Exim. All this module does is to call
16functions from the OpenSSL library. */
17
18
19/* Heading stuff */
20
21#include <openssl/lhash.h>
22#include <openssl/ssl.h>
23#include <openssl/err.h>
24#include <openssl/rand.h>
10ca4f1c
JH
25#ifndef OPENSSL_NO_ECDH
26# include <openssl/ec.h>
27#endif
f2de3a33 28#ifndef DISABLE_OCSP
e51c7be2 29# include <openssl/ocsp.h>
3f7eeb86 30#endif
c0635b6d 31#ifdef SUPPORT_DANE
05e796ad 32# include "danessl.h"
85098ee7
JH
33#endif
34
3f7eeb86 35
f2de3a33
JH
36#ifndef DISABLE_OCSP
37# define EXIM_OCSP_SKEW_SECONDS (300L)
38# define EXIM_OCSP_MAX_AGE (-1L)
3f7eeb86 39#endif
059ec3d9 40
3bcbbbe2 41#if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
e51c7be2 42# define EXIM_HAVE_OPENSSL_TLSEXT
3bcbbbe2 43#endif
c8dfb21d
JH
44#if OPENSSL_VERSION_NUMBER >= 0x00908000L
45# define EXIM_HAVE_RSA_GENKEY_EX
46#endif
47#if OPENSSL_VERSION_NUMBER >= 0x10100000L
48# define EXIM_HAVE_OCSP_RESP_COUNT
49#else
50# define EXIM_HAVE_EPHEM_RSA_KEX
51# define EXIM_HAVE_RAND_PSEUDO
52#endif
53#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
8442641e 54# define EXIM_HAVE_SHA256
c8dfb21d 55#endif
34e3241d 56
d7978c0f
JH
57/* X509_check_host provides sane certificate hostname checking, but was added
58to OpenSSL late, after other projects forked off the code-base. So in
59addition to guarding against the base version number, beware that LibreSSL
60does not (at this time) support this function.
61
62If LibreSSL gains a different API, perhaps via libtls, then we'll probably
63opt to disentangle and ask a LibreSSL user to provide glue for a third
64crypto provider for libtls instead of continuing to tie the OpenSSL glue
65into even twistier knots. If LibreSSL gains the same API, we can just
66change this guard and punt the issue for a while longer. */
67
34e3241d
PP
68#ifndef LIBRESSL_VERSION_NUMBER
69# if OPENSSL_VERSION_NUMBER >= 0x010100000L
70# define EXIM_HAVE_OPENSSL_CHECKHOST
8420742d 71# define EXIM_HAVE_OPENSSL_DH_BITS
7a8b9519 72# define EXIM_HAVE_OPENSSL_TLS_METHOD
f20cfa4a 73# define EXIM_HAVE_OPENSSL_KEYLOG
7434882d
JH
74# else
75# define EXIM_NEED_OPENSSL_INIT
34e3241d
PP
76# endif
77# if OPENSSL_VERSION_NUMBER >= 0x010000000L \
2dfb468b 78 && (OPENSSL_VERSION_NUMBER & 0x0000ff000L) >= 0x000002000L
34e3241d
PP
79# define EXIM_HAVE_OPENSSL_CHECKHOST
80# endif
11aa88b0 81#endif
10ca4f1c 82
11aa88b0
RA
83#if !defined(LIBRESSL_VERSION_NUMBER) \
84 || LIBRESSL_VERSION_NUMBER >= 0x20010000L
10ca4f1c
JH
85# if !defined(OPENSSL_NO_ECDH)
86# if OPENSSL_VERSION_NUMBER >= 0x0090800fL
8442641e 87# define EXIM_HAVE_ECDH
10ca4f1c
JH
88# endif
89# if OPENSSL_VERSION_NUMBER >= 0x10002000L
10ca4f1c
JH
90# define EXIM_HAVE_OPENSSL_EC_NIST2NID
91# endif
92# endif
2dfb468b 93#endif
3bcbbbe2 94
8a40db1c
JH
95#ifndef LIBRESSL_VERSION_NUMBER
96# if OPENSSL_VERSION_NUMBER >= 0x010101000L
97# define OPENSSL_HAVE_KEYLOG_CB
d7f31bb6 98# define OPENSSL_HAVE_NUM_TICKETS
8a40db1c
JH
99# endif
100#endif
101
67791ce4
JH
102#if !defined(EXIM_HAVE_OPENSSL_TLSEXT) && !defined(DISABLE_OCSP)
103# warning "OpenSSL library version too old; define DISABLE_OCSP in Makefile"
104# define DISABLE_OCSP
105#endif
106
a6510420
JH
107#ifdef EXIM_HAVE_OPENSSL_CHECKHOST
108# include <openssl/x509v3.h>
109#endif
110
8442641e
JH
111/*************************************************
112* OpenSSL option parse *
113*************************************************/
114
115typedef struct exim_openssl_option {
116 uschar *name;
117 long value;
118} exim_openssl_option;
119/* We could use a macro to expand, but we need the ifdef and not all the
120options document which version they were introduced in. Policylet: include
121all options unless explicitly for DTLS, let the administrator choose which
122to apply.
123
124This list is current as of:
125 ==> 1.0.1b <==
126Plus SSL_OP_SAFARI_ECDHE_ECDSA_BUG from 2013-June patch/discussion on openssl-dev
127Plus SSL_OP_NO_TLSv1_3 for 1.1.2-dev
128*/
129static exim_openssl_option exim_openssl_options[] = {
130/* KEEP SORTED ALPHABETICALLY! */
131#ifdef SSL_OP_ALL
132 { US"all", SSL_OP_ALL },
133#endif
134#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
135 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
136#endif
137#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
138 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
139#endif
140#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
141 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
142#endif
143#ifdef SSL_OP_EPHEMERAL_RSA
144 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
145#endif
146#ifdef SSL_OP_LEGACY_SERVER_CONNECT
147 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
148#endif
149#ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
150 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
151#endif
152#ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
153 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
154#endif
155#ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
156 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
157#endif
158#ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
159 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
160#endif
161#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
162 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
163#endif
164#ifdef SSL_OP_NO_COMPRESSION
165 { US"no_compression", SSL_OP_NO_COMPRESSION },
166#endif
167#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
168 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
169#endif
170#ifdef SSL_OP_NO_SSLv2
171 { US"no_sslv2", SSL_OP_NO_SSLv2 },
172#endif
173#ifdef SSL_OP_NO_SSLv3
174 { US"no_sslv3", SSL_OP_NO_SSLv3 },
175#endif
176#ifdef SSL_OP_NO_TICKET
177 { US"no_ticket", SSL_OP_NO_TICKET },
178#endif
179#ifdef SSL_OP_NO_TLSv1
180 { US"no_tlsv1", SSL_OP_NO_TLSv1 },
181#endif
182#ifdef SSL_OP_NO_TLSv1_1
183#if SSL_OP_NO_TLSv1_1 == 0x00000400L
184 /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
185#warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
186#else
187 { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
188#endif
189#endif
190#ifdef SSL_OP_NO_TLSv1_2
191 { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
192#endif
193#ifdef SSL_OP_NO_TLSv1_3
194 { US"no_tlsv1_3", SSL_OP_NO_TLSv1_3 },
195#endif
196#ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
197 { US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
198#endif
199#ifdef SSL_OP_SINGLE_DH_USE
200 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
201#endif
202#ifdef SSL_OP_SINGLE_ECDH_USE
203 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
204#endif
205#ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
206 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
207#endif
208#ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
209 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
210#endif
211#ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
212 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
213#endif
214#ifdef SSL_OP_TLS_D5_BUG
215 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
216#endif
217#ifdef SSL_OP_TLS_ROLLBACK_BUG
218 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
219#endif
220};
221
222#ifndef MACRO_PREDEF
223static int exim_openssl_options_size = nelem(exim_openssl_options);
224#endif
225
226#ifdef MACRO_PREDEF
227void
228options_tls(void)
229{
8442641e
JH
230uschar buf[64];
231
d7978c0f 232for (struct exim_openssl_option * o = exim_openssl_options;
8442641e
JH
233 o < exim_openssl_options + nelem(exim_openssl_options); o++)
234 {
235 /* Trailing X is workaround for problem with _OPT_OPENSSL_NO_TLSV1
236 being a ".ifdef _OPT_OPENSSL_NO_TLSV1_3" match */
237
238 spf(buf, sizeof(buf), US"_OPT_OPENSSL_%T_X", o->name);
239 builtin_macro_create(buf);
240 }
241}
242#else
243
244/******************************************************************************/
245
059ec3d9
PH
246/* Structure for collecting random data for seeding. */
247
248typedef struct randstuff {
9e3331ea
TK
249 struct timeval tv;
250 pid_t p;
059ec3d9
PH
251} randstuff;
252
253/* Local static variables */
254
a2ff477a
JH
255static BOOL client_verify_callback_called = FALSE;
256static BOOL server_verify_callback_called = FALSE;
059ec3d9
PH
257static const uschar *sid_ctx = US"exim";
258
d4f09789
PP
259/* We have three different contexts to care about.
260
261Simple case: client, `client_ctx`
262 As a client, we can be doing a callout or cut-through delivery while receiving
263 a message. So we have a client context, which should have options initialised
74f1a423
JH
264 from the SMTP Transport. We may also concurrently want to make TLS connections
265 to utility daemons, so client-contexts are allocated and passed around in call
266 args rather than using a gobal.
d4f09789
PP
267
268Server:
269 There are two cases: with and without ServerNameIndication from the client.
270 Given TLS SNI, we can be using different keys, certs and various other
271 configuration settings, because they're re-expanded with $tls_sni set. This
272 allows vhosting with TLS. This SNI is sent in the handshake.
273 A client might not send SNI, so we need a fallback, and an initial setup too.
274 So as a server, we start out using `server_ctx`.
275 If SNI is sent by the client, then we as server, mid-negotiation, try to clone
276 `server_sni` from `server_ctx` and then initialise settings by re-expanding
277 configuration.
278*/
279
74f1a423
JH
280typedef struct {
281 SSL_CTX * ctx;
282 SSL * ssl;
283} exim_openssl_client_tls_ctx;
284
817d9f57 285static SSL_CTX *server_ctx = NULL;
817d9f57 286static SSL *server_ssl = NULL;
389ca47a 287
35731706 288#ifdef EXIM_HAVE_OPENSSL_TLSEXT
817d9f57 289static SSL_CTX *server_sni = NULL;
35731706 290#endif
059ec3d9
PH
291
292static char ssl_errstring[256];
293
294static int ssl_session_timeout = 200;
a2ff477a
JH
295static BOOL client_verify_optional = FALSE;
296static BOOL server_verify_optional = FALSE;
059ec3d9 297
f5d78688 298static BOOL reexpand_tls_files_for_sni = FALSE;
059ec3d9
PH
299
300
7be682ca
PP
301typedef struct tls_ext_ctx_cb {
302 uschar *certificate;
303 uschar *privatekey;
f5d78688 304 BOOL is_server;
a6510420 305#ifndef DISABLE_OCSP
c3033f13 306 STACK_OF(X509) *verify_stack; /* chain for verifying the proof */
f5d78688
JH
307 union {
308 struct {
309 uschar *file;
310 uschar *file_expanded;
311 OCSP_RESPONSE *response;
312 } server;
313 struct {
44662487
JH
314 X509_STORE *verify_store; /* non-null if status requested */
315 BOOL verify_required;
f5d78688
JH
316 } client;
317 } u_ocsp;
3f7eeb86 318#endif
7be682ca
PP
319 uschar *dhparam;
320 /* these are cached from first expand */
321 uschar *server_cipher_list;
322 /* only passed down to tls_error: */
323 host_item *host;
55414b25 324 const uschar * verify_cert_hostnames;
0cbf2b82 325#ifndef DISABLE_EVENT
a7538db1
JH
326 uschar * event_action;
327#endif
7be682ca
PP
328} tls_ext_ctx_cb;
329
330/* should figure out a cleanup of API to handle state preserved per
331implementation, for various reasons, which can be void * in the APIs.
332For now, we hack around it. */
817d9f57
JH
333tls_ext_ctx_cb *client_static_cbinfo = NULL;
334tls_ext_ctx_cb *server_static_cbinfo = NULL;
7be682ca
PP
335
336static int
983207c1 337setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
cf0c6164 338 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr );
059ec3d9 339
3f7eeb86 340/* Callbacks */
3bcbbbe2 341#ifdef EXIM_HAVE_OPENSSL_TLSEXT
3f7eeb86 342static int tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg);
3bcbbbe2 343#endif
f2de3a33 344#ifndef DISABLE_OCSP
f5d78688 345static int tls_server_stapling_cb(SSL *s, void *arg);
3f7eeb86
PP
346#endif
347
059ec3d9
PH
348
349/*************************************************
350* Handle TLS error *
351*************************************************/
352
353/* Called from lots of places when errors occur before actually starting to do
354the TLS handshake, that is, while the session is still in clear. Always returns
355DEFER for a server and FAIL for a client so that most calls can use "return
356tls_error(...)" to do this processing and then give an appropriate return. A
357single function is used for both server and client, because it is called from
358some shared functions.
359
360Argument:
361 prefix text to include in the logged error
362 host NULL if setting up a server;
363 the connected host if setting up a client
7199e1ee 364 msg error message or NULL if we should ask OpenSSL
cf0c6164 365 errstr pointer to output error message
059ec3d9
PH
366
367Returns: OK/DEFER/FAIL
368*/
369
370static int
cf0c6164 371tls_error(uschar * prefix, const host_item * host, uschar * msg, uschar ** errstr)
059ec3d9 372{
c562fd30 373if (!msg)
7199e1ee 374 {
0abc5a13 375 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
cf0c6164 376 msg = US ssl_errstring;
7199e1ee
TF
377 }
378
5a2a0989
JH
379msg = string_sprintf("(%s): %s", prefix, msg);
380DEBUG(D_tls) debug_printf("TLS error '%s'\n", msg);
381if (errstr) *errstr = msg;
cf0c6164 382return host ? FAIL : DEFER;
059ec3d9
PH
383}
384
385
386
387/*************************************************
388* Callback to generate RSA key *
389*************************************************/
390
391/*
392Arguments:
3ae79556 393 s SSL connection (not used)
059ec3d9
PH
394 export not used
395 keylength keylength
396
397Returns: pointer to generated key
398*/
399
400static RSA *
401rsa_callback(SSL *s, int export, int keylength)
402{
403RSA *rsa_key;
c8dfb21d
JH
404#ifdef EXIM_HAVE_RSA_GENKEY_EX
405BIGNUM *bn = BN_new();
406#endif
407
059ec3d9
PH
408export = export; /* Shut picky compilers up */
409DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
c8dfb21d
JH
410
411#ifdef EXIM_HAVE_RSA_GENKEY_EX
412if ( !BN_set_word(bn, (unsigned long)RSA_F4)
f2cb6292 413 || !(rsa_key = RSA_new())
c8dfb21d
JH
414 || !RSA_generate_key_ex(rsa_key, keylength, bn, NULL)
415 )
416#else
23bb6982 417if (!(rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL)))
c8dfb21d
JH
418#endif
419
059ec3d9 420 {
0abc5a13 421 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
059ec3d9
PH
422 log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
423 ssl_errstring);
424 return NULL;
425 }
426return rsa_key;
427}
428
429
430
f5d78688 431/* Extreme debug
f2de3a33 432#ifndef DISABLE_OCSP
f5d78688
JH
433void
434x509_store_dump_cert_s_names(X509_STORE * store)
435{
436STACK_OF(X509_OBJECT) * roots= store->objs;
f5d78688
JH
437static uschar name[256];
438
d7978c0f 439for (int i= 0; i < sk_X509_OBJECT_num(roots); i++)
f5d78688
JH
440 {
441 X509_OBJECT * tmp_obj= sk_X509_OBJECT_value(roots, i);
442 if(tmp_obj->type == X509_LU_X509)
443 {
70e384dd
JH
444 X509_NAME * sn = X509_get_subject_name(tmp_obj->data.x509);
445 if (X509_NAME_oneline(sn, CS name, sizeof(name)))
446 {
447 name[sizeof(name)-1] = '\0';
448 debug_printf(" %s\n", name);
449 }
f5d78688
JH
450 }
451 }
452}
453#endif
454*/
455
059ec3d9 456
0cbf2b82 457#ifndef DISABLE_EVENT
f69979cf
JH
458static int
459verify_event(tls_support * tlsp, X509 * cert, int depth, const uschar * dn,
460 BOOL *calledp, const BOOL *optionalp, const uschar * what)
461{
462uschar * ev;
463uschar * yield;
464X509 * old_cert;
465
466ev = tlsp == &tls_out ? client_static_cbinfo->event_action : event_action;
467if (ev)
468 {
aaba7d03 469 DEBUG(D_tls) debug_printf("verify_event: %s %d\n", what, depth);
f69979cf
JH
470 old_cert = tlsp->peercert;
471 tlsp->peercert = X509_dup(cert);
472 /* NB we do not bother setting peerdn */
473 if ((yield = event_raise(ev, US"tls:cert", string_sprintf("%d", depth))))
474 {
475 log_write(0, LOG_MAIN, "[%s] %s verify denied by event-action: "
476 "depth=%d cert=%s: %s",
477 tlsp == &tls_out ? deliver_host_address : sender_host_address,
478 what, depth, dn, yield);
479 *calledp = TRUE;
480 if (!*optionalp)
481 {
482 if (old_cert) tlsp->peercert = old_cert; /* restore 1st failing cert */
483 return 1; /* reject (leaving peercert set) */
484 }
485 DEBUG(D_tls) debug_printf("Event-action verify failure overridden "
486 "(host in tls_try_verify_hosts)\n");
487 }
488 X509_free(tlsp->peercert);
489 tlsp->peercert = old_cert;
490 }
491return 0;
492}
493#endif
494
059ec3d9
PH
495/*************************************************
496* Callback for verification *
497*************************************************/
498
499/* The SSL library does certificate verification if set up to do so. This
500callback has the current yes/no state is in "state". If verification succeeded,
f69979cf
JH
501we set the certificate-verified flag. If verification failed, what happens
502depends on whether the client is required to present a verifiable certificate
503or not.
059ec3d9
PH
504
505If verification is optional, we change the state to yes, but still log the
506verification error. For some reason (it really would help to have proper
507documentation of OpenSSL), this callback function then gets called again, this
f69979cf
JH
508time with state = 1. We must take care not to set the private verified flag on
509the second time through.
059ec3d9
PH
510
511Note: this function is not called if the client fails to present a certificate
512when asked. We get here only if a certificate has been received. Handling of
513optional verification for this case is done when requesting SSL to verify, by
514setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
515
a7538db1
JH
516May be called multiple times for different issues with a certificate, even
517for a given "depth" in the certificate chain.
518
059ec3d9 519Arguments:
f2f2c91b
JH
520 preverify_ok current yes/no state as 1/0
521 x509ctx certificate information.
522 tlsp per-direction (client vs. server) support data
523 calledp has-been-called flag
524 optionalp verification-is-optional flag
059ec3d9 525
f2f2c91b 526Returns: 0 if verification should fail, otherwise 1
059ec3d9
PH
527*/
528
529static int
70e384dd
JH
530verify_callback(int preverify_ok, X509_STORE_CTX * x509ctx,
531 tls_support * tlsp, BOOL * calledp, BOOL * optionalp)
059ec3d9 532{
421aff85 533X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
a7538db1 534int depth = X509_STORE_CTX_get_error_depth(x509ctx);
f69979cf 535uschar dn[256];
059ec3d9 536
70e384dd
JH
537if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
538 {
539 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
540 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
541 tlsp == &tls_out ? deliver_host_address : sender_host_address);
542 return 0;
543 }
f69979cf 544dn[sizeof(dn)-1] = '\0';
059ec3d9 545
f2f2c91b 546if (preverify_ok == 0)
059ec3d9 547 {
f77197ae
JH
548 uschar * extra = verify_mode ? string_sprintf(" (during %c-verify for [%s])",
549 *verify_mode, sender_host_address)
550 : US"";
551 log_write(0, LOG_MAIN, "[%s] SSL verify error%s: depth=%d error=%s cert=%s",
552 tlsp == &tls_out ? deliver_host_address : sender_host_address,
553 extra, depth,
554 X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509ctx)), dn);
a2ff477a 555 *calledp = TRUE;
9d1c15ef
JH
556 if (!*optionalp)
557 {
f69979cf
JH
558 if (!tlsp->peercert)
559 tlsp->peercert = X509_dup(cert); /* record failing cert */
560 return 0; /* reject */
9d1c15ef 561 }
059ec3d9
PH
562 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
563 "tls_try_verify_hosts)\n");
059ec3d9
PH
564 }
565
a7538db1 566else if (depth != 0)
059ec3d9 567 {
f69979cf 568 DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d SN=%s\n", depth, dn);
f2de3a33 569#ifndef DISABLE_OCSP
f5d78688
JH
570 if (tlsp == &tls_out && client_static_cbinfo->u_ocsp.client.verify_store)
571 { /* client, wanting stapling */
572 /* Add the server cert's signing chain as the one
573 for the verification of the OCSP stapled information. */
94431adb 574
f5d78688 575 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
421aff85 576 cert))
f5d78688 577 ERR_clear_error();
c3033f13 578 sk_X509_push(client_static_cbinfo->verify_stack, cert);
f5d78688
JH
579 }
580#endif
0cbf2b82 581#ifndef DISABLE_EVENT
f69979cf
JH
582 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
583 return 0; /* reject, with peercert set */
a7538db1 584#endif
059ec3d9
PH
585 }
586else
587 {
55414b25 588 const uschar * verify_cert_hostnames;
e51c7be2 589
e51c7be2
JH
590 if ( tlsp == &tls_out
591 && ((verify_cert_hostnames = client_static_cbinfo->verify_cert_hostnames)))
afdb5e9c 592 /* client, wanting hostname check */
e51c7be2 593 {
f69979cf 594
740f36d4 595#ifdef EXIM_HAVE_OPENSSL_CHECKHOST
f69979cf
JH
596# ifndef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
597# define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0
598# endif
599# ifndef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
600# define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0
601# endif
e51c7be2 602 int sep = 0;
55414b25 603 const uschar * list = verify_cert_hostnames;
e51c7be2 604 uschar * name;
d8e7834a
JH
605 int rc;
606 while ((name = string_nextinlist(&list, &sep, NULL, 0)))
f40d5be3 607 if ((rc = X509_check_host(cert, CCS name, 0,
8d692470 608 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
740f36d4
JH
609 | X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS,
610 NULL)))
d8e7834a
JH
611 {
612 if (rc < 0)
613 {
93a6fce2 614 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
f77197ae 615 tlsp == &tls_out ? deliver_host_address : sender_host_address);
d8e7834a
JH
616 name = NULL;
617 }
e51c7be2 618 break;
d8e7834a 619 }
e51c7be2 620 if (!name)
f69979cf 621#else
e51c7be2 622 if (!tls_is_name_for_cert(verify_cert_hostnames, cert))
f69979cf 623#endif
e51c7be2 624 {
f77197ae
JH
625 uschar * extra = verify_mode
626 ? string_sprintf(" (during %c-verify for [%s])",
627 *verify_mode, sender_host_address)
628 : US"";
e51c7be2 629 log_write(0, LOG_MAIN,
f77197ae
JH
630 "[%s] SSL verify error%s: certificate name mismatch: DN=\"%s\" H=\"%s\"",
631 tlsp == &tls_out ? deliver_host_address : sender_host_address,
632 extra, dn, verify_cert_hostnames);
a3ef7310
JH
633 *calledp = TRUE;
634 if (!*optionalp)
f69979cf
JH
635 {
636 if (!tlsp->peercert)
637 tlsp->peercert = X509_dup(cert); /* record failing cert */
638 return 0; /* reject */
639 }
a3ef7310
JH
640 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
641 "tls_try_verify_hosts)\n");
e51c7be2 642 }
f69979cf 643 }
e51c7be2 644
0cbf2b82 645#ifndef DISABLE_EVENT
f69979cf
JH
646 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
647 return 0; /* reject, with peercert set */
e51c7be2
JH
648#endif
649
93dcb1c2 650 DEBUG(D_tls) debug_printf("SSL%s verify ok: depth=0 SN=%s\n",
f69979cf 651 *calledp ? "" : " authenticated", dn);
93dcb1c2
JH
652 if (!*calledp) tlsp->certificate_verified = TRUE;
653 *calledp = TRUE;
059ec3d9
PH
654 }
655
a7538db1 656return 1; /* accept, at least for this level */
059ec3d9
PH
657}
658
a2ff477a 659static int
f2f2c91b 660verify_callback_client(int preverify_ok, X509_STORE_CTX *x509ctx)
a2ff477a 661{
f2f2c91b
JH
662return verify_callback(preverify_ok, x509ctx, &tls_out,
663 &client_verify_callback_called, &client_verify_optional);
a2ff477a
JH
664}
665
666static int
f2f2c91b 667verify_callback_server(int preverify_ok, X509_STORE_CTX *x509ctx)
a2ff477a 668{
f2f2c91b
JH
669return verify_callback(preverify_ok, x509ctx, &tls_in,
670 &server_verify_callback_called, &server_verify_optional);
a2ff477a
JH
671}
672
059ec3d9 673
c0635b6d 674#ifdef SUPPORT_DANE
53a7196b 675
e5cccda9
JH
676/* This gets called *by* the dane library verify callback, which interposes
677itself.
678*/
679static int
f2f2c91b 680verify_callback_client_dane(int preverify_ok, X509_STORE_CTX * x509ctx)
e5cccda9
JH
681{
682X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
f69979cf 683uschar dn[256];
83b27293 684int depth = X509_STORE_CTX_get_error_depth(x509ctx);
5c75db2e 685#ifndef DISABLE_EVENT
f69979cf 686BOOL dummy_called, optional = FALSE;
83b27293 687#endif
e5cccda9 688
70e384dd
JH
689if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
690 {
691 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
692 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
693 deliver_host_address);
694 return 0;
695 }
f69979cf 696dn[sizeof(dn)-1] = '\0';
e5cccda9 697
f2f2c91b
JH
698DEBUG(D_tls) debug_printf("verify_callback_client_dane: %s depth %d %s\n",
699 preverify_ok ? "ok":"BAD", depth, dn);
e5cccda9 700
0cbf2b82 701#ifndef DISABLE_EVENT
f69979cf
JH
702 if (verify_event(&tls_out, cert, depth, dn,
703 &dummy_called, &optional, US"DANE"))
704 return 0; /* reject, with peercert set */
83b27293
JH
705#endif
706
f2f2c91b 707if (preverify_ok == 1)
6fbf3599
JH
708 {
709 tls_out.dane_verified = tls_out.certificate_verified = TRUE;
710#ifndef DISABLE_OCSP
711 if (client_static_cbinfo->u_ocsp.client.verify_store)
712 { /* client, wanting stapling */
713 /* Add the server cert's signing chain as the one
714 for the verification of the OCSP stapled information. */
715
716 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
717 cert))
718 ERR_clear_error();
719 sk_X509_push(client_static_cbinfo->verify_stack, cert);
720 }
721#endif
722 }
f2f2c91b
JH
723else
724 {
725 int err = X509_STORE_CTX_get_error(x509ctx);
726 DEBUG(D_tls)
727 debug_printf(" - err %d '%s'\n", err, X509_verify_cert_error_string(err));
3c51463e 728 if (err == X509_V_ERR_APPLICATION_VERIFICATION)
f2f2c91b
JH
729 preverify_ok = 1;
730 }
731return preverify_ok;
e5cccda9 732}
53a7196b 733
c0635b6d 734#endif /*SUPPORT_DANE*/
e5cccda9 735
059ec3d9
PH
736
737/*************************************************
738* Information callback *
739*************************************************/
740
741/* The SSL library functions call this from time to time to indicate what they
7be682ca
PP
742are doing. We copy the string to the debugging output when TLS debugging has
743been requested.
059ec3d9
PH
744
745Arguments:
746 s the SSL connection
747 where
748 ret
749
750Returns: nothing
751*/
752
753static void
754info_callback(SSL *s, int where, int ret)
755{
0abc5a13
JH
756DEBUG(D_tls)
757 {
758 const uschar * str;
759
760 if (where & SSL_ST_CONNECT)
48224640 761 str = US"SSL_connect";
0abc5a13 762 else if (where & SSL_ST_ACCEPT)
48224640 763 str = US"SSL_accept";
0abc5a13 764 else
48224640 765 str = US"SSL info (undefined)";
0abc5a13
JH
766
767 if (where & SSL_CB_LOOP)
768 debug_printf("%s: %s\n", str, SSL_state_string_long(s));
769 else if (where & SSL_CB_ALERT)
770 debug_printf("SSL3 alert %s:%s:%s\n",
48224640 771 str = where & SSL_CB_READ ? US"read" : US"write",
0abc5a13
JH
772 SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
773 else if (where & SSL_CB_EXIT)
774 if (ret == 0)
775 debug_printf("%s: failed in %s\n", str, SSL_state_string_long(s));
776 else if (ret < 0)
777 debug_printf("%s: error in %s\n", str, SSL_state_string_long(s));
778 else if (where & SSL_CB_HANDSHAKE_START)
779 debug_printf("%s: hshake start: %s\n", str, SSL_state_string_long(s));
780 else if (where & SSL_CB_HANDSHAKE_DONE)
781 debug_printf("%s: hshake done: %s\n", str, SSL_state_string_long(s));
782 }
059ec3d9
PH
783}
784
8238bc7b 785#ifdef OPENSSL_HAVE_KEYLOG_CB
8a40db1c
JH
786static void
787keylog_callback(const SSL *ssl, const char *line)
788{
789DEBUG(D_tls) debug_printf("%.200s\n", line);
790}
8238bc7b 791#endif
8a40db1c 792
059ec3d9
PH
793
794
795/*************************************************
796* Initialize for DH *
797*************************************************/
798
799/* If dhparam is set, expand it, and load up the parameters for DH encryption.
800
801Arguments:
038597d2 802 sctx The current SSL CTX (inbound or outbound)
a799883d 803 dhparam DH parameter file or fixed parameter identity string
7199e1ee 804 host connected host, if client; NULL if server
cf0c6164 805 errstr error string pointer
059ec3d9
PH
806
807Returns: TRUE if OK (nothing to set up, or setup worked)
808*/
809
810static BOOL
cf0c6164 811init_dh(SSL_CTX *sctx, uschar *dhparam, const host_item *host, uschar ** errstr)
059ec3d9 812{
059ec3d9
PH
813BIO *bio;
814DH *dh;
815uschar *dhexpanded;
a799883d 816const char *pem;
6600985a 817int dh_bitsize;
059ec3d9 818
cf0c6164 819if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded, errstr))
059ec3d9
PH
820 return FALSE;
821
0df4ab80 822if (!dhexpanded || !*dhexpanded)
a799883d 823 bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
a799883d 824else if (dhexpanded[0] == '/')
059ec3d9 825 {
0df4ab80 826 if (!(bio = BIO_new_file(CS dhexpanded, "r")))
059ec3d9 827 {
7199e1ee 828 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
cf0c6164 829 host, US strerror(errno), errstr);
a799883d 830 return FALSE;
059ec3d9 831 }
a799883d
PP
832 }
833else
834 {
835 if (Ustrcmp(dhexpanded, "none") == 0)
059ec3d9 836 {
a799883d
PP
837 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
838 return TRUE;
059ec3d9 839 }
a799883d 840
0df4ab80 841 if (!(pem = std_dh_prime_named(dhexpanded)))
a799883d
PP
842 {
843 tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
cf0c6164 844 host, US strerror(errno), errstr);
a799883d
PP
845 return FALSE;
846 }
847 bio = BIO_new_mem_buf(CS pem, -1);
848 }
849
0df4ab80 850if (!(dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)))
a799883d 851 {
059ec3d9 852 BIO_free(bio);
a799883d 853 tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
cf0c6164 854 host, NULL, errstr);
a799883d
PP
855 return FALSE;
856 }
857
6600985a
PP
858/* note: our default limit of 2236 is not a multiple of 8; the limit comes from
859 * an NSS limit, and the GnuTLS APIs handle bit-sizes fine, so we went with
860 * 2236. But older OpenSSL can only report in bytes (octets), not bits.
861 * If someone wants to dance at the edge, then they can raise the limit or use
862 * current libraries. */
863#ifdef EXIM_HAVE_OPENSSL_DH_BITS
864/* Added in commit 26c79d5641d; `git describe --contains` says OpenSSL_1_1_0-pre1~1022
865 * This predates OpenSSL_1_1_0 (before a, b, ...) so is in all 1.1.0 */
866dh_bitsize = DH_bits(dh);
867#else
868dh_bitsize = 8 * DH_size(dh);
869#endif
870
a799883d
PP
871/* Even if it is larger, we silently return success rather than cause things
872 * to fail out, so that a too-large DH will not knock out all TLS; it's a
873 * debatable choice. */
6600985a 874if (dh_bitsize > tls_dh_max_bits)
a799883d
PP
875 {
876 DEBUG(D_tls)
170f4904 877 debug_printf("dhparams file %d bits, is > tls_dh_max_bits limit of %d\n",
6600985a 878 dh_bitsize, tls_dh_max_bits);
a799883d
PP
879 }
880else
881 {
882 SSL_CTX_set_tmp_dh(sctx, dh);
883 DEBUG(D_tls)
884 debug_printf("Diffie-Hellman initialized from %s with %d-bit prime\n",
6600985a 885 dhexpanded ? dhexpanded : US"default", dh_bitsize);
059ec3d9
PH
886 }
887
a799883d
PP
888DH_free(dh);
889BIO_free(bio);
890
891return TRUE;
059ec3d9
PH
892}
893
894
895
896
038597d2
PP
897/*************************************************
898* Initialize for ECDH *
899*************************************************/
900
901/* Load parameters for ECDH encryption.
902
903For now, we stick to NIST P-256 because: it's simple and easy to configure;
904it avoids any patent issues that might bite redistributors; despite events in
905the news and concerns over curve choices, we're not cryptographers, we're not
906pretending to be, and this is "good enough" to be better than no support,
907protecting against most adversaries. Given another year or two, there might
908be sufficient clarity about a "right" way forward to let us make an informed
909decision, instead of a knee-jerk reaction.
910
911Longer-term, we should look at supporting both various named curves and
912external files generated with "openssl ecparam", much as we do for init_dh().
913We should also support "none" as a value, to explicitly avoid initialisation.
914
915Patches welcome.
916
917Arguments:
918 sctx The current SSL CTX (inbound or outbound)
919 host connected host, if client; NULL if server
cf0c6164 920 errstr error string pointer
038597d2
PP
921
922Returns: TRUE if OK (nothing to set up, or setup worked)
923*/
924
925static BOOL
cf0c6164 926init_ecdh(SSL_CTX * sctx, host_item * host, uschar ** errstr)
038597d2 927{
63f0dbe0
JH
928#ifdef OPENSSL_NO_ECDH
929return TRUE;
930#else
931
10ca4f1c
JH
932EC_KEY * ecdh;
933uschar * exp_curve;
934int nid;
935BOOL rv;
936
038597d2
PP
937if (host) /* No ECDH setup for clients, only for servers */
938 return TRUE;
939
10ca4f1c 940# ifndef EXIM_HAVE_ECDH
038597d2
PP
941DEBUG(D_tls)
942 debug_printf("No OpenSSL API to define ECDH parameters, skipping\n");
943return TRUE;
038597d2 944# else
10ca4f1c 945
cf0c6164 946if (!expand_check(tls_eccurve, US"tls_eccurve", &exp_curve, errstr))
10ca4f1c
JH
947 return FALSE;
948if (!exp_curve || !*exp_curve)
949 return TRUE;
950
8e53a4fc 951/* "auto" needs to be handled carefully.
4c04137d 952 * OpenSSL < 1.0.2: we do not select anything, but fallback to prime256v1
8e53a4fc 953 * OpenSSL < 1.1.0: we have to call SSL_CTX_set_ecdh_auto
4c04137d 954 * (openssl/ssl.h defines SSL_CTRL_SET_ECDH_AUTO)
8e53a4fc
HSHR
955 * OpenSSL >= 1.1.0: we do not set anything, the libray does autoselection
956 * https://github.com/openssl/openssl/commit/fe6ef2472db933f01b59cad82aa925736935984b
957 */
10ca4f1c 958if (Ustrcmp(exp_curve, "auto") == 0)
038597d2 959 {
8e53a4fc 960#if OPENSSL_VERSION_NUMBER < 0x10002000L
10ca4f1c 961 DEBUG(D_tls) debug_printf(
8e53a4fc 962 "ECDH OpenSSL < 1.0.2: temp key parameter settings: overriding \"auto\" with \"prime256v1\"\n");
78a3bbd5 963 exp_curve = US"prime256v1";
8e53a4fc
HSHR
964#else
965# if defined SSL_CTRL_SET_ECDH_AUTO
966 DEBUG(D_tls) debug_printf(
967 "ECDH OpenSSL 1.0.2+ temp key parameter settings: autoselection\n");
10ca4f1c
JH
968 SSL_CTX_set_ecdh_auto(sctx, 1);
969 return TRUE;
8e53a4fc
HSHR
970# else
971 DEBUG(D_tls) debug_printf(
972 "ECDH OpenSSL 1.1.0+ temp key parameter settings: default selection\n");
973 return TRUE;
974# endif
975#endif
10ca4f1c 976 }
038597d2 977
10ca4f1c
JH
978DEBUG(D_tls) debug_printf("ECDH: curve '%s'\n", exp_curve);
979if ( (nid = OBJ_sn2nid (CCS exp_curve)) == NID_undef
980# ifdef EXIM_HAVE_OPENSSL_EC_NIST2NID
981 && (nid = EC_curve_nist2nid(CCS exp_curve)) == NID_undef
982# endif
983 )
984 {
cf0c6164
JH
985 tls_error(string_sprintf("Unknown curve name tls_eccurve '%s'", exp_curve),
986 host, NULL, errstr);
10ca4f1c
JH
987 return FALSE;
988 }
038597d2 989
10ca4f1c
JH
990if (!(ecdh = EC_KEY_new_by_curve_name(nid)))
991 {
cf0c6164 992 tls_error(US"Unable to create ec curve", host, NULL, errstr);
10ca4f1c 993 return FALSE;
038597d2 994 }
10ca4f1c
JH
995
996/* The "tmp" in the name here refers to setting a temporary key
997not to the stability of the interface. */
998
999if ((rv = SSL_CTX_set_tmp_ecdh(sctx, ecdh) == 0))
cf0c6164 1000 tls_error(string_sprintf("Error enabling '%s' curve", exp_curve), host, NULL, errstr);
10ca4f1c
JH
1001else
1002 DEBUG(D_tls) debug_printf("ECDH: enabled '%s' curve\n", exp_curve);
1003
1004EC_KEY_free(ecdh);
1005return !rv;
1006
1007# endif /*EXIM_HAVE_ECDH*/
1008#endif /*OPENSSL_NO_ECDH*/
038597d2
PP
1009}
1010
1011
1012
1013
f2de3a33 1014#ifndef DISABLE_OCSP
3f7eeb86
PP
1015/*************************************************
1016* Load OCSP information into state *
1017*************************************************/
f5d78688 1018/* Called to load the server OCSP response from the given file into memory, once
3f7eeb86
PP
1019caller has determined this is needed. Checks validity. Debugs a message
1020if invalid.
1021
1022ASSUMES: single response, for single cert.
1023
1024Arguments:
1025 sctx the SSL_CTX* to update
1026 cbinfo various parts of session state
1027 expanded the filename putatively holding an OCSP response
1028
1029*/
1030
1031static void
f5d78688 1032ocsp_load_response(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo, const uschar *expanded)
3f7eeb86 1033{
ee5b1e28
JH
1034BIO * bio;
1035OCSP_RESPONSE * resp;
1036OCSP_BASICRESP * basic_response;
1037OCSP_SINGLERESP * single_response;
1038ASN1_GENERALIZEDTIME * rev, * thisupd, * nextupd;
ee5b1e28 1039STACK_OF(X509) * sk;
3f7eeb86
PP
1040unsigned long verify_flags;
1041int status, reason, i;
1042
f5d78688
JH
1043cbinfo->u_ocsp.server.file_expanded = string_copy(expanded);
1044if (cbinfo->u_ocsp.server.response)
3f7eeb86 1045 {
f5d78688
JH
1046 OCSP_RESPONSE_free(cbinfo->u_ocsp.server.response);
1047 cbinfo->u_ocsp.server.response = NULL;
3f7eeb86
PP
1048 }
1049
ee5b1e28 1050if (!(bio = BIO_new_file(CS cbinfo->u_ocsp.server.file_expanded, "rb")))
3f7eeb86
PP
1051 {
1052 DEBUG(D_tls) debug_printf("Failed to open OCSP response file \"%s\"\n",
f5d78688 1053 cbinfo->u_ocsp.server.file_expanded);
3f7eeb86
PP
1054 return;
1055 }
1056
1057resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
1058BIO_free(bio);
1059if (!resp)
1060 {
1061 DEBUG(D_tls) debug_printf("Error reading OCSP response.\n");
1062 return;
1063 }
1064
ee5b1e28 1065if ((status = OCSP_response_status(resp)) != OCSP_RESPONSE_STATUS_SUCCESSFUL)
3f7eeb86
PP
1066 {
1067 DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n",
1068 OCSP_response_status_str(status), status);
f5d78688 1069 goto bad;
3f7eeb86
PP
1070 }
1071
ee5b1e28 1072if (!(basic_response = OCSP_response_get1_basic(resp)))
3f7eeb86
PP
1073 {
1074 DEBUG(D_tls)
1075 debug_printf("OCSP response parse error: unable to extract basic response.\n");
f5d78688 1076 goto bad;
3f7eeb86
PP
1077 }
1078
c3033f13 1079sk = cbinfo->verify_stack;
3f7eeb86
PP
1080verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */
1081
1082/* May need to expose ability to adjust those flags?
1083OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
1084OCSP_TRUSTOTHER OCSP_NOINTERN */
1085
4c04137d 1086/* This does a full verify on the OCSP proof before we load it for serving
ee5b1e28
JH
1087up; possibly overkill - just date-checks might be nice enough.
1088
1089OCSP_basic_verify takes a "store" arg, but does not
1090use it for the chain verification, which is all we do
1091when OCSP_NOVERIFY is set. The content from the wire
1092"basic_response" and a cert-stack "sk" are all that is used.
1093
c3033f13
JH
1094We have a stack, loaded in setup_certs() if tls_verify_certificates
1095was a file (not a directory, or "system"). It is unfortunate we
1096cannot used the connection context store, as that would neatly
1097handle the "system" case too, but there seems to be no library
1098function for getting a stack from a store.
e3555426 1099[ In OpenSSL 1.1 - ? X509_STORE_CTX_get0_chain(ctx) ? ]
c3033f13
JH
1100We do not free the stack since it could be needed a second time for
1101SNI handling.
1102
4c04137d 1103Separately we might try to replace using OCSP_basic_verify() - which seems to not
5ec37a55 1104be a public interface into the OpenSSL library (there's no manual entry) -
ee5b1e28 1105But what with? We also use OCSP_basic_verify in the client stapling callback.
4c04137d 1106And there we NEED it; we must verify that status... unless the
ee5b1e28
JH
1107library does it for us anyway? */
1108
1109if ((i = OCSP_basic_verify(basic_response, sk, NULL, verify_flags)) < 0)
3f7eeb86 1110 {
ee5b1e28
JH
1111 DEBUG(D_tls)
1112 {
0abc5a13 1113 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3f7eeb86 1114 debug_printf("OCSP response verify failure: %s\n", US ssl_errstring);
f5d78688
JH
1115 }
1116 goto bad;
3f7eeb86
PP
1117 }
1118
1119/* Here's the simplifying assumption: there's only one response, for the
1120one certificate we use, and nothing for anything else in a chain. If this
1121proves false, we need to extract a cert id from our issued cert
1122(tls_certificate) and use that for OCSP_resp_find_status() (which finds the
1123right cert in the stack and then calls OCSP_single_get0_status()).
1124
1125I'm hoping to avoid reworking a bunch more of how we handle state here. */
ee5b1e28
JH
1126
1127if (!(single_response = OCSP_resp_get0(basic_response, 0)))
3f7eeb86
PP
1128 {
1129 DEBUG(D_tls)
1130 debug_printf("Unable to get first response from OCSP basic response.\n");
f5d78688 1131 goto bad;
3f7eeb86
PP
1132 }
1133
1134status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
f5d78688 1135if (status != V_OCSP_CERTSTATUS_GOOD)
3f7eeb86 1136 {
f5d78688
JH
1137 DEBUG(D_tls) debug_printf("OCSP response bad cert status: %s (%d) %s (%d)\n",
1138 OCSP_cert_status_str(status), status,
1139 OCSP_crl_reason_str(reason), reason);
1140 goto bad;
3f7eeb86
PP
1141 }
1142
1143if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1144 {
1145 DEBUG(D_tls) debug_printf("OCSP status invalid times.\n");
f5d78688 1146 goto bad;
3f7eeb86
PP
1147 }
1148
f5d78688 1149supply_response:
47195144 1150 cbinfo->u_ocsp.server.response = resp; /*XXX stack?*/
f5d78688
JH
1151return;
1152
1153bad:
8768d548 1154 if (f.running_in_test_harness)
018058b2
JH
1155 {
1156 extern char ** environ;
d7978c0f 1157 if (environ) for (uschar ** p = USS environ; *p; p++)
018058b2
JH
1158 if (Ustrncmp(*p, "EXIM_TESTHARNESS_DISABLE_OCSPVALIDITYCHECK", 42) == 0)
1159 {
1160 DEBUG(D_tls) debug_printf("Supplying known bad OCSP response\n");
1161 goto supply_response;
1162 }
1163 }
f5d78688 1164return;
3f7eeb86 1165}
f2de3a33 1166#endif /*!DISABLE_OCSP*/
3f7eeb86
PP
1167
1168
1169
1170
23bb6982
JH
1171/* Create and install a selfsigned certificate, for use in server mode */
1172
1173static int
cf0c6164 1174tls_install_selfsign(SSL_CTX * sctx, uschar ** errstr)
23bb6982
JH
1175{
1176X509 * x509 = NULL;
1177EVP_PKEY * pkey;
1178RSA * rsa;
1179X509_NAME * name;
1180uschar * where;
1181
1182where = US"allocating pkey";
1183if (!(pkey = EVP_PKEY_new()))
1184 goto err;
1185
1186where = US"allocating cert";
1187if (!(x509 = X509_new()))
1188 goto err;
1189
1190where = US"generating pkey";
6aac3239 1191if (!(rsa = rsa_callback(NULL, 0, 2048)))
23bb6982
JH
1192 goto err;
1193
4c04137d 1194where = US"assigning pkey";
23bb6982
JH
1195if (!EVP_PKEY_assign_RSA(pkey, rsa))
1196 goto err;
1197
1198X509_set_version(x509, 2); /* N+1 - version 3 */
1613fd68 1199ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
23bb6982
JH
1200X509_gmtime_adj(X509_get_notBefore(x509), 0);
1201X509_gmtime_adj(X509_get_notAfter(x509), (long)60 * 60); /* 1 hour */
1202X509_set_pubkey(x509, pkey);
1203
1204name = X509_get_subject_name(x509);
1205X509_NAME_add_entry_by_txt(name, "C",
4dc2379a 1206 MBSTRING_ASC, CUS "UK", -1, -1, 0);
23bb6982 1207X509_NAME_add_entry_by_txt(name, "O",
4dc2379a 1208 MBSTRING_ASC, CUS "Exim Developers", -1, -1, 0);
23bb6982 1209X509_NAME_add_entry_by_txt(name, "CN",
4dc2379a 1210 MBSTRING_ASC, CUS smtp_active_hostname, -1, -1, 0);
23bb6982
JH
1211X509_set_issuer_name(x509, name);
1212
1213where = US"signing cert";
1214if (!X509_sign(x509, pkey, EVP_md5()))
1215 goto err;
1216
1217where = US"installing selfsign cert";
1218if (!SSL_CTX_use_certificate(sctx, x509))
1219 goto err;
1220
1221where = US"installing selfsign key";
1222if (!SSL_CTX_use_PrivateKey(sctx, pkey))
1223 goto err;
1224
1225return OK;
1226
1227err:
cf0c6164 1228 (void) tls_error(where, NULL, NULL, errstr);
23bb6982
JH
1229 if (x509) X509_free(x509);
1230 if (pkey) EVP_PKEY_free(pkey);
1231 return DEFER;
1232}
1233
1234
1235
1236
ba86e143
JH
1237static int
1238tls_add_certfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1239 uschar ** errstr)
1240{
1241DEBUG(D_tls) debug_printf("tls_certificate file %s\n", file);
1242if (!SSL_CTX_use_certificate_chain_file(sctx, CS file))
1243 return tls_error(string_sprintf(
1244 "SSL_CTX_use_certificate_chain_file file=%s", file),
1245 cbinfo->host, NULL, errstr);
1246return 0;
1247}
1248
1249static int
1250tls_add_pkeyfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1251 uschar ** errstr)
1252{
1253DEBUG(D_tls) debug_printf("tls_privatekey file %s\n", file);
1254if (!SSL_CTX_use_PrivateKey_file(sctx, CS file, SSL_FILETYPE_PEM))
1255 return tls_error(string_sprintf(
1256 "SSL_CTX_use_PrivateKey_file file=%s", file), cbinfo->host, NULL, errstr);
1257return 0;
1258}
1259
1260
059ec3d9 1261/*************************************************
7be682ca
PP
1262* Expand key and cert file specs *
1263*************************************************/
1264
f5d78688 1265/* Called once during tls_init and possibly again during TLS setup, for a
7be682ca
PP
1266new context, if Server Name Indication was used and tls_sni was seen in
1267the certificate string.
1268
1269Arguments:
1270 sctx the SSL_CTX* to update
1271 cbinfo various parts of session state
cf0c6164 1272 errstr error string pointer
7be682ca
PP
1273
1274Returns: OK/DEFER/FAIL
1275*/
1276
1277static int
cf0c6164
JH
1278tls_expand_session_files(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo,
1279 uschar ** errstr)
7be682ca
PP
1280{
1281uschar *expanded;
1282
23bb6982 1283if (!cbinfo->certificate)
7be682ca 1284 {
ba86e143 1285 if (!cbinfo->is_server) /* client */
23bb6982 1286 return OK;
afdb5e9c 1287 /* server */
cf0c6164 1288 if (tls_install_selfsign(sctx, errstr) != OK)
23bb6982 1289 return DEFER;
7be682ca 1290 }
23bb6982
JH
1291else
1292 {
ba86e143
JH
1293 int err;
1294
23bb6982
JH
1295 if (Ustrstr(cbinfo->certificate, US"tls_sni") ||
1296 Ustrstr(cbinfo->certificate, US"tls_in_sni") ||
1297 Ustrstr(cbinfo->certificate, US"tls_out_sni")
1298 )
1299 reexpand_tls_files_for_sni = TRUE;
7be682ca 1300
cf0c6164 1301 if (!expand_check(cbinfo->certificate, US"tls_certificate", &expanded, errstr))
23bb6982
JH
1302 return DEFER;
1303
ba86e143
JH
1304 if (expanded)
1305 if (cbinfo->is_server)
1306 {
1307 const uschar * file_list = expanded;
1308 int sep = 0;
1309 uschar * file;
1310
1311 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1312 if ((err = tls_add_certfile(sctx, cbinfo, file, errstr)))
1313 return err;
1314 }
1315 else /* would there ever be a need for multiple client certs? */
1316 if ((err = tls_add_certfile(sctx, cbinfo, expanded, errstr)))
1317 return err;
7be682ca 1318
5a2a0989
JH
1319 if ( cbinfo->privatekey
1320 && !expand_check(cbinfo->privatekey, US"tls_privatekey", &expanded, errstr))
23bb6982 1321 return DEFER;
7be682ca 1322
23bb6982
JH
1323 /* If expansion was forced to fail, key_expanded will be NULL. If the result
1324 of the expansion is an empty string, ignore it also, and assume the private
1325 key is in the same file as the certificate. */
1326
1327 if (expanded && *expanded)
ba86e143
JH
1328 if (cbinfo->is_server)
1329 {
1330 const uschar * file_list = expanded;
1331 int sep = 0;
1332 uschar * file;
1333
1334 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1335 if ((err = tls_add_pkeyfile(sctx, cbinfo, file, errstr)))
1336 return err;
1337 }
1338 else /* would there ever be a need for multiple client certs? */
1339 if ((err = tls_add_pkeyfile(sctx, cbinfo, expanded, errstr)))
1340 return err;
7be682ca
PP
1341 }
1342
f2de3a33 1343#ifndef DISABLE_OCSP
f40d5be3 1344if (cbinfo->is_server && cbinfo->u_ocsp.server.file)
3f7eeb86 1345 {
47195144 1346 /*XXX stack*/
cf0c6164 1347 if (!expand_check(cbinfo->u_ocsp.server.file, US"tls_ocsp_file", &expanded, errstr))
3f7eeb86
PP
1348 return DEFER;
1349
f40d5be3 1350 if (expanded && *expanded)
3f7eeb86
PP
1351 {
1352 DEBUG(D_tls) debug_printf("tls_ocsp_file %s\n", expanded);
f40d5be3
JH
1353 if ( cbinfo->u_ocsp.server.file_expanded
1354 && (Ustrcmp(expanded, cbinfo->u_ocsp.server.file_expanded) == 0))
3f7eeb86 1355 {
f40d5be3
JH
1356 DEBUG(D_tls) debug_printf(" - value unchanged, using existing values\n");
1357 }
1358 else
f40d5be3 1359 ocsp_load_response(sctx, cbinfo, expanded);
3f7eeb86
PP
1360 }
1361 }
1362#endif
1363
7be682ca
PP
1364return OK;
1365}
1366
1367
1368
1369
1370/*************************************************
1371* Callback to handle SNI *
1372*************************************************/
1373
1374/* Called when acting as server during the TLS session setup if a Server Name
1375Indication extension was sent by the client.
1376
1377API documentation is OpenSSL s_server.c implementation.
1378
1379Arguments:
1380 s SSL* of the current session
1381 ad unknown (part of OpenSSL API) (unused)
1382 arg Callback of "our" registered data
1383
1384Returns: SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
1385*/
1386
3bcbbbe2 1387#ifdef EXIM_HAVE_OPENSSL_TLSEXT
7be682ca 1388static int
7be682ca
PP
1389tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg)
1390{
1391const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3f7eeb86 1392tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
7be682ca 1393int rc;
3f0945ff 1394int old_pool = store_pool;
cf0c6164 1395uschar * dummy_errstr;
7be682ca
PP
1396
1397if (!servername)
1398 return SSL_TLSEXT_ERR_OK;
1399
3f0945ff 1400DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
7be682ca
PP
1401 reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
1402
1403/* Make the extension value available for expansion */
3f0945ff 1404store_pool = POOL_PERM;
817d9f57 1405tls_in.sni = string_copy(US servername);
3f0945ff 1406store_pool = old_pool;
7be682ca
PP
1407
1408if (!reexpand_tls_files_for_sni)
1409 return SSL_TLSEXT_ERR_OK;
1410
1411/* Can't find an SSL_CTX_clone() or equivalent, so we do it manually;
1412not confident that memcpy wouldn't break some internal reference counting.
1413Especially since there's a references struct member, which would be off. */
1414
7a8b9519
JH
1415#ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1416if (!(server_sni = SSL_CTX_new(TLS_server_method())))
1417#else
0df4ab80 1418if (!(server_sni = SSL_CTX_new(SSLv23_server_method())))
7a8b9519 1419#endif
7be682ca 1420 {
0abc5a13 1421 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
7be682ca 1422 DEBUG(D_tls) debug_printf("SSL_CTX_new() failed: %s\n", ssl_errstring);
5a2a0989 1423 goto bad;
7be682ca
PP
1424 }
1425
1426/* Not sure how many of these are actually needed, since SSL object
1427already exists. Might even need this selfsame callback, for reneg? */
1428
817d9f57
JH
1429SSL_CTX_set_info_callback(server_sni, SSL_CTX_get_info_callback(server_ctx));
1430SSL_CTX_set_mode(server_sni, SSL_CTX_get_mode(server_ctx));
1431SSL_CTX_set_options(server_sni, SSL_CTX_get_options(server_ctx));
1432SSL_CTX_set_timeout(server_sni, SSL_CTX_get_timeout(server_ctx));
1433SSL_CTX_set_tlsext_servername_callback(server_sni, tls_servername_cb);
1434SSL_CTX_set_tlsext_servername_arg(server_sni, cbinfo);
038597d2 1435
cf0c6164
JH
1436if ( !init_dh(server_sni, cbinfo->dhparam, NULL, &dummy_errstr)
1437 || !init_ecdh(server_sni, NULL, &dummy_errstr)
038597d2 1438 )
5a2a0989 1439 goto bad;
038597d2 1440
ca954d7f
JH
1441if ( cbinfo->server_cipher_list
1442 && !SSL_CTX_set_cipher_list(server_sni, CS cbinfo->server_cipher_list))
5a2a0989 1443 goto bad;
ca954d7f 1444
f2de3a33 1445#ifndef DISABLE_OCSP
f5d78688 1446if (cbinfo->u_ocsp.server.file)
3f7eeb86 1447 {
f5d78688 1448 SSL_CTX_set_tlsext_status_cb(server_sni, tls_server_stapling_cb);
14c7b357 1449 SSL_CTX_set_tlsext_status_arg(server_sni, cbinfo);
3f7eeb86
PP
1450 }
1451#endif
7be682ca 1452
c3033f13 1453if ((rc = setup_certs(server_sni, tls_verify_certificates, tls_crl, NULL, FALSE,
cf0c6164 1454 verify_callback_server, &dummy_errstr)) != OK)
5a2a0989 1455 goto bad;
7be682ca 1456
3f7eeb86
PP
1457/* do this after setup_certs, because this can require the certs for verifying
1458OCSP information. */
cf0c6164 1459if ((rc = tls_expand_session_files(server_sni, cbinfo, &dummy_errstr)) != OK)
5a2a0989 1460 goto bad;
a799883d 1461
7be682ca 1462DEBUG(D_tls) debug_printf("Switching SSL context.\n");
817d9f57 1463SSL_set_SSL_CTX(s, server_sni);
7be682ca 1464return SSL_TLSEXT_ERR_OK;
5a2a0989
JH
1465
1466bad: return SSL_TLSEXT_ERR_ALERT_FATAL;
7be682ca 1467}
3bcbbbe2 1468#endif /* EXIM_HAVE_OPENSSL_TLSEXT */
7be682ca
PP
1469
1470
1471
1472
f2de3a33 1473#ifndef DISABLE_OCSP
f5d78688 1474
3f7eeb86
PP
1475/*************************************************
1476* Callback to handle OCSP Stapling *
1477*************************************************/
1478
1479/* Called when acting as server during the TLS session setup if the client
1480requests OCSP information with a Certificate Status Request.
1481
1482Documentation via openssl s_server.c and the Apache patch from the OpenSSL
1483project.
1484
1485*/
1486
1487static int
f5d78688 1488tls_server_stapling_cb(SSL *s, void *arg)
3f7eeb86
PP
1489{
1490const tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
47195144 1491uschar *response_der; /*XXX blob */
3f7eeb86
PP
1492int response_der_len;
1493
47195144
JH
1494/*XXX stack: use SSL_get_certificate() to see which cert; from that work
1495out which ocsp blob to send. Unfortunately, SSL_get_certificate is known
1496buggy in current OpenSSL; it returns the last cert loaded always rather than
1497the one actually presented. So we can't support a stack of OCSP proofs at
1498this time. */
1499
af4a1bca 1500DEBUG(D_tls)
b3ef41c9 1501 debug_printf("Received TLS status request (OCSP stapling); %s response\n",
f5d78688
JH
1502 cbinfo->u_ocsp.server.response ? "have" : "lack");
1503
44662487 1504tls_in.ocsp = OCSP_NOT_RESP;
f5d78688 1505if (!cbinfo->u_ocsp.server.response)
3f7eeb86
PP
1506 return SSL_TLSEXT_ERR_NOACK;
1507
1508response_der = NULL;
47195144 1509response_der_len = i2d_OCSP_RESPONSE(cbinfo->u_ocsp.server.response, /*XXX stack*/
44662487 1510 &response_der);
3f7eeb86
PP
1511if (response_der_len <= 0)
1512 return SSL_TLSEXT_ERR_NOACK;
1513
5e55c7a9 1514SSL_set_tlsext_status_ocsp_resp(server_ssl, response_der, response_der_len);
44662487 1515tls_in.ocsp = OCSP_VFIED;
3f7eeb86
PP
1516return SSL_TLSEXT_ERR_OK;
1517}
1518
3f7eeb86 1519
f5d78688
JH
1520static void
1521time_print(BIO * bp, const char * str, ASN1_GENERALIZEDTIME * time)
1522{
1523BIO_printf(bp, "\t%s: ", str);
1524ASN1_GENERALIZEDTIME_print(bp, time);
1525BIO_puts(bp, "\n");
1526}
1527
1528static int
1529tls_client_stapling_cb(SSL *s, void *arg)
1530{
1531tls_ext_ctx_cb * cbinfo = arg;
1532const unsigned char * p;
1533int len;
1534OCSP_RESPONSE * rsp;
1535OCSP_BASICRESP * bs;
1536int i;
1537
1538DEBUG(D_tls) debug_printf("Received TLS status response (OCSP stapling):");
1539len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1540if(!p)
1541 {
44662487 1542 /* Expect this when we requested ocsp but got none */
6c6d6e48 1543 if (cbinfo->u_ocsp.client.verify_required && LOGGING(tls_cipher))
44662487 1544 log_write(0, LOG_MAIN, "Received TLS status callback, null content");
f5d78688
JH
1545 else
1546 DEBUG(D_tls) debug_printf(" null\n");
44662487 1547 return cbinfo->u_ocsp.client.verify_required ? 0 : 1;
f5d78688 1548 }
018058b2 1549
f5d78688
JH
1550if(!(rsp = d2i_OCSP_RESPONSE(NULL, &p, len)))
1551 {
018058b2 1552 tls_out.ocsp = OCSP_FAILED;
6c6d6e48 1553 if (LOGGING(tls_cipher))
1eca31ca 1554 log_write(0, LOG_MAIN, "Received TLS cert status response, parse error");
f5d78688
JH
1555 else
1556 DEBUG(D_tls) debug_printf(" parse error\n");
1557 return 0;
1558 }
1559
1560if(!(bs = OCSP_response_get1_basic(rsp)))
1561 {
018058b2 1562 tls_out.ocsp = OCSP_FAILED;
6c6d6e48 1563 if (LOGGING(tls_cipher))
1eca31ca 1564 log_write(0, LOG_MAIN, "Received TLS cert status response, error parsing response");
f5d78688
JH
1565 else
1566 DEBUG(D_tls) debug_printf(" error parsing response\n");
1567 OCSP_RESPONSE_free(rsp);
1568 return 0;
1569 }
1570
1571/* We'd check the nonce here if we'd put one in the request. */
1572/* However that would defeat cacheability on the server so we don't. */
1573
f5d78688
JH
1574/* This section of code reworked from OpenSSL apps source;
1575 The OpenSSL Project retains copyright:
1576 Copyright (c) 1999 The OpenSSL Project. All rights reserved.
1577*/
1578 {
1579 BIO * bp = NULL;
f5d78688
JH
1580 int status, reason;
1581 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1582
57887ecc 1583 DEBUG(D_tls) bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
f5d78688
JH
1584
1585 /*OCSP_RESPONSE_print(bp, rsp, 0); extreme debug: stapling content */
1586
1587 /* Use the chain that verified the server cert to verify the stapled info */
1588 /* DEBUG(D_tls) x509_store_dump_cert_s_names(cbinfo->u_ocsp.client.verify_store); */
1589
c3033f13 1590 if ((i = OCSP_basic_verify(bs, cbinfo->verify_stack,
44662487 1591 cbinfo->u_ocsp.client.verify_store, 0)) <= 0)
f5d78688 1592 {
018058b2 1593 tls_out.ocsp = OCSP_FAILED;
57887ecc
JH
1594 if (LOGGING(tls_cipher)) log_write(0, LOG_MAIN,
1595 "Received TLS cert status response, itself unverifiable: %s",
1596 ERR_reason_error_string(ERR_peek_error()));
f5d78688
JH
1597 BIO_printf(bp, "OCSP response verify failure\n");
1598 ERR_print_errors(bp);
57887ecc 1599 OCSP_RESPONSE_print(bp, rsp, 0);
c8dfb21d 1600 goto failed;
f5d78688
JH
1601 }
1602
1603 BIO_printf(bp, "OCSP response well-formed and signed OK\n");
1604
c8dfb21d
JH
1605 /*XXX So we have a good stapled OCSP status. How do we know
1606 it is for the cert of interest? OpenSSL 1.1.0 has a routine
1607 OCSP_resp_find_status() which matches on a cert id, which presumably
1608 we should use. Making an id needs OCSP_cert_id_new(), which takes
1609 issuerName, issuerKey, serialNumber. Are they all in the cert?
1610
1611 For now, carry on blindly accepting the resp. */
1612
f5d78688 1613 {
f5d78688
JH
1614 OCSP_SINGLERESP * single;
1615
c8dfb21d
JH
1616#ifdef EXIM_HAVE_OCSP_RESP_COUNT
1617 if (OCSP_resp_count(bs) != 1)
1618#else
1619 STACK_OF(OCSP_SINGLERESP) * sresp = bs->tbsResponseData->responses;
f5d78688 1620 if (sk_OCSP_SINGLERESP_num(sresp) != 1)
c8dfb21d 1621#endif
f5d78688 1622 {
018058b2 1623 tls_out.ocsp = OCSP_FAILED;
44662487
JH
1624 log_write(0, LOG_MAIN, "OCSP stapling "
1625 "with multiple responses not handled");
c8dfb21d 1626 goto failed;
f5d78688
JH
1627 }
1628 single = OCSP_resp_get0(bs, 0);
44662487
JH
1629 status = OCSP_single_get0_status(single, &reason, &rev,
1630 &thisupd, &nextupd);
f5d78688
JH
1631 }
1632
f5d78688
JH
1633 DEBUG(D_tls) time_print(bp, "This OCSP Update", thisupd);
1634 DEBUG(D_tls) if(nextupd) time_print(bp, "Next OCSP Update", nextupd);
44662487
JH
1635 if (!OCSP_check_validity(thisupd, nextupd,
1636 EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
f5d78688 1637 {
018058b2 1638 tls_out.ocsp = OCSP_FAILED;
f5d78688
JH
1639 DEBUG(D_tls) ERR_print_errors(bp);
1640 log_write(0, LOG_MAIN, "Server OSCP dates invalid");
f5d78688 1641 }
44662487 1642 else
f5d78688 1643 {
44662487
JH
1644 DEBUG(D_tls) BIO_printf(bp, "Certificate status: %s\n",
1645 OCSP_cert_status_str(status));
1646 switch(status)
1647 {
1648 case V_OCSP_CERTSTATUS_GOOD:
44662487 1649 tls_out.ocsp = OCSP_VFIED;
018058b2 1650 i = 1;
c8dfb21d 1651 goto good;
44662487 1652 case V_OCSP_CERTSTATUS_REVOKED:
018058b2 1653 tls_out.ocsp = OCSP_FAILED;
44662487
JH
1654 log_write(0, LOG_MAIN, "Server certificate revoked%s%s",
1655 reason != -1 ? "; reason: " : "",
1656 reason != -1 ? OCSP_crl_reason_str(reason) : "");
1657 DEBUG(D_tls) time_print(bp, "Revocation Time", rev);
44662487
JH
1658 break;
1659 default:
018058b2 1660 tls_out.ocsp = OCSP_FAILED;
44662487
JH
1661 log_write(0, LOG_MAIN,
1662 "Server certificate status unknown, in OCSP stapling");
44662487
JH
1663 break;
1664 }
f5d78688 1665 }
c8dfb21d
JH
1666 failed:
1667 i = cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1668 good:
f5d78688
JH
1669 BIO_free(bp);
1670 }
1671
1672OCSP_RESPONSE_free(rsp);
1673return i;
1674}
f2de3a33 1675#endif /*!DISABLE_OCSP*/
3f7eeb86
PP
1676
1677
7be682ca 1678/*************************************************
059ec3d9
PH
1679* Initialize for TLS *
1680*************************************************/
1681
e51c7be2
JH
1682/* Called from both server and client code, to do preliminary initialization
1683of the library. We allocate and return a context structure.
059ec3d9
PH
1684
1685Arguments:
946ecbe0 1686 ctxp returned SSL context
059ec3d9
PH
1687 host connected host, if client; NULL if server
1688 dhparam DH parameter file
1689 certificate certificate file
1690 privatekey private key
f5d78688 1691 ocsp_file file of stapling info (server); flag for require ocsp (client)
059ec3d9 1692 addr address if client; NULL if server (for some randomness)
946ecbe0 1693 cbp place to put allocated callback context
cf0c6164 1694 errstr error string pointer
059ec3d9
PH
1695
1696Returns: OK/DEFER/FAIL
1697*/
1698
1699static int
817d9f57 1700tls_init(SSL_CTX **ctxp, host_item *host, uschar *dhparam, uschar *certificate,
3f7eeb86 1701 uschar *privatekey,
f2de3a33 1702#ifndef DISABLE_OCSP
47195144 1703 uschar *ocsp_file, /*XXX stack, in server*/
3f7eeb86 1704#endif
cf0c6164 1705 address_item *addr, tls_ext_ctx_cb ** cbp, uschar ** errstr)
059ec3d9 1706{
7006ee24 1707SSL_CTX * ctx;
77bb000f 1708long init_options;
7be682ca 1709int rc;
a7538db1 1710tls_ext_ctx_cb * cbinfo;
7be682ca
PP
1711
1712cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
1713cbinfo->certificate = certificate;
1714cbinfo->privatekey = privatekey;
a6510420 1715cbinfo->is_server = host==NULL;
f2de3a33 1716#ifndef DISABLE_OCSP
c3033f13 1717cbinfo->verify_stack = NULL;
a6510420 1718if (!host)
f5d78688
JH
1719 {
1720 cbinfo->u_ocsp.server.file = ocsp_file;
1721 cbinfo->u_ocsp.server.file_expanded = NULL;
1722 cbinfo->u_ocsp.server.response = NULL;
1723 }
1724else
1725 cbinfo->u_ocsp.client.verify_store = NULL;
3f7eeb86 1726#endif
7be682ca 1727cbinfo->dhparam = dhparam;
0df4ab80 1728cbinfo->server_cipher_list = NULL;
7be682ca 1729cbinfo->host = host;
0cbf2b82 1730#ifndef DISABLE_EVENT
a7538db1
JH
1731cbinfo->event_action = NULL;
1732#endif
77bb000f 1733
7434882d 1734#ifdef EXIM_NEED_OPENSSL_INIT
059ec3d9
PH
1735SSL_load_error_strings(); /* basic set up */
1736OpenSSL_add_ssl_algorithms();
7434882d 1737#endif
059ec3d9 1738
c8dfb21d 1739#ifdef EXIM_HAVE_SHA256
77bb000f 1740/* SHA256 is becoming ever more popular. This makes sure it gets added to the
a0475b69
TK
1741list of available digests. */
1742EVP_add_digest(EVP_sha256());
cf1ef1a9 1743#endif
a0475b69 1744
f0f5a555
PP
1745/* Create a context.
1746The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
1747negotiation in the different methods; as far as I can tell, the only
1748*_{server,client}_method which allows negotiation is SSLv23, which exists even
1749when OpenSSL is built without SSLv2 support.
1750By disabling with openssl_options, we can let admins re-enable with the
1751existing knob. */
059ec3d9 1752
7a8b9519
JH
1753#ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1754if (!(ctx = SSL_CTX_new(host ? TLS_client_method() : TLS_server_method())))
1755#else
7006ee24 1756if (!(ctx = SSL_CTX_new(host ? SSLv23_client_method() : SSLv23_server_method())))
7a8b9519 1757#endif
7006ee24 1758 return tls_error(US"SSL_CTX_new", host, NULL, errstr);
059ec3d9
PH
1759
1760/* It turns out that we need to seed the random number generator this early in
1761order to get the full complement of ciphers to work. It took me roughly a day
1762of work to discover this by experiment.
1763
1764On systems that have /dev/urandom, SSL may automatically seed itself from
1765there. Otherwise, we have to make something up as best we can. Double check
1766afterwards. */
1767
1768if (!RAND_status())
1769 {
1770 randstuff r;
9e3331ea 1771 gettimeofday(&r.tv, NULL);
059ec3d9
PH
1772 r.p = getpid();
1773
5903c6ff
JH
1774 RAND_seed(US (&r), sizeof(r));
1775 RAND_seed(US big_buffer, big_buffer_size);
1776 if (addr != NULL) RAND_seed(US addr, sizeof(addr));
059ec3d9
PH
1777
1778 if (!RAND_status())
7199e1ee 1779 return tls_error(US"RAND_status", host,
cf0c6164 1780 US"unable to seed random number generator", errstr);
059ec3d9
PH
1781 }
1782
1783/* Set up the information callback, which outputs if debugging is at a suitable
1784level. */
1785
7006ee24 1786DEBUG(D_tls) SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
8a40db1c
JH
1787#ifdef OPENSSL_HAVE_KEYLOG_CB
1788DEBUG(D_tls) SSL_CTX_set_keylog_callback(ctx, (void (*)())keylog_callback);
1789#endif
059ec3d9 1790
c80c5570 1791/* Automatically re-try reads/writes after renegotiation. */
7006ee24 1792(void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
c80c5570 1793
77bb000f
PP
1794/* Apply administrator-supplied work-arounds.
1795Historically we applied just one requested option,
1796SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
1797moved to an administrator-controlled list of options to specify and
1798grandfathered in the first one as the default value for "openssl_options".
059ec3d9 1799
77bb000f
PP
1800No OpenSSL version number checks: the options we accept depend upon the
1801availability of the option value macros from OpenSSL. */
059ec3d9 1802
7006ee24 1803if (!tls_openssl_options_parse(openssl_options, &init_options))
cf0c6164 1804 return tls_error(US"openssl_options parsing failed", host, NULL, errstr);
77bb000f
PP
1805
1806if (init_options)
1807 {
1808 DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
7006ee24 1809 if (!(SSL_CTX_set_options(ctx, init_options)))
77bb000f 1810 return tls_error(string_sprintf(
cf0c6164 1811 "SSL_CTX_set_option(%#lx)", init_options), host, NULL, errstr);
77bb000f
PP
1812 }
1813else
1814 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
059ec3d9 1815
d7f31bb6
JH
1816#ifdef OPENSSL_HAVE_NUM_TICKETS
1817SSL_CTX_set_num_tickets(ctx, 0); /* send no TLS1.3 stateful-tickets */
1818#endif
1819
a28050f8
JH
1820/* We'd like to disable session cache unconditionally, but foolish Outlook
1821Express clients then give up the first TLS connection and make a second one
1822(which works). Only when there is an IMAP service on the same machine.
1823Presumably OE is trying to use the cache for A on B. Leave it enabled for
1824now, until we work out a decent way of presenting control to the config. It
1825will never be used because we use a new context every time. */
1826#ifdef notdef
7006ee24 1827(void) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
a28050f8 1828#endif
7006ee24 1829
059ec3d9 1830/* Initialize with DH parameters if supplied */
10ca4f1c 1831/* Initialize ECDH temp key parameter selection */
059ec3d9 1832
7006ee24
JH
1833if ( !init_dh(ctx, dhparam, host, errstr)
1834 || !init_ecdh(ctx, host, errstr)
038597d2
PP
1835 )
1836 return DEFER;
059ec3d9 1837
3f7eeb86 1838/* Set up certificate and key (and perhaps OCSP info) */
059ec3d9 1839
7006ee24 1840if ((rc = tls_expand_session_files(ctx, cbinfo, errstr)) != OK)
23bb6982 1841 return rc;
c91535f3 1842
c3033f13
JH
1843/* If we need to handle SNI or OCSP, do so */
1844
3bcbbbe2 1845#ifdef EXIM_HAVE_OPENSSL_TLSEXT
c3033f13
JH
1846# ifndef DISABLE_OCSP
1847 if (!(cbinfo->verify_stack = sk_X509_new_null()))
1848 {
1849 DEBUG(D_tls) debug_printf("failed to create stack for stapling verify\n");
1850 return FAIL;
1851 }
1852# endif
1853
7a8b9519 1854if (!host) /* server */
3f0945ff 1855 {
f2de3a33 1856# ifndef DISABLE_OCSP
f5d78688 1857 /* We check u_ocsp.server.file, not server.response, because we care about if
3f7eeb86
PP
1858 the option exists, not what the current expansion might be, as SNI might
1859 change the certificate and OCSP file in use between now and the time the
1860 callback is invoked. */
f5d78688 1861 if (cbinfo->u_ocsp.server.file)
3f7eeb86 1862 {
7006ee24
JH
1863 SSL_CTX_set_tlsext_status_cb(ctx, tls_server_stapling_cb);
1864 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
3f7eeb86 1865 }
f5d78688 1866# endif
3f0945ff
PP
1867 /* We always do this, so that $tls_sni is available even if not used in
1868 tls_certificate */
7006ee24
JH
1869 SSL_CTX_set_tlsext_servername_callback(ctx, tls_servername_cb);
1870 SSL_CTX_set_tlsext_servername_arg(ctx, cbinfo);
3f0945ff 1871 }
f2de3a33 1872# ifndef DISABLE_OCSP
f5d78688
JH
1873else /* client */
1874 if(ocsp_file) /* wanting stapling */
1875 {
1876 if (!(cbinfo->u_ocsp.client.verify_store = X509_STORE_new()))
1877 {
1878 DEBUG(D_tls) debug_printf("failed to create store for stapling verify\n");
1879 return FAIL;
1880 }
7006ee24
JH
1881 SSL_CTX_set_tlsext_status_cb(ctx, tls_client_stapling_cb);
1882 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
f5d78688
JH
1883 }
1884# endif
7be682ca 1885#endif
059ec3d9 1886
e51c7be2 1887cbinfo->verify_cert_hostnames = NULL;
e51c7be2 1888
c8dfb21d 1889#ifdef EXIM_HAVE_EPHEM_RSA_KEX
059ec3d9 1890/* Set up the RSA callback */
7006ee24 1891SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
c8dfb21d 1892#endif
059ec3d9
PH
1893
1894/* Finally, set the timeout, and we are done */
1895
7006ee24 1896SSL_CTX_set_timeout(ctx, ssl_session_timeout);
059ec3d9 1897DEBUG(D_tls) debug_printf("Initialized TLS\n");
7be682ca 1898
817d9f57 1899*cbp = cbinfo;
7006ee24 1900*ctxp = ctx;
7be682ca 1901
059ec3d9
PH
1902return OK;
1903}
1904
1905
1906
1907
1908/*************************************************
1909* Get name of cipher in use *
1910*************************************************/
1911
817d9f57 1912/*
059ec3d9 1913Argument: pointer to an SSL structure for the connection
817d9f57
JH
1914 buffer to use for answer
1915 size of buffer
1916 pointer to number of bits for cipher
059ec3d9
PH
1917Returns: nothing
1918*/
1919
1920static void
817d9f57 1921construct_cipher_name(SSL *ssl, uschar *cipherbuf, int bsize, int *bits)
059ec3d9 1922{
7a8b9519 1923/* With OpenSSL 1.0.0a, 'c' needs to be const but the documentation doesn't
57b3a7f5
PP
1924yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
1925the accessor functions use const in the prototype. */
059ec3d9 1926
7a8b9519
JH
1927const uschar * ver = CUS SSL_get_version(ssl);
1928const SSL_CIPHER * c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
059ec3d9 1929
817d9f57 1930SSL_CIPHER_get_bits(c, bits);
059ec3d9 1931
817d9f57
JH
1932string_format(cipherbuf, bsize, "%s:%s:%u", ver,
1933 SSL_CIPHER_get_name(c), *bits);
059ec3d9
PH
1934
1935DEBUG(D_tls) debug_printf("Cipher: %s\n", cipherbuf);
1936}
1937
1938
f69979cf 1939static void
70e384dd 1940peer_cert(SSL * ssl, tls_support * tlsp, uschar * peerdn, unsigned siz)
f69979cf
JH
1941{
1942/*XXX we might consider a list-of-certs variable for the cert chain.
1943SSL_get_peer_cert_chain(SSL*). We'd need a new variable type and support
1944in list-handling functions, also consider the difference between the entire
1945chain and the elements sent by the peer. */
1946
70e384dd
JH
1947tlsp->peerdn = NULL;
1948
f69979cf
JH
1949/* Will have already noted peercert on a verify fail; possibly not the leaf */
1950if (!tlsp->peercert)
1951 tlsp->peercert = SSL_get_peer_certificate(ssl);
1952/* Beware anonymous ciphers which lead to server_cert being NULL */
1953if (tlsp->peercert)
70e384dd
JH
1954 if (!X509_NAME_oneline(X509_get_subject_name(tlsp->peercert), CS peerdn, siz))
1955 { DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n"); }
1956 else
1957 {
1958 peerdn[siz-1] = '\0';
1959 tlsp->peerdn = peerdn; /*XXX a static buffer... */
1960 }
f69979cf
JH
1961}
1962
1963
059ec3d9
PH
1964
1965
1966
1967/*************************************************
1968* Set up for verifying certificates *
1969*************************************************/
1970
0e8aed8a 1971#ifndef DISABLE_OCSP
c3033f13
JH
1972/* Load certs from file, return TRUE on success */
1973
1974static BOOL
1975chain_from_pem_file(const uschar * file, STACK_OF(X509) * verify_stack)
1976{
1977BIO * bp;
1978X509 * x;
1979
dec766a1
WB
1980while (sk_X509_num(verify_stack) > 0)
1981 X509_free(sk_X509_pop(verify_stack));
1982
c3033f13
JH
1983if (!(bp = BIO_new_file(CS file, "r"))) return FALSE;
1984while ((x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
1985 sk_X509_push(verify_stack, x);
1986BIO_free(bp);
1987return TRUE;
1988}
0e8aed8a 1989#endif
c3033f13
JH
1990
1991
1992
dec766a1
WB
1993/* Called by both client and server startup; on the server possibly
1994repeated after a Server Name Indication.
059ec3d9
PH
1995
1996Arguments:
7be682ca 1997 sctx SSL_CTX* to initialise
059ec3d9
PH
1998 certs certs file or NULL
1999 crl CRL file or NULL
2000 host NULL in a server; the remote host in a client
2001 optional TRUE if called from a server for a host in tls_try_verify_hosts;
2002 otherwise passed as FALSE
983207c1 2003 cert_vfy_cb Callback function for certificate verification
cf0c6164 2004 errstr error string pointer
059ec3d9
PH
2005
2006Returns: OK/DEFER/FAIL
2007*/
2008
2009static int
983207c1 2010setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
cf0c6164 2011 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr)
059ec3d9
PH
2012{
2013uschar *expcerts, *expcrl;
2014
cf0c6164 2015if (!expand_check(certs, US"tls_verify_certificates", &expcerts, errstr))
059ec3d9 2016 return DEFER;
57cc2785 2017DEBUG(D_tls) debug_printf("tls_verify_certificates: %s\n", expcerts);
059ec3d9 2018
10a831a3 2019if (expcerts && *expcerts)
059ec3d9 2020 {
10a831a3
JH
2021 /* Tell the library to use its compiled-in location for the system default
2022 CA bundle. Then add the ones specified in the config, if any. */
cb1d7830 2023
10a831a3 2024 if (!SSL_CTX_set_default_verify_paths(sctx))
cf0c6164 2025 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL, errstr);
10a831a3
JH
2026
2027 if (Ustrcmp(expcerts, "system") != 0)
059ec3d9 2028 {
cb1d7830
JH
2029 struct stat statbuf;
2030
cb1d7830
JH
2031 if (Ustat(expcerts, &statbuf) < 0)
2032 {
2033 log_write(0, LOG_MAIN|LOG_PANIC,
2034 "failed to stat %s for certificates", expcerts);
2035 return DEFER;
2036 }
059ec3d9 2037 else
059ec3d9 2038 {
cb1d7830
JH
2039 uschar *file, *dir;
2040 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
2041 { file = NULL; dir = expcerts; }
2042 else
c3033f13
JH
2043 {
2044 file = expcerts; dir = NULL;
2045#ifndef DISABLE_OCSP
2046 /* In the server if we will be offering an OCSP proof, load chain from
2047 file for verifying the OCSP proof at load time. */
2048
2049 if ( !host
2050 && statbuf.st_size > 0
2051 && server_static_cbinfo->u_ocsp.server.file
2052 && !chain_from_pem_file(file, server_static_cbinfo->verify_stack)
2053 )
2054 {
2055 log_write(0, LOG_MAIN|LOG_PANIC,
57887ecc 2056 "failed to load cert chain from %s", file);
c3033f13
JH
2057 return DEFER;
2058 }
2059#endif
2060 }
cb1d7830
JH
2061
2062 /* If a certificate file is empty, the next function fails with an
2063 unhelpful error message. If we skip it, we get the correct behaviour (no
2064 certificates are recognized, but the error message is still misleading (it
c3033f13 2065 says no certificate was supplied). But this is better. */
cb1d7830 2066
f2f2c91b
JH
2067 if ( (!file || statbuf.st_size > 0)
2068 && !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
cf0c6164 2069 return tls_error(US"SSL_CTX_load_verify_locations", host, NULL, errstr);
cb1d7830
JH
2070
2071 /* Load the list of CAs for which we will accept certs, for sending
2072 to the client. This is only for the one-file tls_verify_certificates
2073 variant.
d7978c0f
JH
2074 If a list isn't loaded into the server, but some verify locations are set,
2075 the server end appears to make a wildcard request for client certs.
10a831a3 2076 Meanwhile, the client library as default behaviour *ignores* the list
cb1d7830
JH
2077 we send over the wire - see man SSL_CTX_set_client_cert_cb.
2078 Because of this, and that the dir variant is likely only used for
d7978c0f
JH
2079 the public-CA bundle (not for a private CA), not worth fixing. */
2080
f2f2c91b 2081 if (file)
cb1d7830 2082 {
2009ecca 2083 STACK_OF(X509_NAME) * names = SSL_load_client_CA_file(CS file);
dec766a1
WB
2084
2085 SSL_CTX_set_client_CA_list(sctx, names);
f2f2c91b 2086 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n",
cb1d7830 2087 sk_X509_NAME_num(names));
cb1d7830 2088 }
059ec3d9
PH
2089 }
2090 }
2091
2092 /* Handle a certificate revocation list. */
2093
10a831a3 2094#if OPENSSL_VERSION_NUMBER > 0x00907000L
059ec3d9 2095
8b417f2c 2096 /* This bit of code is now the version supplied by Lars Mainka. (I have
10a831a3 2097 merely reformatted it into the Exim code style.)
8b417f2c 2098
10a831a3
JH
2099 "From here I changed the code to add support for multiple crl's
2100 in pem format in one file or to support hashed directory entries in
2101 pem format instead of a file. This method now uses the library function
2102 X509_STORE_load_locations to add the CRL location to the SSL context.
2103 OpenSSL will then handle the verify against CA certs and CRLs by
2104 itself in the verify callback." */
8b417f2c 2105
cf0c6164 2106 if (!expand_check(crl, US"tls_crl", &expcrl, errstr)) return DEFER;
10a831a3 2107 if (expcrl && *expcrl)
059ec3d9 2108 {
8b417f2c
PH
2109 struct stat statbufcrl;
2110 if (Ustat(expcrl, &statbufcrl) < 0)
2111 {
2112 log_write(0, LOG_MAIN|LOG_PANIC,
2113 "failed to stat %s for certificates revocation lists", expcrl);
2114 return DEFER;
2115 }
2116 else
059ec3d9 2117 {
8b417f2c
PH
2118 /* is it a file or directory? */
2119 uschar *file, *dir;
7be682ca 2120 X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
8b417f2c 2121 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
059ec3d9 2122 {
8b417f2c
PH
2123 file = NULL;
2124 dir = expcrl;
2125 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
059ec3d9
PH
2126 }
2127 else
2128 {
8b417f2c
PH
2129 file = expcrl;
2130 dir = NULL;
2131 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
059ec3d9 2132 }
8b417f2c 2133 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
cf0c6164 2134 return tls_error(US"X509_STORE_load_locations", host, NULL, errstr);
8b417f2c
PH
2135
2136 /* setting the flags to check against the complete crl chain */
2137
2138 X509_STORE_set_flags(cvstore,
2139 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
059ec3d9 2140 }
059ec3d9
PH
2141 }
2142
10a831a3 2143#endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
059ec3d9
PH
2144
2145 /* If verification is optional, don't fail if no certificate */
2146
7be682ca 2147 SSL_CTX_set_verify(sctx,
5a2a0989 2148 SSL_VERIFY_PEER | (optional ? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
983207c1 2149 cert_vfy_cb);
059ec3d9
PH
2150 }
2151
2152return OK;
2153}
2154
2155
2156
2157/*************************************************
2158* Start a TLS session in a server *
2159*************************************************/
2160
2161/* This is called when Exim is running as a server, after having received
2162the STARTTLS command. It must respond to that command, and then negotiate
2163a TLS session.
2164
2165Arguments:
2166 require_ciphers allowed ciphers
cf0c6164 2167 errstr pointer to error message
059ec3d9
PH
2168
2169Returns: OK on success
2170 DEFER for errors before the start of the negotiation
4c04137d 2171 FAIL for errors during the negotiation; the server can't
059ec3d9
PH
2172 continue running.
2173*/
2174
2175int
cf0c6164 2176tls_server_start(const uschar * require_ciphers, uschar ** errstr)
059ec3d9
PH
2177{
2178int rc;
cf0c6164
JH
2179uschar * expciphers;
2180tls_ext_ctx_cb * cbinfo;
f69979cf 2181static uschar peerdn[256];
817d9f57 2182static uschar cipherbuf[256];
059ec3d9
PH
2183
2184/* Check for previous activation */
2185
74f1a423 2186if (tls_in.active.sock >= 0)
059ec3d9 2187 {
cf0c6164 2188 tls_error(US"STARTTLS received after TLS started", NULL, US"", errstr);
925ac8e4 2189 smtp_printf("554 Already in TLS\r\n", FALSE);
059ec3d9
PH
2190 return FAIL;
2191 }
2192
2193/* Initialize the SSL library. If it fails, it will already have logged
2194the error. */
2195
817d9f57 2196rc = tls_init(&server_ctx, NULL, tls_dhparam, tls_certificate, tls_privatekey,
f2de3a33 2197#ifndef DISABLE_OCSP
47195144 2198 tls_ocsp_file, /*XXX stack*/
3f7eeb86 2199#endif
cf0c6164 2200 NULL, &server_static_cbinfo, errstr);
059ec3d9 2201if (rc != OK) return rc;
817d9f57 2202cbinfo = server_static_cbinfo;
059ec3d9 2203
cf0c6164 2204if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers, errstr))
059ec3d9
PH
2205 return FAIL;
2206
2207/* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
17c76198
PP
2208were historically separated by underscores. So that I can use either form in my
2209tests, and also for general convenience, we turn underscores into hyphens here.
0c3807a8
JH
2210
2211XXX SSL_CTX_set_cipher_list() is replaced by SSL_CTX_set_ciphersuites()
2212for TLS 1.3 . Since we do not call it at present we get the default list:
2213TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
17c76198 2214*/
059ec3d9 2215
c3033f13 2216if (expciphers)
059ec3d9 2217 {
c3033f13 2218 uschar * s = expciphers;
059ec3d9
PH
2219 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
2220 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
817d9f57 2221 if (!SSL_CTX_set_cipher_list(server_ctx, CS expciphers))
cf0c6164 2222 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL, errstr);
7be682ca 2223 cbinfo->server_cipher_list = expciphers;
059ec3d9
PH
2224 }
2225
2226/* If this is a host for which certificate verification is mandatory or
2227optional, set up appropriately. */
2228
817d9f57 2229tls_in.certificate_verified = FALSE;
c0635b6d 2230#ifdef SUPPORT_DANE
53a7196b
JH
2231tls_in.dane_verified = FALSE;
2232#endif
a2ff477a 2233server_verify_callback_called = FALSE;
059ec3d9
PH
2234
2235if (verify_check_host(&tls_verify_hosts) == OK)
2236 {
983207c1 2237 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
afdb5e9c 2238 FALSE, verify_callback_server, errstr);
059ec3d9 2239 if (rc != OK) return rc;
a2ff477a 2240 server_verify_optional = FALSE;
059ec3d9
PH
2241 }
2242else if (verify_check_host(&tls_try_verify_hosts) == OK)
2243 {
983207c1 2244 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
afdb5e9c 2245 TRUE, verify_callback_server, errstr);
059ec3d9 2246 if (rc != OK) return rc;
a2ff477a 2247 server_verify_optional = TRUE;
059ec3d9
PH
2248 }
2249
2250/* Prepare for new connection */
2251
cf0c6164
JH
2252if (!(server_ssl = SSL_new(server_ctx)))
2253 return tls_error(US"SSL_new", NULL, NULL, errstr);
da3ad30d
PP
2254
2255/* Warning: we used to SSL_clear(ssl) here, it was removed.
2256 *
2257 * With the SSL_clear(), we get strange interoperability bugs with
2258 * OpenSSL 1.0.1b and TLS1.1/1.2. It looks as though this may be a bug in
2259 * OpenSSL itself, as a clear should not lead to inability to follow protocols.
2260 *
2261 * The SSL_clear() call is to let an existing SSL* be reused, typically after
2262 * session shutdown. In this case, we have a brand new object and there's no
2263 * obvious reason to immediately clear it. I'm guessing that this was
2264 * originally added because of incomplete initialisation which the clear fixed,
2265 * in some historic release.
2266 */
059ec3d9
PH
2267
2268/* Set context and tell client to go ahead, except in the case of TLS startup
2269on connection, where outputting anything now upsets the clients and tends to
2270make them disconnect. We need to have an explicit fflush() here, to force out
2271the response. Other smtp_printf() calls do not need it, because in non-TLS
2272mode, the fflush() happens when smtp_getc() is called. */
2273
817d9f57
JH
2274SSL_set_session_id_context(server_ssl, sid_ctx, Ustrlen(sid_ctx));
2275if (!tls_in.on_connect)
059ec3d9 2276 {
925ac8e4 2277 smtp_printf("220 TLS go ahead\r\n", FALSE);
059ec3d9
PH
2278 fflush(smtp_out);
2279 }
2280
2281/* Now negotiate the TLS session. We put our own timer on it, since it seems
2282that the OpenSSL library doesn't. */
2283
817d9f57
JH
2284SSL_set_wfd(server_ssl, fileno(smtp_out));
2285SSL_set_rfd(server_ssl, fileno(smtp_in));
2286SSL_set_accept_state(server_ssl);
059ec3d9
PH
2287
2288DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
2289
2290sigalrm_seen = FALSE;
c2a1bba0 2291if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
817d9f57 2292rc = SSL_accept(server_ssl);
c2a1bba0 2293ALARM_CLR(0);
059ec3d9
PH
2294
2295if (rc <= 0)
2296 {
cf0c6164 2297 (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
059ec3d9
PH
2298 return FAIL;
2299 }
2300
2301DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
25fa0868
JH
2302ERR_clear_error(); /* Even success can leave errors in the stack. Seen with
2303 anon-authentication ciphersuite negociated. */
059ec3d9
PH
2304
2305/* TLS has been set up. Adjust the input functions to read via TLS,
2306and initialize things. */
2307
f69979cf
JH
2308peer_cert(server_ssl, &tls_in, peerdn, sizeof(peerdn));
2309
059ec3d9
PH
2310DEBUG(D_tls)
2311 {
2312 uschar buf[2048];
817d9f57 2313 if (SSL_get_shared_ciphers(server_ssl, CS buf, sizeof(buf)) != NULL)
059ec3d9 2314 debug_printf("Shared ciphers: %s\n", buf);
f20cfa4a
JH
2315
2316#ifdef EXIM_HAVE_OPENSSL_KEYLOG
2317 {
2318 BIO * bp = BIO_new(BIO_s_mem());
2319 uschar * s;
2320 int len;
2321 SSL_SESSION_print_keylog(bp, SSL_get_session(server_ssl));
2322 len = (int) BIO_get_mem_data(bp, CSS &s);
2323 debug_printf("%.*s", len, s);
2324 BIO_free(bp);
2325 }
2326#endif
059ec3d9
PH
2327 }
2328
f20cfa4a
JH
2329construct_cipher_name(server_ssl, cipherbuf, sizeof(cipherbuf), &tls_in.bits);
2330tls_in.cipher = cipherbuf;
2331
9d1c15ef
JH
2332/* Record the certificate we presented */
2333 {
2334 X509 * crt = SSL_get_certificate(server_ssl);
2335 tls_in.ourcert = crt ? X509_dup(crt) : NULL;
2336 }
059ec3d9 2337
817d9f57
JH
2338/* Only used by the server-side tls (tls_in), including tls_getc.
2339 Client-side (tls_out) reads (seem to?) go via
2340 smtp_read_response()/ip_recv().
2341 Hence no need to duplicate for _in and _out.
2342 */
b808677c 2343if (!ssl_xfer_buffer) ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
059ec3d9 2344ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
8b77d27a 2345ssl_xfer_eof = ssl_xfer_error = FALSE;
059ec3d9
PH
2346
2347receive_getc = tls_getc;
0d81dabc 2348receive_getbuf = tls_getbuf;
584e96c6 2349receive_get_cache = tls_get_cache;
059ec3d9
PH
2350receive_ungetc = tls_ungetc;
2351receive_feof = tls_feof;
2352receive_ferror = tls_ferror;
58eb016e 2353receive_smtp_buffered = tls_smtp_buffered;
059ec3d9 2354
74f1a423
JH
2355tls_in.active.sock = fileno(smtp_out);
2356tls_in.active.tls_ctx = NULL; /* not using explicit ctx for server-side */
059ec3d9
PH
2357return OK;
2358}
2359
2360
2361
2362
043b1248
JH
2363static int
2364tls_client_basic_ctx_init(SSL_CTX * ctx,
cf0c6164
JH
2365 host_item * host, smtp_transport_options_block * ob, tls_ext_ctx_cb * cbinfo,
2366 uschar ** errstr)
043b1248
JH
2367{
2368int rc;
94431adb 2369/* stick to the old behaviour for compatibility if tls_verify_certificates is
043b1248
JH
2370 set but both tls_verify_hosts and tls_try_verify_hosts is not set. Check only
2371 the specified host patterns if one of them is defined */
2372
610ff438
JH
2373if ( ( !ob->tls_verify_hosts
2374 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2375 )
3c07dd2d 2376 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
aa2a70ba 2377 )
043b1248 2378 client_verify_optional = FALSE;
3c07dd2d 2379else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
aa2a70ba
JH
2380 client_verify_optional = TRUE;
2381else
2382 return OK;
2383
2384if ((rc = setup_certs(ctx, ob->tls_verify_certificates,
cf0c6164
JH
2385 ob->tls_crl, host, client_verify_optional, verify_callback_client,
2386 errstr)) != OK)
aa2a70ba 2387 return rc;
043b1248 2388
3c07dd2d 2389if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
043b1248 2390 {
4af0d74a 2391 cbinfo->verify_cert_hostnames =
8c5d388a 2392#ifdef SUPPORT_I18N
4af0d74a
JH
2393 string_domain_utf8_to_alabel(host->name, NULL);
2394#else
2395 host->name;
2396#endif
aa2a70ba
JH
2397 DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
2398 cbinfo->verify_cert_hostnames);
043b1248 2399 }
043b1248
JH
2400return OK;
2401}
059ec3d9 2402
fde080a4 2403
c0635b6d 2404#ifdef SUPPORT_DANE
fde080a4 2405static int
cf0c6164 2406dane_tlsa_load(SSL * ssl, host_item * host, dns_answer * dnsa, uschar ** errstr)
fde080a4 2407{
fde080a4
JH
2408dns_scan dnss;
2409const char * hostnames[2] = { CS host->name, NULL };
2410int found = 0;
2411
2412if (DANESSL_init(ssl, NULL, hostnames) != 1)
cf0c6164 2413 return tls_error(US"hostnames load", host, NULL, errstr);
fde080a4 2414
d7978c0f 2415for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
fde080a4 2416 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
1b76ad22 2417 ) if (rr->type == T_TLSA && rr->size > 3)
fde080a4 2418 {
c3033f13 2419 const uschar * p = rr->data;
fde080a4
JH
2420 uint8_t usage, selector, mtype;
2421 const char * mdname;
2422
fde080a4 2423 usage = *p++;
133d2546
JH
2424
2425 /* Only DANE-TA(2) and DANE-EE(3) are supported */
2426 if (usage != 2 && usage != 3) continue;
2427
fde080a4
JH
2428 selector = *p++;
2429 mtype = *p++;
2430
2431 switch (mtype)
2432 {
133d2546
JH
2433 default: continue; /* Only match-types 0, 1, 2 are supported */
2434 case 0: mdname = NULL; break;
2435 case 1: mdname = "sha256"; break;
2436 case 2: mdname = "sha512"; break;
fde080a4
JH
2437 }
2438
133d2546 2439 found++;
fde080a4
JH
2440 switch (DANESSL_add_tlsa(ssl, usage, selector, mdname, p, rr->size - 3))
2441 {
2442 default:
cf0c6164 2443 return tls_error(US"tlsa load", host, NULL, errstr);
c035b645 2444 case 0: /* action not taken */
fde080a4
JH
2445 case 1: break;
2446 }
594706ea
JH
2447
2448 tls_out.tlsa_usage |= 1<<usage;
fde080a4
JH
2449 }
2450
2451if (found)
2452 return OK;
2453
133d2546 2454log_write(0, LOG_MAIN, "DANE error: No usable TLSA records");
6ebd79ec 2455return DEFER;
fde080a4 2456}
c0635b6d 2457#endif /*SUPPORT_DANE*/
fde080a4
JH
2458
2459
2460
059ec3d9
PH
2461/*************************************************
2462* Start a TLS session in a client *
2463*************************************************/
2464
2465/* Called from the smtp transport after STARTTLS has been accepted.
2466
2467Argument:
2468 fd the fd of the connection
afdb5e9c
JH
2469 host connected host (for messages and option-tests)
2470 addr the first address (for some randomness; can be NULL)
a7538db1 2471 tb transport (always smtp)
0e66b3b6 2472 tlsa_dnsa tlsa lookup, if DANE, else null
afdb5e9c 2473 tlsp record details of channel configuration here; must be non-NULL
cf0c6164 2474 errstr error string pointer
059ec3d9 2475
74f1a423 2476Returns: Pointer to TLS session context, or NULL on error
059ec3d9
PH
2477*/
2478
74f1a423 2479void *
f5d78688 2480tls_client_start(int fd, host_item *host, address_item *addr,
cf0c6164 2481 transport_instance * tb,
c0635b6d 2482#ifdef SUPPORT_DANE
cf0c6164 2483 dns_answer * tlsa_dnsa,
0e66b3b6 2484#endif
74f1a423 2485 tls_support * tlsp, uschar ** errstr)
059ec3d9 2486{
afdb5e9c
JH
2487smtp_transport_options_block * ob = tb
2488 ? (smtp_transport_options_block *)tb->options_block
2489 : &smtp_transport_option_defaults;
74f1a423 2490exim_openssl_client_tls_ctx * exim_client_ctx;
f69979cf 2491static uschar peerdn[256];
868f5672 2492uschar * expciphers;
059ec3d9 2493int rc;
817d9f57 2494static uschar cipherbuf[256];
043b1248
JH
2495
2496#ifndef DISABLE_OCSP
043b1248 2497BOOL request_ocsp = FALSE;
6634ac8d 2498BOOL require_ocsp = FALSE;
043b1248 2499#endif
043b1248 2500
74f1a423
JH
2501rc = store_pool;
2502store_pool = POOL_PERM;
2503exim_client_ctx = store_get(sizeof(exim_openssl_client_tls_ctx));
2504store_pool = rc;
2505
c0635b6d 2506#ifdef SUPPORT_DANE
74f1a423 2507tlsp->tlsa_usage = 0;
043b1248
JH
2508#endif
2509
f2de3a33 2510#ifndef DISABLE_OCSP
043b1248 2511 {
c0635b6d 2512# ifdef SUPPORT_DANE
4f59c424
JH
2513 if ( tlsa_dnsa
2514 && ob->hosts_request_ocsp[0] == '*'
2515 && ob->hosts_request_ocsp[1] == '\0'
2516 )
2517 {
2518 /* Unchanged from default. Use a safer one under DANE */
2519 request_ocsp = TRUE;
2520 ob->hosts_request_ocsp = US"${if or { {= {0}{$tls_out_tlsa_usage}} "
2521 " {= {4}{$tls_out_tlsa_usage}} } "
2522 " {*}{}}";
2523 }
2524# endif
2525
5130845b 2526 if ((require_ocsp =
3c07dd2d 2527 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK))
fca41d5a
JH
2528 request_ocsp = TRUE;
2529 else
c0635b6d 2530# ifdef SUPPORT_DANE
4f59c424 2531 if (!request_ocsp)
fca41d5a 2532# endif
5130845b 2533 request_ocsp =
3c07dd2d 2534 verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
043b1248 2535 }
f5d78688 2536#endif
059ec3d9 2537
74f1a423 2538rc = tls_init(&exim_client_ctx->ctx, host, NULL,
65867078 2539 ob->tls_certificate, ob->tls_privatekey,
f2de3a33 2540#ifndef DISABLE_OCSP
44662487 2541 (void *)(long)request_ocsp,
3f7eeb86 2542#endif
cf0c6164 2543 addr, &client_static_cbinfo, errstr);
74f1a423 2544if (rc != OK) return NULL;
059ec3d9 2545
74f1a423 2546tlsp->certificate_verified = FALSE;
a2ff477a 2547client_verify_callback_called = FALSE;
059ec3d9 2548
5ec37a55
PP
2549expciphers = NULL;
2550#ifdef SUPPORT_DANE
2551if (tlsa_dnsa)
2552 {
2553 /* We fall back to tls_require_ciphers if unset, empty or forced failure, but
2554 other failures should be treated as problems. */
2555 if (ob->dane_require_tls_ciphers &&
2556 !expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2557 &expciphers, errstr))
74f1a423 2558 return NULL;
5ec37a55
PP
2559 if (expciphers && *expciphers == '\0')
2560 expciphers = NULL;
2561 }
2562#endif
2563if (!expciphers &&
2564 !expand_check(ob->tls_require_ciphers, US"tls_require_ciphers",
2565 &expciphers, errstr))
74f1a423 2566 return NULL;
059ec3d9
PH
2567
2568/* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2569are separated by underscores. So that I can use either form in my tests, and
2570also for general convenience, we turn underscores into hyphens here. */
2571
cf0c6164 2572if (expciphers)
059ec3d9
PH
2573 {
2574 uschar *s = expciphers;
cf0c6164 2575 while (*s) { if (*s == '_') *s = '-'; s++; }
059ec3d9 2576 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
74f1a423
JH
2577 if (!SSL_CTX_set_cipher_list(exim_client_ctx->ctx, CS expciphers))
2578 {
2579 tls_error(US"SSL_CTX_set_cipher_list", host, NULL, errstr);
2580 return NULL;
2581 }
059ec3d9
PH
2582 }
2583
c0635b6d 2584#ifdef SUPPORT_DANE
0e66b3b6 2585if (tlsa_dnsa)
a63be306 2586 {
74f1a423 2587 SSL_CTX_set_verify(exim_client_ctx->ctx,
02af313d
JH
2588 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2589 verify_callback_client_dane);
e5cccda9 2590
043b1248 2591 if (!DANESSL_library_init())
74f1a423
JH
2592 {
2593 tls_error(US"library init", host, NULL, errstr);
2594 return NULL;
2595 }
2596 if (DANESSL_CTX_init(exim_client_ctx->ctx) <= 0)
2597 {
2598 tls_error(US"context init", host, NULL, errstr);
2599 return NULL;
2600 }
043b1248
JH
2601 }
2602else
e51c7be2 2603
043b1248
JH
2604#endif
2605
74f1a423
JH
2606 if (tls_client_basic_ctx_init(exim_client_ctx->ctx, host, ob,
2607 client_static_cbinfo, errstr) != OK)
2608 return NULL;
059ec3d9 2609
74f1a423
JH
2610if (!(exim_client_ctx->ssl = SSL_new(exim_client_ctx->ctx)))
2611 {
2612 tls_error(US"SSL_new", host, NULL, errstr);
2613 return NULL;
2614 }
2615SSL_set_session_id_context(exim_client_ctx->ssl, sid_ctx, Ustrlen(sid_ctx));
2616SSL_set_fd(exim_client_ctx->ssl, fd);
2617SSL_set_connect_state(exim_client_ctx->ssl);
059ec3d9 2618
65867078 2619if (ob->tls_sni)
3f0945ff 2620 {
74f1a423
JH
2621 if (!expand_check(ob->tls_sni, US"tls_sni", &tlsp->sni, errstr))
2622 return NULL;
2623 if (!tlsp->sni)
2c9a0e86
PP
2624 {
2625 DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n");
2626 }
74f1a423
JH
2627 else if (!Ustrlen(tlsp->sni))
2628 tlsp->sni = NULL;
3f0945ff
PP
2629 else
2630 {
35731706 2631#ifdef EXIM_HAVE_OPENSSL_TLSEXT
74f1a423
JH
2632 DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tlsp->sni);
2633 SSL_set_tlsext_host_name(exim_client_ctx->ssl, tlsp->sni);
35731706 2634#else
66802652 2635 log_write(0, LOG_MAIN, "SNI unusable with this OpenSSL library version; ignoring \"%s\"\n",
74f1a423 2636 tlsp->sni);
35731706 2637#endif
3f0945ff
PP
2638 }
2639 }
2640
c0635b6d 2641#ifdef SUPPORT_DANE
0e66b3b6 2642if (tlsa_dnsa)
74f1a423
JH
2643 if (dane_tlsa_load(exim_client_ctx->ssl, host, tlsa_dnsa, errstr) != OK)
2644 return NULL;
594706ea
JH
2645#endif
2646
f2de3a33 2647#ifndef DISABLE_OCSP
f5d78688
JH
2648/* Request certificate status at connection-time. If the server
2649does OCSP stapling we will get the callback (set in tls_init()) */
c0635b6d 2650# ifdef SUPPORT_DANE
44662487
JH
2651if (request_ocsp)
2652 {
594706ea 2653 const uschar * s;
41afb5cb
JH
2654 if ( ((s = ob->hosts_require_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
2655 || ((s = ob->hosts_request_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
594706ea
JH
2656 )
2657 { /* Re-eval now $tls_out_tlsa_usage is populated. If
2658 this means we avoid the OCSP request, we wasted the setup
2659 cost in tls_init(). */
3c07dd2d 2660 require_ocsp = verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
5130845b 2661 request_ocsp = require_ocsp
3c07dd2d 2662 || verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
594706ea
JH
2663 }
2664 }
b50c8b84
JH
2665# endif
2666
594706ea
JH
2667if (request_ocsp)
2668 {
74f1a423 2669 SSL_set_tlsext_status_type(exim_client_ctx->ssl, TLSEXT_STATUSTYPE_ocsp);
44662487 2670 client_static_cbinfo->u_ocsp.client.verify_required = require_ocsp;
74f1a423 2671 tlsp->ocsp = OCSP_NOT_RESP;
44662487 2672 }
f5d78688
JH
2673#endif
2674
0cbf2b82 2675#ifndef DISABLE_EVENT
afdb5e9c 2676client_static_cbinfo->event_action = tb ? tb->event_action : NULL;
a7538db1 2677#endif
043b1248 2678
059ec3d9
PH
2679/* There doesn't seem to be a built-in timeout on connection. */
2680
2681DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
2682sigalrm_seen = FALSE;
c2a1bba0 2683ALARM(ob->command_timeout);
74f1a423 2684rc = SSL_connect(exim_client_ctx->ssl);
c2a1bba0 2685ALARM_CLR(0);
059ec3d9 2686
c0635b6d 2687#ifdef SUPPORT_DANE
0e66b3b6 2688if (tlsa_dnsa)
74f1a423 2689 DANESSL_cleanup(exim_client_ctx->ssl);
043b1248
JH
2690#endif
2691
059ec3d9 2692if (rc <= 0)
74f1a423
JH
2693 {
2694 tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL, errstr);
2695 return NULL;
2696 }
059ec3d9 2697
f20cfa4a
JH
2698DEBUG(D_tls)
2699 {
2700 debug_printf("SSL_connect succeeded\n");
2701#ifdef EXIM_HAVE_OPENSSL_KEYLOG
2702 {
2703 BIO * bp = BIO_new(BIO_s_mem());
2704 uschar * s;
2705 int len;
2706 SSL_SESSION_print_keylog(bp, SSL_get_session(server_ssl));
2707 len = (int) BIO_get_mem_data(bp, CSS &s);
2708 debug_printf("%.*s", len, s);
2709 BIO_free(bp);
2710 }
2711#endif
2712 }
059ec3d9 2713
74f1a423 2714peer_cert(exim_client_ctx->ssl, tlsp, peerdn, sizeof(peerdn));
059ec3d9 2715
74f1a423
JH
2716construct_cipher_name(exim_client_ctx->ssl, cipherbuf, sizeof(cipherbuf), &tlsp->bits);
2717tlsp->cipher = cipherbuf;
059ec3d9 2718
9d1c15ef
JH
2719/* Record the certificate we presented */
2720 {
74f1a423
JH
2721 X509 * crt = SSL_get_certificate(exim_client_ctx->ssl);
2722 tlsp->ourcert = crt ? X509_dup(crt) : NULL;
9d1c15ef
JH
2723 }
2724
74f1a423
JH
2725tlsp->active.sock = fd;
2726tlsp->active.tls_ctx = exim_client_ctx;
2727return exim_client_ctx;
059ec3d9
PH
2728}
2729
2730
2731
2732
2733
0d81dabc
JH
2734static BOOL
2735tls_refill(unsigned lim)
2736{
2737int error;
2738int inbytes;
2739
2740DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", server_ssl,
2741 ssl_xfer_buffer, ssl_xfer_buffer_size);
2742
c2a1bba0 2743if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
0d81dabc
JH
2744inbytes = SSL_read(server_ssl, CS ssl_xfer_buffer,
2745 MIN(ssl_xfer_buffer_size, lim));
2746error = SSL_get_error(server_ssl, inbytes);
c2a1bba0 2747if (smtp_receive_timeout > 0) ALARM_CLR(0);
9723f966
JH
2748
2749if (had_command_timeout) /* set by signal handler */
2750 smtp_command_timeout_exit(); /* does not return */
2751if (had_command_sigterm)
2752 smtp_command_sigterm_exit();
2753if (had_data_timeout)
2754 smtp_data_timeout_exit();
2755if (had_data_sigint)
2756 smtp_data_sigint_exit();
0d81dabc
JH
2757
2758/* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
2759closed down, not that the socket itself has been closed down. Revert to
2760non-SSL handling. */
2761
74f1a423 2762switch(error)
0d81dabc 2763 {
74f1a423
JH
2764 case SSL_ERROR_NONE:
2765 break;
2766
2767 case SSL_ERROR_ZERO_RETURN:
2768 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
0d81dabc 2769
74f1a423
JH
2770 receive_getc = smtp_getc;
2771 receive_getbuf = smtp_getbuf;
2772 receive_get_cache = smtp_get_cache;
2773 receive_ungetc = smtp_ungetc;
2774 receive_feof = smtp_feof;
2775 receive_ferror = smtp_ferror;
2776 receive_smtp_buffered = smtp_buffered;
0d81dabc 2777
74f1a423
JH
2778 if (SSL_get_shutdown(server_ssl) == SSL_RECEIVED_SHUTDOWN)
2779 SSL_shutdown(server_ssl);
dec766a1 2780
37f0ce65 2781#ifndef DISABLE_OCSP
74f1a423
JH
2782 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
2783 server_static_cbinfo->verify_stack = NULL;
37f0ce65 2784#endif
74f1a423
JH
2785 SSL_free(server_ssl);
2786 SSL_CTX_free(server_ctx);
2787 server_ctx = NULL;
2788 server_ssl = NULL;
2789 tls_in.active.sock = -1;
2790 tls_in.active.tls_ctx = NULL;
2791 tls_in.bits = 0;
2792 tls_in.cipher = NULL;
2793 tls_in.peerdn = NULL;
2794 tls_in.sni = NULL;
0d81dabc 2795
74f1a423 2796 return FALSE;
0d81dabc 2797
74f1a423
JH
2798 /* Handle genuine errors */
2799 case SSL_ERROR_SSL:
0abc5a13 2800 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
74f1a423
JH
2801 log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
2802 ssl_xfer_error = TRUE;
2803 return FALSE;
0d81dabc 2804
74f1a423
JH
2805 default:
2806 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
2807 DEBUG(D_tls) if (error == SSL_ERROR_SYSCALL)
2808 debug_printf(" - syscall %s\n", strerror(errno));
2809 ssl_xfer_error = TRUE;
2810 return FALSE;
0d81dabc
JH
2811 }
2812
2813#ifndef DISABLE_DKIM
2814dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
2815#endif
2816ssl_xfer_buffer_hwm = inbytes;
2817ssl_xfer_buffer_lwm = 0;
2818return TRUE;
2819}
2820
2821
059ec3d9
PH
2822/*************************************************
2823* TLS version of getc *
2824*************************************************/
2825
2826/* This gets the next byte from the TLS input buffer. If the buffer is empty,
2827it refills the buffer via the SSL reading function.
2828
bd8fbe36 2829Arguments: lim Maximum amount to read/buffer
059ec3d9 2830Returns: the next character or EOF
817d9f57
JH
2831
2832Only used by the server-side TLS.
059ec3d9
PH
2833*/
2834
2835int
bd8fbe36 2836tls_getc(unsigned lim)
059ec3d9
PH
2837{
2838if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
0d81dabc
JH
2839 if (!tls_refill(lim))
2840 return ssl_xfer_error ? EOF : smtp_getc(lim);
059ec3d9 2841
0d81dabc 2842/* Something in the buffer; return next uschar */
059ec3d9 2843
0d81dabc
JH
2844return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
2845}
059ec3d9 2846
0d81dabc
JH
2847uschar *
2848tls_getbuf(unsigned * len)
2849{
2850unsigned size;
2851uschar * buf;
ba084640 2852
0d81dabc
JH
2853if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
2854 if (!tls_refill(*len))
059ec3d9 2855 {
0d81dabc
JH
2856 if (!ssl_xfer_error) return smtp_getbuf(len);
2857 *len = 0;
2858 return NULL;
059ec3d9 2859 }
c80c5570 2860
0d81dabc
JH
2861if ((size = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm) > *len)
2862 size = *len;
2863buf = &ssl_xfer_buffer[ssl_xfer_buffer_lwm];
2864ssl_xfer_buffer_lwm += size;
2865*len = size;
2866return buf;
059ec3d9
PH
2867}
2868
0d81dabc 2869
584e96c6
JH
2870void
2871tls_get_cache()
2872{
9960d1e5 2873#ifndef DISABLE_DKIM
584e96c6
JH
2874int n = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm;
2875if (n > 0)
2876 dkim_exim_verify_feed(ssl_xfer_buffer+ssl_xfer_buffer_lwm, n);
584e96c6 2877#endif
9960d1e5 2878}
584e96c6 2879
059ec3d9 2880
925ac8e4
JH
2881BOOL
2882tls_could_read(void)
2883{
a5ffa9b4 2884return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm || SSL_pending(server_ssl) > 0;
925ac8e4
JH
2885}
2886
059ec3d9
PH
2887
2888/*************************************************
2889* Read bytes from TLS channel *
2890*************************************************/
2891
2892/*
2893Arguments:
74f1a423 2894 ct_ctx client context pointer, or NULL for the one global server context
059ec3d9
PH
2895 buff buffer of data
2896 len size of buffer
2897
2898Returns: the number of bytes read
afdb5e9c 2899 -1 after a failed read, including EOF
817d9f57
JH
2900
2901Only used by the client-side TLS.
059ec3d9
PH
2902*/
2903
2904int
74f1a423 2905tls_read(void * ct_ctx, uschar *buff, size_t len)
059ec3d9 2906{
74f1a423 2907SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
059ec3d9
PH
2908int inbytes;
2909int error;
2910
389ca47a 2911DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
c80c5570 2912 buff, (unsigned int)len);
059ec3d9 2913
389ca47a
JH
2914inbytes = SSL_read(ssl, CS buff, len);
2915error = SSL_get_error(ssl, inbytes);
059ec3d9
PH
2916
2917if (error == SSL_ERROR_ZERO_RETURN)
2918 {
2919 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2920 return -1;
2921 }
2922else if (error != SSL_ERROR_NONE)
059ec3d9 2923 return -1;
059ec3d9
PH
2924
2925return inbytes;
2926}
2927
2928
2929
2930
2931
2932/*************************************************
2933* Write bytes down TLS channel *
2934*************************************************/
2935
2936/*
2937Arguments:
74f1a423 2938 ct_ctx client context pointer, or NULL for the one global server context
059ec3d9
PH
2939 buff buffer of data
2940 len number of bytes
925ac8e4 2941 more further data expected soon
059ec3d9
PH
2942
2943Returns: the number of bytes after a successful write,
2944 -1 after a failed write
817d9f57
JH
2945
2946Used by both server-side and client-side TLS.
059ec3d9
PH
2947*/
2948
2949int
74f1a423 2950tls_write(void * ct_ctx, const uschar *buff, size_t len, BOOL more)
059ec3d9 2951{
ac35befe 2952size_t olen = len;
d7978c0f 2953int outbytes, error;
74f1a423 2954SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
acec9514 2955static gstring * corked = NULL;
a5ffa9b4 2956
ef698bf6 2957DEBUG(D_tls) debug_printf("%s(%p, %lu%s)\n", __FUNCTION__,
b93be52e 2958 buff, (unsigned long)len, more ? ", more" : "");
a5ffa9b4
JH
2959
2960/* Lacking a CORK or MSG_MORE facility (such as GnuTLS has) we copy data when
2961"more" is notified. This hack is only ok if small amounts are involved AND only
2962one stream does it, in one context (i.e. no store reset). Currently it is used
2963for the responses to the received SMTP MAIL , RCPT, DATA sequence, only. */
ac35befe
JH
2964/* + if PIPE_COMMAND, banner & ehlo-resp for smmtp-on-connect. Suspect there's
2965a store reset there, so use POOL_PERM. */
2966/* + if CHUNKING, cmds EHLO,MAIL,RCPT(s),BDAT */
a5ffa9b4 2967
ac35befe 2968if ((more || corked))
a5ffa9b4 2969 {
ee8b8090
JH
2970#ifdef EXPERIMENTAL_PIPE_CONNECT
2971 int save_pool = store_pool;
2972 store_pool = POOL_PERM;
2973#endif
2974
acec9514 2975 corked = string_catn(corked, buff, len);
ee8b8090
JH
2976
2977#ifdef EXPERIMENTAL_PIPE_CONNECT
2978 store_pool = save_pool;
2979#endif
2980
a5ffa9b4
JH
2981 if (more)
2982 return len;
acec9514
JH
2983 buff = CUS corked->s;
2984 len = corked->ptr;
2985 corked = NULL;
a5ffa9b4 2986 }
059ec3d9 2987
d7978c0f 2988for (int left = len; left > 0;)
059ec3d9 2989 {
74f1a423 2990 DEBUG(D_tls) debug_printf("SSL_write(%p, %p, %d)\n", ssl, buff, left);
059ec3d9
PH
2991 outbytes = SSL_write(ssl, CS buff, left);
2992 error = SSL_get_error(ssl, outbytes);
2993 DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
2994 switch (error)
2995 {
2996 case SSL_ERROR_SSL:
0abc5a13 2997 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
96f5fe4c
JH
2998 log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
2999 return -1;
059ec3d9
PH
3000
3001 case SSL_ERROR_NONE:
96f5fe4c
JH
3002 left -= outbytes;
3003 buff += outbytes;
3004 break;
059ec3d9
PH
3005
3006 case SSL_ERROR_ZERO_RETURN:
96f5fe4c
JH
3007 log_write(0, LOG_MAIN, "SSL channel closed on write");
3008 return -1;
059ec3d9 3009
817d9f57 3010 case SSL_ERROR_SYSCALL:
96f5fe4c
JH
3011 log_write(0, LOG_MAIN, "SSL_write: (from %s) syscall: %s",
3012 sender_fullhost ? sender_fullhost : US"<unknown>",
3013 strerror(errno));
3014 return -1;
817d9f57 3015
059ec3d9 3016 default:
96f5fe4c
JH
3017 log_write(0, LOG_MAIN, "SSL_write error %d", error);
3018 return -1;
059ec3d9
PH
3019 }
3020 }
ac35befe 3021return olen;
059ec3d9
PH
3022}
3023
3024
3025
3026/*************************************************
3027* Close down a TLS session *
3028*************************************************/
3029
3030/* This is also called from within a delivery subprocess forked from the
3031daemon, to shut down the TLS library, without actually doing a shutdown (which
3032would tamper with the SSL session in the parent process).
3033
dec766a1 3034Arguments:
74f1a423 3035 ct_ctx client TLS context pointer, or NULL for the one global server context
dec766a1
WB
3036 shutdown 1 if TLS close-alert is to be sent,
3037 2 if also response to be waited for
3038
059ec3d9 3039Returns: nothing
817d9f57
JH
3040
3041Used by both server-side and client-side TLS.
059ec3d9
PH
3042*/
3043
3044void
74f1a423 3045tls_close(void * ct_ctx, int shutdown)
059ec3d9 3046{
74f1a423
JH
3047exim_openssl_client_tls_ctx * o_ctx = ct_ctx;
3048SSL_CTX **ctxp = o_ctx ? &o_ctx->ctx : &server_ctx;
3049SSL **sslp = o_ctx ? &o_ctx->ssl : &server_ssl;
3050int *fdp = o_ctx ? &tls_out.active.sock : &tls_in.active.sock;
817d9f57
JH
3051
3052if (*fdp < 0) return; /* TLS was not active */
059ec3d9
PH
3053
3054if (shutdown)
3055 {
dec766a1
WB
3056 int rc;
3057 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
3058 shutdown > 1 ? " (with response-wait)" : "");
3059
3060 if ( (rc = SSL_shutdown(*sslp)) == 0 /* send "close notify" alert */
3061 && shutdown > 1)
3062 {
c2a1bba0 3063 ALARM(2);
dec766a1 3064 rc = SSL_shutdown(*sslp); /* wait for response */
c2a1bba0 3065 ALARM_CLR(0);
dec766a1
WB
3066 }
3067
3068 if (rc < 0) DEBUG(D_tls)
3069 {
0abc5a13 3070 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
dec766a1
WB
3071 debug_printf("SSL_shutdown: %s\n", ssl_errstring);
3072 }
3073 }
3074
37f0ce65 3075#ifndef DISABLE_OCSP
74f1a423 3076if (!o_ctx) /* server side */
dec766a1
WB
3077 {
3078 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
dec766a1 3079 server_static_cbinfo->verify_stack = NULL;
059ec3d9 3080 }
37f0ce65 3081#endif
059ec3d9 3082
dec766a1 3083SSL_CTX_free(*ctxp);
817d9f57 3084SSL_free(*sslp);
dec766a1 3085*ctxp = NULL;
817d9f57 3086*sslp = NULL;
817d9f57 3087*fdp = -1;
059ec3d9
PH
3088}
3089
36f12725
NM
3090
3091
3092
3093/*************************************************
3375e053
PP
3094* Let tls_require_ciphers be checked at startup *
3095*************************************************/
3096
3097/* The tls_require_ciphers option, if set, must be something which the
3098library can parse.
3099
3100Returns: NULL on success, or error message
3101*/
3102
3103uschar *
3104tls_validate_require_cipher(void)
3105{
3106SSL_CTX *ctx;
3107uschar *s, *expciphers, *err;
3108
3109/* this duplicates from tls_init(), we need a better "init just global
3110state, for no specific purpose" singleton function of our own */
3111
7434882d 3112#ifdef EXIM_NEED_OPENSSL_INIT
3375e053
PP
3113SSL_load_error_strings();
3114OpenSSL_add_ssl_algorithms();
7434882d 3115#endif
3375e053
PP
3116#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3117/* SHA256 is becoming ever more popular. This makes sure it gets added to the
3118list of available digests. */
3119EVP_add_digest(EVP_sha256());
3120#endif
3121
3122if (!(tls_require_ciphers && *tls_require_ciphers))
3123 return NULL;
3124
cf0c6164
JH
3125if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3126 &err))
3375e053
PP
3127 return US"failed to expand tls_require_ciphers";
3128
3129if (!(expciphers && *expciphers))
3130 return NULL;
3131
3132/* normalisation ripped from above */
3133s = expciphers;
3134while (*s != 0) { if (*s == '_') *s = '-'; s++; }
3135
3136err = NULL;
3137
7a8b9519
JH
3138#ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
3139if (!(ctx = SSL_CTX_new(TLS_server_method())))
3140#else
3141if (!(ctx = SSL_CTX_new(SSLv23_server_method())))
3142#endif
3375e053 3143 {
0abc5a13 3144 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3375e053
PP
3145 return string_sprintf("SSL_CTX_new() failed: %s", ssl_errstring);
3146 }
3147
3148DEBUG(D_tls)
3149 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3150
3151if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
3152 {
0abc5a13 3153 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
cf0c6164
JH
3154 err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed: %s",
3155 expciphers, ssl_errstring);
3375e053
PP
3156 }
3157
3158SSL_CTX_free(ctx);
3159
3160return err;
3161}
3162
3163
3164
3165
3166/*************************************************
36f12725
NM
3167* Report the library versions. *
3168*************************************************/
3169
3170/* There have historically been some issues with binary compatibility in
3171OpenSSL libraries; if Exim (like many other applications) is built against
3172one version of OpenSSL but the run-time linker picks up another version,
3173it can result in serious failures, including crashing with a SIGSEGV. So
3174report the version found by the compiler and the run-time version.
3175
f64a1e23
PP
3176Note: some OS vendors backport security fixes without changing the version
3177number/string, and the version date remains unchanged. The _build_ date
3178will change, so we can more usefully assist with version diagnosis by also
3179reporting the build date.
3180
36f12725
NM
3181Arguments: a FILE* to print the results to
3182Returns: nothing
3183*/
3184
3185void
3186tls_version_report(FILE *f)
3187{
754a0503 3188fprintf(f, "Library version: OpenSSL: Compile: %s\n"
f64a1e23
PP
3189 " Runtime: %s\n"
3190 " : %s\n",
754a0503 3191 OPENSSL_VERSION_TEXT,
f64a1e23
PP
3192 SSLeay_version(SSLEAY_VERSION),
3193 SSLeay_version(SSLEAY_BUILT_ON));
3194/* third line is 38 characters for the %s and the line is 73 chars long;
3195the OpenSSL output includes a "built on: " prefix already. */
36f12725
NM
3196}
3197
9e3331ea
TK
3198
3199
3200
3201/*************************************************
17c76198 3202* Random number generation *
9e3331ea
TK
3203*************************************************/
3204
3205/* Pseudo-random number generation. The result is not expected to be
3206cryptographically strong but not so weak that someone will shoot themselves
3207in the foot using it as a nonce in input in some email header scheme or
3208whatever weirdness they'll twist this into. The result should handle fork()
3209and avoid repeating sequences. OpenSSL handles that for us.
3210
3211Arguments:
3212 max range maximum
3213Returns a random number in range [0, max-1]
3214*/
3215
3216int
17c76198 3217vaguely_random_number(int max)
9e3331ea
TK
3218{
3219unsigned int r;
3220int i, needed_len;
de6135a0
PP
3221static pid_t pidlast = 0;
3222pid_t pidnow;
9e3331ea
TK
3223uschar smallbuf[sizeof(r)];
3224
3225if (max <= 1)
3226 return 0;
3227
de6135a0
PP
3228pidnow = getpid();
3229if (pidnow != pidlast)
3230 {
3231 /* Although OpenSSL documents that "OpenSSL makes sure that the PRNG state
3232 is unique for each thread", this doesn't apparently apply across processes,
3233 so our own warning from vaguely_random_number_fallback() applies here too.
3234 Fix per PostgreSQL. */
3235 if (pidlast != 0)
3236 RAND_cleanup();
3237 pidlast = pidnow;
3238 }
3239
9e3331ea
TK
3240/* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
3241if (!RAND_status())
3242 {
3243 randstuff r;
3244 gettimeofday(&r.tv, NULL);
3245 r.p = getpid();
3246
5903c6ff 3247 RAND_seed(US (&r), sizeof(r));
9e3331ea
TK
3248 }
3249/* We're after pseudo-random, not random; if we still don't have enough data
3250in the internal PRNG then our options are limited. We could sleep and hope
3251for entropy to come along (prayer technique) but if the system is so depleted
3252in the first place then something is likely to just keep taking it. Instead,
3253we'll just take whatever little bit of pseudo-random we can still manage to
3254get. */
3255
3256needed_len = sizeof(r);
3257/* Don't take 8 times more entropy than needed if int is 8 octets and we were
3258asked for a number less than 10. */
3259for (r = max, i = 0; r; ++i)
3260 r >>= 1;
3261i = (i + 7) / 8;
3262if (i < needed_len)
3263 needed_len = i;
3264
c8dfb21d 3265#ifdef EXIM_HAVE_RAND_PSEUDO
9e3331ea 3266/* We do not care if crypto-strong */
17c76198 3267i = RAND_pseudo_bytes(smallbuf, needed_len);
c8dfb21d
JH
3268#else
3269i = RAND_bytes(smallbuf, needed_len);
3270#endif
3271
17c76198
PP
3272if (i < 0)
3273 {
3274 DEBUG(D_all)
3275 debug_printf("OpenSSL RAN