1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
8 /* Portions Copyright (c) The OpenSSL Project 1999 */
10 /* This module provides the TLS (aka SSL) support for Exim using the OpenSSL
11 library. It is #included into the tls.c file when that library is used. The
12 code herein is based on a patch that was originally contributed by Steve
13 Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
15 No cryptographic code is included in Exim. All this module does is to call
16 functions from the OpenSSL library. */
21 #include <openssl/lhash.h>
22 #include <openssl/ssl.h>
23 #include <openssl/err.h>
24 #include <openssl/rand.h>
25 #ifndef OPENSSL_NO_ECDH
26 # include <openssl/ec.h>
29 # include <openssl/ocsp.h>
37 # define EXIM_OCSP_SKEW_SECONDS (300L)
38 # define EXIM_OCSP_MAX_AGE (-1L)
41 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
42 # define EXIM_HAVE_OPENSSL_TLSEXT
44 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
45 # define EXIM_HAVE_RSA_GENKEY_EX
47 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
48 # define EXIM_HAVE_OCSP_RESP_COUNT
50 # define EXIM_HAVE_EPHEM_RSA_KEX
51 # define EXIM_HAVE_RAND_PSEUDO
53 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
54 # define EXIM_HAVE_SHA256
57 /* X509_check_host provides sane certificate hostname checking, but was added
58 to OpenSSL late, after other projects forked off the code-base. So in
59 addition to guarding against the base version number, beware that LibreSSL
60 does not (at this time) support this function.
62 If LibreSSL gains a different API, perhaps via libtls, then we'll probably
63 opt to disentangle and ask a LibreSSL user to provide glue for a third
64 crypto provider for libtls instead of continuing to tie the OpenSSL glue
65 into even twistier knots. If LibreSSL gains the same API, we can just
66 change this guard and punt the issue for a while longer. */
68 #ifndef LIBRESSL_VERSION_NUMBER
69 # if OPENSSL_VERSION_NUMBER >= 0x010100000L
70 # define EXIM_HAVE_OPENSSL_CHECKHOST
71 # define EXIM_HAVE_OPENSSL_DH_BITS
72 # define EXIM_HAVE_OPENSSL_TLS_METHOD
73 # define EXIM_HAVE_OPENSSL_KEYLOG
74 # define EXIM_HAVE_OPENSSL_CIPHER_GET_ID
76 # define EXIM_NEED_OPENSSL_INIT
78 # if OPENSSL_VERSION_NUMBER >= 0x010000000L \
79 && (OPENSSL_VERSION_NUMBER & 0x0000ff000L) >= 0x000002000L
80 # define EXIM_HAVE_OPENSSL_CHECKHOST
84 #if !defined(LIBRESSL_VERSION_NUMBER) \
85 || LIBRESSL_VERSION_NUMBER >= 0x20010000L
86 # if !defined(OPENSSL_NO_ECDH)
87 # if OPENSSL_VERSION_NUMBER >= 0x0090800fL
88 # define EXIM_HAVE_ECDH
90 # if OPENSSL_VERSION_NUMBER >= 0x10002000L
91 # define EXIM_HAVE_OPENSSL_EC_NIST2NID
96 #ifndef LIBRESSL_VERSION_NUMBER
97 # if OPENSSL_VERSION_NUMBER >= 0x010101000L
98 # define OPENSSL_HAVE_KEYLOG_CB
99 # define OPENSSL_HAVE_NUM_TICKETS
100 # define EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
104 #if !defined(EXIM_HAVE_OPENSSL_TLSEXT) && !defined(DISABLE_OCSP)
105 # warning "OpenSSL library version too old; define DISABLE_OCSP in Makefile"
106 # define DISABLE_OCSP
109 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
110 # include <openssl/x509v3.h>
113 #ifndef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
114 # ifndef EXIM_HAVE_OPENSSL_CIPHER_GET_ID
115 # define SSL_CIPHER_get_id(c) (c->id)
117 # include "tls-cipher-stdname.c"
120 /*************************************************
121 * OpenSSL option parse *
122 *************************************************/
124 typedef struct exim_openssl_option {
127 } exim_openssl_option;
128 /* We could use a macro to expand, but we need the ifdef and not all the
129 options document which version they were introduced in. Policylet: include
130 all options unless explicitly for DTLS, let the administrator choose which
133 This list is current as of:
135 Plus SSL_OP_SAFARI_ECDHE_ECDSA_BUG from 2013-June patch/discussion on openssl-dev
136 Plus SSL_OP_NO_TLSv1_3 for 1.1.2-dev
138 static exim_openssl_option exim_openssl_options[] = {
139 /* KEEP SORTED ALPHABETICALLY! */
141 { US"all", SSL_OP_ALL },
143 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
144 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
146 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
147 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
149 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
150 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
152 #ifdef SSL_OP_EPHEMERAL_RSA
153 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
155 #ifdef SSL_OP_LEGACY_SERVER_CONNECT
156 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
158 #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
159 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
161 #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
162 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
164 #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
165 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
167 #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
168 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
170 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
171 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
173 #ifdef SSL_OP_NO_COMPRESSION
174 { US"no_compression", SSL_OP_NO_COMPRESSION },
176 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
177 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
179 #ifdef SSL_OP_NO_SSLv2
180 { US"no_sslv2", SSL_OP_NO_SSLv2 },
182 #ifdef SSL_OP_NO_SSLv3
183 { US"no_sslv3", SSL_OP_NO_SSLv3 },
185 #ifdef SSL_OP_NO_TICKET
186 { US"no_ticket", SSL_OP_NO_TICKET },
188 #ifdef SSL_OP_NO_TLSv1
189 { US"no_tlsv1", SSL_OP_NO_TLSv1 },
191 #ifdef SSL_OP_NO_TLSv1_1
192 #if SSL_OP_NO_TLSv1_1 == 0x00000400L
193 /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
194 #warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
196 { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
199 #ifdef SSL_OP_NO_TLSv1_2
200 { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
202 #ifdef SSL_OP_NO_TLSv1_3
203 { US"no_tlsv1_3", SSL_OP_NO_TLSv1_3 },
205 #ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
206 { US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
208 #ifdef SSL_OP_SINGLE_DH_USE
209 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
211 #ifdef SSL_OP_SINGLE_ECDH_USE
212 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
214 #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
215 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
217 #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
218 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
220 #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
221 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
223 #ifdef SSL_OP_TLS_D5_BUG
224 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
226 #ifdef SSL_OP_TLS_ROLLBACK_BUG
227 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
232 static int exim_openssl_options_size = nelem(exim_openssl_options);
241 for (struct exim_openssl_option * o = exim_openssl_options;
242 o < exim_openssl_options + nelem(exim_openssl_options); o++)
244 /* Trailing X is workaround for problem with _OPT_OPENSSL_NO_TLSV1
245 being a ".ifdef _OPT_OPENSSL_NO_TLSV1_3" match */
247 spf(buf, sizeof(buf), US"_OPT_OPENSSL_%T_X", o->name);
248 builtin_macro_create(buf);
253 /******************************************************************************/
255 /* Structure for collecting random data for seeding. */
257 typedef struct randstuff {
262 /* Local static variables */
264 static BOOL client_verify_callback_called = FALSE;
265 static BOOL server_verify_callback_called = FALSE;
266 static const uschar *sid_ctx = US"exim";
268 /* We have three different contexts to care about.
270 Simple case: client, `client_ctx`
271 As a client, we can be doing a callout or cut-through delivery while receiving
272 a message. So we have a client context, which should have options initialised
273 from the SMTP Transport. We may also concurrently want to make TLS connections
274 to utility daemons, so client-contexts are allocated and passed around in call
275 args rather than using a gobal.
278 There are two cases: with and without ServerNameIndication from the client.
279 Given TLS SNI, we can be using different keys, certs and various other
280 configuration settings, because they're re-expanded with $tls_sni set. This
281 allows vhosting with TLS. This SNI is sent in the handshake.
282 A client might not send SNI, so we need a fallback, and an initial setup too.
283 So as a server, we start out using `server_ctx`.
284 If SNI is sent by the client, then we as server, mid-negotiation, try to clone
285 `server_sni` from `server_ctx` and then initialise settings by re-expanding
292 } exim_openssl_client_tls_ctx;
294 static SSL_CTX *server_ctx = NULL;
295 static SSL *server_ssl = NULL;
297 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
298 static SSL_CTX *server_sni = NULL;
301 static char ssl_errstring[256];
303 static int ssl_session_timeout = 200;
304 static BOOL client_verify_optional = FALSE;
305 static BOOL server_verify_optional = FALSE;
307 static BOOL reexpand_tls_files_for_sni = FALSE;
310 typedef struct tls_ext_ctx_cb {
315 STACK_OF(X509) *verify_stack; /* chain for verifying the proof */
319 uschar *file_expanded;
320 OCSP_RESPONSE *response;
323 X509_STORE *verify_store; /* non-null if status requested */
324 BOOL verify_required;
329 /* these are cached from first expand */
330 uschar *server_cipher_list;
331 /* only passed down to tls_error: */
333 const uschar * verify_cert_hostnames;
334 #ifndef DISABLE_EVENT
335 uschar * event_action;
339 /* should figure out a cleanup of API to handle state preserved per
340 implementation, for various reasons, which can be void * in the APIs.
341 For now, we hack around it. */
342 tls_ext_ctx_cb *client_static_cbinfo = NULL;
343 tls_ext_ctx_cb *server_static_cbinfo = NULL;
346 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
347 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr );
350 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
351 static int tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg);
354 static int tls_server_stapling_cb(SSL *s, void *arg);
358 /*************************************************
360 *************************************************/
362 /* Called from lots of places when errors occur before actually starting to do
363 the TLS handshake, that is, while the session is still in clear. Always returns
364 DEFER for a server and FAIL for a client so that most calls can use "return
365 tls_error(...)" to do this processing and then give an appropriate return. A
366 single function is used for both server and client, because it is called from
367 some shared functions.
370 prefix text to include in the logged error
371 host NULL if setting up a server;
372 the connected host if setting up a client
373 msg error message or NULL if we should ask OpenSSL
374 errstr pointer to output error message
376 Returns: OK/DEFER/FAIL
380 tls_error(uschar * prefix, const host_item * host, uschar * msg, uschar ** errstr)
384 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
385 msg = US ssl_errstring;
388 msg = string_sprintf("(%s): %s", prefix, msg);
389 DEBUG(D_tls) debug_printf("TLS error '%s'\n", msg);
390 if (errstr) *errstr = msg;
391 return host ? FAIL : DEFER;
396 /*************************************************
397 * Callback to generate RSA key *
398 *************************************************/
402 s SSL connection (not used)
406 Returns: pointer to generated key
410 rsa_callback(SSL *s, int export, int keylength)
413 #ifdef EXIM_HAVE_RSA_GENKEY_EX
414 BIGNUM *bn = BN_new();
417 export = export; /* Shut picky compilers up */
418 DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
420 #ifdef EXIM_HAVE_RSA_GENKEY_EX
421 if ( !BN_set_word(bn, (unsigned long)RSA_F4)
422 || !(rsa_key = RSA_new())
423 || !RSA_generate_key_ex(rsa_key, keylength, bn, NULL)
426 if (!(rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL)))
430 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
431 log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
443 x509_store_dump_cert_s_names(X509_STORE * store)
445 STACK_OF(X509_OBJECT) * roots= store->objs;
446 static uschar name[256];
448 for (int i= 0; i < sk_X509_OBJECT_num(roots); i++)
450 X509_OBJECT * tmp_obj= sk_X509_OBJECT_value(roots, i);
451 if(tmp_obj->type == X509_LU_X509)
453 X509_NAME * sn = X509_get_subject_name(tmp_obj->data.x509);
454 if (X509_NAME_oneline(sn, CS name, sizeof(name)))
456 name[sizeof(name)-1] = '\0';
457 debug_printf(" %s\n", name);
466 #ifndef DISABLE_EVENT
468 verify_event(tls_support * tlsp, X509 * cert, int depth, const uschar * dn,
469 BOOL *calledp, const BOOL *optionalp, const uschar * what)
475 ev = tlsp == &tls_out ? client_static_cbinfo->event_action : event_action;
478 DEBUG(D_tls) debug_printf("verify_event: %s %d\n", what, depth);
479 old_cert = tlsp->peercert;
480 tlsp->peercert = X509_dup(cert);
481 /* NB we do not bother setting peerdn */
482 if ((yield = event_raise(ev, US"tls:cert", string_sprintf("%d", depth))))
484 log_write(0, LOG_MAIN, "[%s] %s verify denied by event-action: "
485 "depth=%d cert=%s: %s",
486 tlsp == &tls_out ? deliver_host_address : sender_host_address,
487 what, depth, dn, yield);
491 if (old_cert) tlsp->peercert = old_cert; /* restore 1st failing cert */
492 return 1; /* reject (leaving peercert set) */
494 DEBUG(D_tls) debug_printf("Event-action verify failure overridden "
495 "(host in tls_try_verify_hosts)\n");
497 X509_free(tlsp->peercert);
498 tlsp->peercert = old_cert;
504 /*************************************************
505 * Callback for verification *
506 *************************************************/
508 /* The SSL library does certificate verification if set up to do so. This
509 callback has the current yes/no state is in "state". If verification succeeded,
510 we set the certificate-verified flag. If verification failed, what happens
511 depends on whether the client is required to present a verifiable certificate
514 If verification is optional, we change the state to yes, but still log the
515 verification error. For some reason (it really would help to have proper
516 documentation of OpenSSL), this callback function then gets called again, this
517 time with state = 1. We must take care not to set the private verified flag on
518 the second time through.
520 Note: this function is not called if the client fails to present a certificate
521 when asked. We get here only if a certificate has been received. Handling of
522 optional verification for this case is done when requesting SSL to verify, by
523 setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
525 May be called multiple times for different issues with a certificate, even
526 for a given "depth" in the certificate chain.
529 preverify_ok current yes/no state as 1/0
530 x509ctx certificate information.
531 tlsp per-direction (client vs. server) support data
532 calledp has-been-called flag
533 optionalp verification-is-optional flag
535 Returns: 0 if verification should fail, otherwise 1
539 verify_callback(int preverify_ok, X509_STORE_CTX * x509ctx,
540 tls_support * tlsp, BOOL * calledp, BOOL * optionalp)
542 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
543 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
546 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
548 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
549 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
550 tlsp == &tls_out ? deliver_host_address : sender_host_address);
553 dn[sizeof(dn)-1] = '\0';
555 if (preverify_ok == 0)
557 uschar * extra = verify_mode ? string_sprintf(" (during %c-verify for [%s])",
558 *verify_mode, sender_host_address)
560 log_write(0, LOG_MAIN, "[%s] SSL verify error%s: depth=%d error=%s cert=%s",
561 tlsp == &tls_out ? deliver_host_address : sender_host_address,
563 X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509ctx)), dn);
568 tlsp->peercert = X509_dup(cert); /* record failing cert */
569 return 0; /* reject */
571 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
572 "tls_try_verify_hosts)\n");
577 DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d SN=%s\n", depth, dn);
579 if (tlsp == &tls_out && client_static_cbinfo->u_ocsp.client.verify_store)
580 { /* client, wanting stapling */
581 /* Add the server cert's signing chain as the one
582 for the verification of the OCSP stapled information. */
584 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
587 sk_X509_push(client_static_cbinfo->verify_stack, cert);
590 #ifndef DISABLE_EVENT
591 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
592 return 0; /* reject, with peercert set */
597 const uschar * verify_cert_hostnames;
599 if ( tlsp == &tls_out
600 && ((verify_cert_hostnames = client_static_cbinfo->verify_cert_hostnames)))
601 /* client, wanting hostname check */
604 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
605 # ifndef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
606 # define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0
608 # ifndef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
609 # define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0
612 const uschar * list = verify_cert_hostnames;
615 while ((name = string_nextinlist(&list, &sep, NULL, 0)))
616 if ((rc = X509_check_host(cert, CCS name, 0,
617 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
618 | X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS,
623 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
624 tlsp == &tls_out ? deliver_host_address : sender_host_address);
631 if (!tls_is_name_for_cert(verify_cert_hostnames, cert))
634 uschar * extra = verify_mode
635 ? string_sprintf(" (during %c-verify for [%s])",
636 *verify_mode, sender_host_address)
638 log_write(0, LOG_MAIN,
639 "[%s] SSL verify error%s: certificate name mismatch: DN=\"%s\" H=\"%s\"",
640 tlsp == &tls_out ? deliver_host_address : sender_host_address,
641 extra, dn, verify_cert_hostnames);
646 tlsp->peercert = X509_dup(cert); /* record failing cert */
647 return 0; /* reject */
649 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
650 "tls_try_verify_hosts)\n");
654 #ifndef DISABLE_EVENT
655 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
656 return 0; /* reject, with peercert set */
659 DEBUG(D_tls) debug_printf("SSL%s verify ok: depth=0 SN=%s\n",
660 *calledp ? "" : " authenticated", dn);
661 if (!*calledp) tlsp->certificate_verified = TRUE;
665 return 1; /* accept, at least for this level */
669 verify_callback_client(int preverify_ok, X509_STORE_CTX *x509ctx)
671 return verify_callback(preverify_ok, x509ctx, &tls_out,
672 &client_verify_callback_called, &client_verify_optional);
676 verify_callback_server(int preverify_ok, X509_STORE_CTX *x509ctx)
678 return verify_callback(preverify_ok, x509ctx, &tls_in,
679 &server_verify_callback_called, &server_verify_optional);
685 /* This gets called *by* the dane library verify callback, which interposes
689 verify_callback_client_dane(int preverify_ok, X509_STORE_CTX * x509ctx)
691 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
693 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
694 #ifndef DISABLE_EVENT
695 BOOL dummy_called, optional = FALSE;
698 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
700 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
701 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
702 deliver_host_address);
705 dn[sizeof(dn)-1] = '\0';
707 DEBUG(D_tls) debug_printf("verify_callback_client_dane: %s depth %d %s\n",
708 preverify_ok ? "ok":"BAD", depth, dn);
710 #ifndef DISABLE_EVENT
711 if (verify_event(&tls_out, cert, depth, dn,
712 &dummy_called, &optional, US"DANE"))
713 return 0; /* reject, with peercert set */
716 if (preverify_ok == 1)
718 tls_out.dane_verified = tls_out.certificate_verified = TRUE;
720 if (client_static_cbinfo->u_ocsp.client.verify_store)
721 { /* client, wanting stapling */
722 /* Add the server cert's signing chain as the one
723 for the verification of the OCSP stapled information. */
725 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
728 sk_X509_push(client_static_cbinfo->verify_stack, cert);
734 int err = X509_STORE_CTX_get_error(x509ctx);
736 debug_printf(" - err %d '%s'\n", err, X509_verify_cert_error_string(err));
737 if (err == X509_V_ERR_APPLICATION_VERIFICATION)
743 #endif /*SUPPORT_DANE*/
746 /*************************************************
747 * Information callback *
748 *************************************************/
750 /* The SSL library functions call this from time to time to indicate what they
751 are doing. We copy the string to the debugging output when TLS debugging has
763 info_callback(SSL *s, int where, int ret)
769 if (where & SSL_ST_CONNECT)
770 str = US"SSL_connect";
771 else if (where & SSL_ST_ACCEPT)
772 str = US"SSL_accept";
774 str = US"SSL info (undefined)";
776 if (where & SSL_CB_LOOP)
777 debug_printf("%s: %s\n", str, SSL_state_string_long(s));
778 else if (where & SSL_CB_ALERT)
779 debug_printf("SSL3 alert %s:%s:%s\n",
780 str = where & SSL_CB_READ ? US"read" : US"write",
781 SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
782 else if (where & SSL_CB_EXIT)
784 debug_printf("%s: failed in %s\n", str, SSL_state_string_long(s));
786 debug_printf("%s: error in %s\n", str, SSL_state_string_long(s));
787 else if (where & SSL_CB_HANDSHAKE_START)
788 debug_printf("%s: hshake start: %s\n", str, SSL_state_string_long(s));
789 else if (where & SSL_CB_HANDSHAKE_DONE)
790 debug_printf("%s: hshake done: %s\n", str, SSL_state_string_long(s));
794 #ifdef OPENSSL_HAVE_KEYLOG_CB
796 keylog_callback(const SSL *ssl, const char *line)
798 DEBUG(D_tls) debug_printf("%.200s\n", line);
804 /*************************************************
805 * Initialize for DH *
806 *************************************************/
808 /* If dhparam is set, expand it, and load up the parameters for DH encryption.
811 sctx The current SSL CTX (inbound or outbound)
812 dhparam DH parameter file or fixed parameter identity string
813 host connected host, if client; NULL if server
814 errstr error string pointer
816 Returns: TRUE if OK (nothing to set up, or setup worked)
820 init_dh(SSL_CTX *sctx, uschar *dhparam, const host_item *host, uschar ** errstr)
828 if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded, errstr))
831 if (!dhexpanded || !*dhexpanded)
832 bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
833 else if (dhexpanded[0] == '/')
835 if (!(bio = BIO_new_file(CS dhexpanded, "r")))
837 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
838 host, US strerror(errno), errstr);
844 if (Ustrcmp(dhexpanded, "none") == 0)
846 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
850 if (!(pem = std_dh_prime_named(dhexpanded)))
852 tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
853 host, US strerror(errno), errstr);
856 bio = BIO_new_mem_buf(CS pem, -1);
859 if (!(dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)))
862 tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
867 /* note: our default limit of 2236 is not a multiple of 8; the limit comes from
868 * an NSS limit, and the GnuTLS APIs handle bit-sizes fine, so we went with
869 * 2236. But older OpenSSL can only report in bytes (octets), not bits.
870 * If someone wants to dance at the edge, then they can raise the limit or use
871 * current libraries. */
872 #ifdef EXIM_HAVE_OPENSSL_DH_BITS
873 /* Added in commit 26c79d5641d; `git describe --contains` says OpenSSL_1_1_0-pre1~1022
874 * This predates OpenSSL_1_1_0 (before a, b, ...) so is in all 1.1.0 */
875 dh_bitsize = DH_bits(dh);
877 dh_bitsize = 8 * DH_size(dh);
880 /* Even if it is larger, we silently return success rather than cause things
881 * to fail out, so that a too-large DH will not knock out all TLS; it's a
882 * debatable choice. */
883 if (dh_bitsize > tls_dh_max_bits)
886 debug_printf("dhparams file %d bits, is > tls_dh_max_bits limit of %d\n",
887 dh_bitsize, tls_dh_max_bits);
891 SSL_CTX_set_tmp_dh(sctx, dh);
893 debug_printf("Diffie-Hellman initialized from %s with %d-bit prime\n",
894 dhexpanded ? dhexpanded : US"default", dh_bitsize);
906 /*************************************************
907 * Initialize for ECDH *
908 *************************************************/
910 /* Load parameters for ECDH encryption.
912 For now, we stick to NIST P-256 because: it's simple and easy to configure;
913 it avoids any patent issues that might bite redistributors; despite events in
914 the news and concerns over curve choices, we're not cryptographers, we're not
915 pretending to be, and this is "good enough" to be better than no support,
916 protecting against most adversaries. Given another year or two, there might
917 be sufficient clarity about a "right" way forward to let us make an informed
918 decision, instead of a knee-jerk reaction.
920 Longer-term, we should look at supporting both various named curves and
921 external files generated with "openssl ecparam", much as we do for init_dh().
922 We should also support "none" as a value, to explicitly avoid initialisation.
927 sctx The current SSL CTX (inbound or outbound)
928 host connected host, if client; NULL if server
929 errstr error string pointer
931 Returns: TRUE if OK (nothing to set up, or setup worked)
935 init_ecdh(SSL_CTX * sctx, host_item * host, uschar ** errstr)
937 #ifdef OPENSSL_NO_ECDH
946 if (host) /* No ECDH setup for clients, only for servers */
949 # ifndef EXIM_HAVE_ECDH
951 debug_printf("No OpenSSL API to define ECDH parameters, skipping\n");
955 if (!expand_check(tls_eccurve, US"tls_eccurve", &exp_curve, errstr))
957 if (!exp_curve || !*exp_curve)
960 /* "auto" needs to be handled carefully.
961 * OpenSSL < 1.0.2: we do not select anything, but fallback to prime256v1
962 * OpenSSL < 1.1.0: we have to call SSL_CTX_set_ecdh_auto
963 * (openssl/ssl.h defines SSL_CTRL_SET_ECDH_AUTO)
964 * OpenSSL >= 1.1.0: we do not set anything, the libray does autoselection
965 * https://github.com/openssl/openssl/commit/fe6ef2472db933f01b59cad82aa925736935984b
967 if (Ustrcmp(exp_curve, "auto") == 0)
969 #if OPENSSL_VERSION_NUMBER < 0x10002000L
970 DEBUG(D_tls) debug_printf(
971 "ECDH OpenSSL < 1.0.2: temp key parameter settings: overriding \"auto\" with \"prime256v1\"\n");
972 exp_curve = US"prime256v1";
974 # if defined SSL_CTRL_SET_ECDH_AUTO
975 DEBUG(D_tls) debug_printf(
976 "ECDH OpenSSL 1.0.2+ temp key parameter settings: autoselection\n");
977 SSL_CTX_set_ecdh_auto(sctx, 1);
980 DEBUG(D_tls) debug_printf(
981 "ECDH OpenSSL 1.1.0+ temp key parameter settings: default selection\n");
987 DEBUG(D_tls) debug_printf("ECDH: curve '%s'\n", exp_curve);
988 if ( (nid = OBJ_sn2nid (CCS exp_curve)) == NID_undef
989 # ifdef EXIM_HAVE_OPENSSL_EC_NIST2NID
990 && (nid = EC_curve_nist2nid(CCS exp_curve)) == NID_undef
994 tls_error(string_sprintf("Unknown curve name tls_eccurve '%s'", exp_curve),
999 if (!(ecdh = EC_KEY_new_by_curve_name(nid)))
1001 tls_error(US"Unable to create ec curve", host, NULL, errstr);
1005 /* The "tmp" in the name here refers to setting a temporary key
1006 not to the stability of the interface. */
1008 if ((rv = SSL_CTX_set_tmp_ecdh(sctx, ecdh) == 0))
1009 tls_error(string_sprintf("Error enabling '%s' curve", exp_curve), host, NULL, errstr);
1011 DEBUG(D_tls) debug_printf("ECDH: enabled '%s' curve\n", exp_curve);
1016 # endif /*EXIM_HAVE_ECDH*/
1017 #endif /*OPENSSL_NO_ECDH*/
1023 #ifndef DISABLE_OCSP
1024 /*************************************************
1025 * Load OCSP information into state *
1026 *************************************************/
1027 /* Called to load the server OCSP response from the given file into memory, once
1028 caller has determined this is needed. Checks validity. Debugs a message
1031 ASSUMES: single response, for single cert.
1034 sctx the SSL_CTX* to update
1035 cbinfo various parts of session state
1036 expanded the filename putatively holding an OCSP response
1041 ocsp_load_response(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo, const uschar *expanded)
1044 OCSP_RESPONSE * resp;
1045 OCSP_BASICRESP * basic_response;
1046 OCSP_SINGLERESP * single_response;
1047 ASN1_GENERALIZEDTIME * rev, * thisupd, * nextupd;
1048 STACK_OF(X509) * sk;
1049 unsigned long verify_flags;
1050 int status, reason, i;
1052 cbinfo->u_ocsp.server.file_expanded = string_copy(expanded);
1053 if (cbinfo->u_ocsp.server.response)
1055 OCSP_RESPONSE_free(cbinfo->u_ocsp.server.response);
1056 cbinfo->u_ocsp.server.response = NULL;
1059 if (!(bio = BIO_new_file(CS cbinfo->u_ocsp.server.file_expanded, "rb")))
1061 DEBUG(D_tls) debug_printf("Failed to open OCSP response file \"%s\"\n",
1062 cbinfo->u_ocsp.server.file_expanded);
1066 resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
1070 DEBUG(D_tls) debug_printf("Error reading OCSP response.\n");
1074 if ((status = OCSP_response_status(resp)) != OCSP_RESPONSE_STATUS_SUCCESSFUL)
1076 DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n",
1077 OCSP_response_status_str(status), status);
1081 if (!(basic_response = OCSP_response_get1_basic(resp)))
1084 debug_printf("OCSP response parse error: unable to extract basic response.\n");
1088 sk = cbinfo->verify_stack;
1089 verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */
1091 /* May need to expose ability to adjust those flags?
1092 OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
1093 OCSP_TRUSTOTHER OCSP_NOINTERN */
1095 /* This does a full verify on the OCSP proof before we load it for serving
1096 up; possibly overkill - just date-checks might be nice enough.
1098 OCSP_basic_verify takes a "store" arg, but does not
1099 use it for the chain verification, which is all we do
1100 when OCSP_NOVERIFY is set. The content from the wire
1101 "basic_response" and a cert-stack "sk" are all that is used.
1103 We have a stack, loaded in setup_certs() if tls_verify_certificates
1104 was a file (not a directory, or "system"). It is unfortunate we
1105 cannot used the connection context store, as that would neatly
1106 handle the "system" case too, but there seems to be no library
1107 function for getting a stack from a store.
1108 [ In OpenSSL 1.1 - ? X509_STORE_CTX_get0_chain(ctx) ? ]
1109 We do not free the stack since it could be needed a second time for
1112 Separately we might try to replace using OCSP_basic_verify() - which seems to not
1113 be a public interface into the OpenSSL library (there's no manual entry) -
1114 But what with? We also use OCSP_basic_verify in the client stapling callback.
1115 And there we NEED it; we must verify that status... unless the
1116 library does it for us anyway? */
1118 if ((i = OCSP_basic_verify(basic_response, sk, NULL, verify_flags)) < 0)
1122 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1123 debug_printf("OCSP response verify failure: %s\n", US ssl_errstring);
1128 /* Here's the simplifying assumption: there's only one response, for the
1129 one certificate we use, and nothing for anything else in a chain. If this
1130 proves false, we need to extract a cert id from our issued cert
1131 (tls_certificate) and use that for OCSP_resp_find_status() (which finds the
1132 right cert in the stack and then calls OCSP_single_get0_status()).
1134 I'm hoping to avoid reworking a bunch more of how we handle state here. */
1136 if (!(single_response = OCSP_resp_get0(basic_response, 0)))
1139 debug_printf("Unable to get first response from OCSP basic response.\n");
1143 status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
1144 if (status != V_OCSP_CERTSTATUS_GOOD)
1146 DEBUG(D_tls) debug_printf("OCSP response bad cert status: %s (%d) %s (%d)\n",
1147 OCSP_cert_status_str(status), status,
1148 OCSP_crl_reason_str(reason), reason);
1152 if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1154 DEBUG(D_tls) debug_printf("OCSP status invalid times.\n");
1159 cbinfo->u_ocsp.server.response = resp; /*XXX stack?*/
1163 if (f.running_in_test_harness)
1165 extern char ** environ;
1166 if (environ) for (uschar ** p = USS environ; *p; p++)
1167 if (Ustrncmp(*p, "EXIM_TESTHARNESS_DISABLE_OCSPVALIDITYCHECK", 42) == 0)
1169 DEBUG(D_tls) debug_printf("Supplying known bad OCSP response\n");
1170 goto supply_response;
1175 #endif /*!DISABLE_OCSP*/
1180 /* Create and install a selfsigned certificate, for use in server mode */
1183 tls_install_selfsign(SSL_CTX * sctx, uschar ** errstr)
1191 where = US"allocating pkey";
1192 if (!(pkey = EVP_PKEY_new()))
1195 where = US"allocating cert";
1196 if (!(x509 = X509_new()))
1199 where = US"generating pkey";
1200 if (!(rsa = rsa_callback(NULL, 0, 2048)))
1203 where = US"assigning pkey";
1204 if (!EVP_PKEY_assign_RSA(pkey, rsa))
1207 X509_set_version(x509, 2); /* N+1 - version 3 */
1208 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
1209 X509_gmtime_adj(X509_get_notBefore(x509), 0);
1210 X509_gmtime_adj(X509_get_notAfter(x509), (long)60 * 60); /* 1 hour */
1211 X509_set_pubkey(x509, pkey);
1213 name = X509_get_subject_name(x509);
1214 X509_NAME_add_entry_by_txt(name, "C",
1215 MBSTRING_ASC, CUS "UK", -1, -1, 0);
1216 X509_NAME_add_entry_by_txt(name, "O",
1217 MBSTRING_ASC, CUS "Exim Developers", -1, -1, 0);
1218 X509_NAME_add_entry_by_txt(name, "CN",
1219 MBSTRING_ASC, CUS smtp_active_hostname, -1, -1, 0);
1220 X509_set_issuer_name(x509, name);
1222 where = US"signing cert";
1223 if (!X509_sign(x509, pkey, EVP_md5()))
1226 where = US"installing selfsign cert";
1227 if (!SSL_CTX_use_certificate(sctx, x509))
1230 where = US"installing selfsign key";
1231 if (!SSL_CTX_use_PrivateKey(sctx, pkey))
1237 (void) tls_error(where, NULL, NULL, errstr);
1238 if (x509) X509_free(x509);
1239 if (pkey) EVP_PKEY_free(pkey);
1247 tls_add_certfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1250 DEBUG(D_tls) debug_printf("tls_certificate file %s\n", file);
1251 if (!SSL_CTX_use_certificate_chain_file(sctx, CS file))
1252 return tls_error(string_sprintf(
1253 "SSL_CTX_use_certificate_chain_file file=%s", file),
1254 cbinfo->host, NULL, errstr);
1259 tls_add_pkeyfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1262 DEBUG(D_tls) debug_printf("tls_privatekey file %s\n", file);
1263 if (!SSL_CTX_use_PrivateKey_file(sctx, CS file, SSL_FILETYPE_PEM))
1264 return tls_error(string_sprintf(
1265 "SSL_CTX_use_PrivateKey_file file=%s", file), cbinfo->host, NULL, errstr);
1270 /*************************************************
1271 * Expand key and cert file specs *
1272 *************************************************/
1274 /* Called once during tls_init and possibly again during TLS setup, for a
1275 new context, if Server Name Indication was used and tls_sni was seen in
1276 the certificate string.
1279 sctx the SSL_CTX* to update
1280 cbinfo various parts of session state
1281 errstr error string pointer
1283 Returns: OK/DEFER/FAIL
1287 tls_expand_session_files(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo,
1292 if (!cbinfo->certificate)
1294 if (!cbinfo->is_server) /* client */
1297 if (tls_install_selfsign(sctx, errstr) != OK)
1304 if (Ustrstr(cbinfo->certificate, US"tls_sni") ||
1305 Ustrstr(cbinfo->certificate, US"tls_in_sni") ||
1306 Ustrstr(cbinfo->certificate, US"tls_out_sni")
1308 reexpand_tls_files_for_sni = TRUE;
1310 if (!expand_check(cbinfo->certificate, US"tls_certificate", &expanded, errstr))
1314 if (cbinfo->is_server)
1316 const uschar * file_list = expanded;
1320 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1321 if ((err = tls_add_certfile(sctx, cbinfo, file, errstr)))
1324 else /* would there ever be a need for multiple client certs? */
1325 if ((err = tls_add_certfile(sctx, cbinfo, expanded, errstr)))
1328 if ( cbinfo->privatekey
1329 && !expand_check(cbinfo->privatekey, US"tls_privatekey", &expanded, errstr))
1332 /* If expansion was forced to fail, key_expanded will be NULL. If the result
1333 of the expansion is an empty string, ignore it also, and assume the private
1334 key is in the same file as the certificate. */
1336 if (expanded && *expanded)
1337 if (cbinfo->is_server)
1339 const uschar * file_list = expanded;
1343 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1344 if ((err = tls_add_pkeyfile(sctx, cbinfo, file, errstr)))
1347 else /* would there ever be a need for multiple client certs? */
1348 if ((err = tls_add_pkeyfile(sctx, cbinfo, expanded, errstr)))
1352 #ifndef DISABLE_OCSP
1353 if (cbinfo->is_server && cbinfo->u_ocsp.server.file)
1356 if (!expand_check(cbinfo->u_ocsp.server.file, US"tls_ocsp_file", &expanded, errstr))
1359 if (expanded && *expanded)
1361 DEBUG(D_tls) debug_printf("tls_ocsp_file %s\n", expanded);
1362 if ( cbinfo->u_ocsp.server.file_expanded
1363 && (Ustrcmp(expanded, cbinfo->u_ocsp.server.file_expanded) == 0))
1365 DEBUG(D_tls) debug_printf(" - value unchanged, using existing values\n");
1368 ocsp_load_response(sctx, cbinfo, expanded);
1379 /*************************************************
1380 * Callback to handle SNI *
1381 *************************************************/
1383 /* Called when acting as server during the TLS session setup if a Server Name
1384 Indication extension was sent by the client.
1386 API documentation is OpenSSL s_server.c implementation.
1389 s SSL* of the current session
1390 ad unknown (part of OpenSSL API) (unused)
1391 arg Callback of "our" registered data
1393 Returns: SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
1396 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
1398 tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg)
1400 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1401 tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1403 int old_pool = store_pool;
1404 uschar * dummy_errstr;
1407 return SSL_TLSEXT_ERR_OK;
1409 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
1410 reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
1412 /* Make the extension value available for expansion */
1413 store_pool = POOL_PERM;
1414 tls_in.sni = string_copy(US servername);
1415 store_pool = old_pool;
1417 if (!reexpand_tls_files_for_sni)
1418 return SSL_TLSEXT_ERR_OK;
1420 /* Can't find an SSL_CTX_clone() or equivalent, so we do it manually;
1421 not confident that memcpy wouldn't break some internal reference counting.
1422 Especially since there's a references struct member, which would be off. */
1424 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1425 if (!(server_sni = SSL_CTX_new(TLS_server_method())))
1427 if (!(server_sni = SSL_CTX_new(SSLv23_server_method())))
1430 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1431 DEBUG(D_tls) debug_printf("SSL_CTX_new() failed: %s\n", ssl_errstring);
1435 /* Not sure how many of these are actually needed, since SSL object
1436 already exists. Might even need this selfsame callback, for reneg? */
1438 SSL_CTX_set_info_callback(server_sni, SSL_CTX_get_info_callback(server_ctx));
1439 SSL_CTX_set_mode(server_sni, SSL_CTX_get_mode(server_ctx));
1440 SSL_CTX_set_options(server_sni, SSL_CTX_get_options(server_ctx));
1441 SSL_CTX_set_timeout(server_sni, SSL_CTX_get_timeout(server_ctx));
1442 SSL_CTX_set_tlsext_servername_callback(server_sni, tls_servername_cb);
1443 SSL_CTX_set_tlsext_servername_arg(server_sni, cbinfo);
1445 if ( !init_dh(server_sni, cbinfo->dhparam, NULL, &dummy_errstr)
1446 || !init_ecdh(server_sni, NULL, &dummy_errstr)
1450 if ( cbinfo->server_cipher_list
1451 && !SSL_CTX_set_cipher_list(server_sni, CS cbinfo->server_cipher_list))
1454 #ifndef DISABLE_OCSP
1455 if (cbinfo->u_ocsp.server.file)
1457 SSL_CTX_set_tlsext_status_cb(server_sni, tls_server_stapling_cb);
1458 SSL_CTX_set_tlsext_status_arg(server_sni, cbinfo);
1462 if ((rc = setup_certs(server_sni, tls_verify_certificates, tls_crl, NULL, FALSE,
1463 verify_callback_server, &dummy_errstr)) != OK)
1466 /* do this after setup_certs, because this can require the certs for verifying
1467 OCSP information. */
1468 if ((rc = tls_expand_session_files(server_sni, cbinfo, &dummy_errstr)) != OK)
1471 DEBUG(D_tls) debug_printf("Switching SSL context.\n");
1472 SSL_set_SSL_CTX(s, server_sni);
1473 return SSL_TLSEXT_ERR_OK;
1475 bad: return SSL_TLSEXT_ERR_ALERT_FATAL;
1477 #endif /* EXIM_HAVE_OPENSSL_TLSEXT */
1482 #ifndef DISABLE_OCSP
1484 /*************************************************
1485 * Callback to handle OCSP Stapling *
1486 *************************************************/
1488 /* Called when acting as server during the TLS session setup if the client
1489 requests OCSP information with a Certificate Status Request.
1491 Documentation via openssl s_server.c and the Apache patch from the OpenSSL
1497 tls_server_stapling_cb(SSL *s, void *arg)
1499 const tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1500 uschar *response_der; /*XXX blob */
1501 int response_der_len;
1503 /*XXX stack: use SSL_get_certificate() to see which cert; from that work
1504 out which ocsp blob to send. Unfortunately, SSL_get_certificate is known
1505 buggy in current OpenSSL; it returns the last cert loaded always rather than
1506 the one actually presented. So we can't support a stack of OCSP proofs at
1510 debug_printf("Received TLS status request (OCSP stapling); %s response\n",
1511 cbinfo->u_ocsp.server.response ? "have" : "lack");
1513 tls_in.ocsp = OCSP_NOT_RESP;
1514 if (!cbinfo->u_ocsp.server.response)
1515 return SSL_TLSEXT_ERR_NOACK;
1517 response_der = NULL;
1518 response_der_len = i2d_OCSP_RESPONSE(cbinfo->u_ocsp.server.response, /*XXX stack*/
1520 if (response_der_len <= 0)
1521 return SSL_TLSEXT_ERR_NOACK;
1523 SSL_set_tlsext_status_ocsp_resp(server_ssl, response_der, response_der_len);
1524 tls_in.ocsp = OCSP_VFIED;
1525 return SSL_TLSEXT_ERR_OK;
1530 time_print(BIO * bp, const char * str, ASN1_GENERALIZEDTIME * time)
1532 BIO_printf(bp, "\t%s: ", str);
1533 ASN1_GENERALIZEDTIME_print(bp, time);
1538 tls_client_stapling_cb(SSL *s, void *arg)
1540 tls_ext_ctx_cb * cbinfo = arg;
1541 const unsigned char * p;
1543 OCSP_RESPONSE * rsp;
1544 OCSP_BASICRESP * bs;
1547 DEBUG(D_tls) debug_printf("Received TLS status response (OCSP stapling):");
1548 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1551 /* Expect this when we requested ocsp but got none */
1552 if (cbinfo->u_ocsp.client.verify_required && LOGGING(tls_cipher))
1553 log_write(0, LOG_MAIN, "Received TLS status callback, null content");
1555 DEBUG(D_tls) debug_printf(" null\n");
1556 return cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1559 if(!(rsp = d2i_OCSP_RESPONSE(NULL, &p, len)))
1561 tls_out.ocsp = OCSP_FAILED;
1562 if (LOGGING(tls_cipher))
1563 log_write(0, LOG_MAIN, "Received TLS cert status response, parse error");
1565 DEBUG(D_tls) debug_printf(" parse error\n");
1569 if(!(bs = OCSP_response_get1_basic(rsp)))
1571 tls_out.ocsp = OCSP_FAILED;
1572 if (LOGGING(tls_cipher))
1573 log_write(0, LOG_MAIN, "Received TLS cert status response, error parsing response");
1575 DEBUG(D_tls) debug_printf(" error parsing response\n");
1576 OCSP_RESPONSE_free(rsp);
1580 /* We'd check the nonce here if we'd put one in the request. */
1581 /* However that would defeat cacheability on the server so we don't. */
1583 /* This section of code reworked from OpenSSL apps source;
1584 The OpenSSL Project retains copyright:
1585 Copyright (c) 1999 The OpenSSL Project. All rights reserved.
1590 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1592 DEBUG(D_tls) bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
1594 /*OCSP_RESPONSE_print(bp, rsp, 0); extreme debug: stapling content */
1596 /* Use the chain that verified the server cert to verify the stapled info */
1597 /* DEBUG(D_tls) x509_store_dump_cert_s_names(cbinfo->u_ocsp.client.verify_store); */
1599 if ((i = OCSP_basic_verify(bs, cbinfo->verify_stack,
1600 cbinfo->u_ocsp.client.verify_store, 0)) <= 0)
1602 tls_out.ocsp = OCSP_FAILED;
1603 if (LOGGING(tls_cipher)) log_write(0, LOG_MAIN,
1604 "Received TLS cert status response, itself unverifiable: %s",
1605 ERR_reason_error_string(ERR_peek_error()));
1606 BIO_printf(bp, "OCSP response verify failure\n");
1607 ERR_print_errors(bp);
1608 OCSP_RESPONSE_print(bp, rsp, 0);
1612 BIO_printf(bp, "OCSP response well-formed and signed OK\n");
1614 /*XXX So we have a good stapled OCSP status. How do we know
1615 it is for the cert of interest? OpenSSL 1.1.0 has a routine
1616 OCSP_resp_find_status() which matches on a cert id, which presumably
1617 we should use. Making an id needs OCSP_cert_id_new(), which takes
1618 issuerName, issuerKey, serialNumber. Are they all in the cert?
1620 For now, carry on blindly accepting the resp. */
1623 OCSP_SINGLERESP * single;
1625 #ifdef EXIM_HAVE_OCSP_RESP_COUNT
1626 if (OCSP_resp_count(bs) != 1)
1628 STACK_OF(OCSP_SINGLERESP) * sresp = bs->tbsResponseData->responses;
1629 if (sk_OCSP_SINGLERESP_num(sresp) != 1)
1632 tls_out.ocsp = OCSP_FAILED;
1633 log_write(0, LOG_MAIN, "OCSP stapling "
1634 "with multiple responses not handled");
1637 single = OCSP_resp_get0(bs, 0);
1638 status = OCSP_single_get0_status(single, &reason, &rev,
1639 &thisupd, &nextupd);
1642 DEBUG(D_tls) time_print(bp, "This OCSP Update", thisupd);
1643 DEBUG(D_tls) if(nextupd) time_print(bp, "Next OCSP Update", nextupd);
1644 if (!OCSP_check_validity(thisupd, nextupd,
1645 EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1647 tls_out.ocsp = OCSP_FAILED;
1648 DEBUG(D_tls) ERR_print_errors(bp);
1649 log_write(0, LOG_MAIN, "Server OSCP dates invalid");
1653 DEBUG(D_tls) BIO_printf(bp, "Certificate status: %s\n",
1654 OCSP_cert_status_str(status));
1657 case V_OCSP_CERTSTATUS_GOOD:
1658 tls_out.ocsp = OCSP_VFIED;
1661 case V_OCSP_CERTSTATUS_REVOKED:
1662 tls_out.ocsp = OCSP_FAILED;
1663 log_write(0, LOG_MAIN, "Server certificate revoked%s%s",
1664 reason != -1 ? "; reason: " : "",
1665 reason != -1 ? OCSP_crl_reason_str(reason) : "");
1666 DEBUG(D_tls) time_print(bp, "Revocation Time", rev);
1669 tls_out.ocsp = OCSP_FAILED;
1670 log_write(0, LOG_MAIN,
1671 "Server certificate status unknown, in OCSP stapling");
1676 i = cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1681 OCSP_RESPONSE_free(rsp);
1684 #endif /*!DISABLE_OCSP*/
1687 /*************************************************
1688 * Initialize for TLS *
1689 *************************************************/
1691 /* Called from both server and client code, to do preliminary initialization
1692 of the library. We allocate and return a context structure.
1695 ctxp returned SSL context
1696 host connected host, if client; NULL if server
1697 dhparam DH parameter file
1698 certificate certificate file
1699 privatekey private key
1700 ocsp_file file of stapling info (server); flag for require ocsp (client)
1701 addr address if client; NULL if server (for some randomness)
1702 cbp place to put allocated callback context
1703 errstr error string pointer
1705 Returns: OK/DEFER/FAIL
1709 tls_init(SSL_CTX **ctxp, host_item *host, uschar *dhparam, uschar *certificate,
1711 #ifndef DISABLE_OCSP
1712 uschar *ocsp_file, /*XXX stack, in server*/
1714 address_item *addr, tls_ext_ctx_cb ** cbp, uschar ** errstr)
1719 tls_ext_ctx_cb * cbinfo;
1721 cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
1722 cbinfo->certificate = certificate;
1723 cbinfo->privatekey = privatekey;
1724 cbinfo->is_server = host==NULL;
1725 #ifndef DISABLE_OCSP
1726 cbinfo->verify_stack = NULL;
1729 cbinfo->u_ocsp.server.file = ocsp_file;
1730 cbinfo->u_ocsp.server.file_expanded = NULL;
1731 cbinfo->u_ocsp.server.response = NULL;
1734 cbinfo->u_ocsp.client.verify_store = NULL;
1736 cbinfo->dhparam = dhparam;
1737 cbinfo->server_cipher_list = NULL;
1738 cbinfo->host = host;
1739 #ifndef DISABLE_EVENT
1740 cbinfo->event_action = NULL;
1743 #ifdef EXIM_NEED_OPENSSL_INIT
1744 SSL_load_error_strings(); /* basic set up */
1745 OpenSSL_add_ssl_algorithms();
1748 #ifdef EXIM_HAVE_SHA256
1749 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
1750 list of available digests. */
1751 EVP_add_digest(EVP_sha256());
1754 /* Create a context.
1755 The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
1756 negotiation in the different methods; as far as I can tell, the only
1757 *_{server,client}_method which allows negotiation is SSLv23, which exists even
1758 when OpenSSL is built without SSLv2 support.
1759 By disabling with openssl_options, we can let admins re-enable with the
1762 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1763 if (!(ctx = SSL_CTX_new(host ? TLS_client_method() : TLS_server_method())))
1765 if (!(ctx = SSL_CTX_new(host ? SSLv23_client_method() : SSLv23_server_method())))
1767 return tls_error(US"SSL_CTX_new", host, NULL, errstr);
1769 /* It turns out that we need to seed the random number generator this early in
1770 order to get the full complement of ciphers to work. It took me roughly a day
1771 of work to discover this by experiment.
1773 On systems that have /dev/urandom, SSL may automatically seed itself from
1774 there. Otherwise, we have to make something up as best we can. Double check
1780 gettimeofday(&r.tv, NULL);
1783 RAND_seed(US (&r), sizeof(r));
1784 RAND_seed(US big_buffer, big_buffer_size);
1785 if (addr != NULL) RAND_seed(US addr, sizeof(addr));
1788 return tls_error(US"RAND_status", host,
1789 US"unable to seed random number generator", errstr);
1792 /* Set up the information callback, which outputs if debugging is at a suitable
1795 DEBUG(D_tls) SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
1796 #ifdef OPENSSL_HAVE_KEYLOG_CB
1797 DEBUG(D_tls) SSL_CTX_set_keylog_callback(ctx, (void (*)())keylog_callback);
1800 /* Automatically re-try reads/writes after renegotiation. */
1801 (void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1803 /* Apply administrator-supplied work-arounds.
1804 Historically we applied just one requested option,
1805 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
1806 moved to an administrator-controlled list of options to specify and
1807 grandfathered in the first one as the default value for "openssl_options".
1809 No OpenSSL version number checks: the options we accept depend upon the
1810 availability of the option value macros from OpenSSL. */
1812 if (!tls_openssl_options_parse(openssl_options, &init_options))
1813 return tls_error(US"openssl_options parsing failed", host, NULL, errstr);
1817 DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
1818 if (!(SSL_CTX_set_options(ctx, init_options)))
1819 return tls_error(string_sprintf(
1820 "SSL_CTX_set_option(%#lx)", init_options), host, NULL, errstr);
1823 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
1825 #ifdef OPENSSL_HAVE_NUM_TICKETS
1826 SSL_CTX_set_num_tickets(ctx, 0); /* send no TLS1.3 stateful-tickets */
1829 /* We'd like to disable session cache unconditionally, but foolish Outlook
1830 Express clients then give up the first TLS connection and make a second one
1831 (which works). Only when there is an IMAP service on the same machine.
1832 Presumably OE is trying to use the cache for A on B. Leave it enabled for
1833 now, until we work out a decent way of presenting control to the config. It
1834 will never be used because we use a new context every time. */
1836 (void) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1839 /* Initialize with DH parameters if supplied */
1840 /* Initialize ECDH temp key parameter selection */
1842 if ( !init_dh(ctx, dhparam, host, errstr)
1843 || !init_ecdh(ctx, host, errstr)
1847 /* Set up certificate and key (and perhaps OCSP info) */
1849 if ((rc = tls_expand_session_files(ctx, cbinfo, errstr)) != OK)
1852 /* If we need to handle SNI or OCSP, do so */
1854 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
1855 # ifndef DISABLE_OCSP
1856 if (!(cbinfo->verify_stack = sk_X509_new_null()))
1858 DEBUG(D_tls) debug_printf("failed to create stack for stapling verify\n");
1863 if (!host) /* server */
1865 # ifndef DISABLE_OCSP
1866 /* We check u_ocsp.server.file, not server.response, because we care about if
1867 the option exists, not what the current expansion might be, as SNI might
1868 change the certificate and OCSP file in use between now and the time the
1869 callback is invoked. */
1870 if (cbinfo->u_ocsp.server.file)
1872 SSL_CTX_set_tlsext_status_cb(ctx, tls_server_stapling_cb);
1873 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
1876 /* We always do this, so that $tls_sni is available even if not used in
1878 SSL_CTX_set_tlsext_servername_callback(ctx, tls_servername_cb);
1879 SSL_CTX_set_tlsext_servername_arg(ctx, cbinfo);
1881 # ifndef DISABLE_OCSP
1883 if(ocsp_file) /* wanting stapling */
1885 if (!(cbinfo->u_ocsp.client.verify_store = X509_STORE_new()))
1887 DEBUG(D_tls) debug_printf("failed to create store for stapling verify\n");
1890 SSL_CTX_set_tlsext_status_cb(ctx, tls_client_stapling_cb);
1891 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
1896 cbinfo->verify_cert_hostnames = NULL;
1898 #ifdef EXIM_HAVE_EPHEM_RSA_KEX
1899 /* Set up the RSA callback */
1900 SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
1903 /* Finally, set the timeout, and we are done */
1905 SSL_CTX_set_timeout(ctx, ssl_session_timeout);
1906 DEBUG(D_tls) debug_printf("Initialized TLS\n");
1917 /*************************************************
1918 * Get name of cipher in use *
1919 *************************************************/
1922 Argument: pointer to an SSL structure for the connection
1923 pointer to number of bits for cipher
1924 Returns: pointer to allocated string in perm-pool
1928 construct_cipher_name(SSL * ssl, int * bits)
1930 int pool = store_pool;
1931 /* With OpenSSL 1.0.0a, 'c' needs to be const but the documentation doesn't
1932 yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
1933 the accessor functions use const in the prototype. */
1935 const uschar * ver = CUS SSL_get_version(ssl);
1936 const SSL_CIPHER * c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
1939 SSL_CIPHER_get_bits(c, bits);
1941 store_pool = POOL_PERM;
1942 s = string_sprintf("%s:%s:%u", ver, SSL_CIPHER_get_name(c), *bits);
1944 DEBUG(D_tls) debug_printf("Cipher: %s\n", s);
1949 /* Get IETF-standard name for ciphersuite.
1950 Argument: pointer to an SSL structure for the connection
1951 Returns: pointer to string
1954 static const uschar *
1955 cipher_stdname_ssl(SSL * ssl)
1957 #ifdef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
1958 return CUS SSL_CIPHER_standard_name(SSL_get_current_cipher(ssl));
1960 ushort id = 0xffff & SSL_CIPHER_get_id(SSL_get_current_cipher(ssl));
1961 return cipher_stdname(id >> 8, id & 0xff);
1967 peer_cert(SSL * ssl, tls_support * tlsp, uschar * peerdn, unsigned siz)
1969 /*XXX we might consider a list-of-certs variable for the cert chain.
1970 SSL_get_peer_cert_chain(SSL*). We'd need a new variable type and support
1971 in list-handling functions, also consider the difference between the entire
1972 chain and the elements sent by the peer. */
1974 tlsp->peerdn = NULL;
1976 /* Will have already noted peercert on a verify fail; possibly not the leaf */
1977 if (!tlsp->peercert)
1978 tlsp->peercert = SSL_get_peer_certificate(ssl);
1979 /* Beware anonymous ciphers which lead to server_cert being NULL */
1981 if (!X509_NAME_oneline(X509_get_subject_name(tlsp->peercert), CS peerdn, siz))
1982 { DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n"); }
1985 peerdn[siz-1] = '\0';
1986 tlsp->peerdn = peerdn; /*XXX a static buffer... */
1994 /*************************************************
1995 * Set up for verifying certificates *
1996 *************************************************/
1998 #ifndef DISABLE_OCSP
1999 /* Load certs from file, return TRUE on success */
2002 chain_from_pem_file(const uschar * file, STACK_OF(X509) * verify_stack)
2007 while (sk_X509_num(verify_stack) > 0)
2008 X509_free(sk_X509_pop(verify_stack));
2010 if (!(bp = BIO_new_file(CS file, "r"))) return FALSE;
2011 while ((x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
2012 sk_X509_push(verify_stack, x);
2020 /* Called by both client and server startup; on the server possibly
2021 repeated after a Server Name Indication.
2024 sctx SSL_CTX* to initialise
2025 certs certs file or NULL
2026 crl CRL file or NULL
2027 host NULL in a server; the remote host in a client
2028 optional TRUE if called from a server for a host in tls_try_verify_hosts;
2029 otherwise passed as FALSE
2030 cert_vfy_cb Callback function for certificate verification
2031 errstr error string pointer
2033 Returns: OK/DEFER/FAIL
2037 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
2038 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr)
2040 uschar *expcerts, *expcrl;
2042 if (!expand_check(certs, US"tls_verify_certificates", &expcerts, errstr))
2044 DEBUG(D_tls) debug_printf("tls_verify_certificates: %s\n", expcerts);
2046 if (expcerts && *expcerts)
2048 /* Tell the library to use its compiled-in location for the system default
2049 CA bundle. Then add the ones specified in the config, if any. */
2051 if (!SSL_CTX_set_default_verify_paths(sctx))
2052 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL, errstr);
2054 if (Ustrcmp(expcerts, "system") != 0)
2056 struct stat statbuf;
2058 if (Ustat(expcerts, &statbuf) < 0)
2060 log_write(0, LOG_MAIN|LOG_PANIC,
2061 "failed to stat %s for certificates", expcerts);
2067 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
2068 { file = NULL; dir = expcerts; }
2071 file = expcerts; dir = NULL;
2072 #ifndef DISABLE_OCSP
2073 /* In the server if we will be offering an OCSP proof, load chain from
2074 file for verifying the OCSP proof at load time. */
2077 && statbuf.st_size > 0
2078 && server_static_cbinfo->u_ocsp.server.file
2079 && !chain_from_pem_file(file, server_static_cbinfo->verify_stack)
2082 log_write(0, LOG_MAIN|LOG_PANIC,
2083 "failed to load cert chain from %s", file);
2089 /* If a certificate file is empty, the next function fails with an
2090 unhelpful error message. If we skip it, we get the correct behaviour (no
2091 certificates are recognized, but the error message is still misleading (it
2092 says no certificate was supplied). But this is better. */
2094 if ( (!file || statbuf.st_size > 0)
2095 && !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
2096 return tls_error(US"SSL_CTX_load_verify_locations", host, NULL, errstr);
2098 /* Load the list of CAs for which we will accept certs, for sending
2099 to the client. This is only for the one-file tls_verify_certificates
2101 If a list isn't loaded into the server, but some verify locations are set,
2102 the server end appears to make a wildcard request for client certs.
2103 Meanwhile, the client library as default behaviour *ignores* the list
2104 we send over the wire - see man SSL_CTX_set_client_cert_cb.
2105 Because of this, and that the dir variant is likely only used for
2106 the public-CA bundle (not for a private CA), not worth fixing. */
2110 STACK_OF(X509_NAME) * names = SSL_load_client_CA_file(CS file);
2112 SSL_CTX_set_client_CA_list(sctx, names);
2113 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n",
2114 sk_X509_NAME_num(names));
2119 /* Handle a certificate revocation list. */
2121 #if OPENSSL_VERSION_NUMBER > 0x00907000L
2123 /* This bit of code is now the version supplied by Lars Mainka. (I have
2124 merely reformatted it into the Exim code style.)
2126 "From here I changed the code to add support for multiple crl's
2127 in pem format in one file or to support hashed directory entries in
2128 pem format instead of a file. This method now uses the library function
2129 X509_STORE_load_locations to add the CRL location to the SSL context.
2130 OpenSSL will then handle the verify against CA certs and CRLs by
2131 itself in the verify callback." */
2133 if (!expand_check(crl, US"tls_crl", &expcrl, errstr)) return DEFER;
2134 if (expcrl && *expcrl)
2136 struct stat statbufcrl;
2137 if (Ustat(expcrl, &statbufcrl) < 0)
2139 log_write(0, LOG_MAIN|LOG_PANIC,
2140 "failed to stat %s for certificates revocation lists", expcrl);
2145 /* is it a file or directory? */
2147 X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
2148 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
2152 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
2158 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
2160 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
2161 return tls_error(US"X509_STORE_load_locations", host, NULL, errstr);
2163 /* setting the flags to check against the complete crl chain */
2165 X509_STORE_set_flags(cvstore,
2166 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2170 #endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
2172 /* If verification is optional, don't fail if no certificate */
2174 SSL_CTX_set_verify(sctx,
2175 SSL_VERIFY_PEER | (optional ? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
2184 /*************************************************
2185 * Start a TLS session in a server *
2186 *************************************************/
2188 /* This is called when Exim is running as a server, after having received
2189 the STARTTLS command. It must respond to that command, and then negotiate
2193 require_ciphers allowed ciphers
2194 errstr pointer to error message
2196 Returns: OK on success
2197 DEFER for errors before the start of the negotiation
2198 FAIL for errors during the negotiation; the server can't
2203 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
2206 uschar * expciphers;
2207 tls_ext_ctx_cb * cbinfo;
2208 static uschar peerdn[256];
2210 /* Check for previous activation */
2212 if (tls_in.active.sock >= 0)
2214 tls_error(US"STARTTLS received after TLS started", NULL, US"", errstr);
2215 smtp_printf("554 Already in TLS\r\n", FALSE);
2219 /* Initialize the SSL library. If it fails, it will already have logged
2222 rc = tls_init(&server_ctx, NULL, tls_dhparam, tls_certificate, tls_privatekey,
2223 #ifndef DISABLE_OCSP
2224 tls_ocsp_file, /*XXX stack*/
2226 NULL, &server_static_cbinfo, errstr);
2227 if (rc != OK) return rc;
2228 cbinfo = server_static_cbinfo;
2230 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers, errstr))
2233 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2234 were historically separated by underscores. So that I can use either form in my
2235 tests, and also for general convenience, we turn underscores into hyphens here.
2237 XXX SSL_CTX_set_cipher_list() is replaced by SSL_CTX_set_ciphersuites()
2238 for TLS 1.3 . Since we do not call it at present we get the default list:
2239 TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
2244 uschar * s = expciphers;
2245 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
2246 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
2247 if (!SSL_CTX_set_cipher_list(server_ctx, CS expciphers))
2248 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL, errstr);
2249 cbinfo->server_cipher_list = expciphers;
2252 /* If this is a host for which certificate verification is mandatory or
2253 optional, set up appropriately. */
2255 tls_in.certificate_verified = FALSE;
2257 tls_in.dane_verified = FALSE;
2259 server_verify_callback_called = FALSE;
2261 if (verify_check_host(&tls_verify_hosts) == OK)
2263 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
2264 FALSE, verify_callback_server, errstr);
2265 if (rc != OK) return rc;
2266 server_verify_optional = FALSE;
2268 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2270 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
2271 TRUE, verify_callback_server, errstr);
2272 if (rc != OK) return rc;
2273 server_verify_optional = TRUE;
2276 /* Prepare for new connection */
2278 if (!(server_ssl = SSL_new(server_ctx)))
2279 return tls_error(US"SSL_new", NULL, NULL, errstr);
2281 /* Warning: we used to SSL_clear(ssl) here, it was removed.
2283 * With the SSL_clear(), we get strange interoperability bugs with
2284 * OpenSSL 1.0.1b and TLS1.1/1.2. It looks as though this may be a bug in
2285 * OpenSSL itself, as a clear should not lead to inability to follow protocols.
2287 * The SSL_clear() call is to let an existing SSL* be reused, typically after
2288 * session shutdown. In this case, we have a brand new object and there's no
2289 * obvious reason to immediately clear it. I'm guessing that this was
2290 * originally added because of incomplete initialisation which the clear fixed,
2291 * in some historic release.
2294 /* Set context and tell client to go ahead, except in the case of TLS startup
2295 on connection, where outputting anything now upsets the clients and tends to
2296 make them disconnect. We need to have an explicit fflush() here, to force out
2297 the response. Other smtp_printf() calls do not need it, because in non-TLS
2298 mode, the fflush() happens when smtp_getc() is called. */
2300 SSL_set_session_id_context(server_ssl, sid_ctx, Ustrlen(sid_ctx));
2301 if (!tls_in.on_connect)
2303 smtp_printf("220 TLS go ahead\r\n", FALSE);
2307 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2308 that the OpenSSL library doesn't. */
2310 SSL_set_wfd(server_ssl, fileno(smtp_out));
2311 SSL_set_rfd(server_ssl, fileno(smtp_in));
2312 SSL_set_accept_state(server_ssl);
2314 DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
2316 sigalrm_seen = FALSE;
2317 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2318 rc = SSL_accept(server_ssl);
2323 (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
2327 DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
2329 /* TLS has been set up. Adjust the input functions to read via TLS,
2330 and initialize things. */
2332 peer_cert(server_ssl, &tls_in, peerdn, sizeof(peerdn));
2334 tls_in.cipher = construct_cipher_name(server_ssl, &tls_in.bits);
2335 tls_in.cipher_stdname = cipher_stdname_ssl(server_ssl);
2340 if (SSL_get_shared_ciphers(server_ssl, CS buf, sizeof(buf)))
2341 debug_printf("Shared ciphers: %s\n", buf);
2343 #ifdef EXIM_HAVE_OPENSSL_KEYLOG
2345 BIO * bp = BIO_new(BIO_s_mem());
2348 SSL_SESSION_print_keylog(bp, SSL_get_session(server_ssl));
2349 len = (int) BIO_get_mem_data(bp, CSS &s);
2350 debug_printf("%.*s", len, s);
2356 /* Record the certificate we presented */
2358 X509 * crt = SSL_get_certificate(server_ssl);
2359 tls_in.ourcert = crt ? X509_dup(crt) : NULL;
2362 /* Only used by the server-side tls (tls_in), including tls_getc.
2363 Client-side (tls_out) reads (seem to?) go via
2364 smtp_read_response()/ip_recv().
2365 Hence no need to duplicate for _in and _out.
2367 if (!ssl_xfer_buffer) ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2368 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
2369 ssl_xfer_eof = ssl_xfer_error = FALSE;
2371 receive_getc = tls_getc;
2372 receive_getbuf = tls_getbuf;
2373 receive_get_cache = tls_get_cache;
2374 receive_ungetc = tls_ungetc;
2375 receive_feof = tls_feof;
2376 receive_ferror = tls_ferror;
2377 receive_smtp_buffered = tls_smtp_buffered;
2379 tls_in.active.sock = fileno(smtp_out);
2380 tls_in.active.tls_ctx = NULL; /* not using explicit ctx for server-side */
2388 tls_client_basic_ctx_init(SSL_CTX * ctx,
2389 host_item * host, smtp_transport_options_block * ob, tls_ext_ctx_cb * cbinfo,
2393 /* stick to the old behaviour for compatibility if tls_verify_certificates is
2394 set but both tls_verify_hosts and tls_try_verify_hosts is not set. Check only
2395 the specified host patterns if one of them is defined */
2397 if ( ( !ob->tls_verify_hosts
2398 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2400 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
2402 client_verify_optional = FALSE;
2403 else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
2404 client_verify_optional = TRUE;
2408 if ((rc = setup_certs(ctx, ob->tls_verify_certificates,
2409 ob->tls_crl, host, client_verify_optional, verify_callback_client,
2413 if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
2415 cbinfo->verify_cert_hostnames =
2417 string_domain_utf8_to_alabel(host->name, NULL);
2421 DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
2422 cbinfo->verify_cert_hostnames);
2430 dane_tlsa_load(SSL * ssl, host_item * host, dns_answer * dnsa, uschar ** errstr)
2433 const char * hostnames[2] = { CS host->name, NULL };
2436 if (DANESSL_init(ssl, NULL, hostnames) != 1)
2437 return tls_error(US"hostnames load", host, NULL, errstr);
2439 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
2440 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2441 ) if (rr->type == T_TLSA && rr->size > 3)
2443 const uschar * p = rr->data;
2444 uint8_t usage, selector, mtype;
2445 const char * mdname;
2449 /* Only DANE-TA(2) and DANE-EE(3) are supported */
2450 if (usage != 2 && usage != 3) continue;
2457 default: continue; /* Only match-types 0, 1, 2 are supported */
2458 case 0: mdname = NULL; break;
2459 case 1: mdname = "sha256"; break;
2460 case 2: mdname = "sha512"; break;
2464 switch (DANESSL_add_tlsa(ssl, usage, selector, mdname, p, rr->size - 3))
2467 return tls_error(US"tlsa load", host, NULL, errstr);
2468 case 0: /* action not taken */
2472 tls_out.tlsa_usage |= 1<<usage;
2478 log_write(0, LOG_MAIN, "DANE error: No usable TLSA records");
2481 #endif /*SUPPORT_DANE*/
2485 /*************************************************
2486 * Start a TLS session in a client *
2487 *************************************************/
2489 /* Called from the smtp transport after STARTTLS has been accepted.
2492 fd the fd of the connection
2493 host connected host (for messages and option-tests)
2494 addr the first address (for some randomness; can be NULL)
2495 tb transport (always smtp)
2496 tlsa_dnsa tlsa lookup, if DANE, else null
2497 tlsp record details of channel configuration here; must be non-NULL
2498 errstr error string pointer
2500 Returns: Pointer to TLS session context, or NULL on error
2504 tls_client_start(int fd, host_item *host, address_item *addr,
2505 transport_instance * tb,
2507 dns_answer * tlsa_dnsa,
2509 tls_support * tlsp, uschar ** errstr)
2511 smtp_transport_options_block * ob = tb
2512 ? (smtp_transport_options_block *)tb->options_block
2513 : &smtp_transport_option_defaults;
2514 exim_openssl_client_tls_ctx * exim_client_ctx;
2515 static uschar peerdn[256];
2516 uschar * expciphers;
2519 #ifndef DISABLE_OCSP
2520 BOOL request_ocsp = FALSE;
2521 BOOL require_ocsp = FALSE;
2525 store_pool = POOL_PERM;
2526 exim_client_ctx = store_get(sizeof(exim_openssl_client_tls_ctx));
2530 tlsp->tlsa_usage = 0;
2533 #ifndef DISABLE_OCSP
2535 # ifdef SUPPORT_DANE
2537 && ob->hosts_request_ocsp[0] == '*'
2538 && ob->hosts_request_ocsp[1] == '\0'
2541 /* Unchanged from default. Use a safer one under DANE */
2542 request_ocsp = TRUE;
2543 ob->hosts_request_ocsp = US"${if or { {= {0}{$tls_out_tlsa_usage}} "
2544 " {= {4}{$tls_out_tlsa_usage}} } "
2550 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK))
2551 request_ocsp = TRUE;
2553 # ifdef SUPPORT_DANE
2557 verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2561 rc = tls_init(&exim_client_ctx->ctx, host, NULL,
2562 ob->tls_certificate, ob->tls_privatekey,
2563 #ifndef DISABLE_OCSP
2564 (void *)(long)request_ocsp,
2566 addr, &client_static_cbinfo, errstr);
2567 if (rc != OK) return NULL;
2569 tlsp->certificate_verified = FALSE;
2570 client_verify_callback_called = FALSE;
2576 /* We fall back to tls_require_ciphers if unset, empty or forced failure, but
2577 other failures should be treated as problems. */
2578 if (ob->dane_require_tls_ciphers &&
2579 !expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2580 &expciphers, errstr))
2582 if (expciphers && *expciphers == '\0')
2587 !expand_check(ob->tls_require_ciphers, US"tls_require_ciphers",
2588 &expciphers, errstr))
2591 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2592 are separated by underscores. So that I can use either form in my tests, and
2593 also for general convenience, we turn underscores into hyphens here. */
2597 uschar *s = expciphers;
2598 while (*s) { if (*s == '_') *s = '-'; s++; }
2599 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
2600 if (!SSL_CTX_set_cipher_list(exim_client_ctx->ctx, CS expciphers))
2602 tls_error(US"SSL_CTX_set_cipher_list", host, NULL, errstr);
2610 SSL_CTX_set_verify(exim_client_ctx->ctx,
2611 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2612 verify_callback_client_dane);
2614 if (!DANESSL_library_init())
2616 tls_error(US"library init", host, NULL, errstr);
2619 if (DANESSL_CTX_init(exim_client_ctx->ctx) <= 0)
2621 tls_error(US"context init", host, NULL, errstr);
2629 if (tls_client_basic_ctx_init(exim_client_ctx->ctx, host, ob,
2630 client_static_cbinfo, errstr) != OK)
2633 if (!(exim_client_ctx->ssl = SSL_new(exim_client_ctx->ctx)))
2635 tls_error(US"SSL_new", host, NULL, errstr);
2638 SSL_set_session_id_context(exim_client_ctx->ssl, sid_ctx, Ustrlen(sid_ctx));
2639 SSL_set_fd(exim_client_ctx->ssl, fd);
2640 SSL_set_connect_state(exim_client_ctx->ssl);
2644 if (!expand_check(ob->tls_sni, US"tls_sni", &tlsp->sni, errstr))
2648 DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n");
2650 else if (!Ustrlen(tlsp->sni))
2654 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
2655 DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tlsp->sni);
2656 SSL_set_tlsext_host_name(exim_client_ctx->ssl, tlsp->sni);
2658 log_write(0, LOG_MAIN, "SNI unusable with this OpenSSL library version; ignoring \"%s\"\n",
2666 if (dane_tlsa_load(exim_client_ctx->ssl, host, tlsa_dnsa, errstr) != OK)
2670 #ifndef DISABLE_OCSP
2671 /* Request certificate status at connection-time. If the server
2672 does OCSP stapling we will get the callback (set in tls_init()) */
2673 # ifdef SUPPORT_DANE
2677 if ( ((s = ob->hosts_require_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
2678 || ((s = ob->hosts_request_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
2680 { /* Re-eval now $tls_out_tlsa_usage is populated. If
2681 this means we avoid the OCSP request, we wasted the setup
2682 cost in tls_init(). */
2683 require_ocsp = verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
2684 request_ocsp = require_ocsp
2685 || verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2692 SSL_set_tlsext_status_type(exim_client_ctx->ssl, TLSEXT_STATUSTYPE_ocsp);
2693 client_static_cbinfo->u_ocsp.client.verify_required = require_ocsp;
2694 tlsp->ocsp = OCSP_NOT_RESP;
2698 #ifndef DISABLE_EVENT
2699 client_static_cbinfo->event_action = tb ? tb->event_action : NULL;
2702 /* There doesn't seem to be a built-in timeout on connection. */
2704 DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
2705 sigalrm_seen = FALSE;
2706 ALARM(ob->command_timeout);
2707 rc = SSL_connect(exim_client_ctx->ssl);
2712 DANESSL_cleanup(exim_client_ctx->ssl);
2717 tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL, errstr);
2723 debug_printf("SSL_connect succeeded\n");
2724 #ifdef EXIM_HAVE_OPENSSL_KEYLOG
2726 BIO * bp = BIO_new(BIO_s_mem());
2729 SSL_SESSION_print_keylog(bp, SSL_get_session(server_ssl));
2730 len = (int) BIO_get_mem_data(bp, CSS &s);
2731 debug_printf("%.*s", len, s);
2737 peer_cert(exim_client_ctx->ssl, tlsp, peerdn, sizeof(peerdn));
2739 tlsp->cipher = construct_cipher_name(exim_client_ctx->ssl, &tlsp->bits);
2740 tlsp->cipher_stdname = cipher_stdname_ssl(exim_client_ctx->ssl);
2742 /* Record the certificate we presented */
2744 X509 * crt = SSL_get_certificate(exim_client_ctx->ssl);
2745 tlsp->ourcert = crt ? X509_dup(crt) : NULL;
2748 tlsp->active.sock = fd;
2749 tlsp->active.tls_ctx = exim_client_ctx;
2750 return exim_client_ctx;
2758 tls_refill(unsigned lim)
2763 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", server_ssl,
2764 ssl_xfer_buffer, ssl_xfer_buffer_size);
2766 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2767 inbytes = SSL_read(server_ssl, CS ssl_xfer_buffer,
2768 MIN(ssl_xfer_buffer_size, lim));
2769 error = SSL_get_error(server_ssl, inbytes);
2770 if (smtp_receive_timeout > 0) ALARM_CLR(0);
2772 if (had_command_timeout) /* set by signal handler */
2773 smtp_command_timeout_exit(); /* does not return */
2774 if (had_command_sigterm)
2775 smtp_command_sigterm_exit();
2776 if (had_data_timeout)
2777 smtp_data_timeout_exit();
2778 if (had_data_sigint)
2779 smtp_data_sigint_exit();
2781 /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
2782 closed down, not that the socket itself has been closed down. Revert to
2783 non-SSL handling. */
2787 case SSL_ERROR_NONE:
2790 case SSL_ERROR_ZERO_RETURN:
2791 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2793 receive_getc = smtp_getc;
2794 receive_getbuf = smtp_getbuf;
2795 receive_get_cache = smtp_get_cache;
2796 receive_ungetc = smtp_ungetc;
2797 receive_feof = smtp_feof;
2798 receive_ferror = smtp_ferror;
2799 receive_smtp_buffered = smtp_buffered;
2801 if (SSL_get_shutdown(server_ssl) == SSL_RECEIVED_SHUTDOWN)
2802 SSL_shutdown(server_ssl);
2804 #ifndef DISABLE_OCSP
2805 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
2806 server_static_cbinfo->verify_stack = NULL;
2808 SSL_free(server_ssl);
2809 SSL_CTX_free(server_ctx);
2812 tls_in.active.sock = -1;
2813 tls_in.active.tls_ctx = NULL;
2815 tls_in.cipher = NULL;
2816 tls_in.peerdn = NULL;
2821 /* Handle genuine errors */
2823 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
2824 log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
2825 ssl_xfer_error = TRUE;
2829 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
2830 DEBUG(D_tls) if (error == SSL_ERROR_SYSCALL)
2831 debug_printf(" - syscall %s\n", strerror(errno));
2832 ssl_xfer_error = TRUE;
2836 #ifndef DISABLE_DKIM
2837 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
2839 ssl_xfer_buffer_hwm = inbytes;
2840 ssl_xfer_buffer_lwm = 0;
2845 /*************************************************
2846 * TLS version of getc *
2847 *************************************************/
2849 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
2850 it refills the buffer via the SSL reading function.
2852 Arguments: lim Maximum amount to read/buffer
2853 Returns: the next character or EOF
2855 Only used by the server-side TLS.
2859 tls_getc(unsigned lim)
2861 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
2862 if (!tls_refill(lim))
2863 return ssl_xfer_error ? EOF : smtp_getc(lim);
2865 /* Something in the buffer; return next uschar */
2867 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
2871 tls_getbuf(unsigned * len)
2876 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
2877 if (!tls_refill(*len))
2879 if (!ssl_xfer_error) return smtp_getbuf(len);
2884 if ((size = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm) > *len)
2886 buf = &ssl_xfer_buffer[ssl_xfer_buffer_lwm];
2887 ssl_xfer_buffer_lwm += size;
2896 #ifndef DISABLE_DKIM
2897 int n = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm;
2899 dkim_exim_verify_feed(ssl_xfer_buffer+ssl_xfer_buffer_lwm, n);
2905 tls_could_read(void)
2907 return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm || SSL_pending(server_ssl) > 0;
2911 /*************************************************
2912 * Read bytes from TLS channel *
2913 *************************************************/
2917 ct_ctx client context pointer, or NULL for the one global server context
2921 Returns: the number of bytes read
2922 -1 after a failed read, including EOF
2924 Only used by the client-side TLS.
2928 tls_read(void * ct_ctx, uschar *buff, size_t len)
2930 SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
2934 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
2935 buff, (unsigned int)len);
2937 inbytes = SSL_read(ssl, CS buff, len);
2938 error = SSL_get_error(ssl, inbytes);
2940 if (error == SSL_ERROR_ZERO_RETURN)
2942 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2945 else if (error != SSL_ERROR_NONE)
2955 /*************************************************
2956 * Write bytes down TLS channel *
2957 *************************************************/
2961 ct_ctx client context pointer, or NULL for the one global server context
2964 more further data expected soon
2966 Returns: the number of bytes after a successful write,
2967 -1 after a failed write
2969 Used by both server-side and client-side TLS.
2973 tls_write(void * ct_ctx, const uschar *buff, size_t len, BOOL more)
2976 int outbytes, error;
2977 SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
2978 static gstring * corked = NULL;
2980 DEBUG(D_tls) debug_printf("%s(%p, %lu%s)\n", __FUNCTION__,
2981 buff, (unsigned long)len, more ? ", more" : "");
2983 /* Lacking a CORK or MSG_MORE facility (such as GnuTLS has) we copy data when
2984 "more" is notified. This hack is only ok if small amounts are involved AND only
2985 one stream does it, in one context (i.e. no store reset). Currently it is used
2986 for the responses to the received SMTP MAIL , RCPT, DATA sequence, only. */
2987 /* + if PIPE_COMMAND, banner & ehlo-resp for smmtp-on-connect. Suspect there's
2988 a store reset there, so use POOL_PERM. */
2989 /* + if CHUNKING, cmds EHLO,MAIL,RCPT(s),BDAT */
2991 if ((more || corked))
2993 #ifdef EXPERIMENTAL_PIPE_CONNECT
2994 int save_pool = store_pool;
2995 store_pool = POOL_PERM;
2998 corked = string_catn(corked, buff, len);
3000 #ifdef EXPERIMENTAL_PIPE_CONNECT
3001 store_pool = save_pool;
3006 buff = CUS corked->s;
3011 for (int left = len; left > 0;)
3013 DEBUG(D_tls) debug_printf("SSL_write(%p, %p, %d)\n", ssl, buff, left);
3014 outbytes = SSL_write(ssl, CS buff, left);
3015 error = SSL_get_error(ssl, outbytes);
3016 DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
3020 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3021 log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
3024 case SSL_ERROR_NONE:
3029 case SSL_ERROR_ZERO_RETURN:
3030 log_write(0, LOG_MAIN, "SSL channel closed on write");
3033 case SSL_ERROR_SYSCALL:
3034 log_write(0, LOG_MAIN, "SSL_write: (from %s) syscall: %s",
3035 sender_fullhost ? sender_fullhost : US"<unknown>",
3040 log_write(0, LOG_MAIN, "SSL_write error %d", error);
3049 /*************************************************
3050 * Close down a TLS session *
3051 *************************************************/
3053 /* This is also called from within a delivery subprocess forked from the
3054 daemon, to shut down the TLS library, without actually doing a shutdown (which
3055 would tamper with the SSL session in the parent process).
3058 ct_ctx client TLS context pointer, or NULL for the one global server context
3059 shutdown 1 if TLS close-alert is to be sent,
3060 2 if also response to be waited for
3064 Used by both server-side and client-side TLS.
3068 tls_close(void * ct_ctx, int shutdown)
3070 exim_openssl_client_tls_ctx * o_ctx = ct_ctx;
3071 SSL_CTX **ctxp = o_ctx ? &o_ctx->ctx : &server_ctx;
3072 SSL **sslp = o_ctx ? &o_ctx->ssl : &server_ssl;
3073 int *fdp = o_ctx ? &tls_out.active.sock : &tls_in.active.sock;
3075 if (*fdp < 0) return; /* TLS was not active */
3080 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
3081 shutdown > 1 ? " (with response-wait)" : "");
3083 if ( (rc = SSL_shutdown(*sslp)) == 0 /* send "close notify" alert */
3087 rc = SSL_shutdown(*sslp); /* wait for response */
3091 if (rc < 0) DEBUG(D_tls)
3093 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3094 debug_printf("SSL_shutdown: %s\n", ssl_errstring);
3098 #ifndef DISABLE_OCSP
3099 if (!o_ctx) /* server side */
3101 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
3102 server_static_cbinfo->verify_stack = NULL;
3106 SSL_CTX_free(*ctxp);
3116 /*************************************************
3117 * Let tls_require_ciphers be checked at startup *
3118 *************************************************/
3120 /* The tls_require_ciphers option, if set, must be something which the
3123 Returns: NULL on success, or error message
3127 tls_validate_require_cipher(void)
3130 uschar *s, *expciphers, *err;
3132 /* this duplicates from tls_init(), we need a better "init just global
3133 state, for no specific purpose" singleton function of our own */
3135 #ifdef EXIM_NEED_OPENSSL_INIT
3136 SSL_load_error_strings();
3137 OpenSSL_add_ssl_algorithms();
3139 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3140 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
3141 list of available digests. */
3142 EVP_add_digest(EVP_sha256());
3145 if (!(tls_require_ciphers && *tls_require_ciphers))
3148 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3150 return US"failed to expand tls_require_ciphers";
3152 if (!(expciphers && *expciphers))
3155 /* normalisation ripped from above */
3157 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
3161 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
3162 if (!(ctx = SSL_CTX_new(TLS_server_method())))
3164 if (!(ctx = SSL_CTX_new(SSLv23_server_method())))
3167 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3168 return string_sprintf("SSL_CTX_new() failed: %s", ssl_errstring);
3172 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3174 if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
3176 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3177 err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed: %s",
3178 expciphers, ssl_errstring);
3189 /*************************************************
3190 * Report the library versions. *
3191 *************************************************/
3193 /* There have historically been some issues with binary compatibility in
3194 OpenSSL libraries; if Exim (like many other applications) is built against
3195 one version of OpenSSL but the run-time linker picks up another version,
3196 it can result in serious failures, including crashing with a SIGSEGV. So
3197 report the version found by the compiler and the run-time version.
3199 Note: some OS vendors backport security fixes without changing the version
3200 number/string, and the version date remains unchanged. The _build_ date
3201 will change, so we can more usefully assist with version diagnosis by also
3202 reporting the build date.
3204 Arguments: a FILE* to print the results to
3209 tls_version_report(FILE *f)
3211 fprintf(f, "Library version: OpenSSL: Compile: %s\n"
3214 OPENSSL_VERSION_TEXT,
3215 SSLeay_version(SSLEAY_VERSION),
3216 SSLeay_version(SSLEAY_BUILT_ON));
3217 /* third line is 38 characters for the %s and the line is 73 chars long;
3218 the OpenSSL output includes a "built on: " prefix already. */
3224 /*************************************************
3225 * Random number generation *
3226 *************************************************/
3228 /* Pseudo-random number generation. The result is not expected to be
3229 cryptographically strong but not so weak that someone will shoot themselves
3230 in the foot using it as a nonce in input in some email header scheme or
3231 whatever weirdness they'll twist this into. The result should handle fork()
3232 and avoid repeating sequences. OpenSSL handles that for us.
3236 Returns a random number in range [0, max-1]
3240 vaguely_random_number(int max)
3244 static pid_t pidlast = 0;
3246 uschar smallbuf[sizeof(r)];
3252 if (pidnow != pidlast)
3254 /* Although OpenSSL documents that "OpenSSL makes sure that the PRNG state
3255 is unique for each thread", this doesn't apparently apply across processes,
3256 so our own warning from vaguely_random_number_fallback() applies here too.
3257 Fix per PostgreSQL. */
3263 /* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
3267 gettimeofday(&r.tv, NULL);
3270 RAND_seed(US (&r), sizeof(r));
3272 /* We're after pseudo-random, not random; if we still don't have enough data
3273 in the internal PRNG then our options are limited. We could sleep and hope
3274 for entropy to come along (prayer technique) but if the system is so depleted
3275 in the first place then something is likely to just keep taking it. Instead,
3276 we'll just take whatever little bit of pseudo-random we can still manage to
3279 needed_len = sizeof(r);
3280 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
3281 asked for a number less than 10. */
3282 for (r = max, i = 0; r; ++i)
3288 #ifdef EXIM_HAVE_RAND_PSEUDO
3289 /* We do not care if crypto-strong */
3290 i = RAND_pseudo_bytes(smallbuf, needed_len);
3292 i = RAND_bytes(smallbuf, needed_len);
3298 debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
3299 return vaguely_random_number_fallback(max);
3303 for (uschar * p = smallbuf; needed_len; --needed_len, ++p)
3306 /* We don't particularly care about weighted results; if someone wants
3307 smooth distribution and cares enough then they should submit a patch then. */
3314 /*************************************************
3315 * OpenSSL option parse *
3316 *************************************************/
3318 /* Parse one option for tls_openssl_options_parse below
3321 name one option name
3322 value place to store a value for it
3323 Returns success or failure in parsing
3329 tls_openssl_one_option_parse(uschar *name, long *value)
3332 int last = exim_openssl_options_size;
3333 while (last > first)
3335 int middle = (first + last)/2;
3336 int c = Ustrcmp(name, exim_openssl_options[middle].name);
3339 *value = exim_openssl_options[middle].value;
3353 /*************************************************
3354 * OpenSSL option parsing logic *
3355 *************************************************/
3357 /* OpenSSL has a number of compatibility options which an administrator might
3358 reasonably wish to set. Interpret a list similarly to decode_bits(), so that
3359 we look like log_selector.
3362 option_spec the administrator-supplied string of options
3363 results ptr to long storage for the options bitmap
3364 Returns success or failure
3368 tls_openssl_options_parse(uschar *option_spec, long *results)
3373 BOOL adding, item_parsed;
3375 result = SSL_OP_NO_TICKET;
3376 /* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
3377 * from default because it increases BEAST susceptibility. */
3378 #ifdef SSL_OP_NO_SSLv2
3379 result |= SSL_OP_NO_SSLv2;
3381 #ifdef SSL_OP_SINGLE_DH_USE
3382 result |= SSL_OP_SINGLE_DH_USE;
3391 for (uschar * s = option_spec; *s != '\0'; /**/)
3393 while (isspace(*s)) ++s;
3396 if (*s != '+' && *s != '-')
3398 DEBUG(D_tls) debug_printf("malformed openssl option setting: "
3399 "+ or - expected but found \"%s\"\n", s);
3402 adding = *s++ == '+';
3403 for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
3406 item_parsed = tls_openssl_one_option_parse(s, &item);
3410 DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
3413 DEBUG(D_tls) debug_printf("openssl option, %s from %lx: %lx (%s)\n",
3414 adding ? "adding" : "removing", result, item, s);
3426 #endif /*!MACRO_PREDEF*/
3429 /* End of tls-openssl.c */