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
58 * X509_check_host provides sane certificate hostname checking, but was added
59 * to OpenSSL late, after other projects forked off the code-base. So in
60 * addition to guarding against the base version number, beware that LibreSSL
61 * does not (at this time) support this function.
63 * If LibreSSL gains a different API, perhaps via libtls, then we'll probably
64 * opt to disentangle and ask a LibreSSL user to provide glue for a third
65 * crypto provider for libtls instead of continuing to tie the OpenSSL glue
66 * into even twistier knots. If LibreSSL gains the same API, we can just
67 * change this guard and punt the issue for a while longer.
69 #ifndef LIBRESSL_VERSION_NUMBER
70 # if OPENSSL_VERSION_NUMBER >= 0x010100000L
71 # define EXIM_HAVE_OPENSSL_CHECKHOST
72 # define EXIM_HAVE_OPENSSL_DH_BITS
73 # define EXIM_HAVE_OPENSSL_TLS_METHOD
75 # if OPENSSL_VERSION_NUMBER >= 0x010000000L \
76 && (OPENSSL_VERSION_NUMBER & 0x0000ff000L) >= 0x000002000L
77 # define EXIM_HAVE_OPENSSL_CHECKHOST
81 #if !defined(LIBRESSL_VERSION_NUMBER) \
82 || LIBRESSL_VERSION_NUMBER >= 0x20010000L
83 # if !defined(OPENSSL_NO_ECDH)
84 # if OPENSSL_VERSION_NUMBER >= 0x0090800fL
85 # define EXIM_HAVE_ECDH
87 # if OPENSSL_VERSION_NUMBER >= 0x10002000L
88 # define EXIM_HAVE_OPENSSL_EC_NIST2NID
93 #if !defined(EXIM_HAVE_OPENSSL_TLSEXT) && !defined(DISABLE_OCSP)
94 # warning "OpenSSL library version too old; define DISABLE_OCSP in Makefile"
98 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
99 # include <openssl/x509v3.h>
102 /*************************************************
103 * OpenSSL option parse *
104 *************************************************/
106 typedef struct exim_openssl_option {
109 } exim_openssl_option;
110 /* We could use a macro to expand, but we need the ifdef and not all the
111 options document which version they were introduced in. Policylet: include
112 all options unless explicitly for DTLS, let the administrator choose which
115 This list is current as of:
117 Plus SSL_OP_SAFARI_ECDHE_ECDSA_BUG from 2013-June patch/discussion on openssl-dev
118 Plus SSL_OP_NO_TLSv1_3 for 1.1.2-dev
120 static exim_openssl_option exim_openssl_options[] = {
121 /* KEEP SORTED ALPHABETICALLY! */
123 { US"all", SSL_OP_ALL },
125 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
126 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
128 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
129 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
131 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
132 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
134 #ifdef SSL_OP_EPHEMERAL_RSA
135 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
137 #ifdef SSL_OP_LEGACY_SERVER_CONNECT
138 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
140 #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
141 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
143 #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
144 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
146 #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
147 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
149 #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
150 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
152 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
153 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
155 #ifdef SSL_OP_NO_COMPRESSION
156 { US"no_compression", SSL_OP_NO_COMPRESSION },
158 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
159 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
161 #ifdef SSL_OP_NO_SSLv2
162 { US"no_sslv2", SSL_OP_NO_SSLv2 },
164 #ifdef SSL_OP_NO_SSLv3
165 { US"no_sslv3", SSL_OP_NO_SSLv3 },
167 #ifdef SSL_OP_NO_TICKET
168 { US"no_ticket", SSL_OP_NO_TICKET },
170 #ifdef SSL_OP_NO_TLSv1
171 { US"no_tlsv1", SSL_OP_NO_TLSv1 },
173 #ifdef SSL_OP_NO_TLSv1_1
174 #if SSL_OP_NO_TLSv1_1 == 0x00000400L
175 /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
176 #warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
178 { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
181 #ifdef SSL_OP_NO_TLSv1_2
182 { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
184 #ifdef SSL_OP_NO_TLSv1_3
185 { US"no_tlsv1_3", SSL_OP_NO_TLSv1_3 },
187 #ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
188 { US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
190 #ifdef SSL_OP_SINGLE_DH_USE
191 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
193 #ifdef SSL_OP_SINGLE_ECDH_USE
194 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
196 #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
197 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
199 #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
200 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
202 #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
203 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
205 #ifdef SSL_OP_TLS_D5_BUG
206 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
208 #ifdef SSL_OP_TLS_ROLLBACK_BUG
209 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
214 static int exim_openssl_options_size = nelem(exim_openssl_options);
221 struct exim_openssl_option * o;
224 for (o = exim_openssl_options;
225 o < exim_openssl_options + nelem(exim_openssl_options); o++)
227 /* Trailing X is workaround for problem with _OPT_OPENSSL_NO_TLSV1
228 being a ".ifdef _OPT_OPENSSL_NO_TLSV1_3" match */
230 spf(buf, sizeof(buf), US"_OPT_OPENSSL_%T_X", o->name);
231 builtin_macro_create(buf);
236 /******************************************************************************/
238 /* Structure for collecting random data for seeding. */
240 typedef struct randstuff {
245 /* Local static variables */
247 static BOOL client_verify_callback_called = FALSE;
248 static BOOL server_verify_callback_called = FALSE;
249 static const uschar *sid_ctx = US"exim";
251 /* We have three different contexts to care about.
253 Simple case: client, `client_ctx`
254 As a client, we can be doing a callout or cut-through delivery while receiving
255 a message. So we have a client context, which should have options initialised
256 from the SMTP Transport. We may also concurrently want to make TLS connections
257 to utility daemons, so client-contexts are allocated and passed around in call
258 args rather than using a gobal.
261 There are two cases: with and without ServerNameIndication from the client.
262 Given TLS SNI, we can be using different keys, certs and various other
263 configuration settings, because they're re-expanded with $tls_sni set. This
264 allows vhosting with TLS. This SNI is sent in the handshake.
265 A client might not send SNI, so we need a fallback, and an initial setup too.
266 So as a server, we start out using `server_ctx`.
267 If SNI is sent by the client, then we as server, mid-negotiation, try to clone
268 `server_sni` from `server_ctx` and then initialise settings by re-expanding
275 } exim_openssl_client_tls_ctx;
277 static SSL_CTX *server_ctx = NULL;
278 static SSL *server_ssl = NULL;
280 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
281 static SSL_CTX *server_sni = NULL;
284 static char ssl_errstring[256];
286 static int ssl_session_timeout = 200;
287 static BOOL client_verify_optional = FALSE;
288 static BOOL server_verify_optional = FALSE;
290 static BOOL reexpand_tls_files_for_sni = FALSE;
293 typedef struct tls_ext_ctx_cb {
298 STACK_OF(X509) *verify_stack; /* chain for verifying the proof */
302 uschar *file_expanded;
303 OCSP_RESPONSE *response;
306 X509_STORE *verify_store; /* non-null if status requested */
307 BOOL verify_required;
312 /* these are cached from first expand */
313 uschar *server_cipher_list;
314 /* only passed down to tls_error: */
316 const uschar * verify_cert_hostnames;
317 #ifndef DISABLE_EVENT
318 uschar * event_action;
322 /* should figure out a cleanup of API to handle state preserved per
323 implementation, for various reasons, which can be void * in the APIs.
324 For now, we hack around it. */
325 tls_ext_ctx_cb *client_static_cbinfo = NULL;
326 tls_ext_ctx_cb *server_static_cbinfo = NULL;
329 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
330 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr );
333 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
334 static int tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg);
337 static int tls_server_stapling_cb(SSL *s, void *arg);
341 /*************************************************
343 *************************************************/
345 /* Called from lots of places when errors occur before actually starting to do
346 the TLS handshake, that is, while the session is still in clear. Always returns
347 DEFER for a server and FAIL for a client so that most calls can use "return
348 tls_error(...)" to do this processing and then give an appropriate return. A
349 single function is used for both server and client, because it is called from
350 some shared functions.
353 prefix text to include in the logged error
354 host NULL if setting up a server;
355 the connected host if setting up a client
356 msg error message or NULL if we should ask OpenSSL
357 errstr pointer to output error message
359 Returns: OK/DEFER/FAIL
363 tls_error(uschar * prefix, const host_item * host, uschar * msg, uschar ** errstr)
367 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
368 msg = US ssl_errstring;
371 if (errstr) *errstr = string_sprintf("(%s): %s", prefix, msg);
372 return host ? FAIL : DEFER;
377 /*************************************************
378 * Callback to generate RSA key *
379 *************************************************/
383 s SSL connection (not used)
387 Returns: pointer to generated key
391 rsa_callback(SSL *s, int export, int keylength)
394 #ifdef EXIM_HAVE_RSA_GENKEY_EX
395 BIGNUM *bn = BN_new();
398 export = export; /* Shut picky compilers up */
399 DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
401 #ifdef EXIM_HAVE_RSA_GENKEY_EX
402 if ( !BN_set_word(bn, (unsigned long)RSA_F4)
403 || !(rsa_key = RSA_new())
404 || !RSA_generate_key_ex(rsa_key, keylength, bn, NULL)
407 if (!(rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL)))
411 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
412 log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
424 x509_store_dump_cert_s_names(X509_STORE * store)
426 STACK_OF(X509_OBJECT) * roots= store->objs;
428 static uschar name[256];
430 for(i= 0; i<sk_X509_OBJECT_num(roots); i++)
432 X509_OBJECT * tmp_obj= sk_X509_OBJECT_value(roots, i);
433 if(tmp_obj->type == X509_LU_X509)
435 X509_NAME * sn = X509_get_subject_name(tmp_obj->data.x509);
436 if (X509_NAME_oneline(sn, CS name, sizeof(name)))
438 name[sizeof(name)-1] = '\0';
439 debug_printf(" %s\n", name);
448 #ifndef DISABLE_EVENT
450 verify_event(tls_support * tlsp, X509 * cert, int depth, const uschar * dn,
451 BOOL *calledp, const BOOL *optionalp, const uschar * what)
457 ev = tlsp == &tls_out ? client_static_cbinfo->event_action : event_action;
460 DEBUG(D_tls) debug_printf("verify_event: %s %d\n", what, depth);
461 old_cert = tlsp->peercert;
462 tlsp->peercert = X509_dup(cert);
463 /* NB we do not bother setting peerdn */
464 if ((yield = event_raise(ev, US"tls:cert", string_sprintf("%d", depth))))
466 log_write(0, LOG_MAIN, "[%s] %s verify denied by event-action: "
467 "depth=%d cert=%s: %s",
468 tlsp == &tls_out ? deliver_host_address : sender_host_address,
469 what, depth, dn, yield);
473 if (old_cert) tlsp->peercert = old_cert; /* restore 1st failing cert */
474 return 1; /* reject (leaving peercert set) */
476 DEBUG(D_tls) debug_printf("Event-action verify failure overridden "
477 "(host in tls_try_verify_hosts)\n");
479 X509_free(tlsp->peercert);
480 tlsp->peercert = old_cert;
486 /*************************************************
487 * Callback for verification *
488 *************************************************/
490 /* The SSL library does certificate verification if set up to do so. This
491 callback has the current yes/no state is in "state". If verification succeeded,
492 we set the certificate-verified flag. If verification failed, what happens
493 depends on whether the client is required to present a verifiable certificate
496 If verification is optional, we change the state to yes, but still log the
497 verification error. For some reason (it really would help to have proper
498 documentation of OpenSSL), this callback function then gets called again, this
499 time with state = 1. We must take care not to set the private verified flag on
500 the second time through.
502 Note: this function is not called if the client fails to present a certificate
503 when asked. We get here only if a certificate has been received. Handling of
504 optional verification for this case is done when requesting SSL to verify, by
505 setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
507 May be called multiple times for different issues with a certificate, even
508 for a given "depth" in the certificate chain.
511 preverify_ok current yes/no state as 1/0
512 x509ctx certificate information.
513 tlsp per-direction (client vs. server) support data
514 calledp has-been-called flag
515 optionalp verification-is-optional flag
517 Returns: 0 if verification should fail, otherwise 1
521 verify_callback(int preverify_ok, X509_STORE_CTX * x509ctx,
522 tls_support * tlsp, BOOL * calledp, BOOL * optionalp)
524 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
525 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
528 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
530 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
531 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
532 tlsp == &tls_out ? deliver_host_address : sender_host_address);
535 dn[sizeof(dn)-1] = '\0';
537 if (preverify_ok == 0)
539 uschar * extra = verify_mode ? string_sprintf(" (during %c-verify for [%s])",
540 *verify_mode, sender_host_address)
542 log_write(0, LOG_MAIN, "[%s] SSL verify error%s: depth=%d error=%s cert=%s",
543 tlsp == &tls_out ? deliver_host_address : sender_host_address,
545 X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509ctx)), dn);
550 tlsp->peercert = X509_dup(cert); /* record failing cert */
551 return 0; /* reject */
553 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
554 "tls_try_verify_hosts)\n");
559 DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d SN=%s\n", depth, dn);
561 if (tlsp == &tls_out && client_static_cbinfo->u_ocsp.client.verify_store)
562 { /* client, wanting stapling */
563 /* Add the server cert's signing chain as the one
564 for the verification of the OCSP stapled information. */
566 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
569 sk_X509_push(client_static_cbinfo->verify_stack, cert);
572 #ifndef DISABLE_EVENT
573 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
574 return 0; /* reject, with peercert set */
579 const uschar * verify_cert_hostnames;
581 if ( tlsp == &tls_out
582 && ((verify_cert_hostnames = client_static_cbinfo->verify_cert_hostnames)))
583 /* client, wanting hostname check */
586 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
587 # ifndef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
588 # define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0
590 # ifndef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
591 # define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0
594 const uschar * list = verify_cert_hostnames;
597 while ((name = string_nextinlist(&list, &sep, NULL, 0)))
598 if ((rc = X509_check_host(cert, CCS name, 0,
599 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
600 | X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS,
605 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
606 tlsp == &tls_out ? deliver_host_address : sender_host_address);
613 if (!tls_is_name_for_cert(verify_cert_hostnames, cert))
616 uschar * extra = verify_mode
617 ? string_sprintf(" (during %c-verify for [%s])",
618 *verify_mode, sender_host_address)
620 log_write(0, LOG_MAIN,
621 "[%s] SSL verify error%s: certificate name mismatch: DN=\"%s\" H=\"%s\"",
622 tlsp == &tls_out ? deliver_host_address : sender_host_address,
623 extra, dn, verify_cert_hostnames);
628 tlsp->peercert = X509_dup(cert); /* record failing cert */
629 return 0; /* reject */
631 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
632 "tls_try_verify_hosts)\n");
636 #ifndef DISABLE_EVENT
637 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
638 return 0; /* reject, with peercert set */
641 DEBUG(D_tls) debug_printf("SSL%s verify ok: depth=0 SN=%s\n",
642 *calledp ? "" : " authenticated", dn);
643 if (!*calledp) tlsp->certificate_verified = TRUE;
647 return 1; /* accept, at least for this level */
651 verify_callback_client(int preverify_ok, X509_STORE_CTX *x509ctx)
653 return verify_callback(preverify_ok, x509ctx, &tls_out,
654 &client_verify_callback_called, &client_verify_optional);
658 verify_callback_server(int preverify_ok, X509_STORE_CTX *x509ctx)
660 return verify_callback(preverify_ok, x509ctx, &tls_in,
661 &server_verify_callback_called, &server_verify_optional);
667 /* This gets called *by* the dane library verify callback, which interposes
671 verify_callback_client_dane(int preverify_ok, X509_STORE_CTX * x509ctx)
673 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
675 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
676 #ifndef DISABLE_EVENT
677 BOOL dummy_called, optional = FALSE;
680 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
682 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
683 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
684 deliver_host_address);
687 dn[sizeof(dn)-1] = '\0';
689 DEBUG(D_tls) debug_printf("verify_callback_client_dane: %s depth %d %s\n",
690 preverify_ok ? "ok":"BAD", depth, dn);
692 #ifndef DISABLE_EVENT
693 if (verify_event(&tls_out, cert, depth, dn,
694 &dummy_called, &optional, US"DANE"))
695 return 0; /* reject, with peercert set */
698 if (preverify_ok == 1)
700 tls_out.dane_verified = tls_out.certificate_verified = TRUE;
702 if (client_static_cbinfo->u_ocsp.client.verify_store)
703 { /* client, wanting stapling */
704 /* Add the server cert's signing chain as the one
705 for the verification of the OCSP stapled information. */
707 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
710 sk_X509_push(client_static_cbinfo->verify_stack, cert);
716 int err = X509_STORE_CTX_get_error(x509ctx);
718 debug_printf(" - err %d '%s'\n", err, X509_verify_cert_error_string(err));
719 if (err == X509_V_ERR_APPLICATION_VERIFICATION)
725 #endif /*SUPPORT_DANE*/
728 /*************************************************
729 * Information callback *
730 *************************************************/
732 /* The SSL library functions call this from time to time to indicate what they
733 are doing. We copy the string to the debugging output when TLS debugging has
745 info_callback(SSL *s, int where, int ret)
751 if (where & SSL_ST_CONNECT)
752 str = US"SSL_connect";
753 else if (where & SSL_ST_ACCEPT)
754 str = US"SSL_accept";
756 str = US"SSL info (undefined)";
758 if (where & SSL_CB_LOOP)
759 debug_printf("%s: %s\n", str, SSL_state_string_long(s));
760 else if (where & SSL_CB_ALERT)
761 debug_printf("SSL3 alert %s:%s:%s\n",
762 str = where & SSL_CB_READ ? US"read" : US"write",
763 SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
764 else if (where & SSL_CB_EXIT)
766 debug_printf("%s: failed in %s\n", str, SSL_state_string_long(s));
768 debug_printf("%s: error in %s\n", str, SSL_state_string_long(s));
769 else if (where & SSL_CB_HANDSHAKE_START)
770 debug_printf("%s: hshake start: %s\n", str, SSL_state_string_long(s));
771 else if (where & SSL_CB_HANDSHAKE_DONE)
772 debug_printf("%s: hshake done: %s\n", str, SSL_state_string_long(s));
778 /*************************************************
779 * Initialize for DH *
780 *************************************************/
782 /* If dhparam is set, expand it, and load up the parameters for DH encryption.
785 sctx The current SSL CTX (inbound or outbound)
786 dhparam DH parameter file or fixed parameter identity string
787 host connected host, if client; NULL if server
788 errstr error string pointer
790 Returns: TRUE if OK (nothing to set up, or setup worked)
794 init_dh(SSL_CTX *sctx, uschar *dhparam, const host_item *host, uschar ** errstr)
802 if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded, errstr))
805 if (!dhexpanded || !*dhexpanded)
806 bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
807 else if (dhexpanded[0] == '/')
809 if (!(bio = BIO_new_file(CS dhexpanded, "r")))
811 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
812 host, US strerror(errno), errstr);
818 if (Ustrcmp(dhexpanded, "none") == 0)
820 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
824 if (!(pem = std_dh_prime_named(dhexpanded)))
826 tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
827 host, US strerror(errno), errstr);
830 bio = BIO_new_mem_buf(CS pem, -1);
833 if (!(dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)))
836 tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
841 /* note: our default limit of 2236 is not a multiple of 8; the limit comes from
842 * an NSS limit, and the GnuTLS APIs handle bit-sizes fine, so we went with
843 * 2236. But older OpenSSL can only report in bytes (octets), not bits.
844 * If someone wants to dance at the edge, then they can raise the limit or use
845 * current libraries. */
846 #ifdef EXIM_HAVE_OPENSSL_DH_BITS
847 /* Added in commit 26c79d5641d; `git describe --contains` says OpenSSL_1_1_0-pre1~1022
848 * This predates OpenSSL_1_1_0 (before a, b, ...) so is in all 1.1.0 */
849 dh_bitsize = DH_bits(dh);
851 dh_bitsize = 8 * DH_size(dh);
854 /* Even if it is larger, we silently return success rather than cause things
855 * to fail out, so that a too-large DH will not knock out all TLS; it's a
856 * debatable choice. */
857 if (dh_bitsize > tls_dh_max_bits)
860 debug_printf("dhparams file %d bits, is > tls_dh_max_bits limit of %d\n",
861 dh_bitsize, tls_dh_max_bits);
865 SSL_CTX_set_tmp_dh(sctx, dh);
867 debug_printf("Diffie-Hellman initialized from %s with %d-bit prime\n",
868 dhexpanded ? dhexpanded : US"default", dh_bitsize);
880 /*************************************************
881 * Initialize for ECDH *
882 *************************************************/
884 /* Load parameters for ECDH encryption.
886 For now, we stick to NIST P-256 because: it's simple and easy to configure;
887 it avoids any patent issues that might bite redistributors; despite events in
888 the news and concerns over curve choices, we're not cryptographers, we're not
889 pretending to be, and this is "good enough" to be better than no support,
890 protecting against most adversaries. Given another year or two, there might
891 be sufficient clarity about a "right" way forward to let us make an informed
892 decision, instead of a knee-jerk reaction.
894 Longer-term, we should look at supporting both various named curves and
895 external files generated with "openssl ecparam", much as we do for init_dh().
896 We should also support "none" as a value, to explicitly avoid initialisation.
901 sctx The current SSL CTX (inbound or outbound)
902 host connected host, if client; NULL if server
903 errstr error string pointer
905 Returns: TRUE if OK (nothing to set up, or setup worked)
909 init_ecdh(SSL_CTX * sctx, host_item * host, uschar ** errstr)
911 #ifdef OPENSSL_NO_ECDH
920 if (host) /* No ECDH setup for clients, only for servers */
923 # ifndef EXIM_HAVE_ECDH
925 debug_printf("No OpenSSL API to define ECDH parameters, skipping\n");
929 if (!expand_check(tls_eccurve, US"tls_eccurve", &exp_curve, errstr))
931 if (!exp_curve || !*exp_curve)
934 /* "auto" needs to be handled carefully.
935 * OpenSSL < 1.0.2: we do not select anything, but fallback to prime256v1
936 * OpenSSL < 1.1.0: we have to call SSL_CTX_set_ecdh_auto
937 * (openssl/ssl.h defines SSL_CTRL_SET_ECDH_AUTO)
938 * OpenSSL >= 1.1.0: we do not set anything, the libray does autoselection
939 * https://github.com/openssl/openssl/commit/fe6ef2472db933f01b59cad82aa925736935984b
941 if (Ustrcmp(exp_curve, "auto") == 0)
943 #if OPENSSL_VERSION_NUMBER < 0x10002000L
944 DEBUG(D_tls) debug_printf(
945 "ECDH OpenSSL < 1.0.2: temp key parameter settings: overriding \"auto\" with \"prime256v1\"\n");
946 exp_curve = US"prime256v1";
948 # if defined SSL_CTRL_SET_ECDH_AUTO
949 DEBUG(D_tls) debug_printf(
950 "ECDH OpenSSL 1.0.2+ temp key parameter settings: autoselection\n");
951 SSL_CTX_set_ecdh_auto(sctx, 1);
954 DEBUG(D_tls) debug_printf(
955 "ECDH OpenSSL 1.1.0+ temp key parameter settings: default selection\n");
961 DEBUG(D_tls) debug_printf("ECDH: curve '%s'\n", exp_curve);
962 if ( (nid = OBJ_sn2nid (CCS exp_curve)) == NID_undef
963 # ifdef EXIM_HAVE_OPENSSL_EC_NIST2NID
964 && (nid = EC_curve_nist2nid(CCS exp_curve)) == NID_undef
968 tls_error(string_sprintf("Unknown curve name tls_eccurve '%s'", exp_curve),
973 if (!(ecdh = EC_KEY_new_by_curve_name(nid)))
975 tls_error(US"Unable to create ec curve", host, NULL, errstr);
979 /* The "tmp" in the name here refers to setting a temporary key
980 not to the stability of the interface. */
982 if ((rv = SSL_CTX_set_tmp_ecdh(sctx, ecdh) == 0))
983 tls_error(string_sprintf("Error enabling '%s' curve", exp_curve), host, NULL, errstr);
985 DEBUG(D_tls) debug_printf("ECDH: enabled '%s' curve\n", exp_curve);
990 # endif /*EXIM_HAVE_ECDH*/
991 #endif /*OPENSSL_NO_ECDH*/
998 /*************************************************
999 * Load OCSP information into state *
1000 *************************************************/
1001 /* Called to load the server OCSP response from the given file into memory, once
1002 caller has determined this is needed. Checks validity. Debugs a message
1005 ASSUMES: single response, for single cert.
1008 sctx the SSL_CTX* to update
1009 cbinfo various parts of session state
1010 expanded the filename putatively holding an OCSP response
1015 ocsp_load_response(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo, const uschar *expanded)
1018 OCSP_RESPONSE * resp;
1019 OCSP_BASICRESP * basic_response;
1020 OCSP_SINGLERESP * single_response;
1021 ASN1_GENERALIZEDTIME * rev, * thisupd, * nextupd;
1022 STACK_OF(X509) * sk;
1023 unsigned long verify_flags;
1024 int status, reason, i;
1026 cbinfo->u_ocsp.server.file_expanded = string_copy(expanded);
1027 if (cbinfo->u_ocsp.server.response)
1029 OCSP_RESPONSE_free(cbinfo->u_ocsp.server.response);
1030 cbinfo->u_ocsp.server.response = NULL;
1033 if (!(bio = BIO_new_file(CS cbinfo->u_ocsp.server.file_expanded, "rb")))
1035 DEBUG(D_tls) debug_printf("Failed to open OCSP response file \"%s\"\n",
1036 cbinfo->u_ocsp.server.file_expanded);
1040 resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
1044 DEBUG(D_tls) debug_printf("Error reading OCSP response.\n");
1048 if ((status = OCSP_response_status(resp)) != OCSP_RESPONSE_STATUS_SUCCESSFUL)
1050 DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n",
1051 OCSP_response_status_str(status), status);
1055 if (!(basic_response = OCSP_response_get1_basic(resp)))
1058 debug_printf("OCSP response parse error: unable to extract basic response.\n");
1062 sk = cbinfo->verify_stack;
1063 verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */
1065 /* May need to expose ability to adjust those flags?
1066 OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
1067 OCSP_TRUSTOTHER OCSP_NOINTERN */
1069 /* This does a full verify on the OCSP proof before we load it for serving
1070 up; possibly overkill - just date-checks might be nice enough.
1072 OCSP_basic_verify takes a "store" arg, but does not
1073 use it for the chain verification, which is all we do
1074 when OCSP_NOVERIFY is set. The content from the wire
1075 "basic_response" and a cert-stack "sk" are all that is used.
1077 We have a stack, loaded in setup_certs() if tls_verify_certificates
1078 was a file (not a directory, or "system"). It is unfortunate we
1079 cannot used the connection context store, as that would neatly
1080 handle the "system" case too, but there seems to be no library
1081 function for getting a stack from a store.
1082 [ In OpenSSL 1.1 - ? X509_STORE_CTX_get0_chain(ctx) ? ]
1083 We do not free the stack since it could be needed a second time for
1086 Separately we might try to replace using OCSP_basic_verify() - which seems to not
1087 be a public interface into the OpenSSL library (there's no manual entry) -
1088 But what with? We also use OCSP_basic_verify in the client stapling callback.
1089 And there we NEED it; we must verify that status... unless the
1090 library does it for us anyway? */
1092 if ((i = OCSP_basic_verify(basic_response, sk, NULL, verify_flags)) < 0)
1096 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1097 debug_printf("OCSP response verify failure: %s\n", US ssl_errstring);
1102 /* Here's the simplifying assumption: there's only one response, for the
1103 one certificate we use, and nothing for anything else in a chain. If this
1104 proves false, we need to extract a cert id from our issued cert
1105 (tls_certificate) and use that for OCSP_resp_find_status() (which finds the
1106 right cert in the stack and then calls OCSP_single_get0_status()).
1108 I'm hoping to avoid reworking a bunch more of how we handle state here. */
1110 if (!(single_response = OCSP_resp_get0(basic_response, 0)))
1113 debug_printf("Unable to get first response from OCSP basic response.\n");
1117 status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
1118 if (status != V_OCSP_CERTSTATUS_GOOD)
1120 DEBUG(D_tls) debug_printf("OCSP response bad cert status: %s (%d) %s (%d)\n",
1121 OCSP_cert_status_str(status), status,
1122 OCSP_crl_reason_str(reason), reason);
1126 if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1128 DEBUG(D_tls) debug_printf("OCSP status invalid times.\n");
1133 cbinfo->u_ocsp.server.response = resp; /*XXX stack?*/
1137 if (f.running_in_test_harness)
1139 extern char ** environ;
1141 if (environ) for (p = USS environ; *p; p++)
1142 if (Ustrncmp(*p, "EXIM_TESTHARNESS_DISABLE_OCSPVALIDITYCHECK", 42) == 0)
1144 DEBUG(D_tls) debug_printf("Supplying known bad OCSP response\n");
1145 goto supply_response;
1150 #endif /*!DISABLE_OCSP*/
1155 /* Create and install a selfsigned certificate, for use in server mode */
1158 tls_install_selfsign(SSL_CTX * sctx, uschar ** errstr)
1166 where = US"allocating pkey";
1167 if (!(pkey = EVP_PKEY_new()))
1170 where = US"allocating cert";
1171 if (!(x509 = X509_new()))
1174 where = US"generating pkey";
1175 if (!(rsa = rsa_callback(NULL, 0, 1024)))
1178 where = US"assigning pkey";
1179 if (!EVP_PKEY_assign_RSA(pkey, rsa))
1182 X509_set_version(x509, 2); /* N+1 - version 3 */
1183 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
1184 X509_gmtime_adj(X509_get_notBefore(x509), 0);
1185 X509_gmtime_adj(X509_get_notAfter(x509), (long)60 * 60); /* 1 hour */
1186 X509_set_pubkey(x509, pkey);
1188 name = X509_get_subject_name(x509);
1189 X509_NAME_add_entry_by_txt(name, "C",
1190 MBSTRING_ASC, CUS "UK", -1, -1, 0);
1191 X509_NAME_add_entry_by_txt(name, "O",
1192 MBSTRING_ASC, CUS "Exim Developers", -1, -1, 0);
1193 X509_NAME_add_entry_by_txt(name, "CN",
1194 MBSTRING_ASC, CUS smtp_active_hostname, -1, -1, 0);
1195 X509_set_issuer_name(x509, name);
1197 where = US"signing cert";
1198 if (!X509_sign(x509, pkey, EVP_md5()))
1201 where = US"installing selfsign cert";
1202 if (!SSL_CTX_use_certificate(sctx, x509))
1205 where = US"installing selfsign key";
1206 if (!SSL_CTX_use_PrivateKey(sctx, pkey))
1212 (void) tls_error(where, NULL, NULL, errstr);
1213 if (x509) X509_free(x509);
1214 if (pkey) EVP_PKEY_free(pkey);
1222 tls_add_certfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1225 DEBUG(D_tls) debug_printf("tls_certificate file %s\n", file);
1226 if (!SSL_CTX_use_certificate_chain_file(sctx, CS file))
1227 return tls_error(string_sprintf(
1228 "SSL_CTX_use_certificate_chain_file file=%s", file),
1229 cbinfo->host, NULL, errstr);
1234 tls_add_pkeyfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1237 DEBUG(D_tls) debug_printf("tls_privatekey file %s\n", file);
1238 if (!SSL_CTX_use_PrivateKey_file(sctx, CS file, SSL_FILETYPE_PEM))
1239 return tls_error(string_sprintf(
1240 "SSL_CTX_use_PrivateKey_file file=%s", file), cbinfo->host, NULL, errstr);
1245 /*************************************************
1246 * Expand key and cert file specs *
1247 *************************************************/
1249 /* Called once during tls_init and possibly again during TLS setup, for a
1250 new context, if Server Name Indication was used and tls_sni was seen in
1251 the certificate string.
1254 sctx the SSL_CTX* to update
1255 cbinfo various parts of session state
1256 errstr error string pointer
1258 Returns: OK/DEFER/FAIL
1262 tls_expand_session_files(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo,
1267 if (!cbinfo->certificate)
1269 if (!cbinfo->is_server) /* client */
1272 if (tls_install_selfsign(sctx, errstr) != OK)
1279 if (Ustrstr(cbinfo->certificate, US"tls_sni") ||
1280 Ustrstr(cbinfo->certificate, US"tls_in_sni") ||
1281 Ustrstr(cbinfo->certificate, US"tls_out_sni")
1283 reexpand_tls_files_for_sni = TRUE;
1285 if (!expand_check(cbinfo->certificate, US"tls_certificate", &expanded, errstr))
1289 if (cbinfo->is_server)
1291 const uschar * file_list = expanded;
1295 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1296 if ((err = tls_add_certfile(sctx, cbinfo, file, errstr)))
1299 else /* would there ever be a need for multiple client certs? */
1300 if ((err = tls_add_certfile(sctx, cbinfo, expanded, errstr)))
1303 if (cbinfo->privatekey != NULL &&
1304 !expand_check(cbinfo->privatekey, US"tls_privatekey", &expanded, errstr))
1307 /* If expansion was forced to fail, key_expanded will be NULL. If the result
1308 of the expansion is an empty string, ignore it also, and assume the private
1309 key is in the same file as the certificate. */
1311 if (expanded && *expanded)
1312 if (cbinfo->is_server)
1314 const uschar * file_list = expanded;
1318 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1319 if ((err = tls_add_pkeyfile(sctx, cbinfo, file, errstr)))
1322 else /* would there ever be a need for multiple client certs? */
1323 if ((err = tls_add_pkeyfile(sctx, cbinfo, expanded, errstr)))
1327 #ifndef DISABLE_OCSP
1328 if (cbinfo->is_server && cbinfo->u_ocsp.server.file)
1331 if (!expand_check(cbinfo->u_ocsp.server.file, US"tls_ocsp_file", &expanded, errstr))
1334 if (expanded && *expanded)
1336 DEBUG(D_tls) debug_printf("tls_ocsp_file %s\n", expanded);
1337 if ( cbinfo->u_ocsp.server.file_expanded
1338 && (Ustrcmp(expanded, cbinfo->u_ocsp.server.file_expanded) == 0))
1340 DEBUG(D_tls) debug_printf(" - value unchanged, using existing values\n");
1343 ocsp_load_response(sctx, cbinfo, expanded);
1354 /*************************************************
1355 * Callback to handle SNI *
1356 *************************************************/
1358 /* Called when acting as server during the TLS session setup if a Server Name
1359 Indication extension was sent by the client.
1361 API documentation is OpenSSL s_server.c implementation.
1364 s SSL* of the current session
1365 ad unknown (part of OpenSSL API) (unused)
1366 arg Callback of "our" registered data
1368 Returns: SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
1371 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
1373 tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg)
1375 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1376 tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1378 int old_pool = store_pool;
1379 uschar * dummy_errstr;
1382 return SSL_TLSEXT_ERR_OK;
1384 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
1385 reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
1387 /* Make the extension value available for expansion */
1388 store_pool = POOL_PERM;
1389 tls_in.sni = string_copy(US servername);
1390 store_pool = old_pool;
1392 if (!reexpand_tls_files_for_sni)
1393 return SSL_TLSEXT_ERR_OK;
1395 /* Can't find an SSL_CTX_clone() or equivalent, so we do it manually;
1396 not confident that memcpy wouldn't break some internal reference counting.
1397 Especially since there's a references struct member, which would be off. */
1399 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1400 if (!(server_sni = SSL_CTX_new(TLS_server_method())))
1402 if (!(server_sni = SSL_CTX_new(SSLv23_server_method())))
1405 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1406 DEBUG(D_tls) debug_printf("SSL_CTX_new() failed: %s\n", ssl_errstring);
1407 return SSL_TLSEXT_ERR_NOACK;
1410 /* Not sure how many of these are actually needed, since SSL object
1411 already exists. Might even need this selfsame callback, for reneg? */
1413 SSL_CTX_set_info_callback(server_sni, SSL_CTX_get_info_callback(server_ctx));
1414 SSL_CTX_set_mode(server_sni, SSL_CTX_get_mode(server_ctx));
1415 SSL_CTX_set_options(server_sni, SSL_CTX_get_options(server_ctx));
1416 SSL_CTX_set_timeout(server_sni, SSL_CTX_get_timeout(server_ctx));
1417 SSL_CTX_set_tlsext_servername_callback(server_sni, tls_servername_cb);
1418 SSL_CTX_set_tlsext_servername_arg(server_sni, cbinfo);
1420 if ( !init_dh(server_sni, cbinfo->dhparam, NULL, &dummy_errstr)
1421 || !init_ecdh(server_sni, NULL, &dummy_errstr)
1423 return SSL_TLSEXT_ERR_NOACK;
1425 if ( cbinfo->server_cipher_list
1426 && !SSL_CTX_set_cipher_list(server_sni, CS cbinfo->server_cipher_list))
1427 return SSL_TLSEXT_ERR_NOACK;
1429 #ifndef DISABLE_OCSP
1430 if (cbinfo->u_ocsp.server.file)
1432 SSL_CTX_set_tlsext_status_cb(server_sni, tls_server_stapling_cb);
1433 SSL_CTX_set_tlsext_status_arg(server_sni, cbinfo);
1437 if ((rc = setup_certs(server_sni, tls_verify_certificates, tls_crl, NULL, FALSE,
1438 verify_callback_server, &dummy_errstr)) != OK)
1439 return SSL_TLSEXT_ERR_NOACK;
1441 /* do this after setup_certs, because this can require the certs for verifying
1442 OCSP information. */
1443 if ((rc = tls_expand_session_files(server_sni, cbinfo, &dummy_errstr)) != OK)
1444 return SSL_TLSEXT_ERR_NOACK;
1446 DEBUG(D_tls) debug_printf("Switching SSL context.\n");
1447 SSL_set_SSL_CTX(s, server_sni);
1449 return SSL_TLSEXT_ERR_OK;
1451 #endif /* EXIM_HAVE_OPENSSL_TLSEXT */
1456 #ifndef DISABLE_OCSP
1458 /*************************************************
1459 * Callback to handle OCSP Stapling *
1460 *************************************************/
1462 /* Called when acting as server during the TLS session setup if the client
1463 requests OCSP information with a Certificate Status Request.
1465 Documentation via openssl s_server.c and the Apache patch from the OpenSSL
1471 tls_server_stapling_cb(SSL *s, void *arg)
1473 const tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1474 uschar *response_der; /*XXX blob */
1475 int response_der_len;
1477 /*XXX stack: use SSL_get_certificate() to see which cert; from that work
1478 out which ocsp blob to send. Unfortunately, SSL_get_certificate is known
1479 buggy in current OpenSSL; it returns the last cert loaded always rather than
1480 the one actually presented. So we can't support a stack of OCSP proofs at
1484 debug_printf("Received TLS status request (OCSP stapling); %s response\n",
1485 cbinfo->u_ocsp.server.response ? "have" : "lack");
1487 tls_in.ocsp = OCSP_NOT_RESP;
1488 if (!cbinfo->u_ocsp.server.response)
1489 return SSL_TLSEXT_ERR_NOACK;
1491 response_der = NULL;
1492 response_der_len = i2d_OCSP_RESPONSE(cbinfo->u_ocsp.server.response, /*XXX stack*/
1494 if (response_der_len <= 0)
1495 return SSL_TLSEXT_ERR_NOACK;
1497 SSL_set_tlsext_status_ocsp_resp(server_ssl, response_der, response_der_len);
1498 tls_in.ocsp = OCSP_VFIED;
1499 return SSL_TLSEXT_ERR_OK;
1504 time_print(BIO * bp, const char * str, ASN1_GENERALIZEDTIME * time)
1506 BIO_printf(bp, "\t%s: ", str);
1507 ASN1_GENERALIZEDTIME_print(bp, time);
1512 tls_client_stapling_cb(SSL *s, void *arg)
1514 tls_ext_ctx_cb * cbinfo = arg;
1515 const unsigned char * p;
1517 OCSP_RESPONSE * rsp;
1518 OCSP_BASICRESP * bs;
1521 DEBUG(D_tls) debug_printf("Received TLS status response (OCSP stapling):");
1522 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1525 /* Expect this when we requested ocsp but got none */
1526 if (cbinfo->u_ocsp.client.verify_required && LOGGING(tls_cipher))
1527 log_write(0, LOG_MAIN, "Received TLS status callback, null content");
1529 DEBUG(D_tls) debug_printf(" null\n");
1530 return cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1533 if(!(rsp = d2i_OCSP_RESPONSE(NULL, &p, len)))
1535 tls_out.ocsp = OCSP_FAILED;
1536 if (LOGGING(tls_cipher))
1537 log_write(0, LOG_MAIN, "Received TLS cert status response, parse error");
1539 DEBUG(D_tls) debug_printf(" parse error\n");
1543 if(!(bs = OCSP_response_get1_basic(rsp)))
1545 tls_out.ocsp = OCSP_FAILED;
1546 if (LOGGING(tls_cipher))
1547 log_write(0, LOG_MAIN, "Received TLS cert status response, error parsing response");
1549 DEBUG(D_tls) debug_printf(" error parsing response\n");
1550 OCSP_RESPONSE_free(rsp);
1554 /* We'd check the nonce here if we'd put one in the request. */
1555 /* However that would defeat cacheability on the server so we don't. */
1557 /* This section of code reworked from OpenSSL apps source;
1558 The OpenSSL Project retains copyright:
1559 Copyright (c) 1999 The OpenSSL Project. All rights reserved.
1564 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1566 DEBUG(D_tls) bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
1568 /*OCSP_RESPONSE_print(bp, rsp, 0); extreme debug: stapling content */
1570 /* Use the chain that verified the server cert to verify the stapled info */
1571 /* DEBUG(D_tls) x509_store_dump_cert_s_names(cbinfo->u_ocsp.client.verify_store); */
1573 if ((i = OCSP_basic_verify(bs, cbinfo->verify_stack,
1574 cbinfo->u_ocsp.client.verify_store, 0)) <= 0)
1576 tls_out.ocsp = OCSP_FAILED;
1577 if (LOGGING(tls_cipher)) log_write(0, LOG_MAIN,
1578 "Received TLS cert status response, itself unverifiable: %s",
1579 ERR_reason_error_string(ERR_peek_error()));
1580 BIO_printf(bp, "OCSP response verify failure\n");
1581 ERR_print_errors(bp);
1582 OCSP_RESPONSE_print(bp, rsp, 0);
1586 BIO_printf(bp, "OCSP response well-formed and signed OK\n");
1588 /*XXX So we have a good stapled OCSP status. How do we know
1589 it is for the cert of interest? OpenSSL 1.1.0 has a routine
1590 OCSP_resp_find_status() which matches on a cert id, which presumably
1591 we should use. Making an id needs OCSP_cert_id_new(), which takes
1592 issuerName, issuerKey, serialNumber. Are they all in the cert?
1594 For now, carry on blindly accepting the resp. */
1597 OCSP_SINGLERESP * single;
1599 #ifdef EXIM_HAVE_OCSP_RESP_COUNT
1600 if (OCSP_resp_count(bs) != 1)
1602 STACK_OF(OCSP_SINGLERESP) * sresp = bs->tbsResponseData->responses;
1603 if (sk_OCSP_SINGLERESP_num(sresp) != 1)
1606 tls_out.ocsp = OCSP_FAILED;
1607 log_write(0, LOG_MAIN, "OCSP stapling "
1608 "with multiple responses not handled");
1611 single = OCSP_resp_get0(bs, 0);
1612 status = OCSP_single_get0_status(single, &reason, &rev,
1613 &thisupd, &nextupd);
1616 DEBUG(D_tls) time_print(bp, "This OCSP Update", thisupd);
1617 DEBUG(D_tls) if(nextupd) time_print(bp, "Next OCSP Update", nextupd);
1618 if (!OCSP_check_validity(thisupd, nextupd,
1619 EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1621 tls_out.ocsp = OCSP_FAILED;
1622 DEBUG(D_tls) ERR_print_errors(bp);
1623 log_write(0, LOG_MAIN, "Server OSCP dates invalid");
1627 DEBUG(D_tls) BIO_printf(bp, "Certificate status: %s\n",
1628 OCSP_cert_status_str(status));
1631 case V_OCSP_CERTSTATUS_GOOD:
1632 tls_out.ocsp = OCSP_VFIED;
1635 case V_OCSP_CERTSTATUS_REVOKED:
1636 tls_out.ocsp = OCSP_FAILED;
1637 log_write(0, LOG_MAIN, "Server certificate revoked%s%s",
1638 reason != -1 ? "; reason: " : "",
1639 reason != -1 ? OCSP_crl_reason_str(reason) : "");
1640 DEBUG(D_tls) time_print(bp, "Revocation Time", rev);
1643 tls_out.ocsp = OCSP_FAILED;
1644 log_write(0, LOG_MAIN,
1645 "Server certificate status unknown, in OCSP stapling");
1650 i = cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1655 OCSP_RESPONSE_free(rsp);
1658 #endif /*!DISABLE_OCSP*/
1661 /*************************************************
1662 * Initialize for TLS *
1663 *************************************************/
1665 /* Called from both server and client code, to do preliminary initialization
1666 of the library. We allocate and return a context structure.
1669 ctxp returned SSL context
1670 host connected host, if client; NULL if server
1671 dhparam DH parameter file
1672 certificate certificate file
1673 privatekey private key
1674 ocsp_file file of stapling info (server); flag for require ocsp (client)
1675 addr address if client; NULL if server (for some randomness)
1676 cbp place to put allocated callback context
1677 errstr error string pointer
1679 Returns: OK/DEFER/FAIL
1683 tls_init(SSL_CTX **ctxp, host_item *host, uschar *dhparam, uschar *certificate,
1685 #ifndef DISABLE_OCSP
1686 uschar *ocsp_file, /*XXX stack, in server*/
1688 address_item *addr, tls_ext_ctx_cb ** cbp, uschar ** errstr)
1693 tls_ext_ctx_cb * cbinfo;
1695 cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
1696 cbinfo->certificate = certificate;
1697 cbinfo->privatekey = privatekey;
1698 cbinfo->is_server = host==NULL;
1699 #ifndef DISABLE_OCSP
1700 cbinfo->verify_stack = NULL;
1703 cbinfo->u_ocsp.server.file = ocsp_file;
1704 cbinfo->u_ocsp.server.file_expanded = NULL;
1705 cbinfo->u_ocsp.server.response = NULL;
1708 cbinfo->u_ocsp.client.verify_store = NULL;
1710 cbinfo->dhparam = dhparam;
1711 cbinfo->server_cipher_list = NULL;
1712 cbinfo->host = host;
1713 #ifndef DISABLE_EVENT
1714 cbinfo->event_action = NULL;
1717 SSL_load_error_strings(); /* basic set up */
1718 OpenSSL_add_ssl_algorithms();
1720 #ifdef EXIM_HAVE_SHA256
1721 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
1722 list of available digests. */
1723 EVP_add_digest(EVP_sha256());
1726 /* Create a context.
1727 The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
1728 negotiation in the different methods; as far as I can tell, the only
1729 *_{server,client}_method which allows negotiation is SSLv23, which exists even
1730 when OpenSSL is built without SSLv2 support.
1731 By disabling with openssl_options, we can let admins re-enable with the
1734 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1735 if (!(ctx = SSL_CTX_new(host ? TLS_client_method() : TLS_server_method())))
1737 if (!(ctx = SSL_CTX_new(host ? SSLv23_client_method() : SSLv23_server_method())))
1739 return tls_error(US"SSL_CTX_new", host, NULL, errstr);
1741 /* It turns out that we need to seed the random number generator this early in
1742 order to get the full complement of ciphers to work. It took me roughly a day
1743 of work to discover this by experiment.
1745 On systems that have /dev/urandom, SSL may automatically seed itself from
1746 there. Otherwise, we have to make something up as best we can. Double check
1752 gettimeofday(&r.tv, NULL);
1755 RAND_seed(US (&r), sizeof(r));
1756 RAND_seed(US big_buffer, big_buffer_size);
1757 if (addr != NULL) RAND_seed(US addr, sizeof(addr));
1760 return tls_error(US"RAND_status", host,
1761 US"unable to seed random number generator", errstr);
1764 /* Set up the information callback, which outputs if debugging is at a suitable
1767 DEBUG(D_tls) SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
1769 /* Automatically re-try reads/writes after renegotiation. */
1770 (void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1772 /* Apply administrator-supplied work-arounds.
1773 Historically we applied just one requested option,
1774 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
1775 moved to an administrator-controlled list of options to specify and
1776 grandfathered in the first one as the default value for "openssl_options".
1778 No OpenSSL version number checks: the options we accept depend upon the
1779 availability of the option value macros from OpenSSL. */
1781 if (!tls_openssl_options_parse(openssl_options, &init_options))
1782 return tls_error(US"openssl_options parsing failed", host, NULL, errstr);
1786 DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
1787 if (!(SSL_CTX_set_options(ctx, init_options)))
1788 return tls_error(string_sprintf(
1789 "SSL_CTX_set_option(%#lx)", init_options), host, NULL, errstr);
1792 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
1794 /* We'd like to disable session cache unconditionally, but foolish Outlook
1795 Express clients then give up the first TLS connection and make a second one
1796 (which works). Only when there is an IMAP service on the same machine.
1797 Presumably OE is trying to use the cache for A on B. Leave it enabled for
1798 now, until we work out a decent way of presenting control to the config. It
1799 will never be used because we use a new context every time. */
1801 (void) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1804 /* Initialize with DH parameters if supplied */
1805 /* Initialize ECDH temp key parameter selection */
1807 if ( !init_dh(ctx, dhparam, host, errstr)
1808 || !init_ecdh(ctx, host, errstr)
1812 /* Set up certificate and key (and perhaps OCSP info) */
1814 if ((rc = tls_expand_session_files(ctx, cbinfo, errstr)) != OK)
1817 /* If we need to handle SNI or OCSP, do so */
1819 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
1820 # ifndef DISABLE_OCSP
1821 if (!(cbinfo->verify_stack = sk_X509_new_null()))
1823 DEBUG(D_tls) debug_printf("failed to create stack for stapling verify\n");
1828 if (!host) /* server */
1830 # ifndef DISABLE_OCSP
1831 /* We check u_ocsp.server.file, not server.response, because we care about if
1832 the option exists, not what the current expansion might be, as SNI might
1833 change the certificate and OCSP file in use between now and the time the
1834 callback is invoked. */
1835 if (cbinfo->u_ocsp.server.file)
1837 SSL_CTX_set_tlsext_status_cb(ctx, tls_server_stapling_cb);
1838 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
1841 /* We always do this, so that $tls_sni is available even if not used in
1843 SSL_CTX_set_tlsext_servername_callback(ctx, tls_servername_cb);
1844 SSL_CTX_set_tlsext_servername_arg(ctx, cbinfo);
1846 # ifndef DISABLE_OCSP
1848 if(ocsp_file) /* wanting stapling */
1850 if (!(cbinfo->u_ocsp.client.verify_store = X509_STORE_new()))
1852 DEBUG(D_tls) debug_printf("failed to create store for stapling verify\n");
1855 SSL_CTX_set_tlsext_status_cb(ctx, tls_client_stapling_cb);
1856 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
1861 cbinfo->verify_cert_hostnames = NULL;
1863 #ifdef EXIM_HAVE_EPHEM_RSA_KEX
1864 /* Set up the RSA callback */
1865 SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
1868 /* Finally, set the timeout, and we are done */
1870 SSL_CTX_set_timeout(ctx, ssl_session_timeout);
1871 DEBUG(D_tls) debug_printf("Initialized TLS\n");
1882 /*************************************************
1883 * Get name of cipher in use *
1884 *************************************************/
1887 Argument: pointer to an SSL structure for the connection
1888 buffer to use for answer
1890 pointer to number of bits for cipher
1895 construct_cipher_name(SSL *ssl, uschar *cipherbuf, int bsize, int *bits)
1897 /* With OpenSSL 1.0.0a, 'c' needs to be const but the documentation doesn't
1898 yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
1899 the accessor functions use const in the prototype. */
1901 const uschar * ver = CUS SSL_get_version(ssl);
1902 const SSL_CIPHER * c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
1904 SSL_CIPHER_get_bits(c, bits);
1906 string_format(cipherbuf, bsize, "%s:%s:%u", ver,
1907 SSL_CIPHER_get_name(c), *bits);
1909 DEBUG(D_tls) debug_printf("Cipher: %s\n", cipherbuf);
1914 peer_cert(SSL * ssl, tls_support * tlsp, uschar * peerdn, unsigned siz)
1916 /*XXX we might consider a list-of-certs variable for the cert chain.
1917 SSL_get_peer_cert_chain(SSL*). We'd need a new variable type and support
1918 in list-handling functions, also consider the difference between the entire
1919 chain and the elements sent by the peer. */
1921 tlsp->peerdn = NULL;
1923 /* Will have already noted peercert on a verify fail; possibly not the leaf */
1924 if (!tlsp->peercert)
1925 tlsp->peercert = SSL_get_peer_certificate(ssl);
1926 /* Beware anonymous ciphers which lead to server_cert being NULL */
1928 if (!X509_NAME_oneline(X509_get_subject_name(tlsp->peercert), CS peerdn, siz))
1929 { DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n"); }
1932 peerdn[siz-1] = '\0';
1933 tlsp->peerdn = peerdn; /*XXX a static buffer... */
1941 /*************************************************
1942 * Set up for verifying certificates *
1943 *************************************************/
1945 #ifndef DISABLE_OCSP
1946 /* Load certs from file, return TRUE on success */
1949 chain_from_pem_file(const uschar * file, STACK_OF(X509) * verify_stack)
1954 while (sk_X509_num(verify_stack) > 0)
1955 X509_free(sk_X509_pop(verify_stack));
1957 if (!(bp = BIO_new_file(CS file, "r"))) return FALSE;
1958 while ((x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
1959 sk_X509_push(verify_stack, x);
1967 /* Called by both client and server startup; on the server possibly
1968 repeated after a Server Name Indication.
1971 sctx SSL_CTX* to initialise
1972 certs certs file or NULL
1973 crl CRL file or NULL
1974 host NULL in a server; the remote host in a client
1975 optional TRUE if called from a server for a host in tls_try_verify_hosts;
1976 otherwise passed as FALSE
1977 cert_vfy_cb Callback function for certificate verification
1978 errstr error string pointer
1980 Returns: OK/DEFER/FAIL
1984 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
1985 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr)
1987 uschar *expcerts, *expcrl;
1989 if (!expand_check(certs, US"tls_verify_certificates", &expcerts, errstr))
1991 DEBUG(D_tls) debug_printf("tls_verify_certificates: %s\n", expcerts);
1993 if (expcerts && *expcerts)
1995 /* Tell the library to use its compiled-in location for the system default
1996 CA bundle. Then add the ones specified in the config, if any. */
1998 if (!SSL_CTX_set_default_verify_paths(sctx))
1999 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL, errstr);
2001 if (Ustrcmp(expcerts, "system") != 0)
2003 struct stat statbuf;
2005 if (Ustat(expcerts, &statbuf) < 0)
2007 log_write(0, LOG_MAIN|LOG_PANIC,
2008 "failed to stat %s for certificates", expcerts);
2014 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
2015 { file = NULL; dir = expcerts; }
2018 file = expcerts; dir = NULL;
2019 #ifndef DISABLE_OCSP
2020 /* In the server if we will be offering an OCSP proof, load chain from
2021 file for verifying the OCSP proof at load time. */
2024 && statbuf.st_size > 0
2025 && server_static_cbinfo->u_ocsp.server.file
2026 && !chain_from_pem_file(file, server_static_cbinfo->verify_stack)
2029 log_write(0, LOG_MAIN|LOG_PANIC,
2030 "failed to load cert chain from %s", file);
2036 /* If a certificate file is empty, the next function fails with an
2037 unhelpful error message. If we skip it, we get the correct behaviour (no
2038 certificates are recognized, but the error message is still misleading (it
2039 says no certificate was supplied). But this is better. */
2041 if ( (!file || statbuf.st_size > 0)
2042 && !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
2043 return tls_error(US"SSL_CTX_load_verify_locations", host, NULL, errstr);
2045 /* Load the list of CAs for which we will accept certs, for sending
2046 to the client. This is only for the one-file tls_verify_certificates
2048 If a list isn't loaded into the server, but
2049 some verify locations are set, the server end appears to make
2050 a wildcard request for client certs.
2051 Meanwhile, the client library as default behaviour *ignores* the list
2052 we send over the wire - see man SSL_CTX_set_client_cert_cb.
2053 Because of this, and that the dir variant is likely only used for
2054 the public-CA bundle (not for a private CA), not worth fixing.
2058 STACK_OF(X509_NAME) * names = SSL_load_client_CA_file(CS file);
2060 SSL_CTX_set_client_CA_list(sctx, names);
2061 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n",
2062 sk_X509_NAME_num(names));
2067 /* Handle a certificate revocation list. */
2069 #if OPENSSL_VERSION_NUMBER > 0x00907000L
2071 /* This bit of code is now the version supplied by Lars Mainka. (I have
2072 merely reformatted it into the Exim code style.)
2074 "From here I changed the code to add support for multiple crl's
2075 in pem format in one file or to support hashed directory entries in
2076 pem format instead of a file. This method now uses the library function
2077 X509_STORE_load_locations to add the CRL location to the SSL context.
2078 OpenSSL will then handle the verify against CA certs and CRLs by
2079 itself in the verify callback." */
2081 if (!expand_check(crl, US"tls_crl", &expcrl, errstr)) return DEFER;
2082 if (expcrl && *expcrl)
2084 struct stat statbufcrl;
2085 if (Ustat(expcrl, &statbufcrl) < 0)
2087 log_write(0, LOG_MAIN|LOG_PANIC,
2088 "failed to stat %s for certificates revocation lists", expcrl);
2093 /* is it a file or directory? */
2095 X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
2096 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
2100 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
2106 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
2108 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
2109 return tls_error(US"X509_STORE_load_locations", host, NULL, errstr);
2111 /* setting the flags to check against the complete crl chain */
2113 X509_STORE_set_flags(cvstore,
2114 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2118 #endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
2120 /* If verification is optional, don't fail if no certificate */
2122 SSL_CTX_set_verify(sctx,
2123 SSL_VERIFY_PEER | (optional? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
2132 /*************************************************
2133 * Start a TLS session in a server *
2134 *************************************************/
2136 /* This is called when Exim is running as a server, after having received
2137 the STARTTLS command. It must respond to that command, and then negotiate
2141 require_ciphers allowed ciphers
2142 errstr pointer to error message
2144 Returns: OK on success
2145 DEFER for errors before the start of the negotiation
2146 FAIL for errors during the negotiation; the server can't
2151 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
2154 uschar * expciphers;
2155 tls_ext_ctx_cb * cbinfo;
2156 static uschar peerdn[256];
2157 static uschar cipherbuf[256];
2159 /* Check for previous activation */
2161 if (tls_in.active.sock >= 0)
2163 tls_error(US"STARTTLS received after TLS started", NULL, US"", errstr);
2164 smtp_printf("554 Already in TLS\r\n", FALSE);
2168 /* Initialize the SSL library. If it fails, it will already have logged
2171 rc = tls_init(&server_ctx, NULL, tls_dhparam, tls_certificate, tls_privatekey,
2172 #ifndef DISABLE_OCSP
2173 tls_ocsp_file, /*XXX stack*/
2175 NULL, &server_static_cbinfo, errstr);
2176 if (rc != OK) return rc;
2177 cbinfo = server_static_cbinfo;
2179 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers, errstr))
2182 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2183 were historically separated by underscores. So that I can use either form in my
2184 tests, and also for general convenience, we turn underscores into hyphens here.
2186 XXX SSL_CTX_set_cipher_list() is replaced by SSL_CTX_set_ciphersuites()
2187 for TLS 1.3 . Since we do not call it at present we get the default list:
2188 TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
2193 uschar * s = expciphers;
2194 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
2195 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
2196 if (!SSL_CTX_set_cipher_list(server_ctx, CS expciphers))
2197 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL, errstr);
2198 cbinfo->server_cipher_list = expciphers;
2201 /* If this is a host for which certificate verification is mandatory or
2202 optional, set up appropriately. */
2204 tls_in.certificate_verified = FALSE;
2206 tls_in.dane_verified = FALSE;
2208 server_verify_callback_called = FALSE;
2210 if (verify_check_host(&tls_verify_hosts) == OK)
2212 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
2213 FALSE, verify_callback_server, errstr);
2214 if (rc != OK) return rc;
2215 server_verify_optional = FALSE;
2217 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2219 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
2220 TRUE, verify_callback_server, errstr);
2221 if (rc != OK) return rc;
2222 server_verify_optional = TRUE;
2225 /* Prepare for new connection */
2227 if (!(server_ssl = SSL_new(server_ctx)))
2228 return tls_error(US"SSL_new", NULL, NULL, errstr);
2230 /* Warning: we used to SSL_clear(ssl) here, it was removed.
2232 * With the SSL_clear(), we get strange interoperability bugs with
2233 * OpenSSL 1.0.1b and TLS1.1/1.2. It looks as though this may be a bug in
2234 * OpenSSL itself, as a clear should not lead to inability to follow protocols.
2236 * The SSL_clear() call is to let an existing SSL* be reused, typically after
2237 * session shutdown. In this case, we have a brand new object and there's no
2238 * obvious reason to immediately clear it. I'm guessing that this was
2239 * originally added because of incomplete initialisation which the clear fixed,
2240 * in some historic release.
2243 /* Set context and tell client to go ahead, except in the case of TLS startup
2244 on connection, where outputting anything now upsets the clients and tends to
2245 make them disconnect. We need to have an explicit fflush() here, to force out
2246 the response. Other smtp_printf() calls do not need it, because in non-TLS
2247 mode, the fflush() happens when smtp_getc() is called. */
2249 SSL_set_session_id_context(server_ssl, sid_ctx, Ustrlen(sid_ctx));
2250 if (!tls_in.on_connect)
2252 smtp_printf("220 TLS go ahead\r\n", FALSE);
2256 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2257 that the OpenSSL library doesn't. */
2259 SSL_set_wfd(server_ssl, fileno(smtp_out));
2260 SSL_set_rfd(server_ssl, fileno(smtp_in));
2261 SSL_set_accept_state(server_ssl);
2263 DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
2265 sigalrm_seen = FALSE;
2266 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2267 rc = SSL_accept(server_ssl);
2272 (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
2276 DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
2278 /* TLS has been set up. Adjust the input functions to read via TLS,
2279 and initialize things. */
2281 peer_cert(server_ssl, &tls_in, peerdn, sizeof(peerdn));
2283 construct_cipher_name(server_ssl, cipherbuf, sizeof(cipherbuf), &tls_in.bits);
2284 tls_in.cipher = cipherbuf;
2289 if (SSL_get_shared_ciphers(server_ssl, CS buf, sizeof(buf)) != NULL)
2290 debug_printf("Shared ciphers: %s\n", buf);
2293 /* Record the certificate we presented */
2295 X509 * crt = SSL_get_certificate(server_ssl);
2296 tls_in.ourcert = crt ? X509_dup(crt) : NULL;
2299 /* Only used by the server-side tls (tls_in), including tls_getc.
2300 Client-side (tls_out) reads (seem to?) go via
2301 smtp_read_response()/ip_recv().
2302 Hence no need to duplicate for _in and _out.
2304 if (!ssl_xfer_buffer) ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2305 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
2306 ssl_xfer_eof = ssl_xfer_error = FALSE;
2308 receive_getc = tls_getc;
2309 receive_getbuf = tls_getbuf;
2310 receive_get_cache = tls_get_cache;
2311 receive_ungetc = tls_ungetc;
2312 receive_feof = tls_feof;
2313 receive_ferror = tls_ferror;
2314 receive_smtp_buffered = tls_smtp_buffered;
2316 tls_in.active.sock = fileno(smtp_out);
2317 tls_in.active.tls_ctx = NULL; /* not using explicit ctx for server-side */
2325 tls_client_basic_ctx_init(SSL_CTX * ctx,
2326 host_item * host, smtp_transport_options_block * ob, tls_ext_ctx_cb * cbinfo,
2330 /* stick to the old behaviour for compatibility if tls_verify_certificates is
2331 set but both tls_verify_hosts and tls_try_verify_hosts is not set. Check only
2332 the specified host patterns if one of them is defined */
2334 if ( ( !ob->tls_verify_hosts
2335 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2337 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
2339 client_verify_optional = FALSE;
2340 else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
2341 client_verify_optional = TRUE;
2345 if ((rc = setup_certs(ctx, ob->tls_verify_certificates,
2346 ob->tls_crl, host, client_verify_optional, verify_callback_client,
2350 if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
2352 cbinfo->verify_cert_hostnames =
2354 string_domain_utf8_to_alabel(host->name, NULL);
2358 DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
2359 cbinfo->verify_cert_hostnames);
2367 dane_tlsa_load(SSL * ssl, host_item * host, dns_answer * dnsa, uschar ** errstr)
2371 const char * hostnames[2] = { CS host->name, NULL };
2374 if (DANESSL_init(ssl, NULL, hostnames) != 1)
2375 return tls_error(US"hostnames load", host, NULL, errstr);
2377 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
2379 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2380 ) if (rr->type == T_TLSA && rr->size > 3)
2382 const uschar * p = rr->data;
2383 uint8_t usage, selector, mtype;
2384 const char * mdname;
2388 /* Only DANE-TA(2) and DANE-EE(3) are supported */
2389 if (usage != 2 && usage != 3) continue;
2396 default: continue; /* Only match-types 0, 1, 2 are supported */
2397 case 0: mdname = NULL; break;
2398 case 1: mdname = "sha256"; break;
2399 case 2: mdname = "sha512"; break;
2403 switch (DANESSL_add_tlsa(ssl, usage, selector, mdname, p, rr->size - 3))
2406 return tls_error(US"tlsa load", host, NULL, errstr);
2407 case 0: /* action not taken */
2411 tls_out.tlsa_usage |= 1<<usage;
2417 log_write(0, LOG_MAIN, "DANE error: No usable TLSA records");
2420 #endif /*SUPPORT_DANE*/
2424 /*************************************************
2425 * Start a TLS session in a client *
2426 *************************************************/
2428 /* Called from the smtp transport after STARTTLS has been accepted.
2431 fd the fd of the connection
2432 host connected host (for messages and option-tests)
2433 addr the first address (for some randomness; can be NULL)
2434 tb transport (always smtp)
2435 tlsa_dnsa tlsa lookup, if DANE, else null
2436 tlsp record details of channel configuration here; must be non-NULL
2437 errstr error string pointer
2439 Returns: Pointer to TLS session context, or NULL on error
2443 tls_client_start(int fd, host_item *host, address_item *addr,
2444 transport_instance * tb,
2446 dns_answer * tlsa_dnsa,
2448 tls_support * tlsp, uschar ** errstr)
2450 smtp_transport_options_block * ob = tb
2451 ? (smtp_transport_options_block *)tb->options_block
2452 : &smtp_transport_option_defaults;
2453 exim_openssl_client_tls_ctx * exim_client_ctx;
2454 static uschar peerdn[256];
2455 uschar * expciphers;
2457 static uschar cipherbuf[256];
2459 #ifndef DISABLE_OCSP
2460 BOOL request_ocsp = FALSE;
2461 BOOL require_ocsp = FALSE;
2465 store_pool = POOL_PERM;
2466 exim_client_ctx = store_get(sizeof(exim_openssl_client_tls_ctx));
2470 tlsp->tlsa_usage = 0;
2473 #ifndef DISABLE_OCSP
2475 # ifdef SUPPORT_DANE
2477 && ob->hosts_request_ocsp[0] == '*'
2478 && ob->hosts_request_ocsp[1] == '\0'
2481 /* Unchanged from default. Use a safer one under DANE */
2482 request_ocsp = TRUE;
2483 ob->hosts_request_ocsp = US"${if or { {= {0}{$tls_out_tlsa_usage}} "
2484 " {= {4}{$tls_out_tlsa_usage}} } "
2490 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK))
2491 request_ocsp = TRUE;
2493 # ifdef SUPPORT_DANE
2497 verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2501 rc = tls_init(&exim_client_ctx->ctx, host, NULL,
2502 ob->tls_certificate, ob->tls_privatekey,
2503 #ifndef DISABLE_OCSP
2504 (void *)(long)request_ocsp,
2506 addr, &client_static_cbinfo, errstr);
2507 if (rc != OK) return NULL;
2509 tlsp->certificate_verified = FALSE;
2510 client_verify_callback_called = FALSE;
2516 /* We fall back to tls_require_ciphers if unset, empty or forced failure, but
2517 other failures should be treated as problems. */
2518 if (ob->dane_require_tls_ciphers &&
2519 !expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2520 &expciphers, errstr))
2522 if (expciphers && *expciphers == '\0')
2527 !expand_check(ob->tls_require_ciphers, US"tls_require_ciphers",
2528 &expciphers, errstr))
2531 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2532 are separated by underscores. So that I can use either form in my tests, and
2533 also for general convenience, we turn underscores into hyphens here. */
2537 uschar *s = expciphers;
2538 while (*s) { if (*s == '_') *s = '-'; s++; }
2539 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
2540 if (!SSL_CTX_set_cipher_list(exim_client_ctx->ctx, CS expciphers))
2542 tls_error(US"SSL_CTX_set_cipher_list", host, NULL, errstr);
2550 SSL_CTX_set_verify(exim_client_ctx->ctx,
2551 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2552 verify_callback_client_dane);
2554 if (!DANESSL_library_init())
2556 tls_error(US"library init", host, NULL, errstr);
2559 if (DANESSL_CTX_init(exim_client_ctx->ctx) <= 0)
2561 tls_error(US"context init", host, NULL, errstr);
2569 if (tls_client_basic_ctx_init(exim_client_ctx->ctx, host, ob,
2570 client_static_cbinfo, errstr) != OK)
2573 if (!(exim_client_ctx->ssl = SSL_new(exim_client_ctx->ctx)))
2575 tls_error(US"SSL_new", host, NULL, errstr);
2578 SSL_set_session_id_context(exim_client_ctx->ssl, sid_ctx, Ustrlen(sid_ctx));
2579 SSL_set_fd(exim_client_ctx->ssl, fd);
2580 SSL_set_connect_state(exim_client_ctx->ssl);
2584 if (!expand_check(ob->tls_sni, US"tls_sni", &tlsp->sni, errstr))
2588 DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n");
2590 else if (!Ustrlen(tlsp->sni))
2594 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
2595 DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tlsp->sni);
2596 SSL_set_tlsext_host_name(exim_client_ctx->ssl, tlsp->sni);
2598 log_write(0, LOG_MAIN, "SNI unusable with this OpenSSL library version; ignoring \"%s\"\n",
2606 if (dane_tlsa_load(exim_client_ctx->ssl, host, tlsa_dnsa, errstr) != OK)
2610 #ifndef DISABLE_OCSP
2611 /* Request certificate status at connection-time. If the server
2612 does OCSP stapling we will get the callback (set in tls_init()) */
2613 # ifdef SUPPORT_DANE
2617 if ( ((s = ob->hosts_require_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
2618 || ((s = ob->hosts_request_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
2620 { /* Re-eval now $tls_out_tlsa_usage is populated. If
2621 this means we avoid the OCSP request, we wasted the setup
2622 cost in tls_init(). */
2623 require_ocsp = verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
2624 request_ocsp = require_ocsp
2625 || verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2632 SSL_set_tlsext_status_type(exim_client_ctx->ssl, TLSEXT_STATUSTYPE_ocsp);
2633 client_static_cbinfo->u_ocsp.client.verify_required = require_ocsp;
2634 tlsp->ocsp = OCSP_NOT_RESP;
2638 #ifndef DISABLE_EVENT
2639 client_static_cbinfo->event_action = tb ? tb->event_action : NULL;
2642 /* There doesn't seem to be a built-in timeout on connection. */
2644 DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
2645 sigalrm_seen = FALSE;
2646 ALARM(ob->command_timeout);
2647 rc = SSL_connect(exim_client_ctx->ssl);
2652 DANESSL_cleanup(exim_client_ctx->ssl);
2657 tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL, errstr);
2661 DEBUG(D_tls) debug_printf("SSL_connect succeeded\n");
2663 peer_cert(exim_client_ctx->ssl, tlsp, peerdn, sizeof(peerdn));
2665 construct_cipher_name(exim_client_ctx->ssl, cipherbuf, sizeof(cipherbuf), &tlsp->bits);
2666 tlsp->cipher = cipherbuf;
2668 /* Record the certificate we presented */
2670 X509 * crt = SSL_get_certificate(exim_client_ctx->ssl);
2671 tlsp->ourcert = crt ? X509_dup(crt) : NULL;
2674 tlsp->active.sock = fd;
2675 tlsp->active.tls_ctx = exim_client_ctx;
2676 return exim_client_ctx;
2684 tls_refill(unsigned lim)
2689 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", server_ssl,
2690 ssl_xfer_buffer, ssl_xfer_buffer_size);
2692 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2693 inbytes = SSL_read(server_ssl, CS ssl_xfer_buffer,
2694 MIN(ssl_xfer_buffer_size, lim));
2695 error = SSL_get_error(server_ssl, inbytes);
2696 if (smtp_receive_timeout > 0) ALARM_CLR(0);
2698 if (had_command_timeout) /* set by signal handler */
2699 smtp_command_timeout_exit(); /* does not return */
2700 if (had_command_sigterm)
2701 smtp_command_sigterm_exit();
2702 if (had_data_timeout)
2703 smtp_data_timeout_exit();
2704 if (had_data_sigint)
2705 smtp_data_sigint_exit();
2707 /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
2708 closed down, not that the socket itself has been closed down. Revert to
2709 non-SSL handling. */
2713 case SSL_ERROR_NONE:
2716 case SSL_ERROR_ZERO_RETURN:
2717 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2719 receive_getc = smtp_getc;
2720 receive_getbuf = smtp_getbuf;
2721 receive_get_cache = smtp_get_cache;
2722 receive_ungetc = smtp_ungetc;
2723 receive_feof = smtp_feof;
2724 receive_ferror = smtp_ferror;
2725 receive_smtp_buffered = smtp_buffered;
2727 if (SSL_get_shutdown(server_ssl) == SSL_RECEIVED_SHUTDOWN)
2728 SSL_shutdown(server_ssl);
2730 #ifndef DISABLE_OCSP
2731 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
2732 server_static_cbinfo->verify_stack = NULL;
2734 SSL_free(server_ssl);
2735 SSL_CTX_free(server_ctx);
2738 tls_in.active.sock = -1;
2739 tls_in.active.tls_ctx = NULL;
2741 tls_in.cipher = NULL;
2742 tls_in.peerdn = NULL;
2747 /* Handle genuine errors */
2749 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
2750 log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
2751 ssl_xfer_error = TRUE;
2755 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
2756 DEBUG(D_tls) if (error == SSL_ERROR_SYSCALL)
2757 debug_printf(" - syscall %s\n", strerror(errno));
2758 ssl_xfer_error = TRUE;
2762 #ifndef DISABLE_DKIM
2763 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
2765 ssl_xfer_buffer_hwm = inbytes;
2766 ssl_xfer_buffer_lwm = 0;
2771 /*************************************************
2772 * TLS version of getc *
2773 *************************************************/
2775 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
2776 it refills the buffer via the SSL reading function.
2778 Arguments: lim Maximum amount to read/buffer
2779 Returns: the next character or EOF
2781 Only used by the server-side TLS.
2785 tls_getc(unsigned lim)
2787 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
2788 if (!tls_refill(lim))
2789 return ssl_xfer_error ? EOF : smtp_getc(lim);
2791 /* Something in the buffer; return next uschar */
2793 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
2797 tls_getbuf(unsigned * len)
2802 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
2803 if (!tls_refill(*len))
2805 if (!ssl_xfer_error) return smtp_getbuf(len);
2810 if ((size = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm) > *len)
2812 buf = &ssl_xfer_buffer[ssl_xfer_buffer_lwm];
2813 ssl_xfer_buffer_lwm += size;
2822 #ifndef DISABLE_DKIM
2823 int n = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm;
2825 dkim_exim_verify_feed(ssl_xfer_buffer+ssl_xfer_buffer_lwm, n);
2831 tls_could_read(void)
2833 return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm || SSL_pending(server_ssl) > 0;
2837 /*************************************************
2838 * Read bytes from TLS channel *
2839 *************************************************/
2843 ct_ctx client context pointer, or NULL for the one global server context
2847 Returns: the number of bytes read
2848 -1 after a failed read, including EOF
2850 Only used by the client-side TLS.
2854 tls_read(void * ct_ctx, uschar *buff, size_t len)
2856 SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
2860 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
2861 buff, (unsigned int)len);
2863 inbytes = SSL_read(ssl, CS buff, len);
2864 error = SSL_get_error(ssl, inbytes);
2866 if (error == SSL_ERROR_ZERO_RETURN)
2868 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2871 else if (error != SSL_ERROR_NONE)
2881 /*************************************************
2882 * Write bytes down TLS channel *
2883 *************************************************/
2887 ct_ctx client context pointer, or NULL for the one global server context
2890 more further data expected soon
2892 Returns: the number of bytes after a successful write,
2893 -1 after a failed write
2895 Used by both server-side and client-side TLS.
2899 tls_write(void * ct_ctx, const uschar *buff, size_t len, BOOL more)
2901 int outbytes, error, left;
2902 SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
2903 static gstring * corked = NULL;
2905 DEBUG(D_tls) debug_printf("%s(%p, %lu%s)\n", __FUNCTION__,
2906 buff, (unsigned long)len, more ? ", more" : "");
2908 /* Lacking a CORK or MSG_MORE facility (such as GnuTLS has) we copy data when
2909 "more" is notified. This hack is only ok if small amounts are involved AND only
2910 one stream does it, in one context (i.e. no store reset). Currently it is used
2911 for the responses to the received SMTP MAIL , RCPT, DATA sequence, only. */
2913 if (!ct_ctx && (more || corked))
2915 corked = string_catn(corked, buff, len);
2918 buff = CUS corked->s;
2923 for (left = len; left > 0;)
2925 DEBUG(D_tls) debug_printf("SSL_write(%p, %p, %d)\n", ssl, buff, left);
2926 outbytes = SSL_write(ssl, CS buff, left);
2927 error = SSL_get_error(ssl, outbytes);
2928 DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
2932 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
2933 log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
2936 case SSL_ERROR_NONE:
2941 case SSL_ERROR_ZERO_RETURN:
2942 log_write(0, LOG_MAIN, "SSL channel closed on write");
2945 case SSL_ERROR_SYSCALL:
2946 log_write(0, LOG_MAIN, "SSL_write: (from %s) syscall: %s",
2947 sender_fullhost ? sender_fullhost : US"<unknown>",
2952 log_write(0, LOG_MAIN, "SSL_write error %d", error);
2961 /*************************************************
2962 * Close down a TLS session *
2963 *************************************************/
2965 /* This is also called from within a delivery subprocess forked from the
2966 daemon, to shut down the TLS library, without actually doing a shutdown (which
2967 would tamper with the SSL session in the parent process).
2970 ct_ctx client TLS context pointer, or NULL for the one global server context
2971 shutdown 1 if TLS close-alert is to be sent,
2972 2 if also response to be waited for
2976 Used by both server-side and client-side TLS.
2980 tls_close(void * ct_ctx, int shutdown)
2982 exim_openssl_client_tls_ctx * o_ctx = ct_ctx;
2983 SSL_CTX **ctxp = o_ctx ? &o_ctx->ctx : &server_ctx;
2984 SSL **sslp = o_ctx ? &o_ctx->ssl : &server_ssl;
2985 int *fdp = o_ctx ? &tls_out.active.sock : &tls_in.active.sock;
2987 if (*fdp < 0) return; /* TLS was not active */
2992 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
2993 shutdown > 1 ? " (with response-wait)" : "");
2995 if ( (rc = SSL_shutdown(*sslp)) == 0 /* send "close notify" alert */
2999 rc = SSL_shutdown(*sslp); /* wait for response */
3003 if (rc < 0) DEBUG(D_tls)
3005 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3006 debug_printf("SSL_shutdown: %s\n", ssl_errstring);
3010 #ifndef DISABLE_OCSP
3011 if (!o_ctx) /* server side */
3013 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
3014 server_static_cbinfo->verify_stack = NULL;
3018 SSL_CTX_free(*ctxp);
3028 /*************************************************
3029 * Let tls_require_ciphers be checked at startup *
3030 *************************************************/
3032 /* The tls_require_ciphers option, if set, must be something which the
3035 Returns: NULL on success, or error message
3039 tls_validate_require_cipher(void)
3042 uschar *s, *expciphers, *err;
3044 /* this duplicates from tls_init(), we need a better "init just global
3045 state, for no specific purpose" singleton function of our own */
3047 SSL_load_error_strings();
3048 OpenSSL_add_ssl_algorithms();
3049 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3050 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
3051 list of available digests. */
3052 EVP_add_digest(EVP_sha256());
3055 if (!(tls_require_ciphers && *tls_require_ciphers))
3058 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3060 return US"failed to expand tls_require_ciphers";
3062 if (!(expciphers && *expciphers))
3065 /* normalisation ripped from above */
3067 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
3071 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
3072 if (!(ctx = SSL_CTX_new(TLS_server_method())))
3074 if (!(ctx = SSL_CTX_new(SSLv23_server_method())))
3077 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3078 return string_sprintf("SSL_CTX_new() failed: %s", ssl_errstring);
3082 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3084 if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
3086 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3087 err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed: %s",
3088 expciphers, ssl_errstring);
3099 /*************************************************
3100 * Report the library versions. *
3101 *************************************************/
3103 /* There have historically been some issues with binary compatibility in
3104 OpenSSL libraries; if Exim (like many other applications) is built against
3105 one version of OpenSSL but the run-time linker picks up another version,
3106 it can result in serious failures, including crashing with a SIGSEGV. So
3107 report the version found by the compiler and the run-time version.
3109 Note: some OS vendors backport security fixes without changing the version
3110 number/string, and the version date remains unchanged. The _build_ date
3111 will change, so we can more usefully assist with version diagnosis by also
3112 reporting the build date.
3114 Arguments: a FILE* to print the results to
3119 tls_version_report(FILE *f)
3121 fprintf(f, "Library version: OpenSSL: Compile: %s\n"
3124 OPENSSL_VERSION_TEXT,
3125 SSLeay_version(SSLEAY_VERSION),
3126 SSLeay_version(SSLEAY_BUILT_ON));
3127 /* third line is 38 characters for the %s and the line is 73 chars long;
3128 the OpenSSL output includes a "built on: " prefix already. */
3134 /*************************************************
3135 * Random number generation *
3136 *************************************************/
3138 /* Pseudo-random number generation. The result is not expected to be
3139 cryptographically strong but not so weak that someone will shoot themselves
3140 in the foot using it as a nonce in input in some email header scheme or
3141 whatever weirdness they'll twist this into. The result should handle fork()
3142 and avoid repeating sequences. OpenSSL handles that for us.
3146 Returns a random number in range [0, max-1]
3150 vaguely_random_number(int max)
3154 static pid_t pidlast = 0;
3157 uschar smallbuf[sizeof(r)];
3163 if (pidnow != pidlast)
3165 /* Although OpenSSL documents that "OpenSSL makes sure that the PRNG state
3166 is unique for each thread", this doesn't apparently apply across processes,
3167 so our own warning from vaguely_random_number_fallback() applies here too.
3168 Fix per PostgreSQL. */
3174 /* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
3178 gettimeofday(&r.tv, NULL);
3181 RAND_seed(US (&r), sizeof(r));
3183 /* We're after pseudo-random, not random; if we still don't have enough data
3184 in the internal PRNG then our options are limited. We could sleep and hope
3185 for entropy to come along (prayer technique) but if the system is so depleted
3186 in the first place then something is likely to just keep taking it. Instead,
3187 we'll just take whatever little bit of pseudo-random we can still manage to
3190 needed_len = sizeof(r);
3191 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
3192 asked for a number less than 10. */
3193 for (r = max, i = 0; r; ++i)
3199 #ifdef EXIM_HAVE_RAND_PSEUDO
3200 /* We do not care if crypto-strong */
3201 i = RAND_pseudo_bytes(smallbuf, needed_len);
3203 i = RAND_bytes(smallbuf, needed_len);
3209 debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
3210 return vaguely_random_number_fallback(max);
3214 for (p = smallbuf; needed_len; --needed_len, ++p)
3220 /* We don't particularly care about weighted results; if someone wants
3221 smooth distribution and cares enough then they should submit a patch then. */
3228 /*************************************************
3229 * OpenSSL option parse *
3230 *************************************************/
3232 /* Parse one option for tls_openssl_options_parse below
3235 name one option name
3236 value place to store a value for it
3237 Returns success or failure in parsing
3243 tls_openssl_one_option_parse(uschar *name, long *value)
3246 int last = exim_openssl_options_size;
3247 while (last > first)
3249 int middle = (first + last)/2;
3250 int c = Ustrcmp(name, exim_openssl_options[middle].name);
3253 *value = exim_openssl_options[middle].value;
3267 /*************************************************
3268 * OpenSSL option parsing logic *
3269 *************************************************/
3271 /* OpenSSL has a number of compatibility options which an administrator might
3272 reasonably wish to set. Interpret a list similarly to decode_bits(), so that
3273 we look like log_selector.
3276 option_spec the administrator-supplied string of options
3277 results ptr to long storage for the options bitmap
3278 Returns success or failure
3282 tls_openssl_options_parse(uschar *option_spec, long *results)
3287 BOOL adding, item_parsed;
3289 result = SSL_OP_NO_TICKET;
3290 /* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
3291 * from default because it increases BEAST susceptibility. */
3292 #ifdef SSL_OP_NO_SSLv2
3293 result |= SSL_OP_NO_SSLv2;
3295 #ifdef SSL_OP_SINGLE_DH_USE
3296 result |= SSL_OP_SINGLE_DH_USE;
3305 for (s=option_spec; *s != '\0'; /**/)
3307 while (isspace(*s)) ++s;
3310 if (*s != '+' && *s != '-')
3312 DEBUG(D_tls) debug_printf("malformed openssl option setting: "
3313 "+ or - expected but found \"%s\"\n", s);
3316 adding = *s++ == '+';
3317 for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
3320 item_parsed = tls_openssl_one_option_parse(s, &item);
3324 DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
3327 DEBUG(D_tls) debug_printf("openssl option, %s from %lx: %lx (%s)\n",
3328 adding ? "adding" : "removing", result, item, s);
3340 #endif /*!MACRO_PREDEF*/
3343 /* End of tls-openssl.c */