1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2020 - 2024 */
6 /* Copyright (c) University of Cambridge 1995 - 2019 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
10 /* Portions Copyright (c) The OpenSSL Project 1999 */
12 /* This module provides the TLS (aka SSL) support for Exim using the OpenSSL
13 library. It is #included into the tls.c file when that library is used. The
14 code herein is based on a patch that was originally contributed by Steve
15 Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
17 No cryptographic code is included in Exim. All this module does is to call
18 functions from the OpenSSL library. */
23 #include <openssl/lhash.h>
24 #include <openssl/ssl.h>
25 #include <openssl/err.h>
26 #include <openssl/rand.h>
27 #ifndef OPENSSL_NO_ECDH
28 # include <openssl/ec.h>
31 # include <openssl/ocsp.h>
39 # define EXIM_OCSP_SKEW_SECONDS (300L)
40 # define EXIM_OCSP_MAX_AGE (-1L)
43 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
44 # define EXIM_HAVE_OPENSSL_TLSEXT
46 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
47 # define EXIM_HAVE_RSA_GENKEY_EX
49 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
50 # define EXIM_HAVE_OCSP_RESP_COUNT
51 # define OPENSSL_AUTO_SHA256
52 # define OPENSSL_MIN_PROTO_VERSION
54 # define EXIM_HAVE_EPHEM_RSA_KEX
55 # define EXIM_HAVE_RAND_PSEUDO
57 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
58 # define EXIM_HAVE_SHA256
61 /* X509_check_host provides sane certificate hostname checking, but was added
62 to OpenSSL late, after other projects forked off the code-base. So in
63 addition to guarding against the base version number, beware that LibreSSL
64 does not (at this time) support this function.
66 If LibreSSL gains a different API, perhaps via libtls, then we'll probably
67 opt to disentangle and ask a LibreSSL user to provide glue for a third
68 crypto provider for libtls instead of continuing to tie the OpenSSL glue
69 into even twistier knots. If LibreSSL gains the same API, we can just
70 change this guard and punt the issue for a while longer. */
72 #ifndef LIBRESSL_VERSION_NUMBER
73 # if OPENSSL_VERSION_NUMBER >= 0x010100000L
74 # define EXIM_HAVE_OPENSSL_CHECKHOST
75 # define EXIM_HAVE_OPENSSL_DH_BITS
76 # define EXIM_HAVE_OPENSSL_TLS_METHOD
77 # define EXIM_HAVE_OPENSSL_KEYLOG
78 # define EXIM_HAVE_OPENSSL_CIPHER_GET_ID
79 # define EXIM_HAVE_SESSION_TICKET
80 # define EXIM_HAVE_OPENSSL_TRACE
81 # define EXIM_HAVE_OPENSSL_GET0_SERIAL
82 # define EXIM_HAVE_OPENSSL_OCSP_RESP_GET0_CERTS
83 # define EXIM_HAVE_SSL_GET0_VERIFIED_CHAIN
85 # define EXIM_HAVE_OCSP
87 # define EXIM_HAVE_ALPN /* fail ret from hshake-cb is ignored by LibreSSL */
89 # define EXIM_NEED_OPENSSL_INIT
91 # if OPENSSL_VERSION_NUMBER >= 0x010000000L \
92 && (OPENSSL_VERSION_NUMBER & 0x0000ff000L) >= 0x000002000L
93 # define EXIM_HAVE_OPENSSL_CHECKHOST
95 # if OPENSSL_VERSION_NUMBER < 0x030200020L
96 # define EXIM_OPENSSL_BOGUS_SERVER_ALPN /*XXX when was this fixed? */
100 #if LIBRESSL_VERSION_NUMBER >= 0x3040000fL
101 # define EXIM_HAVE_OPENSSL_CIPHER_GET_ID
102 # define OPENSSL_AUTO_SHA256
104 #if LIBRESSL_VERSION_NUMBER >= 0x3050000fL
105 # define EXIM_HAVE_OPENSSL_OCSP_RESP_GET0_CERTS
108 #if !defined(LIBRESSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x030000000L)
109 # define EXIM_HAVE_EXPORT_CHNL_BNGNG
110 # define EXIM_HAVE_OPENSSL_X509_STORE_GET1_ALL_CERTS
113 #if !defined(LIBRESSL_VERSION_NUMBER) \
114 || LIBRESSL_VERSION_NUMBER >= 0x20010000L
115 # if !defined(OPENSSL_NO_ECDH)
116 # if OPENSSL_VERSION_NUMBER >= 0x0090800fL
117 # define EXIM_HAVE_ECDH
119 # if OPENSSL_VERSION_NUMBER >= 0x10002000L
120 # define EXIM_HAVE_OPENSSL_EC_NIST2NID
125 #ifndef LIBRESSL_VERSION_NUMBER
126 # if OPENSSL_VERSION_NUMBER >= 0x010101000L
127 # define OPENSSL_HAVE_KEYLOG_CB
128 # define OPENSSL_HAVE_NUM_TICKETS
129 # define EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
130 # define EXIM_HAVE_EXP_CHNL_BNGNG
131 # define EXIM_HAVE_OPENSSL_OCSP_RESP_GET0_SIGNER
132 # define EXIM_HAVE_OPENSSL_SET1_GROUPS
134 # define OPENSSL_BAD_SRVR_OURCERT
138 #if !defined(LIBRESSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x010002000L)
139 # define EXIM_HAVE_EXPORT_CHNL_BNGNG
142 #if !defined(EXIM_HAVE_OPENSSL_TLSEXT) && !defined(DISABLE_OCSP)
143 # warning "OpenSSL library version too old; define DISABLE_OCSP in Makefile"
144 # define DISABLE_OCSP
147 #ifndef DISABLE_TLS_RESUME
148 # if OPENSSL_VERSION_NUMBER < 0x0101010L
149 # error OpenSSL version too old for session-resumption
153 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
154 # include <openssl/x509v3.h>
157 #ifndef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
158 # ifndef EXIM_HAVE_OPENSSL_CIPHER_GET_ID
159 # define SSL_CIPHER_get_id(c) (c->id)
161 # ifndef MACRO_PREDEF
162 # include "tls-cipher-stdname.c"
166 #define TESTSUITE_TICKET_LIFE 10 /* seconds */
167 /*************************************************
168 * OpenSSL option parse *
169 *************************************************/
171 typedef struct exim_openssl_option {
174 } exim_openssl_option;
175 /* We could use a macro to expand, but we need the ifdef and not all the
176 options document which version they were introduced in. Policylet: include
177 all options unless explicitly for DTLS, let the administrator choose which
180 This list is current as of:
183 XXX could we autobuild this list, as with predefined-macros?
184 Seems just parsing ssl.h for SSL_OP_.* would be enough (except to exclude DTLS).
185 Also allow a numeric literal?
187 static exim_openssl_option exim_openssl_options[] = {
188 /* KEEP SORTED ALPHABETICALLY! */
190 { US"all", (long) SSL_OP_ALL },
192 #ifdef SSL_OP_ALLOW_NO_DHE_KEX
193 { US"allow_no_dhe_kex", SSL_OP_ALLOW_NO_DHE_KEX },
195 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
196 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
198 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
199 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
201 #ifdef SSL_OP_CRYPTOPRO_TLSEXT_BUG
202 { US"cryptopro_tlsext_bug", SSL_OP_CRYPTOPRO_TLSEXT_BUG },
204 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
205 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
207 #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
208 { US"enable_middlebox_compat", SSL_OP_ENABLE_MIDDLEBOX_COMPAT },
210 #ifdef SSL_OP_EPHEMERAL_RSA
211 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
213 #ifdef SSL_OP_LEGACY_SERVER_CONNECT
214 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
216 #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
217 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
219 #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
220 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
222 #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
223 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
225 #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
226 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
228 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
229 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
231 #ifdef SSL_OP_NO_ANTI_REPLAY
232 { US"no_anti_replay", SSL_OP_NO_ANTI_REPLAY },
234 #ifdef SSL_OP_NO_COMPRESSION
235 { US"no_compression", SSL_OP_NO_COMPRESSION },
237 #ifdef SSL_OP_NO_ENCRYPT_THEN_MAC
238 { US"no_encrypt_then_mac", SSL_OP_NO_ENCRYPT_THEN_MAC },
240 #ifdef SSL_OP_NO_RENEGOTIATION
241 { US"no_renegotiation", SSL_OP_NO_RENEGOTIATION },
243 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
244 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
246 #ifdef SSL_OP_NO_SSLv2
247 { US"no_sslv2", SSL_OP_NO_SSLv2 },
249 #ifdef SSL_OP_NO_SSLv3
250 { US"no_sslv3", SSL_OP_NO_SSLv3 },
252 #ifdef SSL_OP_NO_TICKET
253 { US"no_ticket", SSL_OP_NO_TICKET },
255 #ifdef SSL_OP_NO_TLSv1
256 { US"no_tlsv1", SSL_OP_NO_TLSv1 },
258 #ifdef SSL_OP_NO_TLSv1_1
259 # if OPENSSL_VERSION_NUMBER < 0x30000000L
260 # if SSL_OP_NO_TLSv1_1 == 0x00000400L
261 /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
262 # warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
263 # define NO_SSL_OP_NO_TLSv1_1
266 # ifndef NO_SSL_OP_NO_TLSv1_1
267 { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
270 #ifdef SSL_OP_NO_TLSv1_2
271 { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
273 #ifdef SSL_OP_NO_TLSv1_3
274 { US"no_tlsv1_3", SSL_OP_NO_TLSv1_3 },
276 #ifdef SSL_OP_PRIORITIZE_CHACHA
277 { US"prioritize_chacha", SSL_OP_PRIORITIZE_CHACHA },
279 #ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
280 { US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
282 #ifdef SSL_OP_SINGLE_DH_USE
283 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
285 #ifdef SSL_OP_SINGLE_ECDH_USE
286 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
288 #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
289 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
291 #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
292 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
294 #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
295 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
297 #ifdef SSL_OP_TLS_D5_BUG
298 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
300 #ifdef SSL_OP_TLS_ROLLBACK_BUG
301 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
303 #ifdef SSL_OP_TLSEXT_PADDING
304 { US"tlsext_padding", SSL_OP_TLSEXT_PADDING },
309 static int exim_openssl_options_size = nelem(exim_openssl_options);
310 static long init_options = 0;
319 for (struct exim_openssl_option * o = exim_openssl_options;
320 o < exim_openssl_options + nelem(exim_openssl_options); o++)
322 /* Trailing X is workaround for problem with _OPT_OPENSSL_NO_TLSV1
323 being a ".ifdef _OPT_OPENSSL_NO_TLSV1_3" match */
325 spf(buf, sizeof(buf), US"_OPT_OPENSSL_%T_X", o->name);
326 builtin_macro_create(buf);
329 # ifndef DISABLE_TLS_RESUME
330 builtin_macro_create_var(US"_RESUME_DECODE", RESUME_DECODE_STRING );
332 # ifdef SSL_OP_NO_TLSv1_3
333 builtin_macro_create(US"_HAVE_TLS1_3");
335 # ifdef OPENSSL_BAD_SRVR_OURCERT
336 builtin_macro_create(US"_TLS_BAD_MULTICERT_IN_OURCERT");
338 # ifdef EXIM_HAVE_OCSP
339 builtin_macro_create(US"_HAVE_TLS_OCSP");
340 builtin_macro_create(US"_HAVE_TLS_OCSP_LIST");
342 # ifdef EXIM_HAVE_ALPN
343 builtin_macro_create(US"_HAVE_TLS_ALPN");
348 /******************************************************************************/
350 /* Structure for collecting random data for seeding. */
352 typedef struct randstuff {
357 /* Local static variables */
359 static BOOL client_verify_callback_called = FALSE;
360 static BOOL server_verify_callback_called = FALSE;
361 static const uschar *sid_ctx = US"exim";
363 /* We have three different contexts to care about.
365 Simple case: client, `client_ctx`
366 As a client, we can be doing a callout or cut-through delivery while receiving
367 a message. So we have a client context, which should have options initialised
368 from the SMTP Transport. We may also concurrently want to make TLS connections
369 to utility daemons, so client-contexts are allocated and passed around in call
370 args rather than using a gobal.
373 There are two cases: with and without ServerNameIndication from the client.
374 Given TLS SNI, we can be using different keys, certs and various other
375 configuration settings, because they're re-expanded with $tls_sni set. This
376 allows vhosting with TLS. This SNI is sent in the handshake.
377 A client might not send SNI, so we need a fallback, and an initial setup too.
378 So as a server, we start out using `server_ctx`.
379 If SNI is sent by the client, then we as server, mid-negotiation, try to clone
380 `server_sni` from `server_ctx` and then initialise settings by re-expanding
388 } exim_openssl_client_tls_ctx;
391 /* static SSL_CTX *server_ctx = NULL; */
392 /* static SSL *server_ssl = NULL; */
394 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
395 static SSL_CTX *server_sni = NULL;
397 #ifdef EXIM_HAVE_ALPN
398 static BOOL server_seen_alpn = FALSE;
401 static char ssl_errstring[256];
403 static int ssl_session_timeout = 7200; /* Two hours */
404 static BOOL client_verify_optional = FALSE;
405 static BOOL server_verify_optional = FALSE;
407 static BOOL reexpand_tls_files_for_sni = FALSE;
410 typedef struct ocsp_resp {
411 struct ocsp_resp * next;
412 OCSP_RESPONSE * resp;
415 typedef struct exim_openssl_state {
416 exim_tlslib_state lib_state;
417 #define lib_ctx libdata0
418 #define lib_ssl libdata1
421 uschar * certificate;
428 const uschar *file_expanded;
429 ocsp_resplist *olist;
430 STACK_OF(X509) *verify_stack; /* chain for verifying the proof */
433 X509_STORE *verify_store; /* non-null if status requested */
434 uschar *verify_errstr; /* only if _required */
435 BOOL verify_required;
440 /* these are cached from first expand */
441 uschar * server_cipher_list;
442 /* only passed down to tls_error: */
444 const uschar * verify_cert_hostnames;
445 #ifndef DISABLE_EVENT
446 uschar * event_action;
448 } exim_openssl_state_st;
450 /* should figure out a cleanup of API to handle state preserved per
451 implementation, for various reasons, which can be void * in the APIs.
452 For now, we hack around it. */
453 exim_openssl_state_st *client_static_state = NULL; /*XXX should not use static; multiple concurrent clients! */
454 exim_openssl_state_st state_server = {.is_server = TRUE};
457 setup_certs(SSL_CTX * sctx, uschar ** certs, uschar * crl, host_item * host,
462 static int tls_server_stapling_cb(SSL *s, void *arg);
463 static void x509_stack_dump_cert_s_names(const STACK_OF(X509) * sk);
464 static void x509_store_dump_cert_s_names(X509_STORE * store);
469 /* Daemon-called, before every connection, key create/rotate */
470 #ifndef DISABLE_TLS_RESUME
471 static void tk_init(void);
472 static int tls_exdata_idx = -1;
476 tls_per_lib_daemon_tick(void)
478 #ifndef DISABLE_TLS_RESUME
483 /* Called once at daemon startup */
486 tls_per_lib_daemon_init(void)
488 tls_daemon_creds_reload();
492 /*************************************************
494 *************************************************/
496 /* Called from lots of places when errors occur before actually starting to do
497 the TLS handshake, that is, while the session is still in clear. Always returns
498 DEFER for a server and FAIL for a client so that most calls can use "return
499 tls_error(...)" to do this processing and then give an appropriate return. A
500 single function is used for both server and client, because it is called from
501 some shared functions.
504 prefix text to include in the logged error
505 host NULL if setting up a server;
506 the connected host if setting up a client
507 msg error message or NULL if we should ask OpenSSL
508 errstr pointer to output error message
510 Returns: OK/DEFER/FAIL
514 tls_error(uschar * prefix, const host_item * host, uschar * msg, uschar ** errstr)
518 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
519 msg = US ssl_errstring;
522 msg = string_sprintf("(%s): %s", prefix, msg);
523 DEBUG(D_tls) debug_printf("TLS error '%s'\n", msg);
524 if (errstr) *errstr = msg;
525 return host ? FAIL : DEFER;
530 /**************************************************
531 * General library initalisation *
532 **************************************************/
535 lib_rand_init(void * addr)
538 if (!RAND_status()) return TRUE;
540 gettimeofday(&r.tv, NULL);
542 RAND_seed(US (&r), sizeof(r));
543 RAND_seed(US big_buffer, big_buffer_size);
544 if (addr) RAND_seed(US addr, sizeof(addr));
546 return RAND_status();
551 tls_openssl_init(void)
553 static BOOL once = FALSE;
557 #ifdef EXIM_NEED_OPENSSL_INIT
558 SSL_load_error_strings(); /* basic set up */
559 OpenSSL_add_ssl_algorithms();
562 #if defined(EXIM_HAVE_SHA256) && !defined(OPENSSL_AUTO_SHA256)
563 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
564 list of available digests. */
565 EVP_add_digest(EVP_sha256());
568 (void) lib_rand_init(NULL);
569 (void) tls_openssl_options_parse(openssl_options, &init_options);
574 /*************************************************
575 * Initialize for DH *
576 *************************************************/
578 /* If dhparam is set, expand it, and load up the parameters for DH encryption.
582 sctx The current SSL CTX (inbound or outbound)
583 dhparam DH parameter file or fixed parameter identity string
584 errstr error string pointer
586 Returns: TRUE if OK (nothing to set up, or setup worked)
590 init_dh(SSL_CTX * sctx, uschar * dhparam, uschar ** errstr)
593 #if OPENSSL_VERSION_NUMBER < 0x30000000L
602 if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded, errstr))
605 if (!dhexpanded || !*dhexpanded)
606 bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
607 else if (dhexpanded[0] == '/')
609 if (!(bio = BIO_new_file(CS dhexpanded, "r")))
611 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
612 NULL, US strerror(errno), errstr);
618 if (Ustrcmp(dhexpanded, "none") == 0)
620 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
624 if (!(pem = std_dh_prime_named(dhexpanded)))
626 tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
627 NULL, US strerror(errno), errstr);
630 bio = BIO_new_mem_buf(CS pem, -1);
634 #if OPENSSL_VERSION_NUMBER < 0x30000000L
635 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)
637 pkey = PEM_read_bio_Parameters_ex(bio, NULL, NULL, NULL)
642 tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
647 /* note: our default limit of 2236 is not a multiple of 8; the limit comes from
648 an NSS limit, and the GnuTLS APIs handle bit-sizes fine, so we went with 2236.
649 But older OpenSSL can only report in bytes (octets), not bits. If someone wants
650 to dance at the edge, then they can raise the limit or use current libraries. */
652 #if OPENSSL_VERSION_NUMBER < 0x30000000L
653 # ifdef EXIM_HAVE_OPENSSL_DH_BITS
654 /* Added in commit 26c79d5641d; `git describe --contains` says OpenSSL_1_1_0-pre1~1022
655 This predates OpenSSL_1_1_0 (before a, b, ...) so is in all 1.1.0 */
656 dh_bitsize = DH_bits(dh);
658 dh_bitsize = 8 * DH_size(dh);
661 dh_bitsize = EVP_PKEY_get_bits(pkey);
664 /* Even if it is larger, we silently return success rather than cause things to
665 fail out, so that a too-large DH will not knock out all TLS; it's a debatable
666 choice. Likewise for a failing attempt to set one. */
668 if (dh_bitsize <= tls_dh_max_bits)
671 #if OPENSSL_VERSION_NUMBER < 0x30000000L
672 SSL_CTX_set_tmp_dh(sctx, dh)
674 SSL_CTX_set0_tmp_dh_pkey(sctx, pkey)
678 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
679 log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (D-H param setting '%s'): %s",
680 dhexpanded ? dhexpanded : US"default", ssl_errstring);
681 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
682 /* EVP_PKEY_free(pkey); crashes */
687 debug_printf(" Diffie-Hellman initialized from %s with %d-bit prime\n",
688 dhexpanded ? dhexpanded : US"default", dh_bitsize);
692 debug_printf(" dhparams '%s' %d bits, is > tls_dh_max_bits limit of %d\n",
693 dhexpanded ? dhexpanded : US"default", dh_bitsize, tls_dh_max_bits);
695 #if OPENSSL_VERSION_NUMBER < 0x30000000L
698 /* The EVP_PKEY ownership stays with the ctx; do not free it */
707 /*************************************************
708 * Initialize for ECDH *
709 *************************************************/
711 /* "auto" needs to be handled carefully.
712 OpenSSL < 1.0.2: we do not select anything, but fallback to prime256v1
713 OpenSSL < 1.1.0: we have to call SSL_CTX_set_ecdh_auto
714 (openssl/ssl.h defines SSL_CTRL_SET_ECDH_AUTO)
715 OpenSSL >= 1.1.0: we do not set anything, the libray does autoselection
716 https://github.com/openssl/openssl/commit/fe6ef2472db933f01b59cad82aa925736935984b
721 init_ecdh_auto(SSL_CTX * sctx)
723 #if OPENSSL_VERSION_NUMBER < 0x10002000L
724 DEBUG(D_tls) debug_printf(
725 " ECDH OpenSSL < 1.0.2: temp key parameter settings: overriding \"auto\" with \"prime256v1\"\n");
726 return US"prime256v1";
729 # if defined SSL_CTRL_SET_ECDH_AUTO
731 DEBUG(D_tls) debug_printf(
732 " ECDH OpenSSL 1.0.2+: temp key parameter settings: autoselection\n");
733 SSL_CTX_set_ecdh_auto(sctx, 1);
738 DEBUG(D_tls) debug_printf(
739 " ECDH OpenSSL 1.1.0+: temp key parameter settings: library default selection\n");
746 /* Load parameters for ECDH encryption. Server only.
748 For now, we stick to NIST P-256 because: it's simple and easy to configure;
749 it avoids any patent issues that might bite redistributors; despite events in
750 the news and concerns over curve choices, we're not cryptographers, we're not
751 pretending to be, and this is "good enough" to be better than no support,
752 protecting against most adversaries. Given another year or two, there might
753 be sufficient clarity about a "right" way forward to let us make an informed
754 decision, instead of a knee-jerk reaction.
756 Longer-term, we should look at supporting both various named curves and
757 external files generated with "openssl ecparam", much as we do for init_dh().
758 We should also support "none" as a value, to explicitly avoid initialisation.
763 sctx The current SSL CTX (inbound or outbound)
764 errstr error string pointer
766 Returns: TRUE if OK (nothing to set up, or setup worked)
770 init_ecdh(SSL_CTX * sctx, uschar ** errstr)
772 #ifdef OPENSSL_NO_ECDH
776 # ifndef EXIM_HAVE_ECDH
778 debug_printf(" No OpenSSL API to define ECDH parameters, skipping\n");
783 int ngroups, rc, sep;
784 const uschar * curves_list, * curve;
785 # ifdef EXIM_HAVE_OPENSSL_SET1_GROUPS
791 if (!expand_check(tls_eccurve, US"tls_eccurve", &exp_curve, errstr))
794 /* Is the option deliberately empty? */
796 if (!exp_curve || !*exp_curve)
799 /* Limit the list to hardwired array size. Drop out if any element is "suto". */
801 curves_list = exp_curve;
804 ngroups < nelem(nids)
805 && (curve = string_nextinlist(&curves_list, &sep, NULL, 0));
807 if (Ustrcmp(curve, "auto") == 0)
809 DEBUG(D_tls) if (ngroups > 0)
810 debug_printf(" tls_eccurve 'auto' item takes precedence\n");
811 if ((exp_curve = init_ecdh_auto(sctx))) break; /* have a curve name to set */
812 return TRUE; /* all done */
817 /* Translate to NIDs */
819 curves_list = exp_curve;
820 for (ngroups = 0; curve = string_nextinlist(&curves_list, &sep, NULL, 0);
822 if ( (nids[ngroups] = OBJ_sn2nid (CCS curve)) == NID_undef
823 # ifdef EXIM_HAVE_OPENSSL_EC_NIST2NID
824 && (nids[ngroups] = EC_curve_nist2nid(CCS curve)) == NID_undef
828 uschar * s = string_sprintf("Unknown curve name in tls_eccurve '%s'", curve);
829 DEBUG(D_tls) debug_printf("TLS error: %s\n", s);
830 if (errstr) *errstr = s;
834 # ifdef EXIM_HAVE_OPENSSL_SET1_GROUPS
837 if ((rc = SSL_CTX_set1_groups(sctx, nids, ngroups)) == 0)
838 tls_error(string_sprintf("Error enabling '%s' group(s)", exp_curve), NULL, NULL, errstr);
840 DEBUG(D_tls) debug_printf(" ECDH: enabled '%s' group(s)\n", exp_curve);
842 # else /* Cannot handle a list; only 1 element nids array */
845 if (!(ecdh = EC_KEY_new_by_curve_name(nids[0])))
847 tls_error(US"Unable to create ec curve", NULL, NULL, errstr);
851 /* The "tmp" in the name here refers to setting a temporary key
852 not to the stability of the interface. */
854 if ((rc = SSL_CTX_set_tmp_ecdh(sctx, ecdh)) == 0)
855 tls_error(string_sprintf("Error enabling '%s' curve", exp_curve), NULL, NULL, errstr);
857 DEBUG(D_tls) debug_printf(" ECDH: enabled '%s' curve\n", exp_curve);
860 # endif /*!EXIM_HAVE_OPENSSL_SET1_GROUPS*/
864 # endif /*EXIM_HAVE_ECDH*/
865 #endif /*OPENSSL_NO_ECDH*/
870 /*************************************************
871 * Expand key and cert file specs *
872 *************************************************/
874 #if OPENSSL_VERSION_NUMBER < 0x30000000L
877 s SSL connection (not used)
881 Returns: pointer to generated key
885 rsa_callback(SSL *s, int export, int keylength)
888 #ifdef EXIM_HAVE_RSA_GENKEY_EX
889 BIGNUM *bn = BN_new();
892 DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
894 # ifdef EXIM_HAVE_RSA_GENKEY_EX
895 if ( !BN_set_word(bn, (unsigned long)RSA_F4)
896 || !(rsa_key = RSA_new())
897 || !RSA_generate_key_ex(rsa_key, keylength, bn, NULL)
900 if (!(rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL)))
904 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
905 log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
911 #endif /* pre-3.0.0 */
915 /* Create and install a selfsigned certificate, for use in server mode */
916 /*XXX we could arrange to call this during prelo for a null tls_certificate option.
917 The normal cache inval + relo will suffice.
918 Just need a timer for inval. */
921 tls_install_selfsign(SSL_CTX * sctx, uschar ** errstr)
928 DEBUG(D_tls) debug_printf("TLS: generating selfsigned server cert\n");
929 where = US"allocating pkey";
930 if (!(pkey = EVP_PKEY_new()))
933 where = US"allocating cert";
934 if (!(x509 = X509_new()))
937 where = US"generating pkey";
938 #if OPENSSL_VERSION_NUMBER < 0x30000000L
941 if (!(rsa = rsa_callback(NULL, 0, 2048)))
944 where = US"assigning pkey";
945 if (!EVP_PKEY_assign_RSA(pkey, rsa))
949 pkey = EVP_RSA_gen(2048);
952 X509_set_version(x509, 2); /* N+1 - version 3 */
953 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
954 X509_gmtime_adj(X509_get_notBefore(x509), 0);
955 X509_gmtime_adj(X509_get_notAfter(x509), (long)2 * 60 * 60); /* 2 hour */
956 X509_set_pubkey(x509, pkey);
958 name = X509_get_subject_name(x509);
959 X509_NAME_add_entry_by_txt(name, "C",
960 MBSTRING_ASC, CUS "UK", -1, -1, 0);
961 X509_NAME_add_entry_by_txt(name, "O",
962 MBSTRING_ASC, CUS "Exim Developers", -1, -1, 0);
963 X509_NAME_add_entry_by_txt(name, "CN",
964 MBSTRING_ASC, CUS smtp_active_hostname, -1, -1, 0);
965 X509_set_issuer_name(x509, name);
967 where = US"signing cert";
968 if (!X509_sign(x509, pkey, EVP_md5()))
971 where = US"installing selfsign cert";
972 if (!SSL_CTX_use_certificate(sctx, x509))
975 where = US"installing selfsign key";
976 if (!SSL_CTX_use_PrivateKey(sctx, pkey))
982 (void) tls_error(where, NULL, NULL, errstr);
983 if (x509) X509_free(x509);
984 if (pkey) EVP_PKEY_free(pkey);
994 /*************************************************
995 * Information callback *
996 *************************************************/
998 /* The SSL library functions call this from time to time to indicate what they
999 are doing. We copy the string to the debugging output when TLS debugging has
1003 s the SSL connection
1011 info_callback(const SSL * s, int where, int ret)
1017 if (where & SSL_ST_CONNECT) g = string_append_listele(g, ',', US"SSL_connect");
1018 if (where & SSL_ST_ACCEPT) g = string_append_listele(g, ',', US"SSL_accept");
1019 if (where & SSL_CB_LOOP) g = string_append_listele(g, ',', US"state_chg");
1020 if (where & SSL_CB_EXIT) g = string_append_listele(g, ',', US"hshake_exit");
1021 if (where & SSL_CB_READ) g = string_append_listele(g, ',', US"read");
1022 if (where & SSL_CB_WRITE) g = string_append_listele(g, ',', US"write");
1023 if (where & SSL_CB_ALERT) g = string_append_listele(g, ',', US"alert");
1024 if (where & SSL_CB_HANDSHAKE_START) g = string_append_listele(g, ',', US"hshake_start");
1025 if (where & SSL_CB_HANDSHAKE_DONE) g = string_append_listele(g, ',', US"hshake_done");
1027 if (where & SSL_CB_LOOP)
1028 debug_printf("SSL %s: %s\n", g->s, SSL_state_string_long(s));
1029 else if (where & SSL_CB_ALERT)
1030 debug_printf("SSL %s %s:%s\n", g->s,
1031 SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
1032 else if (where & SSL_CB_EXIT)
1035 debug_printf("SSL %s: %s in %s\n", g->s,
1036 ret == 0 ? "failed" : "error", SSL_state_string_long(s));
1038 else if (where & (SSL_CB_HANDSHAKE_START | SSL_CB_HANDSHAKE_DONE))
1039 debug_printf("SSL %s: %s\n", g->s, SSL_state_string_long(s));
1043 #ifdef OPENSSL_HAVE_KEYLOG_CB
1045 keylog_callback(const SSL *ssl, const char *line)
1049 DEBUG(D_tls) debug_printf("%.200s\n", line);
1050 if (!(filename = getenv("SSLKEYLOGFILE"))) return;
1051 if (!(fp = fopen(filename, "a"))) return;
1052 fprintf(fp, "%s\n", line);
1061 #ifndef DISABLE_EVENT
1063 verify_event(tls_support * tlsp, X509 * cert, int depth, const uschar * dn,
1064 BOOL *calledp, const BOOL *optionalp, const uschar * what)
1070 ev = tlsp == &tls_out ? client_static_state->event_action : event_action;
1073 DEBUG(D_tls) debug_printf("verify_event: %s %d\n", what, depth);
1074 old_cert = tlsp->peercert;
1075 tlsp->peercert = X509_dup(cert);
1076 /* NB we do not bother setting peerdn */
1077 if ((yield = event_raise(ev, US"tls:cert", string_sprintf("%d", depth), &errno)))
1079 log_write(0, LOG_MAIN, "[%s] %s verify denied by event-action: "
1080 "depth=%d cert=%s: %s",
1081 tlsp == &tls_out ? deliver_host_address : sender_host_address,
1082 what, depth, dn, yield);
1086 if (old_cert) tlsp->peercert = old_cert; /* restore 1st failing cert */
1087 return 1; /* reject (leaving peercert set) */
1089 DEBUG(D_tls) debug_printf("Event-action verify failure overridden "
1090 "(host in tls_try_verify_hosts)\n");
1091 tlsp->verify_override = TRUE;
1093 X509_free(tlsp->peercert);
1094 tlsp->peercert = old_cert;
1100 /*************************************************
1101 * Callback for verification *
1102 *************************************************/
1104 /* The SSL library does certificate verification if set up to do so. This
1105 callback has the current yes/no state is in "state". If verification succeeded,
1106 we set the certificate-verified flag. If verification failed, what happens
1107 depends on whether the client is required to present a verifiable certificate
1110 If verification is optional, we change the state to yes, but still log the
1111 verification error. For some reason (it really would help to have proper
1112 documentation of OpenSSL), this callback function then gets called again, this
1113 time with state = 1. We must take care not to set the private verified flag on
1114 the second time through.
1116 Note: this function is not called if the client fails to present a certificate
1117 when asked. We get here only if a certificate has been received. Handling of
1118 optional verification for this case is done when requesting SSL to verify, by
1119 setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
1121 May be called multiple times for different issues with a certificate, even
1122 for a given "depth" in the certificate chain.
1125 preverify_ok current yes/no state as 1/0
1126 x509ctx certificate information.
1127 tlsp per-direction (client vs. server) support data
1128 calledp has-been-called flag
1129 optionalp verification-is-optional flag
1131 Returns: 0 if verification should fail, otherwise 1
1135 verify_callback(int preverify_ok, X509_STORE_CTX * x509ctx,
1136 tls_support * tlsp, BOOL * calledp, BOOL * optionalp)
1138 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
1139 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
1142 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
1144 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
1145 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
1146 tlsp == &tls_out ? deliver_host_address : sender_host_address);
1149 dn[sizeof(dn)-1] = '\0';
1151 tlsp->verify_override = FALSE;
1152 if (preverify_ok == 0)
1154 uschar * extra = verify_mode ? string_sprintf(" (during %c-verify for [%s])",
1155 *verify_mode, sender_host_address)
1157 log_write(0, LOG_MAIN, "[%s] SSL verify error%s: depth=%d error=%s cert=%s",
1158 tlsp == &tls_out ? deliver_host_address : sender_host_address,
1160 X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509ctx)), dn);
1164 if (!tlsp->peercert)
1165 tlsp->peercert = X509_dup(cert); /* record failing cert */
1166 return 0; /* reject */
1168 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
1169 "tls_try_verify_hosts)\n");
1170 tlsp->verify_override = TRUE;
1173 else if (depth != 0)
1175 DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d SN=%s\n", depth, dn);
1176 #ifndef DISABLE_EVENT
1177 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
1178 return 0; /* reject, with peercert set */
1183 const uschar * verify_cert_hostnames;
1185 if ( tlsp == &tls_out
1186 && ((verify_cert_hostnames = client_static_state->verify_cert_hostnames)))
1187 /* client, wanting hostname check */
1190 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
1191 # ifndef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
1192 # define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0
1194 # ifndef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
1195 # define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0
1198 const uschar * list = verify_cert_hostnames;
1201 while ((name = string_nextinlist(&list, &sep, NULL, 0)))
1203 DEBUG(D_tls|D_lookup) debug_printf_indent("%s suitable for cert, per OpenSSL?", name);
1204 if ((rc = X509_check_host(cert, CCS name, 0,
1205 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
1206 | X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS,
1211 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
1212 tlsp == &tls_out ? deliver_host_address : sender_host_address);
1215 DEBUG(D_tls|D_lookup) debug_printf_indent(" yes\n");
1218 else DEBUG(D_tls|D_lookup) debug_printf_indent(" no\n");
1222 if (!tls_is_name_for_cert(verify_cert_hostnames, cert))
1225 uschar * extra = verify_mode
1226 ? string_sprintf(" (during %c-verify for [%s])",
1227 *verify_mode, sender_host_address)
1229 log_write(0, LOG_MAIN,
1230 "[%s] SSL verify error%s: certificate name mismatch: DN=\"%s\" H=\"%s\"",
1231 tlsp == &tls_out ? deliver_host_address : sender_host_address,
1232 extra, dn, verify_cert_hostnames);
1236 if (!tlsp->peercert)
1237 tlsp->peercert = X509_dup(cert); /* record failing cert */
1238 return 0; /* reject */
1240 DEBUG(D_tls) debug_printf("SSL verify name failure overridden (host in "
1241 "tls_try_verify_hosts)\n");
1242 tlsp->verify_override = TRUE;
1246 #ifndef DISABLE_EVENT
1247 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
1248 return 0; /* reject, with peercert set */
1251 DEBUG(D_tls) debug_printf("SSL%s verify ok: depth=0 SN=%s\n",
1252 *calledp ? "" : " authenticated", dn);
1256 return 1; /* accept, at least for this level */
1260 verify_callback_client(int preverify_ok, X509_STORE_CTX *x509ctx)
1262 return verify_callback(preverify_ok, x509ctx, &tls_out,
1263 &client_verify_callback_called, &client_verify_optional);
1267 verify_callback_server(int preverify_ok, X509_STORE_CTX *x509ctx)
1269 return verify_callback(preverify_ok, x509ctx, &tls_in,
1270 &server_verify_callback_called, &server_verify_optional);
1276 /* This gets called *by* the dane library verify callback, which interposes
1280 verify_callback_client_dane(int preverify_ok, X509_STORE_CTX * x509ctx)
1282 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
1284 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
1285 #ifndef DISABLE_EVENT
1286 BOOL dummy_called, optional = FALSE;
1289 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
1291 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
1292 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
1293 deliver_host_address);
1296 dn[sizeof(dn)-1] = '\0';
1298 DEBUG(D_tls) debug_printf("verify_callback_client_dane: %s depth %d %s\n",
1299 preverify_ok ? "ok":"BAD", depth, dn);
1301 #ifndef DISABLE_EVENT
1302 if (verify_event(&tls_out, cert, depth, dn,
1303 &dummy_called, &optional, US"DANE"))
1304 return 0; /* reject, with peercert set */
1307 if (preverify_ok == 1)
1308 tls_out.dane_verified = TRUE;
1311 int err = X509_STORE_CTX_get_error(x509ctx);
1313 debug_printf(" - err %d '%s'\n", err, X509_verify_cert_error_string(err));
1314 if (err == X509_V_ERR_APPLICATION_VERIFICATION)
1317 return preverify_ok;
1320 #endif /*SUPPORT_DANE*/
1323 #ifndef DISABLE_OCSP
1325 time_print(BIO * bp, const char * str, ASN1_GENERALIZEDTIME * time)
1327 BIO_printf(bp, "\t%s: ", str);
1328 ASN1_GENERALIZEDTIME_print(bp, time);
1332 /*************************************************
1333 * Load OCSP information into state *
1334 *************************************************/
1335 /* Called to load the server OCSP response from the given file into memory, once
1336 caller has determined this is needed. Checks validity. Debugs a message
1339 ASSUMES: single response, for single cert.
1342 state various parts of session state
1343 filename the filename putatively holding an OCSP response
1344 is_pem file is PEM format; otherwise is DER
1348 ocsp_load_response(exim_openssl_state_st * state, const uschar * filename,
1352 OCSP_RESPONSE * resp;
1353 OCSP_BASICRESP * basic_response;
1354 OCSP_SINGLERESP * single_response;
1355 ASN1_GENERALIZEDTIME * rev, * thisupd, * nextupd;
1356 STACK_OF(X509) * sk;
1357 int status, reason, i;
1360 debug_printf("tls_ocsp_file (%s) '%s'\n", is_pem ? "PEM" : "DER", filename);
1362 if (!filename || !*filename) return;
1365 if (!(bio = BIO_new_file(CS filename, "rb")))
1367 log_write(0, LOG_MAIN|LOG_PANIC,
1368 "Failed to open OCSP response file \"%s\": %.100s",
1369 filename, ERR_reason_error_string(ERR_get_error()));
1375 uschar * data, * freep;
1378 if (!PEM_read_bio(bio, &dummy, &dummy, &data, &len))
1380 log_write(0, LOG_MAIN|LOG_PANIC, "Failed to read PEM file \"%s\": %.100s",
1381 filename, ERR_reason_error_string(ERR_get_error()));
1385 resp = d2i_OCSP_RESPONSE(NULL, CUSS &data, len);
1386 OPENSSL_free(freep);
1389 resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
1394 log_write(0, LOG_MAIN|LOG_PANIC, "Error reading OCSP response from \"%s\": %s",
1395 filename, ERR_reason_error_string(ERR_get_error()));
1399 if ((status = OCSP_response_status(resp)) != OCSP_RESPONSE_STATUS_SUCCESSFUL)
1401 DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n",
1402 OCSP_response_status_str(status), status);
1408 BIO * bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
1409 OCSP_RESPONSE_print(bp, resp, 0); /* extreme debug: stapling content */
1414 if (!(basic_response = OCSP_response_get1_basic(resp)))
1417 debug_printf("OCSP response parse error: unable to extract basic response.\n");
1421 sk = state->u_ocsp.server.verify_stack; /* set by setup_certs() / chain_from_pem_file() */
1423 /* May need to expose ability to adjust those flags?
1424 OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
1425 OCSP_TRUSTOTHER OCSP_NOINTERN */
1427 /* This does a partial verify (only the signer link, not the whole chain-to-CA)
1428 on the OCSP proof before we load it for serving up; possibly overkill -
1429 just date-checks might be nice enough.
1431 OCSP_basic_verify takes a "store" arg, but does not
1432 use it for the chain verification, when OCSP_NOVERIFY is set.
1433 The content from the wire "basic_response" and a cert-stack "sk" are all
1436 We have a stack, loaded in setup_certs() if tls_verify_certificates
1437 was a file (not a directory, or "system"). It is unfortunate we
1438 cannot used the connection context store, as that would neatly
1439 handle the "system" case too, but there seems to be no library
1440 function for getting a stack from a store.
1441 [ In OpenSSL 1.1 - ? X509_STORE_CTX_get0_chain(ctx) ? ]
1442 [ 3.0.0 - sk = X509_STORE_get1_all_certs(store) ]
1443 We do not free the stack since it could be needed a second time for
1446 Separately we might try to replace using OCSP_basic_verify() - which seems to not
1447 be a public interface into the OpenSSL library (there's no manual entry) -
1448 (in 3.0.0 + it is public)
1449 But what with? We also use OCSP_basic_verify in the client stapling callback.
1450 And there we NEED it; we must verify that status... unless the
1451 library does it for us anyway? */
1453 if ((i = OCSP_basic_verify(basic_response, sk, NULL, OCSP_NOVERIFY)) < 0)
1457 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1458 debug_printf("OCSP response has bad signature: %s\n", US ssl_errstring);
1463 /* Here's the simplifying assumption: there's only one response, for the
1464 one certificate we use, and nothing for anything else in a chain. If this
1465 proves false, we need to extract a cert id from our issued cert
1466 (tls_certificate) and use that for OCSP_resp_find_status() (which finds the
1467 right cert in the stack and then calls OCSP_single_get0_status()).
1469 I'm hoping to avoid reworking a bunch more of how we handle state here.
1471 XXX that will change when we add support for (TLS1.3) whole-chain stapling
1474 if (!(single_response = OCSP_resp_get0(basic_response, 0)))
1477 debug_printf("Unable to get first response from OCSP basic response.\n");
1481 status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
1482 if (status != V_OCSP_CERTSTATUS_GOOD)
1484 DEBUG(D_tls) debug_printf("OCSP response bad cert status: %s (%d) %s (%d)\n",
1485 OCSP_cert_status_str(status), status,
1486 OCSP_crl_reason_str(reason), reason);
1490 if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1494 BIO * bp = BIO_new(BIO_s_mem());
1497 time_print(bp, "This OCSP Update", thisupd);
1498 if (nextupd) time_print(bp, "Next OCSP Update", nextupd);
1499 if ((len = (int) BIO_get_mem_data(bp, CSS &s)) > 0) debug_printf("%.*s", len, s);
1500 debug_printf("OCSP status invalid times.\n");
1506 /* Add the resp to the list used by tls_server_stapling_cb() */
1508 ocsp_resplist ** op = &state->u_ocsp.server.olist, * oentry;
1509 while (oentry = *op)
1511 *op = oentry = store_get(sizeof(ocsp_resplist), GET_UNTAINTED);
1512 oentry->next = NULL;
1513 oentry->resp = resp;
1518 if (f.running_in_test_harness)
1520 extern char ** environ;
1521 if (environ) for (uschar ** p = USS environ; *p; p++)
1522 if (Ustrncmp(*p, "EXIM_TESTHARNESS_DISABLE_OCSPVALIDITYCHECK", 42) == 0)
1524 DEBUG(D_tls) debug_printf("Supplying known bad OCSP response\n");
1525 goto supply_response;
1533 ocsp_free_response_list(exim_openssl_state_st * state)
1535 for (ocsp_resplist * olist = state->u_ocsp.server.olist; olist;
1536 olist = olist->next)
1537 OCSP_RESPONSE_free(olist->resp);
1538 state->u_ocsp.server.olist = NULL;
1540 #endif /*!DISABLE_OCSP*/
1547 tls_add_certfile(SSL_CTX * sctx, exim_openssl_state_st * cbinfo, uschar * file,
1550 DEBUG(D_tls) debug_printf("tls_certificate file '%s'\n", file);
1551 if (!SSL_CTX_use_certificate_chain_file(sctx, CS file))
1552 return tls_error(string_sprintf(
1553 "SSL_CTX_use_certificate_chain_file file=%s", file),
1554 cbinfo->host, NULL, errstr);
1559 tls_add_pkeyfile(SSL_CTX * sctx, exim_openssl_state_st * cbinfo, uschar * file,
1562 DEBUG(D_tls) debug_printf("tls_privatekey file '%s'\n", file);
1563 if (!SSL_CTX_use_PrivateKey_file(sctx, CS file, SSL_FILETYPE_PEM))
1564 return tls_error(string_sprintf(
1565 "SSL_CTX_use_PrivateKey_file file=%s", file), cbinfo->host, NULL, errstr);
1572 /* Called once during tls_init and possibly again during TLS setup, for a
1573 new context, if Server Name Indication was used and tls_sni was seen in
1574 the certificate string.
1577 sctx the SSL_CTX* to update
1578 state various parts of session state
1579 errstr error string pointer
1581 Returns: OK/DEFER/FAIL
1585 tls_expand_session_files(SSL_CTX * sctx, exim_openssl_state_st * state,
1590 if (!state->certificate)
1592 if (!state->is_server) /* client */
1595 if (tls_install_selfsign(sctx, errstr) != OK)
1602 if ( !reexpand_tls_files_for_sni
1603 && ( Ustrstr(state->certificate, US"tls_sni")
1604 || Ustrstr(state->certificate, US"tls_in_sni")
1605 || Ustrstr(state->certificate, US"tls_out_sni")
1607 reexpand_tls_files_for_sni = TRUE;
1609 if ( !expand_check(state->certificate, US"tls_certificate", &expanded, errstr)
1610 || f.expand_string_forcedfail)
1612 if (f.expand_string_forcedfail)
1613 *errstr = US"expansion of tls_certificate failed";
1618 if (state->is_server)
1620 const uschar * file_list = expanded;
1623 #ifndef DISABLE_OCSP
1624 const uschar * olist = state->u_ocsp.server.file;
1627 BOOL fmt_pem = FALSE;
1630 if (!expand_check(olist, US"tls_ocsp_file", USS &olist, errstr))
1632 if (olist && !*olist)
1635 /* If doing a re-expand after SNI, avoid reloading the OCSP
1636 responses when the list of filenames has not changed.
1637 The creds-invali on content change wipes file_expanded, so that
1638 always reloads here. */
1640 if ( state->u_ocsp.server.file_expanded && olist
1641 && (Ustrcmp(olist, state->u_ocsp.server.file_expanded) == 0))
1643 DEBUG(D_tls) debug_printf(" - value unchanged, using existing values\n");
1648 ocsp_free_response_list(state);
1649 state->u_ocsp.server.file_expanded = olist;
1653 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1655 if ((err = tls_add_certfile(sctx, state, file, errstr)))
1658 #ifndef DISABLE_OCSP
1660 if ((ofile = string_nextinlist(&olist, &osep, NULL, 0)))
1662 if (Ustrncmp(ofile, US"PEM ", 4) == 0)
1667 else if (Ustrncmp(ofile, US"DER ", 4) == 0)
1672 ocsp_load_response(state, ofile, fmt_pem);
1675 DEBUG(D_tls) debug_printf("ran out of ocsp file list\n");
1679 else /* would there ever be a need for multiple client certs? */
1680 if ((err = tls_add_certfile(sctx, state, expanded, errstr)))
1683 if ( state->privatekey
1684 && !expand_check(state->privatekey, US"tls_privatekey", &expanded, errstr)
1685 || f.expand_string_forcedfail)
1687 if (f.expand_string_forcedfail)
1688 *errstr = US"expansion of tls_privatekey failed";
1692 /* If expansion was forced to fail, key_expanded will be NULL. If the result
1693 of the expansion is an empty string, ignore it also, and assume the private
1694 key is in the same file as the certificate. */
1696 if (expanded && *expanded)
1697 if (state->is_server)
1699 const uschar * file_list = expanded;
1703 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1704 if ((err = tls_add_pkeyfile(sctx, state, file, errstr)))
1707 else /* would there ever be a need for multiple client certs? */
1708 if ((err = tls_add_pkeyfile(sctx, state, expanded, errstr)))
1718 /**************************************************
1719 * One-time init credentials for server and client *
1720 **************************************************/
1723 normalise_ciphers(uschar ** ciphers, const uschar * pre_expansion_ciphers)
1725 uschar * s = *ciphers;
1727 if (!s || !Ustrchr(s, '_')) return; /* no change needed */
1729 if (s == pre_expansion_ciphers)
1730 s = string_copy(s); /* get writable copy */
1732 for (uschar * t = s; *t; t++) if (*t == '_') *t = '-';
1737 server_load_ciphers(SSL_CTX * ctx, exim_openssl_state_st * state,
1738 uschar * ciphers, uschar ** errstr)
1740 DEBUG(D_tls) debug_printf("required ciphers: %s\n", ciphers);
1741 if (!SSL_CTX_set_cipher_list(ctx, CS ciphers))
1742 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL, errstr);
1743 state->server_cipher_list = ciphers;
1750 lib_ctx_new(SSL_CTX ** ctxp, host_item * host, uschar ** errstr)
1753 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1754 if (!(ctx = SSL_CTX_new(host ? TLS_client_method() : TLS_server_method())))
1756 if (!(ctx = SSL_CTX_new(host ? SSLv23_client_method() : SSLv23_server_method())))
1758 return tls_error(US"SSL_CTX_new", host, NULL, errstr);
1760 /* Set up the information callback, which outputs if debugging is at a suitable
1765 SSL_CTX_set_info_callback(ctx, info_callback);
1766 #if defined(EXIM_HAVE_OPENSSL_TRACE) && !defined(OPENSSL_NO_SSL_TRACE)
1767 /* this needs a debug build of OpenSSL */
1768 SSL_CTX_set_msg_callback(ctx, SSL_trace);
1770 #ifdef OPENSSL_HAVE_KEYLOG_CB
1771 SSL_CTX_set_keylog_callback(ctx, keylog_callback);
1775 /* Automatically re-try reads/writes after renegotiation. */
1776 (void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1783 tls_server_creds_init(void)
1786 uschar * dummy_errstr;
1787 unsigned lifetime = 0;
1791 state_server.lib_state = null_tls_preload;
1793 if (lib_ctx_new(&ctx, NULL, &dummy_errstr) != OK)
1795 state_server.lib_state.lib_ctx = ctx;
1797 /* Preload DH params and EC curve */
1799 if (opt_unset_or_noexpand(tls_dhparam))
1801 DEBUG(D_tls) debug_printf("TLS: preloading DH params '%s' for server\n", tls_dhparam);
1802 if (init_dh(ctx, tls_dhparam, &dummy_errstr))
1803 state_server.lib_state.dh = TRUE;
1806 DEBUG(D_tls) debug_printf("TLS: not preloading DH params for server\n");
1807 if (opt_unset_or_noexpand(tls_eccurve))
1809 DEBUG(D_tls) debug_printf("TLS: preloading ECDH curve '%s' for server\n", tls_eccurve);
1810 if (init_ecdh(ctx, &dummy_errstr))
1811 state_server.lib_state.ecdh = TRUE;
1814 DEBUG(D_tls) debug_printf("TLS: not preloading ECDH curve for server\n");
1816 #if defined(EXIM_HAVE_INOTIFY) || defined(EXIM_HAVE_KEVENT)
1817 /* If we can, preload the Authorities for checking client certs against.
1818 Actual choice to do verify is made (tls_{,try_}verify_hosts)
1819 at TLS conn startup.
1820 Do this before the server ocsp so that its info can verify the ocsp. */
1822 if ( opt_set_and_noexpand(tls_verify_certificates)
1823 && opt_unset_or_noexpand(tls_crl))
1825 /* Watch the default dir also as they are always included */
1827 if ( tls_set_watch(CUS X509_get_default_cert_file(), FALSE)
1828 && tls_set_watch(tls_verify_certificates, FALSE)
1829 && tls_set_watch(tls_crl, FALSE))
1831 uschar * v_certs = tls_verify_certificates;
1832 DEBUG(D_tls) debug_printf("TLS: preloading CA bundle for server\n");
1834 if (setup_certs(ctx, &v_certs, tls_crl, NULL, &dummy_errstr) == OK)
1835 state_server.lib_state.cabundle = TRUE;
1837 /* If we can, preload the server-side cert, key and ocsp */
1839 if ( opt_set_and_noexpand(tls_certificate)
1840 # ifndef DISABLE_OCSP
1841 && opt_unset_or_noexpand(tls_ocsp_file)
1843 && opt_unset_or_noexpand(tls_privatekey))
1845 /* Set watches on the filenames. The implementation does de-duplication
1846 so we can just blindly do them all. */
1848 if ( tls_set_watch(tls_certificate, TRUE)
1849 # ifndef DISABLE_OCSP
1850 && tls_set_watch(tls_ocsp_file, TRUE)
1852 && tls_set_watch(tls_privatekey, TRUE))
1854 state_server.certificate = tls_certificate;
1855 state_server.privatekey = tls_privatekey;
1856 #ifndef DISABLE_OCSP
1857 state_server.u_ocsp.server.file = tls_ocsp_file;
1860 DEBUG(D_tls) debug_printf("TLS: preloading server certs\n");
1861 if (tls_expand_session_files(ctx, &state_server, &dummy_errstr) == OK)
1862 state_server.lib_state.conn_certs = TRUE;
1865 else if ( !tls_certificate && !tls_privatekey
1866 # ifndef DISABLE_OCSP
1870 { /* Generate & preload a selfsigned cert. No files to watch. */
1871 if (tls_expand_session_files(ctx, &state_server, &dummy_errstr) == OK)
1873 state_server.lib_state.conn_certs = TRUE;
1874 lifetime = f.running_in_test_harness ? 2 : 60 * 60; /* 1 hour */
1878 DEBUG(D_tls) debug_printf("TLS: not preloading server certs\n");
1882 DEBUG(D_tls) debug_printf("TLS: not preloading CA bundle for server\n");
1885 #endif /* EXIM_HAVE_INOTIFY */
1888 /* If we can, preload the ciphers control string */
1890 if (opt_set_and_noexpand(tls_require_ciphers))
1892 DEBUG(D_tls) debug_printf("TLS: preloading cipher list for server\n");
1893 normalise_ciphers(&tls_require_ciphers, tls_require_ciphers);
1894 if (server_load_ciphers(ctx, &state_server, tls_require_ciphers,
1895 &dummy_errstr) == OK)
1896 state_server.lib_state.pri_string = TRUE;
1899 DEBUG(D_tls) debug_printf("TLS: not preloading cipher list for server\n");
1906 /* Preload whatever creds are static, onto a transport. The client can then
1907 just copy the pointer as it starts up.
1908 Called from the daemon after a cache-invalidate with watch set; called from
1909 a queue-run startup with watch clear. */
1912 tls_client_creds_init(transport_instance * t, BOOL watch)
1914 smtp_transport_options_block * ob = t->drinst.options_block;
1915 const uschar * trname = t->drinst.name;
1916 exim_openssl_state_st tpt_dummy_state;
1917 host_item * dummy_host = (host_item *)1;
1918 uschar * dummy_errstr;
1923 ob->tls_preload = null_tls_preload;
1924 if (lib_ctx_new(&ctx, dummy_host, &dummy_errstr) != OK)
1926 ob->tls_preload.lib_ctx = ctx;
1928 tpt_dummy_state.lib_state = ob->tls_preload;
1930 #if defined(EXIM_HAVE_INOTIFY) || defined(EXIM_HAVE_KEVENT)
1931 if ( opt_set_and_noexpand(ob->tls_certificate)
1932 && opt_unset_or_noexpand(ob->tls_privatekey))
1935 || ( tls_set_watch(ob->tls_certificate, FALSE)
1936 && tls_set_watch(ob->tls_privatekey, FALSE)
1939 uschar * pkey = ob->tls_privatekey;
1942 debug_printf("TLS: preloading client certs for transport '%s'\n", trname);
1944 if ( tls_add_certfile(ctx, &tpt_dummy_state, ob->tls_certificate,
1946 && tls_add_pkeyfile(ctx, &tpt_dummy_state,
1947 pkey ? pkey : ob->tls_certificate,
1950 ob->tls_preload.conn_certs = TRUE;
1955 debug_printf("TLS: not preloading client certs, for transport '%s'\n", trname);
1958 if ( opt_set_and_noexpand(ob->tls_verify_certificates)
1959 && opt_unset_or_noexpand(ob->tls_crl))
1962 || tls_set_watch(CUS X509_get_default_cert_file(), FALSE)
1963 && tls_set_watch(ob->tls_verify_certificates, FALSE)
1964 && tls_set_watch(ob->tls_crl, FALSE)
1967 uschar * v_certs = ob->tls_verify_certificates;
1969 debug_printf("TLS: preloading CA bundle for transport '%s'\n", trname);
1971 if (setup_certs(ctx, &v_certs,
1972 ob->tls_crl, dummy_host, &dummy_errstr) == OK)
1973 ob->tls_preload.cabundle = TRUE;
1978 debug_printf("TLS: not preloading CA bundle, for transport '%s'\n", trname);
1980 #endif /*EXIM_HAVE_INOTIFY*/
1984 #if defined(EXIM_HAVE_INOTIFY) || defined(EXIM_HAVE_KEVENT)
1985 /* Invalidate the creds cached, by dropping the current ones.
1986 Call when we notice one of the source files has changed. */
1989 tls_server_creds_invalidate(void)
1991 SSL_CTX_free(state_server.lib_state.lib_ctx);
1992 state_server.lib_state = null_tls_preload;
1993 #ifndef DISABLE_OCSP
1994 state_server.u_ocsp.server.file_expanded = NULL;
2000 tls_client_creds_invalidate(transport_instance * t)
2002 smtp_transport_options_block * ob = t->drinst.options_block;
2003 SSL_CTX_free(ob->tls_preload.lib_ctx);
2004 ob->tls_preload = null_tls_preload;
2007 #endif /*EXIM_HAVE_INOTIFY*/
2012 #ifndef DISABLE_OCSP
2014 debug_print_sn(const X509 * cert)
2016 X509_NAME * sn = X509_get_subject_name((X509 *)cert);
2017 static uschar name[256];
2018 if (X509_NAME_oneline(sn, CS name, sizeof(name)))
2020 name[sizeof(name)-1] = '\0';
2021 debug_printf(" %s\n", name);
2026 x509_stack_dump_cert_s_names(const STACK_OF(X509) * sk)
2029 debug_printf(" (null)\n");
2032 int idx = sk_X509_num(sk);
2034 debug_printf(" (empty)\n");
2036 while (--idx >= 0) debug_print_sn(sk_X509_value(sk, idx));
2041 x509_store_dump_cert_s_names(X509_STORE * store)
2043 # ifdef EXIM_HAVE_OPENSSL_X509_STORE_GET1_ALL_CERTS
2045 debug_printf(" (no store)\n");
2048 STACK_OF(X509) * sk = X509_STORE_get1_all_certs(store);
2049 x509_stack_dump_cert_s_names(sk);
2050 sk_X509_pop_free(sk, X509_free);
2054 #endif /*!DISABLE_OCSP*/
2059 #ifndef DISABLE_TLS_RESUME
2060 /* Manage the keysets used for encrypting the session tickets, on the server. */
2062 typedef struct { /* Session ticket encryption key */
2065 const EVP_CIPHER * aes_cipher;
2066 uschar aes_key[32]; /* size needed depends on cipher. aes_128 implies 128/8 = 16? */
2067 # if OPENSSL_VERSION_NUMBER < 0x30000000L
2068 const EVP_MD * hmac_hash;
2070 const uschar * hmac_hashname;
2072 uschar hmac_key[16];
2077 static exim_stek exim_tk; /* current key */
2078 static exim_stek exim_tk_old; /* previous key */
2083 time_t t = time(NULL);
2085 if (exim_tk.name[0])
2087 if (exim_tk.renew >= t) return;
2088 exim_tk_old = exim_tk;
2091 if (f.running_in_test_harness) ssl_session_timeout = TESTSUITE_TICKET_LIFE;
2093 DEBUG(D_tls) debug_printf("OpenSSL: %s STEK\n", exim_tk.name[0] ? "rotating" : "creating");
2094 if (RAND_bytes(exim_tk.aes_key, sizeof(exim_tk.aes_key)) <= 0) return;
2095 if (RAND_bytes(exim_tk.hmac_key, sizeof(exim_tk.hmac_key)) <= 0) return;
2096 if (RAND_bytes(exim_tk.name+1, sizeof(exim_tk.name)-1) <= 0) return;
2098 exim_tk.name[0] = 'E';
2099 exim_tk.aes_cipher = EVP_aes_256_cbc();
2100 # if OPENSSL_VERSION_NUMBER < 0x30000000L
2101 exim_tk.hmac_hash = EVP_sha256();
2103 exim_tk.hmac_hashname = US "sha256";
2105 exim_tk.expire = t + ssl_session_timeout;
2106 exim_tk.renew = t + ssl_session_timeout/2;
2112 if (!exim_tk.name[0]) return NULL;
2117 tk_find(const uschar * name)
2119 return memcmp(name, exim_tk.name, sizeof(exim_tk.name)) == 0 ? &exim_tk
2120 : memcmp(name, exim_tk_old.name, sizeof(exim_tk_old.name)) == 0 ? &exim_tk_old
2127 # if OPENSSL_VERSION_NUMBER < 0x30000000L
2135 /*XXX will want these dependent on the ssl session strength */
2136 # if OPENSSL_VERSION_NUMBER < 0x30000000L
2137 HMAC_Init_ex(hctx, key->hmac_key, sizeof(key->hmac_key),
2138 key->hmac_hash, NULL);
2141 OSSL_PARAM params[3];
2142 uschar * hk = string_copy(key->hmac_hashname); /* need nonconst */
2143 params[0] = OSSL_PARAM_construct_octet_string("key", key->hmac_key, sizeof(key->hmac_key));
2144 params[1] = OSSL_PARAM_construct_utf8_string("digest", CS hk, 0);
2145 params[2] = OSSL_PARAM_construct_end();
2146 if (EVP_MAC_CTX_set_params(hctx, params) == 0)
2148 DEBUG(D_tls) debug_printf("EVP_MAC_CTX_set_params: %s\n",
2149 ERR_reason_error_string(ERR_get_error()));
2150 return 0; /* error in mac initialisation */
2157 /* Callback for session tickets, on server */
2159 ticket_key_callback(SSL * ssl, uschar key_name[16],
2160 uschar * iv, EVP_CIPHER_CTX * c_ctx,
2161 # if OPENSSL_VERSION_NUMBER < 0x30000000L
2168 tls_support * tlsp = state_server.tlsp;
2173 DEBUG(D_tls) debug_printf("ticket_key_callback: create new session\n");
2174 tlsp->resumption |= RESUME_CLIENT_REQUESTED;
2176 if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0)
2177 return -1; /* insufficient random */
2179 if (!(key = tk_current())) /* current key doesn't exist or isn't valid */
2180 return 0; /* key couldn't be created */
2181 memcpy(key_name, key->name, 16);
2182 DEBUG(D_tls) debug_printf("STEK expire " TIME_T_FMT "\n", key->expire - time(NULL));
2184 if (tk_hmac_init(hctx, key) == 0) return 0;
2185 EVP_EncryptInit_ex(c_ctx, key->aes_cipher, NULL, key->aes_key, iv);
2187 DEBUG(D_tls) debug_printf("ticket created\n");
2192 time_t now = time(NULL);
2194 DEBUG(D_tls) debug_printf("ticket_key_callback: retrieve session\n");
2195 tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
2197 if (!(key = tk_find(key_name)) || key->expire < now)
2201 debug_printf("ticket not usable (%s)\n", key ? "expired" : "not found");
2202 if (key) debug_printf("STEK expire " TIME_T_FMT "\n", key->expire - now);
2207 if (tk_hmac_init(hctx, key) == 0) return 0;
2208 EVP_DecryptInit_ex(c_ctx, key->aes_cipher, NULL, key->aes_key, iv);
2210 DEBUG(D_tls) debug_printf("ticket usable, STEK expire " TIME_T_FMT "\n", key->expire - now);
2212 /* The ticket lifetime and renewal are the same as the STEK lifetime and
2213 renewal, which is overenthusiastic. A factor of, say, 3x longer STEK would
2214 be better. To do that we'd have to encode ticket lifetime in the name as
2215 we don't yet see the restored session. Could check posthandshake for TLS1.3
2216 and trigger a new ticket then, but cannot do that for TLS1.2 */
2217 return key->renew < now ? 2 : 1;
2220 #endif /* !DISABLE_TLS_RESUME */
2225 setup_cert_verify(SSL_CTX * ctx, BOOL optional,
2226 int (*cert_vfy_cb)(int, X509_STORE_CTX *))
2228 /* If verification is optional, don't fail if no certificate */
2230 SSL_CTX_set_verify(ctx,
2231 SSL_VERIFY_PEER | (optional ? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
2236 /*************************************************
2237 * Callback to handle SNI *
2238 *************************************************/
2240 /* Called when acting as server during the TLS session setup if a Server Name
2241 Indication extension was sent by the client.
2243 API documentation is OpenSSL s_server.c implementation.
2246 s SSL* of the current session
2247 ad unknown (part of OpenSSL API) (unused)
2248 arg Callback of "our" registered data
2250 Returns: SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
2252 XXX might need to change to using ClientHello callback,
2253 per https://www.openssl.org/docs/manmaster/man3/SSL_client_hello_cb_fn.html
2256 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
2258 tls_servername_cb(SSL * s, int * ad ARG_UNUSED, void * arg)
2260 const char * servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2261 exim_openssl_state_st * state = (exim_openssl_state_st *) arg;
2263 int old_pool = store_pool;
2267 return SSL_TLSEXT_ERR_OK;
2269 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
2270 reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
2272 /* Make the extension value available for expansion */
2273 store_pool = POOL_PERM;
2274 tls_in.sni = string_copy_taint(US servername, GET_TAINTED);
2275 store_pool = old_pool;
2277 if (!reexpand_tls_files_for_sni)
2278 return SSL_TLSEXT_ERR_OK;
2280 /* Can't find an SSL_CTX_clone() or equivalent, so we do it manually;
2281 not confident that memcpy wouldn't break some internal reference counting.
2282 Especially since there's a references struct member, which would be off. */
2284 if (lib_ctx_new(&server_sni, NULL, &errstr) != OK)
2287 /* Not sure how many of these are actually needed, since SSL object
2288 already exists. Might even need this selfsame callback, for reneg? */
2291 SSL_CTX * ctx = state_server.lib_state.lib_ctx;
2292 SSL_CTX_set_info_callback(server_sni, SSL_CTX_get_info_callback(ctx));
2293 SSL_CTX_set_mode(server_sni, SSL_CTX_get_mode(ctx));
2294 #ifdef OPENSSL_MIN_PROTO_VERSION
2295 SSL_CTX_set_min_proto_version(server_sni, SSL3_VERSION);
2297 SSL_CTX_set_options(server_sni, SSL_CTX_get_options(ctx));
2298 SSL_CTX_clear_options(server_sni, ~SSL_CTX_get_options(ctx));
2299 SSL_CTX_set_timeout(server_sni, SSL_CTX_get_timeout(ctx));
2300 SSL_CTX_set_tlsext_servername_callback(server_sni, tls_servername_cb);
2301 SSL_CTX_set_tlsext_servername_arg(server_sni, state);
2304 if ( !init_dh(server_sni, state->dhparam, &errstr)
2305 || !init_ecdh(server_sni, &errstr)
2309 if ( state->server_cipher_list
2310 && !SSL_CTX_set_cipher_list(server_sni, CS state->server_cipher_list))
2313 #ifndef DISABLE_OCSP
2314 if (state->u_ocsp.server.file)
2316 SSL_CTX_set_tlsext_status_cb(server_sni, tls_server_stapling_cb);
2317 SSL_CTX_set_tlsext_status_arg(server_sni, state);
2322 uschar * v_certs = tls_verify_certificates;
2323 if ((rc = setup_certs(server_sni, &v_certs, tls_crl, NULL,
2327 if (v_certs && *v_certs)
2328 setup_cert_verify(server_sni, FALSE, verify_callback_server);
2331 /* do this after setup_certs, because this can require the certs for verifying
2332 OCSP information. */
2333 if ((rc = tls_expand_session_files(server_sni, state, &errstr)) != OK)
2336 DEBUG(D_tls) debug_printf("Switching SSL context.\n");
2337 SSL_set_SSL_CTX(s, server_sni);
2338 return SSL_TLSEXT_ERR_OK;
2341 log_write(0, LOG_MAIN|LOG_PANIC, "%s", errstr);
2342 return SSL_TLSEXT_ERR_ALERT_FATAL;
2344 #endif /* EXIM_HAVE_OPENSSL_TLSEXT */
2349 #ifdef EXIM_HAVE_ALPN
2350 /*************************************************
2351 * Callback to handle ALPN *
2352 *************************************************/
2354 /* Called on server if tls_alpn nonblank after expansion,
2355 when client offers ALPN, after the SNI callback.
2356 If set and not matching the list then we dump the connection */
2359 tls_server_alpn_cb(SSL *ssl, const uschar ** out, uschar * outlen,
2360 const uschar * in, unsigned int inlen, void * arg)
2364 server_seen_alpn = TRUE;
2367 debug_printf("Received TLS ALPN offer:");
2368 for (int pos = 0, siz; pos < inlen; pos += siz+1)
2371 if (pos + 1 + siz > inlen) siz = inlen - pos - 1;
2372 debug_printf(" '%.*s'", siz, in + pos + 1);
2374 debug_printf(". Our list: '%s'\n", tls_alpn);
2377 /* Look for an acceptable ALPN */
2379 if ( inlen > 1 /* at least one name */
2380 && in[0]+1 == inlen /* filling the vector, so exactly one name */
2383 const uschar * list = tls_alpn;
2385 for (uschar * name; name = string_nextinlist(&list, &sep, NULL, 0); )
2386 if (Ustrncmp(in+1, name, in[0]) == 0)
2388 *out = in+1; /* we checked for exactly one, so can just point to it */
2389 #ifndef EXIM_OPENSSL_BOGUS_SERVER_ALPN
2393 return SSL_TLSEXT_ERR_OK; /* use ALPN */
2397 /* More than one name from client, or name did not match our list. */
2399 /* This will be fatal to the TLS conn; would be nice to kill TCP also.
2400 Maybe as an option in future; for now leave control to the config (must-tls). */
2402 for (int pos = 0, siz; pos < inlen; pos += siz+1)
2405 if (pos + 1 + siz > inlen) siz = inlen - pos - 1;
2406 g = string_append_listele_n(g, ':', in + pos + 1, siz);
2408 log_write(0, LOG_MAIN, "TLS ALPN (%Y) rejected", g);
2409 gstring_release_unused(g);
2411 /* We want a connection-fatal result.
2412 Do not use the documented SSL_TLSEXT_ERR_NOACK return. */
2414 return SSL_TLSEXT_ERR_ALERT_FATAL;
2416 #endif /* EXIM_HAVE_ALPN */
2420 #ifndef DISABLE_OCSP
2422 /*************************************************
2423 * Callback to handle OCSP Stapling *
2424 *************************************************/
2426 /* Called when acting as server during the TLS session setup if the client
2427 requests OCSP information with a Certificate Status Request.
2429 Documentation via openssl s_server.c and the Apache patch from the OpenSSL
2435 tls_server_stapling_cb(SSL *s, void *arg)
2437 const exim_openssl_state_st * state = arg;
2438 ocsp_resplist * olist = state->u_ocsp.server.olist;
2439 uschar * response_der; /*XXX blob */
2440 int response_der_len;
2443 debug_printf("Received TLS status request (OCSP stapling); %s response list\n",
2444 olist ? "have" : "lack");
2446 tls_in.ocsp = OCSP_NOT_RESP;
2448 return SSL_TLSEXT_ERR_NOACK;
2450 #ifdef EXIM_HAVE_OPENSSL_GET0_SERIAL
2452 const X509 * cert_sent = SSL_get_certificate(s);
2453 const ASN1_INTEGER * cert_serial = X509_get0_serialNumber(cert_sent);
2454 const BIGNUM * cert_bn = ASN1_INTEGER_to_BN(cert_serial, NULL);
2456 for (; olist; olist = olist->next)
2458 OCSP_BASICRESP * bs = OCSP_response_get1_basic(olist->resp);
2459 const OCSP_SINGLERESP * single = OCSP_resp_get0(bs, 0);
2460 const OCSP_CERTID * cid = OCSP_SINGLERESP_get0_id(single);
2461 ASN1_INTEGER * res_cert_serial;
2462 const BIGNUM * resp_bn;
2463 ASN1_OCTET_STRING * res_cert_iNameHash;
2466 (void) OCSP_id_get0_info(&res_cert_iNameHash, NULL, NULL, &res_cert_serial,
2467 (OCSP_CERTID *) cid);
2468 resp_bn = ASN1_INTEGER_to_BN(res_cert_serial, NULL);
2472 debug_printf("cert serial: %s\n", BN_bn2hex(cert_bn));
2473 debug_printf("resp serial: %s\n", BN_bn2hex(resp_bn));
2476 if (BN_cmp(cert_bn, resp_bn) == 0)
2478 DEBUG(D_tls) debug_printf("matched serial for ocsp\n");
2480 /*XXX TODO: check the rest of the list for duplicate matches.
2481 If any, need to also check the Issuer Name hash.
2482 Without this, we will provide the wrong status in the case of
2487 DEBUG(D_tls) debug_printf("not match serial for ocsp\n");
2491 DEBUG(D_tls) debug_printf("failed to find match for ocsp\n");
2492 return SSL_TLSEXT_ERR_NOACK;
2498 DEBUG(D_tls) debug_printf("OpenSSL version too early to support multi-leaf OCSP\n");
2499 return SSL_TLSEXT_ERR_NOACK;
2503 /*XXX could we do the i2d earlier, rather than during the callback? */
2504 response_der = NULL;
2505 response_der_len = i2d_OCSP_RESPONSE(olist->resp, &response_der);
2506 if (response_der_len <= 0)
2507 return SSL_TLSEXT_ERR_NOACK;
2509 SSL_set_tlsext_status_ocsp_resp(state_server.lib_state.lib_ssl,
2510 response_der, response_der_len);
2511 tls_in.ocsp = OCSP_VFIED;
2512 return SSL_TLSEXT_ERR_OK;
2517 add_chain_to_store(X509_STORE * store, STACK_OF(X509) * sk,
2518 const char * debug_text)
2524 debug_printf("chain for %s:\n", debug_text);
2525 x509_stack_dump_cert_s_names(sk);
2528 if ((idx = sk_X509_num(sk)) > 0)
2530 X509_STORE_add_cert(store, sk_X509_value(sk, idx));
2535 tls_client_stapling_cb(SSL * ssl, void * arg)
2537 exim_openssl_state_st * cbinfo = arg;
2538 const unsigned char * p;
2540 OCSP_RESPONSE * rsp;
2541 OCSP_BASICRESP * bs;
2544 DEBUG(D_tls) debug_printf("Received TLS status callback (OCSP stapling):\n");
2545 len = SSL_get_tlsext_status_ocsp_resp(ssl, &p);
2547 { /* Expect this when we requested ocsp but got none */
2548 if (SSL_session_reused(ssl) && tls_out.ocsp == OCSP_VFIED)
2550 DEBUG(D_tls) debug_printf(" null, but resumed; ocsp vfy stored with session is good\n");
2554 if (cbinfo->u_ocsp.client.verify_required && LOGGING(tls_cipher))
2555 log_write(0, LOG_MAIN, "Required TLS certificate status not received");
2557 DEBUG(D_tls) debug_printf(" null\n");
2559 if (!cbinfo->u_ocsp.client.verify_required)
2561 cbinfo->u_ocsp.client.verify_errstr =
2562 US"(SSL_connect) Required TLS certificate status not received";
2566 if (!(rsp = d2i_OCSP_RESPONSE(NULL, &p, len)))
2568 tls_out.ocsp = OCSP_FAILED; /*XXX should use tlsp-> to permit concurrent outbound */
2569 if (LOGGING(tls_cipher))
2570 log_write(0, LOG_MAIN, "Received TLS cert status response, parse error");
2572 DEBUG(D_tls) debug_printf(" parse error\n");
2576 if (!(bs = OCSP_response_get1_basic(rsp)))
2578 tls_out.ocsp = OCSP_FAILED;
2579 if (LOGGING(tls_cipher))
2580 log_write(0, LOG_MAIN, "Received TLS cert status response, error parsing response");
2582 DEBUG(D_tls) debug_printf(" error parsing response\n");
2583 OCSP_RESPONSE_free(rsp);
2587 /* We'd check the nonce here if we'd put one in the request. */
2588 /* However that would defeat cacheability on the server so we don't. */
2590 /* This section of code reworked from OpenSSL apps source;
2591 The OpenSSL Project retains copyright:
2592 Copyright (c) 1999 The OpenSSL Project. All rights reserved.
2596 X509_STORE * verify_store = NULL;
2597 BOOL have_verified_OCSP_signer = FALSE;
2598 #ifndef EXIM_HAVE_OCSP_RESP_COUNT
2599 STACK_OF(OCSP_SINGLERESP) * sresp = bs->tbsResponseData->responses;
2602 DEBUG(D_tls) bp = BIO_new(BIO_s_mem());
2604 /* Use the CA & chain that verified the server cert to verify the stapled info */
2605 /*XXX could we do an event here, for observability of ocsp? What reasonable data could we give access to? */
2606 /* Dates would be a start. Do we need another opaque variable type, as for certs, plus an extract expansion? */
2609 /* If this routine is not available, we've avoided [in tls_client_start()]
2610 asking for certificate-status under DANE, so this callback won't run for
2611 that combination. It still will for non-DANE. */
2613 #if defined(EXIM_HAVE_OPENSSL_OCSP_RESP_GET0_SIGNER) && defined(SUPPORT_DANE)
2616 if ( tls_out.dane_verified
2617 && (have_verified_OCSP_signer =
2618 OCSP_resp_get0_signer(bs, &signer, SSL_get0_verified_chain(ssl)) == 1))
2621 debug_printf("signer for OCSP basicres is in the verified chain;"
2622 " shortcut its verification\n");
2627 STACK_OF(X509) * verified_chain;
2629 verify_store = X509_STORE_new();
2631 SSL_get0_chain_certs(ssl, &verified_chain);
2632 add_chain_to_store(verify_store, verified_chain,
2633 "'current cert' per SSL_get0_chain_certs()");
2634 #ifdef EXIM_HAVE_SSL_GET0_VERIFIED_CHAIN
2635 verified_chain = SSL_get0_verified_chain(ssl);
2636 add_chain_to_store(verify_store, verified_chain,
2637 "SSL_get0_verified_chain()");
2644 debug_printf("Untrusted intermediate cert stack (from SSL_get_peer_cert_chain()):\n");
2645 x509_stack_dump_cert_s_names(SSL_get_peer_cert_chain(ssl));
2647 debug_printf("will use this CA store for verifying basicresp:\n");
2648 x509_store_dump_cert_s_names(verify_store);
2650 /* OCSP_RESPONSE_print(bp, rsp, 0); extreme debug: stapling content */
2652 debug_printf("certs contained in basicresp:\n");
2653 x509_stack_dump_cert_s_names(
2654 #ifdef EXIM_HAVE_OPENSSL_OCSP_RESP_GET0_CERTS
2655 OCSP_resp_get0_certs(bs)
2661 #ifdef EXIM_HAVE_OPENSSL_X509_STORE_GET1_ALL_CERTS
2662 /* could do via X509_STORE_get0_objects(); not worth it just for debug info */
2665 if (OCSP_resp_get0_signer(bs, &signer, X509_STORE_get1_all_certs(verify_store)) == 1)
2667 debug_printf("found signer for basicres:\n");
2668 debug_print_sn(signer);
2672 debug_printf("failed to find signer for basicres:\n");
2673 ERR_print_errors(bp);
2682 /* Under DANE the trust-anchor (at least in TA mode) is indicated by the TLSA
2683 record in DNS, and probably is not the root of the chain of certificates. So
2684 accept a partial chain for that case (and hope that anchor is visible for
2685 verifying the OCSP stapling).
2686 XXX for EE mode it won't even be that. Does that make OCSP useless for EE?
2688 Worse, for LetsEncrypt-mode (ocsp signer is leaf-signer) under DANE, the
2689 data used within OpenSSL for the signer has nil pointers for signing
2690 algorithms - and a crash results. Avoid this by shortcutting verification,
2691 having determined that the OCSP signer is in the (DANE-)validated set.
2694 #ifndef OCSP_PARTIAL_CHAIN /* defined for 3.0.0 onwards */
2695 # define OCSP_PARTIAL_CHAIN 0
2698 if ((i = OCSP_basic_verify(bs, SSL_get_peer_cert_chain(ssl),
2701 tls_out.dane_verified
2702 ? have_verified_OCSP_signer
2703 ? OCSP_NOVERIFY | OCSP_NOEXPLICIT
2704 : OCSP_PARTIAL_CHAIN | OCSP_NOEXPLICIT
2707 OCSP_NOEXPLICIT)) <= 0)
2709 DEBUG(D_tls) debug_printf("OCSP_basic_verify() fail: returned %d\n", i);
2710 if (ERR_peek_error())
2712 tls_out.ocsp = OCSP_FAILED;
2713 if (LOGGING(tls_cipher))
2715 static uschar peerdn[256];
2716 const uschar * errstr;;
2718 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
2719 ERR_peek_error_all(NULL, NULL, NULL, CCSS &errstr, NULL);
2722 errstr = CUS ERR_reason_error_string(ERR_peek_error());
2724 X509_NAME_oneline(X509_get_subject_name(SSL_get_peer_certificate(ssl)),
2725 CS peerdn, sizeof(peerdn));
2726 log_write(0, LOG_MAIN,
2727 "[%s] %s Received TLS cert (DN: '%.*s') status response, "
2728 "itself unverifiable: %s",
2729 deliver_host_address, deliver_host,
2730 (int)sizeof(peerdn), peerdn, errstr);
2734 BIO_printf(bp, "OCSP response verify failure\n");
2735 ERR_print_errors(bp);
2738 int len = (int) BIO_get_mem_data(bp, CSS &s);
2739 if (len > 0) debug_printf("%.*s", len, s);
2742 OCSP_RESPONSE_print(bp, rsp, 0);
2747 DEBUG(D_tls) debug_printf("no explicit trust for OCSP signing"
2748 " in the root CA certificate; ignoring\n");
2751 DEBUG(D_tls) debug_printf("OCSP response well-formed and signed OK\n");
2753 /*XXX So we have a good stapled OCSP status. How do we know
2754 it is for the cert of interest? OpenSSL 1.1.0 has a routine
2755 OCSP_resp_find_status() which matches on a cert id, which presumably
2756 we should use. Making an id needs OCSP_cert_id_new(), which takes
2757 issuerName, issuerKey, serialNumber. Are they all in the cert?
2759 For now, carry on blindly accepting the resp. */
2762 #ifdef EXIM_HAVE_OCSP_RESP_COUNT
2763 OCSP_resp_count(bs) - 1;
2765 sk_OCSP_SINGLERESP_num(sresp) - 1;
2769 OCSP_SINGLERESP * single = OCSP_resp_get0(bs, idx);
2771 ASN1_GENERALIZEDTIME * rev, * thisupd, * nextupd;
2773 /*XXX so I can see putting a loop in here to handle a rsp with >1 singleresp
2774 - but what happens with a GnuTLS-style input?
2776 we could do with a debug label for each singleresp
2777 - it has a certID with a serialNumber, but I see no API to get that
2779 status = OCSP_single_get0_status(single, &reason, &rev,
2780 &thisupd, &nextupd);
2784 time_print(bp, "This OCSP Update", thisupd);
2785 if (nextupd) time_print(bp, "Next OCSP Update", nextupd);
2787 if (!OCSP_check_validity(thisupd, nextupd,
2788 EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
2790 tls_out.ocsp = OCSP_FAILED;
2791 DEBUG(D_tls) ERR_print_errors(bp);
2792 cbinfo->u_ocsp.client.verify_errstr =
2793 US"(SSL_connect) Server certificate status is out-of-date";
2794 log_write(0, LOG_MAIN, "OCSP dates invalid");
2798 DEBUG(D_tls) BIO_printf(bp, "Certificate status: %s\n",
2799 OCSP_cert_status_str(status));
2802 case V_OCSP_CERTSTATUS_GOOD:
2803 continue; /* the idx loop */
2804 case V_OCSP_CERTSTATUS_REVOKED:
2805 cbinfo->u_ocsp.client.verify_errstr =
2806 US"(SSL_connect) Server certificate revoked";
2807 log_write(0, LOG_MAIN, "Server certificate revoked%s%s",
2808 reason != -1 ? "; reason: " : "",
2809 reason != -1 ? OCSP_crl_reason_str(reason) : "");
2810 DEBUG(D_tls) time_print(bp, "Revocation Time", rev);
2813 cbinfo->u_ocsp.client.verify_errstr =
2814 US"(SSL_connect) Server certificate has unknown status";
2815 log_write(0, LOG_MAIN,
2816 "Server certificate status unknown, in OCSP stapling");
2824 tls_out.ocsp = OCSP_VFIED;
2828 tls_out.ocsp = OCSP_FAILED;
2829 i = cbinfo->u_ocsp.client.verify_required ? 0 : 1;
2833 int len = (int) BIO_get_mem_data(bp, CSS &s);
2834 if (len > 0) debug_printf("%.*s", len, s);
2839 OCSP_RESPONSE_free(rsp);
2842 #endif /*!DISABLE_OCSP*/
2845 /*************************************************
2846 * Initialize for TLS *
2847 *************************************************/
2848 /* Called from both server and client code, to do preliminary initialization
2849 of the library. We allocate and return a context structure.
2852 host connected host, if client; NULL if server
2853 ob transport options block, if client; NULL if server
2854 ocsp_file file of stapling info (server); flag for require ocsp (client)
2855 addr address if client; NULL if server (for some randomness)
2856 caller_state place to put pointer to allocated state-struct
2857 errstr error string pointer
2859 Returns: OK/DEFER/FAIL
2863 tls_init(host_item * host, smtp_transport_options_block * ob,
2864 #ifndef DISABLE_OCSP
2867 address_item *addr, exim_openssl_state_st ** caller_state,
2868 tls_support * tlsp, uschar ** errstr)
2871 exim_openssl_state_st * state;
2874 if (host) /* client */
2876 state = store_malloc(sizeof(exim_openssl_state_st));
2877 memset(state, 0, sizeof(*state));
2878 state->certificate = ob->tls_certificate;
2879 state->privatekey = ob->tls_privatekey;
2880 state->is_server = FALSE;
2881 state->dhparam = NULL;
2882 state->lib_state = ob->tls_preload;
2886 state = &state_server;
2887 state->certificate = tls_certificate;
2888 state->privatekey = tls_privatekey;
2889 state->is_server = TRUE;
2890 state->dhparam = tls_dhparam;
2891 state->lib_state = state_server.lib_state;
2897 if (!state->lib_state.pri_string)
2898 state->server_cipher_list = NULL;
2900 #ifndef DISABLE_EVENT
2901 state->event_action = NULL;
2906 /* It turns out that we need to seed the random number generator this early in
2907 order to get the full complement of ciphers to work. It took me roughly a day
2908 of work to discover this by experiment.
2910 On systems that have /dev/urandom, SSL may automatically seed itself from
2911 there. Otherwise, we have to make something up as best we can. Double check
2914 Although we likely called this before, at daemon startup, this is a chance
2915 to mix in further variable info (time, pid) if needed. */
2917 if (!lib_rand_init(addr))
2918 return tls_error(US"RAND_status", host,
2919 US"unable to seed random number generator", errstr);
2921 /* Apply administrator-supplied work-arounds.
2922 Historically we applied just one requested option,
2923 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
2924 moved to an administrator-controlled list of options to specify and
2925 grandfathered in the first one as the default value for "openssl_options".
2927 No OpenSSL version number checks: the options we accept depend upon the
2928 availability of the option value macros from OpenSSL. */
2931 if (!tls_openssl_options_parse(openssl_options, &init_options))
2932 return tls_error(US"openssl_options parsing failed", host, NULL, errstr);
2934 /* Create a context.
2935 The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
2936 negotiation in the different methods; as far as I can tell, the only
2937 *_{server,client}_method which allows negotiation is SSLv23, which exists even
2938 when OpenSSL is built without SSLv2 support.
2939 By disabling with openssl_options, we can let admins re-enable with the
2942 if (!(ctx = state->lib_state.lib_ctx))
2944 if ((rc = lib_ctx_new(&ctx, host, errstr)) != OK)
2946 state->lib_state.lib_ctx = ctx;
2949 #ifndef DISABLE_TLS_RESUME
2950 tlsp->resumption = RESUME_SUPPORTED;
2954 #ifndef DISABLE_TLS_RESUME
2955 /* Should the server offer session resumption? */
2956 if (!host && verify_check_host(&tls_resumption_hosts) == OK)
2958 DEBUG(D_tls) debug_printf("tls_resumption_hosts overrides openssl_options\n");
2959 init_options &= ~SSL_OP_NO_TICKET;
2960 tlsp->resumption |= RESUME_SERVER_TICKET; /* server will give ticket on request */
2961 tlsp->host_resumable = TRUE;
2965 #ifdef OPENSSL_MIN_PROTO_VERSION
2966 SSL_CTX_set_min_proto_version(ctx, SSL3_VERSION);
2968 DEBUG(D_tls) debug_printf("setting SSL CTX options: %016lx\n", init_options);
2969 SSL_CTX_set_options(ctx, init_options);
2971 uint64_t readback = SSL_CTX_clear_options(ctx, ~init_options);
2972 if (readback != init_options)
2973 return tls_error(string_sprintf(
2974 "SSL_CTX_set_option(%#lx)", init_options), host, NULL, errstr);
2978 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
2980 /* We'd like to disable session cache unconditionally, but foolish Outlook
2981 Express clients then give up the first TLS connection and make a second one
2982 (which works). Only when there is an IMAP service on the same machine.
2983 Presumably OE is trying to use the cache for A on B. Leave it enabled for
2984 now, until we work out a decent way of presenting control to the config. It
2985 will never be used because we use a new context every time. */
2987 (void) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2990 /* Initialize with DH parameters if supplied */
2991 /* Initialize ECDH temp key parameter selection */
2995 if (state->lib_state.dh)
2996 { DEBUG(D_tls) debug_printf("TLS: DH params were preloaded\n"); }
2998 if (!init_dh(ctx, state->dhparam, errstr)) return DEFER;
3000 if (state->lib_state.ecdh)
3001 { DEBUG(D_tls) debug_printf("TLS: ECDH curve was preloaded\n"); }
3003 if (!init_ecdh(ctx, errstr)) return DEFER;
3006 /* Set up certificate and key (and perhaps OCSP info) */
3008 if (state->lib_state.conn_certs)
3011 debug_printf("TLS: %s certs were preloaded\n", host ? "client":"server");
3015 #ifndef DISABLE_OCSP
3016 if (!host) /* server */
3018 state->u_ocsp.server.file = ocsp_file;
3019 state->u_ocsp.server.file_expanded = NULL;
3020 state->u_ocsp.server.olist = NULL;
3023 if ((rc = tls_expand_session_files(ctx, state, errstr)) != OK) return rc;
3026 /* If we need to handle SNI or OCSP, do so */
3028 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
3029 # ifndef DISABLE_OCSP
3030 if (!host && !(state->u_ocsp.server.verify_stack = sk_X509_new_null()))
3032 DEBUG(D_tls) debug_printf("failed to create stack for stapling verify\n");
3037 if (!host) /* server */
3039 # ifndef DISABLE_OCSP
3040 /* We check u_ocsp.server.file, not server.olist, because we care about if
3041 the option exists, not what the current expansion might be, as SNI might
3042 change the certificate and OCSP file in use between now and the time the
3043 callback is invoked. */
3044 if (state->u_ocsp.server.file)
3046 SSL_CTX_set_tlsext_status_cb(ctx, tls_server_stapling_cb);
3047 SSL_CTX_set_tlsext_status_arg(ctx, state);
3050 /* We always do this, so that $tls_sni is available even if not used in
3052 SSL_CTX_set_tlsext_servername_callback(ctx, tls_servername_cb);
3053 SSL_CTX_set_tlsext_servername_arg(ctx, state);
3055 # ifdef EXIM_HAVE_ALPN
3056 if (tls_alpn && *tls_alpn)
3059 if ( expand_check(tls_alpn, US"tls_alpn", &exp_alpn, errstr)
3060 && *exp_alpn && !isblank(*exp_alpn))
3062 tls_alpn = exp_alpn; /* subprocess so ok to overwrite */
3063 SSL_CTX_set_alpn_select_cb(ctx, tls_server_alpn_cb, state);
3070 # ifndef DISABLE_OCSP
3072 if(ocsp_file) /* wanting stapling */
3074 if (!(state->u_ocsp.client.verify_store = X509_STORE_new()))
3076 DEBUG(D_tls) debug_printf("failed to create store for stapling verify\n");
3080 SSL_CTX_set_tlsext_status_cb(ctx, tls_client_stapling_cb);
3081 SSL_CTX_set_tlsext_status_arg(ctx, state);
3084 #endif /*EXIM_HAVE_OPENSSL_TLSEXT*/
3086 state->verify_cert_hostnames = NULL;
3088 #ifdef EXIM_HAVE_EPHEM_RSA_KEX
3089 /* Set up the RSA callback */
3090 SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
3093 /* Finally, set the session cache timeout, and we are done.
3094 The period appears to be also used for (server-generated) session tickets */
3096 SSL_CTX_set_timeout(ctx, ssl_session_timeout);
3097 DEBUG(D_tls) debug_printf("Initialized TLS\n");
3099 *caller_state = state;
3107 /*************************************************
3108 * Get name of cipher in use *
3109 *************************************************/
3112 Argument: pointer to an SSL structure for the connection
3113 pointer to number of bits for cipher
3114 Returns: pointer to allocated string in perm-pool
3118 construct_cipher_name(SSL * ssl, const uschar * ver, int * bits)
3120 int pool = store_pool;
3121 /* With OpenSSL 1.0.0a, 'c' needs to be const but the documentation doesn't
3122 yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
3123 the accessor functions use const in the prototype. */
3125 const SSL_CIPHER * c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
3128 SSL_CIPHER_get_bits(c, bits);
3130 store_pool = POOL_PERM;
3131 s = string_sprintf("%s:%s:%u", ver, SSL_CIPHER_get_name(c), *bits);
3133 DEBUG(D_tls) debug_printf("Cipher: %s\n", s);
3138 /* Get IETF-standard name for ciphersuite.
3139 Argument: pointer to an SSL structure for the connection
3140 Returns: pointer to string
3143 static const uschar *
3144 cipher_stdname_ssl(SSL * ssl)
3146 #ifdef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
3147 return CUS SSL_CIPHER_standard_name(SSL_get_current_cipher(ssl));
3149 ushort id = 0xffff & SSL_CIPHER_get_id(SSL_get_current_cipher(ssl));
3150 return cipher_stdname(id >> 8, id & 0xff);
3155 static const uschar *
3156 tlsver_name(SSL * ssl)
3159 int pool = store_pool;
3161 store_pool = POOL_PERM;
3162 s = string_copy(US SSL_get_version(ssl));
3164 if ((p = Ustrchr(s, 'v'))) /* TLSv1.2 -> TLS1.2 */
3165 for (;; p++) if (!(*p = p[1])) break;
3171 peer_cert(SSL * ssl, tls_support * tlsp, uschar * peerdn, unsigned siz)
3173 /*XXX we might consider a list-of-certs variable for the cert chain.
3174 SSL_get_peer_cert_chain(SSL*). We'd need a new variable type and support
3175 in list-handling functions, also consider the difference between the entire
3176 chain and the elements sent by the peer. */
3178 tlsp->peerdn = NULL;
3180 /* Will have already noted peercert on a verify fail; possibly not the leaf */
3181 if (!tlsp->peercert)
3182 tlsp->peercert = SSL_get_peer_certificate(ssl);
3183 /* Beware anonymous ciphers which lead to server_cert being NULL */
3185 if (!X509_NAME_oneline(X509_get_subject_name(tlsp->peercert), CS peerdn, siz))
3186 { DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n"); }
3189 int oldpool = store_pool;
3191 peerdn[siz-1] = '\0'; /* paranoia */
3192 store_pool = POOL_PERM;
3193 tlsp->peerdn = string_copy(peerdn);
3194 store_pool = oldpool;
3196 /* We used to set CV in the cert-verify callbacks (either plain or dane)
3197 but they don't get called on session-resumption. So use the official
3198 interface, which uses the resumed value. Unfortunately this claims verified
3199 when it actually failed but we're in try-verify mode, due to us wanting the
3200 knowlege that it failed so needing to have the callback and forcing a
3201 permissive return. If we don't force it, the TLS startup is failed.
3202 The extra bit of information is set in verify_override in the cb, stashed
3203 for resumption next to the TLS session, and used here. */
3205 if (!tlsp->verify_override)
3206 tlsp->certificate_verified =
3208 tlsp->dane_verified ||
3210 SSL_get_verify_result(ssl) == X509_V_OK;
3218 /*************************************************
3219 * Set up for verifying certificates *
3220 *************************************************/
3222 #ifndef DISABLE_OCSP
3223 /* In the server, load certs from file, return TRUE on success */
3226 chain_from_pem_file(const uschar * file, STACK_OF(X509) ** vp)
3229 STACK_OF(X509) * verify_stack = *vp;
3232 while (sk_X509_num(verify_stack) > 0)
3233 X509_free(sk_X509_pop(verify_stack));
3235 verify_stack = sk_X509_new_null();
3237 if (!(bp = BIO_new_file(CS file, "r"))) return FALSE;
3238 for (X509 * x; x = PEM_read_bio_X509(bp, NULL, 0, NULL); )
3239 sk_X509_push(verify_stack, x);
3248 /* Called by both client and server startup; on the server possibly
3249 repeated after a Server Name Indication.
3252 sctx SSL_CTX* to initialise
3253 certsp certs file, returned expanded
3254 crl CRL file or NULL
3255 host NULL in a server; the remote host in a client
3256 errstr error string pointer
3258 Returns: OK/DEFER/FAIL
3262 setup_certs(SSL_CTX * sctx, uschar ** certsp, uschar * crl, host_item * host,
3265 uschar * expcerts, * expcrl;
3267 if (!expand_check(*certsp, US"tls_verify_certificates", &expcerts, errstr))
3269 DEBUG(D_tls) debug_printf("tls_verify_certificates: %s\n", expcerts);
3272 if (expcerts && *expcerts)
3274 /* Tell the library to use its compiled-in location for the system default
3275 CA bundle. Then add the ones specified in the config, if any. */
3277 if (!SSL_CTX_set_default_verify_paths(sctx))
3278 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL, errstr);
3280 if (Ustrcmp(expcerts, "system") != 0 && Ustrncmp(expcerts, "system,", 7) != 0)
3282 struct stat statbuf;
3284 if (Ustat(expcerts, &statbuf) < 0)
3286 log_write(0, LOG_MAIN|LOG_PANIC,
3287 "failed to stat %s for certificates", expcerts);
3293 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
3294 { file = NULL; dir = expcerts; }
3297 STACK_OF(X509) * verify_stack =
3298 #ifndef DISABLE_OCSP
3299 !host ? state_server.u_ocsp.server.verify_stack :
3302 STACK_OF(X509) ** vp = &verify_stack;
3304 file = expcerts; dir = NULL;
3305 #ifndef DISABLE_OCSP
3306 /* In the server if we will be offering an OCSP proof; load chain from
3307 file for verifying the OCSP proof at load time. */
3309 /*XXX Glitch! The file here is tls_verify_certs: the chain for verifying the client cert.
3310 This is inconsistent with the need to verify the OCSP proof of the server cert.
3312 /* *debug_printf("file for checking server ocsp stapling is: %s\n", file); */
3314 && statbuf.st_size > 0
3315 && state_server.u_ocsp.server.file
3316 && !chain_from_pem_file(file, vp)
3319 log_write(0, LOG_MAIN|LOG_PANIC,
3320 "failed to load cert chain from %s", file);
3326 /* If a certificate file is empty, the load function fails with an
3327 unhelpful error message. If we skip it, we get the correct behaviour (no
3328 certificates are recognized, but the error message is still misleading (it
3329 says no certificate was supplied). But this is better. */
3331 if ( (!file || statbuf.st_size > 0)
3332 && !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
3333 return tls_error(US"SSL_CTX_load_verify_locations",
3334 host, NULL, errstr);
3336 /* On the server load the list of CAs for which we will accept certs, for
3337 sending to the client. This is only for the one-file
3338 tls_verify_certificates variant.
3339 If a list isn't loaded into the server, but some verify locations are set,
3340 the server end appears to make a wildcard request for client certs.
3341 Meanwhile, the client library as default behaviour *ignores* the list
3342 we send over the wire - see man SSL_CTX_set_client_cert_cb.
3343 Because of this, and that the dir variant is likely only used for
3344 the public-CA bundle (not for a private CA), not worth fixing. */
3348 STACK_OF(X509_NAME) * names = SSL_load_client_CA_file(CS file);
3349 int i = sk_X509_NAME_num(names);
3351 if (!host) SSL_CTX_set_client_CA_list(sctx, names);
3352 DEBUG(D_tls) debug_printf("Added %d additional certificate authorit%s\n",
3353 i, i>1 ? "ies":"y");
3357 debug_printf("Added dir for additional certificate authorities\n");
3361 /* Handle a certificate revocation list. */
3363 #if OPENSSL_VERSION_NUMBER > 0x00907000L
3365 /* This bit of code is now the version supplied by Lars Mainka. (I have
3366 merely reformatted it into the Exim code style.)
3368 "From here I changed the code to add support for multiple crl's
3369 in pem format in one file or to support hashed directory entries in
3370 pem format instead of a file. This method now uses the library function
3371 X509_STORE_load_locations to add the CRL location to the SSL context.
3372 OpenSSL will then handle the verify against CA certs and CRLs by
3373 itself in the verify callback." */
3375 if (!expand_check(crl, US"tls_crl", &expcrl, errstr)) return DEFER;
3376 if (expcrl && *expcrl)
3378 struct stat statbufcrl;
3379 if (Ustat(expcrl, &statbufcrl) < 0)
3381 log_write(0, LOG_MAIN|LOG_PANIC,
3382 "failed to stat %s for certificates revocation lists", expcrl);
3387 /* is it a file or directory? */
3389 X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
3390 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
3394 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
3400 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
3402 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
3403 return tls_error(US"X509_STORE_load_locations", host, NULL, errstr);
3405 /* setting the flags to check against the complete crl chain */
3407 X509_STORE_set_flags(cvstore,
3408 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
3412 #endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
3421 tls_dump_keylog(SSL * ssl)
3423 #ifdef EXIM_HAVE_OPENSSL_KEYLOG
3424 BIO * bp = BIO_new(BIO_s_mem());
3427 SSL_SESSION_print_keylog(bp, SSL_get_session(ssl));
3428 len = (int) BIO_get_mem_data(bp, CSS &s);
3429 if (len > 0) debug_printf("%.*s", len, s);
3435 /* Channel-binding info for authenticators
3436 See description in https://paquier.xyz/postgresql-2/channel-binding-openssl/
3441 tls_get_channel_binding(SSL * ssl, tls_support * tlsp, const void * taintval)
3446 #ifdef EXIM_HAVE_EXPORT_CHNL_BNGNG
3447 if (SSL_version(ssl) > TLS1_2_VERSION)
3449 /* It's not documented by OpenSSL how big the output buffer must be.
3450 The OpenSSL testcases use 80 bytes but don't say why. The GnuTLS impl only
3451 serves out 32B. RFC 9266 says it is 32B.
3452 Interop fails unless we use the same each end. */
3455 tlsp->channelbind_exporter = TRUE;
3456 taintval = GET_UNTAINTED;
3457 if (SSL_export_keying_material(ssl,
3458 s = store_get((int)len, taintval), len,
3459 "EXPORTER-Channel-Binding", (size_t) 24,
3466 len = SSL_get_peer_finished(ssl, &c, 0);
3467 len = SSL_get_peer_finished(ssl, s = store_get((int)len, taintval), len);
3472 int old_pool = store_pool;
3473 store_pool = POOL_PERM;
3474 tlsp->channelbinding = b64encode_taint(CUS s, (int)len, taintval);
3475 store_pool = old_pool;
3476 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage %p %p\n", tlsp->channelbinding, tlsp);
3481 /*************************************************
3482 * Start a TLS session in a server *
3483 *************************************************/
3484 /* This is called when Exim is running as a server, after having received
3485 the STARTTLS command. It must respond to that command, and then negotiate
3489 errstr pointer to error message
3491 Returns: OK on success
3492 DEFER for errors before the start of the negotiation
3493 FAIL for errors during the negotiation; the server can't
3498 tls_server_start(uschar ** errstr)
3501 uschar * expciphers;
3502 exim_openssl_state_st * dummy_statep;
3505 static uschar peerdn[256];
3507 /* Check for previous activation */
3509 if (tls_in.active.sock >= 0)
3511 tls_error(US"STARTTLS received after TLS started", NULL, US"", errstr);
3512 smtp_printf("554 Already in TLS\r\n", SP_NO_MORE);
3516 /* Initialize the SSL library. If it fails, it will already have logged
3519 rc = tls_init(NULL, NULL,
3520 #ifndef DISABLE_OCSP
3523 NULL, &dummy_statep, &tls_in, errstr);
3524 if (rc != OK) return rc;
3525 ctx = state_server.lib_state.lib_ctx;
3527 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
3528 were historically separated by underscores. So that I can use either form in my
3529 tests, and also for general convenience, we turn underscores into hyphens here.
3531 XXX SSL_CTX_set_cipher_list() is replaced by SSL_CTX_set_ciphersuites()
3532 for TLS 1.3 . Since we do not call it at present we get the default list:
3533 TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
3536 if (state_server.lib_state.pri_string)
3537 { DEBUG(D_tls) debug_printf("TLS: cipher list was preloaded\n"); }
3540 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers, errstr))
3545 normalise_ciphers(&expciphers, tls_require_ciphers);
3546 if ((rc = server_load_ciphers(ctx, &state_server, expciphers, errstr)) != OK)
3551 /* If this is a host for which certificate verification is mandatory or
3552 optional, set up appropriately. */
3554 tls_in.certificate_verified = FALSE;
3556 tls_in.dane_verified = FALSE;
3558 server_verify_callback_called = FALSE;
3560 if (verify_check_host(&tls_verify_hosts) == OK)
3561 server_verify_optional = FALSE;
3562 else if (verify_check_host(&tls_try_verify_hosts) == OK)
3563 server_verify_optional = TRUE;
3568 uschar * v_certs = tls_verify_certificates;
3570 if (state_server.lib_state.cabundle)
3572 DEBUG(D_tls) debug_printf("TLS: CA bundle for server was preloaded\n");
3573 setup_cert_verify(ctx, server_verify_optional, verify_callback_server);
3577 if ((rc = setup_certs(ctx, &v_certs, tls_crl, NULL, errstr)) != OK)
3579 if (v_certs && *v_certs)
3580 setup_cert_verify(ctx, server_verify_optional, verify_callback_server);
3585 #ifndef DISABLE_TLS_RESUME
3586 # if OPENSSL_VERSION_NUMBER < 0x30000000L
3587 SSL_CTX_set_tlsext_ticket_key_cb(ctx, ticket_key_callback);
3588 /* despite working, appears to always return failure, so ignoring */
3590 SSL_CTX_set_tlsext_ticket_key_evp_cb(ctx, ticket_key_callback);
3591 /* despite working, appears to always return failure, so ignoring */
3595 #ifdef OPENSSL_HAVE_NUM_TICKETS
3596 # ifndef DISABLE_TLS_RESUME
3597 SSL_CTX_set_num_tickets(ctx, tls_in.host_resumable ? 1 : 0);
3599 SSL_CTX_set_num_tickets(ctx, 0); /* send no TLS1.3 stateful-tickets */
3604 /* Prepare for new connection */
3606 if (!(ssl = SSL_new(ctx)))
3607 return tls_error(US"SSL_new", NULL, NULL, errstr);
3608 state_server.lib_state.lib_ssl = ssl;
3610 /* Warning: we used to SSL_clear(ssl) here, it was removed.
3612 * With the SSL_clear(), we get strange interoperability bugs with
3613 * OpenSSL 1.0.1b and TLS1.1/1.2. It looks as though this may be a bug in
3614 * OpenSSL itself, as a clear should not lead to inability to follow protocols.
3616 * The SSL_clear() call is to let an existing SSL* be reused, typically after
3617 * session shutdown. In this case, we have a brand new object and there's no
3618 * obvious reason to immediately clear it. I'm guessing that this was
3619 * originally added because of incomplete initialisation which the clear fixed,
3620 * in some historic release.
3623 /* Set context and tell client to go ahead, except in the case of TLS startup
3624 on connection, where outputting anything now upsets the clients and tends to
3625 make them disconnect. We need to have an explicit fflush() here, to force out
3626 the response. Other smtp_printf() calls do not need it, because in non-TLS
3627 mode, the fflush() happens when smtp_getc() is called. */
3629 SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
3630 if (!tls_in.on_connect)
3632 smtp_printf("220 TLS go ahead\r\n", SP_NO_MORE);
3636 /* Now negotiate the TLS session. We put our own timer on it, since it seems
3637 that the OpenSSL library doesn't. */
3639 SSL_set_wfd(ssl, fileno(smtp_out));
3640 SSL_set_rfd(ssl, fileno(smtp_in));
3641 SSL_set_accept_state(ssl);
3643 DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
3646 sigalrm_seen = FALSE;
3647 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
3648 rc = SSL_accept(ssl);
3653 int error = SSL_get_error(ssl, rc);
3656 case SSL_ERROR_NONE:
3659 case SSL_ERROR_ZERO_RETURN:
3660 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
3661 (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
3662 #ifndef DISABLE_EVENT
3663 (void) event_raise(event_action, US"tls:fail:connect", *errstr, NULL);
3665 if (SSL_get_shutdown(ssl) == SSL_RECEIVED_SHUTDOWN)
3668 tls_close(NULL, TLS_NO_SHUTDOWN);
3671 /* Handle genuine errors */
3675 int r = ERR_GET_REASON(ERR_peek_error());
3676 if ( r == SSL_R_WRONG_VERSION_NUMBER
3677 #ifdef SSL_R_VERSION_TOO_LOW
3678 || r == SSL_R_VERSION_TOO_LOW
3680 || r == SSL_R_UNKNOWN_PROTOCOL || r == SSL_R_UNSUPPORTED_PROTOCOL)
3681 s = string_sprintf("(%s)", SSL_get_version(ssl));
3682 (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : s, errstr);
3683 #ifndef DISABLE_EVENT
3684 (void) event_raise(event_action, US"tls:fail:connect", *errstr, NULL);
3690 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
3691 if (error == SSL_ERROR_SYSCALL)
3695 *errstr = US"SSL_accept: TCP connection closed by peer";
3696 #ifndef DISABLE_EVENT
3697 (void) event_raise(event_action, US"tls:fail:connect", *errstr, NULL);
3701 DEBUG(D_tls) debug_printf(" - syscall %s\n", strerror(errno));
3703 (void) tls_error(US"SSL_accept", NULL,
3704 sigalrm_seen ? US"timed out"
3705 : ERR_peek_error() ? NULL : string_sprintf("ret %d", error),
3707 #ifndef DISABLE_EVENT
3708 (void) event_raise(event_action, US"tls:fail:connect", *errstr, NULL);
3714 DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
3715 ERR_clear_error(); /* Even success can leave errors in the stack. Seen with
3716 anon-authentication ciphersuite negotiated. */
3718 #ifndef DISABLE_TLS_RESUME
3719 if (SSL_session_reused(ssl))
3721 tls_in.resumption |= RESUME_USED;
3722 DEBUG(D_tls) debug_printf("Session reused\n");
3726 #ifdef EXIM_HAVE_ALPN
3727 /* If require-alpn, check server_seen_alpn here. Else abort TLS */
3728 if (!tls_alpn || !*tls_alpn)
3729 { DEBUG(D_tls) debug_printf("TLS: was not watching for ALPN\n"); }
3730 else if (!server_seen_alpn)
3731 if (verify_check_host(&hosts_require_alpn) == OK)
3733 /* We'd like to send a definitive Alert but OpenSSL provides no facility */
3735 tls_error(US"handshake", NULL, US"ALPN required but not negotiated", errstr);
3739 { DEBUG(D_tls) debug_printf("TLS: no ALPN presented in handshake\n"); }
3742 const uschar * name;
3744 SSL_get0_alpn_selected(ssl, &name, &len);
3746 #ifdef EXIM_OPENSSL_BOGUS_SERVER_ALPN
3747 debug_printf("ALPN negotiated: '%.*s'\n", (int)*name, name+1);
3749 debug_printf("ALPN negotiated: '%.*s'\n", len, name);
3752 debug_printf("ALPN: no protocol negotiated\n");
3757 /* TLS has been set up. Record data for the connection,
3758 adjust the input functions to read via TLS, and initialize things. */
3760 #ifdef SSL_get_extms_support
3761 /*XXX what does this return for tls1.3 ? */
3762 tls_in.ext_master_secret = SSL_get_extms_support(ssl) == 1;
3764 peer_cert(ssl, &tls_in, peerdn, sizeof(peerdn));
3766 tls_in.ver = tlsver_name(ssl);
3767 tls_in.cipher = construct_cipher_name(ssl, tls_in.ver, &tls_in.bits);
3768 tls_in.cipher_stdname = cipher_stdname_ssl(ssl);
3773 if (SSL_get_shared_ciphers(ssl, CS buf, sizeof(buf)))
3774 debug_printf("Shared ciphers: %s\n", buf);
3776 tls_dump_keylog(ssl);
3778 #ifdef EXIM_HAVE_SESSION_TICKET
3780 SSL_SESSION * ss = SSL_get_session(ssl);
3781 if (SSL_SESSION_has_ticket(ss)) /* 1.1.0 */
3782 debug_printf("The session has a ticket, life %lu seconds\n",
3783 SSL_SESSION_get_ticket_lifetime_hint(ss));
3788 /* Record the certificate we presented */
3790 X509 * crt = SSL_get_certificate(ssl);
3791 tls_in.ourcert = crt ? X509_dup(crt) : NULL;
3794 tls_get_channel_binding(ssl, &tls_in, GET_UNTAINTED);
3796 /* Only used by the server-side tls (tls_in), including tls_getc.
3797 Client-side (tls_out) reads (seem to?) go via
3798 smtp_read_response()/ip_recv().
3799 Hence no need to duplicate for _in and _out.
3801 if (!ssl_xfer_buffer) ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
3802 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
3803 ssl_xfer_eof = ssl_xfer_error = FALSE;
3805 receive_getc = tls_getc;
3806 receive_getbuf = tls_getbuf;
3807 receive_get_cache = tls_get_cache;
3808 receive_hasc = tls_hasc;
3809 receive_ungetc = tls_ungetc;
3810 receive_feof = tls_feof;
3811 receive_ferror = tls_ferror;
3813 tls_in.active.sock = fileno(smtp_out);
3814 tls_in.active.tls_ctx = NULL; /* not using explicit ctx for server-side */
3822 tls_client_basic_ctx_init(SSL_CTX * ctx,
3823 host_item * host, smtp_transport_options_block * ob, exim_openssl_state_st * state,
3828 /* Back-compatible old behaviour if tls_verify_certificates is set but both
3829 tls_verify_hosts and tls_try_verify_hosts are not set. Check only the specified
3830 host patterns if one of them is set with content. */
3832 if ( ( ( !ob->tls_verify_hosts || !ob->tls_verify_hosts
3833 || Ustrcmp(ob->tls_try_verify_hosts, ":") == 0
3835 && ( !ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts
3836 || Ustrcmp(ob->tls_try_verify_hosts, ":") == 0
3839 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
3841 client_verify_optional = FALSE;
3842 else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
3843 client_verify_optional = TRUE;
3848 uschar * v_certs = ob->tls_verify_certificates;
3850 if (state->lib_state.cabundle)
3852 DEBUG(D_tls) debug_printf("TLS: CA bundle for tpt was preloaded\n");
3853 setup_cert_verify(ctx, client_verify_optional, verify_callback_client);
3857 if ((rc = setup_certs(ctx, &v_certs, ob->tls_crl, host, errstr)) != OK)
3859 if (v_certs && *v_certs)
3860 setup_cert_verify(ctx, client_verify_optional, verify_callback_client);
3864 if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
3866 state->verify_cert_hostnames =
3868 string_domain_utf8_to_alabel(host->certname, NULL);
3872 DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
3873 state->verify_cert_hostnames);
3881 dane_tlsa_load(SSL * ssl, host_item * host, dns_answer * dnsa, uschar ** errstr)
3884 const char * hostnames[2] = { CS host->name, NULL };
3887 if (DANESSL_init(ssl, NULL, hostnames) != 1)
3888 return tls_error(US"hostnames load", host, NULL, errstr);
3890 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
3891 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
3892 ) if (rr->type == T_TLSA && rr->size > 3)
3894 const uschar * p = rr->data;
3895 uint8_t usage, selector, mtype;
3896 const char * mdname;
3900 /* Only DANE-TA(2) and DANE-EE(3) are supported */
3901 if (usage != 2 && usage != 3) continue;
3908 default: continue; /* Only match-types 0, 1, 2 are supported */
3909 case 0: mdname = NULL; break;
3910 case 1: mdname = "sha256"; break;
3911 case 2: mdname = "sha512"; break;
3915 switch (DANESSL_add_tlsa(ssl, usage, selector, mdname, p, rr->size - 3))
3918 return tls_error(US"tlsa load", host, NULL, errstr);
3919 case 0: /* action not taken */
3923 tls_out.tlsa_usage |= 1<<usage;
3929 log_write(0, LOG_MAIN, "DANE error: No usable TLSA records");
3932 #endif /*SUPPORT_DANE*/
3936 #ifndef DISABLE_TLS_RESUME
3937 /* On the client, get any stashed session for the given IP from hints db
3938 and apply it to the ssl-connection for attempted resumption. */
3941 tls_retrieve_session(tls_support * tlsp, SSL * ssl)
3943 if (tlsp->host_resumable)
3945 dbdata_tls_session * dt;
3947 open_db dbblock, * dbm_file;
3949 tlsp->resumption |= RESUME_CLIENT_REQUESTED;
3951 debug_printf("checking for resumable session for %s\n", tlsp->resume_index);
3952 if ((dbm_file = dbfn_open(US"tls", O_RDWR|O_CREAT, &dbblock, FALSE, FALSE)))
3954 if ((dt = dbfn_read_with_length(dbm_file, tlsp->resume_index, &len)))
3956 SSL_SESSION * ss = NULL;
3957 const uschar * sess_asn1 = dt->session;
3959 len -= sizeof(dbdata_tls_session);
3960 if (!(d2i_SSL_SESSION(&ss, &sess_asn1, (long)len)))
3964 ERR_error_string_n(ERR_get_error(),
3965 ssl_errstring, sizeof(ssl_errstring));
3966 debug_printf("decoding session: %s\n", ssl_errstring);
3971 unsigned long lifetime =
3972 #ifdef EXIM_HAVE_SESSION_TICKET
3973 SSL_SESSION_get_ticket_lifetime_hint(ss);
3974 #else /* Use, fairly arbitrilarily, what we as server would */
3975 f.running_in_test_harness ? TESTSUITE_TICKET_LIFE : ssl_session_timeout;
3977 time_t now = time(NULL), expires = lifetime + dt->time_stamp;
3980 DEBUG(D_tls) debug_printf("session expired (by " TIME_T_FMT "s from %lus)\n", now - expires, lifetime);
3981 dbfn_delete(dbm_file, tlsp->resume_index);
3983 else if (SSL_set_session(ssl, ss))
3985 DEBUG(D_tls) debug_printf("good session (" TIME_T_FMT "s left of %lus)\n", expires - now, lifetime);
3986 tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
3987 tlsp->verify_override = dt->verify_override;
3988 tlsp->ocsp = dt->ocsp;
3992 ERR_error_string_n(ERR_get_error(),
3993 ssl_errstring, sizeof(ssl_errstring));
3994 debug_printf("applying session to ssl: %s\n", ssl_errstring);
3999 DEBUG(D_tls) debug_printf("no session record\n");
4000 dbfn_close(dbm_file);
4006 /* On the client, save the session for later resumption */
4009 tls_save_session_cb(SSL * ssl, SSL_SESSION * ss)
4011 exim_openssl_state_st * cbinfo = SSL_get_ex_data(ssl, tls_exdata_idx);
4014 DEBUG(D_tls) debug_printf("tls_save_session_cb\n");
4016 if (!cbinfo || !(tlsp = cbinfo->tlsp)->host_resumable) return 0;
4018 # ifdef OPENSSL_HAVE_NUM_TICKETS
4019 if (SSL_SESSION_is_resumable(ss)) /* 1.1.1 */
4022 int len = i2d_SSL_SESSION(ss, NULL);
4023 int dlen = sizeof(dbdata_tls_session) + len;
4024 dbdata_tls_session * dt = store_get(dlen, GET_TAINTED);
4025 uschar * s = dt->session;
4026 open_db dbblock, * dbm_file;
4028 DEBUG(D_tls) debug_printf("session is resumable\n");
4029 tlsp->resumption |= RESUME_SERVER_TICKET; /* server gave us a ticket */
4031 dt->verify_override = tlsp->verify_override;
4032 dt->ocsp = tlsp->ocsp;
4033 (void) i2d_SSL_SESSION(ss, &s); /* s gets bumped to end */
4035 if ((dbm_file = dbfn_open(US"tls", O_RDWR|O_CREAT, &dbblock, FALSE, FALSE)))
4037 dbfn_write(dbm_file, tlsp->resume_index, dt, dlen);
4038 dbfn_close(dbm_file);
4039 DEBUG(D_tls) debug_printf("wrote session (len %u) to db\n",
4047 /* Construct a key for session DB lookup, and setup the SSL_CTX for resumption */
4050 tls_client_ctx_resume_prehandshake(
4051 exim_openssl_client_tls_ctx * exim_client_ctx, smtp_connect_args * conn_args,
4052 tls_support * tlsp, smtp_transport_options_block * ob)
4054 tlsp->host_resumable = TRUE;
4055 tls_client_resmption_key(tlsp, conn_args, ob);
4057 SSL_CTX_set_session_cache_mode(exim_client_ctx->ctx,
4058 SSL_SESS_CACHE_CLIENT
4059 | SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_NO_AUTO_CLEAR);
4060 SSL_CTX_sess_set_new_cb(exim_client_ctx->ctx, tls_save_session_cb);
4064 tls_client_ssl_resume_prehandshake(SSL * ssl, tls_support * tlsp,
4065 host_item * host, uschar ** errstr)
4067 if (tlsp->host_resumable)
4070 debug_printf("tls_resumption_hosts overrides openssl_options, enabling tickets\n");
4071 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
4073 tls_exdata_idx = SSL_get_ex_new_index(0, 0, 0, 0, 0);
4074 if (!SSL_set_ex_data(ssl, tls_exdata_idx, client_static_state))
4076 tls_error(US"set ex_data", host, NULL, errstr);
4079 /* debug_printf("tls_exdata_idx %d cbinfo %p\n", tls_exdata_idx, client_static_state); */
4082 tlsp->resumption = RESUME_SUPPORTED;
4083 /* Pick up a previous session, saved on an old ticket */
4084 tls_retrieve_session(tlsp, ssl);
4089 tls_client_resume_posthandshake(exim_openssl_client_tls_ctx * exim_client_ctx,
4092 if (SSL_session_reused(exim_client_ctx->ssl))
4094 DEBUG(D_tls) debug_printf("The session was reused\n");
4095 tlsp->resumption |= RESUME_USED;
4098 #endif /* !DISABLE_TLS_RESUME */
4101 #ifdef EXIM_HAVE_ALPN
4102 /* Expand and convert an Exim list to an ALPN list. False return for fail.
4103 NULL plist return for silent no-ALPN.
4105 Overwite the passed-in list with the expanded version.
4109 tls_alpn_plist(uschar ** tls_alpn, const uschar ** plist, unsigned * plen,
4114 if (!expand_check(*tls_alpn, US"tls_alpn", &exp_alpn, errstr))
4116 *tls_alpn = exp_alpn;
4120 DEBUG(D_tls) debug_printf("Setting TLS ALPN forced to fail, not sending\n");
4125 /* The server implementation only accepts exactly one protocol name
4126 but it's little extra code complexity in the client. */
4128 const uschar * list = exp_alpn;
4129 uschar * p = store_get(Ustrlen(exp_alpn), exp_alpn), * s, * t;
4133 for (t = p; s = string_nextinlist(&list, &sep, NULL, 0); t += len)
4135 *t++ = len = (uschar) Ustrlen(s);
4138 *plist = (*plen = t - p) ? p : NULL;
4142 #endif /* EXIM_HAVE_ALPN */
4145 /*************************************************
4146 * Start a TLS session in a client *
4147 *************************************************/
4149 /* Called from the smtp transport after STARTTLS has been accepted.
4152 cctx connection context
4153 conn_args connection details
4154 cookie datum for randomness; can be NULL
4155 tlsp record details of TLS channel configuration here; must be non-NULL
4156 errstr error string pointer
4158 Returns: TRUE for success with TLS session context set in connection context,
4163 tls_client_start(client_conn_ctx * cctx, smtp_connect_args * conn_args,
4164 void * cookie, tls_support * tlsp, uschar ** errstr)
4166 host_item * host = conn_args->host; /* for msgs and option-tests */
4167 transport_instance * tb = conn_args->tblock; /* always smtp or NULL */
4168 smtp_transport_options_block * ob = tb
4169 ? tb->drinst.options_block
4170 : &smtp_transport_option_defaults;
4171 exim_openssl_client_tls_ctx * exim_client_ctx;
4172 uschar * expciphers;
4174 static uschar peerdn[256];
4176 #ifndef DISABLE_OCSP
4177 BOOL request_ocsp = FALSE;
4178 BOOL require_ocsp = FALSE;
4182 store_pool = POOL_PERM;
4183 exim_client_ctx = store_get(sizeof(exim_openssl_client_tls_ctx), GET_UNTAINTED);
4184 exim_client_ctx->corked = NULL;
4188 tlsp->tlsa_usage = 0;
4191 #ifndef DISABLE_OCSP
4193 # ifdef SUPPORT_DANE
4194 if ( conn_args->dane
4195 && ob->hosts_request_ocsp[0] == '*'
4196 && ob->hosts_request_ocsp[1] == '\0'
4199 /* Unchanged from default. Use a safer one under DANE */
4200 request_ocsp = TRUE;
4201 ob->hosts_request_ocsp = US"${if or { {= {0}{$tls_out_tlsa_usage}} "
4202 " {= {4}{$tls_out_tlsa_usage}} } "
4208 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK))
4209 request_ocsp = TRUE;
4211 # ifdef SUPPORT_DANE
4215 verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
4217 # if defined(SUPPORT_DANE) && !defined(EXIM_HAVE_OPENSSL_OCSP_RESP_GET0_SIGNER)
4218 if (conn_args->dane && (require_ocsp || request_ocsp))
4220 DEBUG(D_tls) debug_printf("OpenSSL version to early to combine OCSP"
4221 " and DANE; disabling OCSP\n");
4222 require_ocsp = request_ocsp = FALSE;
4228 rc = tls_init(host, ob,
4229 #ifndef DISABLE_OCSP
4230 (void *)(long)request_ocsp,
4232 cookie, &client_static_state, tlsp, errstr);
4233 if (rc != OK) return FALSE;
4235 exim_client_ctx->ctx = client_static_state->lib_state.lib_ctx;
4237 tlsp->certificate_verified = FALSE;
4238 client_verify_callback_called = FALSE;
4242 if (conn_args->dane)
4244 /* We fall back to tls_require_ciphers if unset, empty or forced failure, but
4245 other failures should be treated as problems. */
4246 if (ob->dane_require_tls_ciphers &&
4247 !expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
4248 &expciphers, errstr))
4250 if (expciphers && *expciphers == '\0')
4253 normalise_ciphers(&expciphers, ob->dane_require_tls_ciphers);
4258 if (!expand_check(ob->tls_require_ciphers, US"tls_require_ciphers",
4259 &expciphers, errstr))
4262 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
4263 are separated by underscores. So that I can use either form in my tests, and
4264 also for general convenience, we turn underscores into hyphens here. */
4266 normalise_ciphers(&expciphers, ob->tls_require_ciphers);
4271 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
4272 if (!SSL_CTX_set_cipher_list(exim_client_ctx->ctx, CS expciphers))
4274 tls_error(US"SSL_CTX_set_cipher_list", host, NULL, errstr);
4280 if (conn_args->dane)
4282 SSL_CTX_set_verify(exim_client_ctx->ctx,
4283 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
4284 verify_callback_client_dane);
4286 if (!DANESSL_library_init())
4288 tls_error(US"library init", host, NULL, errstr);
4291 if (DANESSL_CTX_init(exim_client_ctx->ctx) <= 0)
4293 tls_error(US"context init", host, NULL, errstr);
4296 DEBUG(D_tls) debug_printf("since dane-mode conn, not loading the usual CA bundle\n");
4302 if (tls_client_basic_ctx_init(exim_client_ctx->ctx, host, ob,
4303 client_static_state, errstr) != OK)
4308 if (!expand_check(ob->tls_sni, US"tls_sni", &tlsp->sni, errstr))
4311 { DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n"); }
4312 else if (!Ustrlen(tlsp->sni))
4316 #ifndef EXIM_HAVE_OPENSSL_TLSEXT
4317 log_write(0, LOG_MAIN, "SNI unusable with this OpenSSL library version; ignoring \"%s\"\n",
4325 #ifdef EXIM_HAVE_ALPN
4327 const uschar * plist;
4330 if (!tls_alpn_plist(&ob->tls_alpn, &plist, &plen, errstr))
4333 if (SSL_CTX_set_alpn_protos(exim_client_ctx->ctx, plist, plen) != 0)
4335 tls_error(US"alpn init", host, NULL, errstr);
4339 DEBUG(D_tls) debug_printf("Setting TLS ALPN '%s'\n", ob->tls_alpn);
4342 log_write(0, LOG_MAIN, "ALPN unusable with this OpenSSL library version; ignoring \"%s\"\n",
4346 #ifndef DISABLE_TLS_RESUME
4347 /*XXX have_lbserver: another cmdline arg possibly, for continued-conn, but use
4348 will be very low. */
4350 if (!conn_args->have_lbserver) /* wanted for tls_client_resmption_key() */
4351 { DEBUG(D_tls) debug_printf("resumption not supported on continued-connection\n"); }
4352 else if (verify_check_given_host(CUSS &ob->tls_resumption_hosts, host) == OK)
4353 tls_client_ctx_resume_prehandshake(exim_client_ctx, conn_args, tlsp, ob);
4357 if (!(exim_client_ctx->ssl = SSL_new(exim_client_ctx->ctx)))
4359 tls_error(US"SSL_new", host, NULL, errstr);
4362 SSL_set_session_id_context(exim_client_ctx->ssl, sid_ctx, Ustrlen(sid_ctx));
4363 SSL_set_fd(exim_client_ctx->ssl, cctx->sock);
4364 SSL_set_connect_state(exim_client_ctx->ssl);
4366 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
4369 DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tlsp->sni);
4370 SSL_set_tlsext_host_name(exim_client_ctx->ssl, tlsp->sni);
4375 if (conn_args->dane)
4376 if (dane_tlsa_load(exim_client_ctx->ssl, host, &conn_args->tlsa_dnsa, errstr) != OK)
4380 #ifndef DISABLE_OCSP
4381 /* Request certificate status at connection-time. If the server
4382 does OCSP stapling we will get the callback (set in tls_init()) */
4383 # ifdef SUPPORT_DANE
4387 if ( ((s = ob->hosts_require_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
4388 || ((s = ob->hosts_request_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
4390 { /* Re-eval now $tls_out_tlsa_usage is populated. If
4391 this means we avoid the OCSP request, we wasted the setup
4392 cost in tls_init(). */
4393 require_ocsp = verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
4394 request_ocsp = require_ocsp
4395 || verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
4402 SSL_set_tlsext_status_type(exim_client_ctx->ssl, TLSEXT_STATUSTYPE_ocsp);
4403 client_static_state->u_ocsp.client.verify_required = require_ocsp;
4404 tlsp->ocsp = OCSP_NOT_RESP;
4408 #ifndef DISABLE_TLS_RESUME
4409 if (!tls_client_ssl_resume_prehandshake(exim_client_ctx->ssl, tlsp, host,
4414 #ifndef DISABLE_EVENT
4415 client_static_state->event_action = tb ? tb->event_action : NULL;
4418 /* There doesn't seem to be a built-in timeout on connection. */
4420 DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
4421 sigalrm_seen = FALSE;
4422 ALARM(ob->command_timeout);
4423 rc = SSL_connect(exim_client_ctx->ssl);
4427 if (conn_args->dane)
4428 DANESSL_cleanup(exim_client_ctx->ssl);
4433 #ifndef DISABLE_OCSP
4434 if (client_static_state->u_ocsp.client.verify_errstr)
4435 { if (errstr) *errstr = client_static_state->u_ocsp.client.verify_errstr; }
4438 tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL, errstr);
4444 debug_printf("SSL_connect succeeded\n");
4445 tls_dump_keylog(exim_client_ctx->ssl);
4448 #ifndef DISABLE_TLS_RESUME
4449 tls_client_resume_posthandshake(exim_client_ctx, tlsp);
4452 #ifdef EXIM_HAVE_ALPN
4453 if (ob->tls_alpn) /* We requested. See what was negotiated. */
4455 const uschar * name;
4458 SSL_get0_alpn_selected(exim_client_ctx->ssl, &name, &len);
4460 { DEBUG(D_tls) debug_printf("ALPN negotiated %u: '%.*s'\n", len, (int)*name, name+1); }
4461 else if (verify_check_given_host(CUSS &ob->hosts_require_alpn, host) == OK)
4463 /* Would like to send a relevant fatal Alert, but OpenSSL has no API */
4464 tls_error(US"handshake", host, US"ALPN required but not negotiated", errstr);
4470 #ifdef SSL_get_extms_support
4471 tlsp->ext_master_secret = SSL_get_extms_support(exim_client_ctx->ssl) == 1;
4473 peer_cert(exim_client_ctx->ssl, tlsp, peerdn, sizeof(peerdn));
4475 tlsp->ver = tlsver_name(exim_client_ctx->ssl);
4476 tlsp->cipher = construct_cipher_name(exim_client_ctx->ssl, tlsp->ver, &tlsp->bits);
4477 tlsp->cipher_stdname = cipher_stdname_ssl(exim_client_ctx->ssl);
4479 /* Record the certificate we presented */
4481 X509 * crt = SSL_get_certificate(exim_client_ctx->ssl);
4482 tlsp->ourcert = crt ? X509_dup(crt) : NULL;
4485 /*XXX will this work with continued-TLS? */
4486 tls_get_channel_binding(exim_client_ctx->ssl, tlsp, GET_TAINTED);
4488 tlsp->active.sock = cctx->sock;
4489 tlsp->active.tls_ctx = exim_client_ctx;
4490 cctx->tls_ctx = exim_client_ctx;
4499 tls_refill(unsigned lim)
4501 SSL * ssl = state_server.lib_state.lib_ssl;
4505 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
4506 ssl_xfer_buffer, ssl_xfer_buffer_size);
4509 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
4510 inbytes = SSL_read(ssl, CS ssl_xfer_buffer,
4511 MIN(ssl_xfer_buffer_size, lim));
4512 error = SSL_get_error(ssl, inbytes);
4513 if (smtp_receive_timeout > 0) ALARM_CLR(0);
4515 if (had_command_timeout) /* set by signal handler */
4516 smtp_command_timeout_exit(); /* does not return */
4517 if (had_command_sigterm)
4518 smtp_command_sigterm_exit();
4519 if (had_data_timeout)
4520 smtp_data_timeout_exit();
4521 if (had_data_sigint)
4522 smtp_data_sigint_exit();
4524 /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
4525 closed down, not that the socket itself has been closed down. Revert to
4526 non-SSL handling. */
4530 case SSL_ERROR_NONE:
4533 case SSL_ERROR_ZERO_RETURN:
4534 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
4536 if (SSL_get_shutdown(ssl) == SSL_RECEIVED_SHUTDOWN)
4539 tls_close(NULL, TLS_NO_SHUTDOWN);
4542 /* Handle genuine errors */
4545 uschar * conn_info = smtp_get_connection_info();
4546 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0) conn_info += 5;
4547 /* I'd like to get separated H= here, but too hard for now */
4548 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
4549 log_write(0, LOG_MAIN, "TLS error (SSL_read): on %s %s", conn_info, ssl_errstring);
4550 ssl_xfer_error = TRUE;
4555 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
4556 DEBUG(D_tls) if (error == SSL_ERROR_SYSCALL)
4557 debug_printf(" - syscall %s\n", strerror(errno));
4558 ssl_xfer_error = TRUE;
4562 #ifndef DISABLE_DKIM
4563 smtp_verify_feed(ssl_xfer_buffer, inbytes);
4565 ssl_xfer_buffer_hwm = inbytes;
4566 ssl_xfer_buffer_lwm = 0;
4571 /*************************************************
4572 * TLS version of getc *
4573 *************************************************/
4575 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
4576 it refills the buffer via the SSL reading function.
4578 Arguments: lim Maximum amount to read/buffer
4579 Returns: the next character or EOF
4581 Only used by the server-side TLS.
4585 tls_getc(unsigned lim)
4587 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
4588 if (!tls_refill(lim))
4589 return ssl_xfer_error ? EOF : smtp_getc(lim);
4591 /* Something in the buffer; return next uschar */
4593 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
4599 return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm;
4603 tls_getbuf(unsigned * len)
4608 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
4609 if (!tls_refill(*len))
4611 if (!ssl_xfer_error) return smtp_getbuf(len);
4616 if ((size = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm) > *len)
4618 buf = &ssl_xfer_buffer[ssl_xfer_buffer_lwm];
4619 ssl_xfer_buffer_lwm += size;
4626 tls_get_cache(unsigned lim)
4628 #ifndef DISABLE_DKIM
4629 int n = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm;
4633 smtp_verify_feed(ssl_xfer_buffer+ssl_xfer_buffer_lwm, n);
4639 tls_could_getc(void)
4641 return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm
4642 || SSL_pending(state_server.lib_state.lib_ssl) > 0;
4646 /*************************************************
4647 * Read bytes from TLS channel *
4648 *************************************************/
4652 ct_ctx client context pointer, or NULL for the one global server context
4656 Returns: the number of bytes read
4657 -1 after a failed read, including EOF
4659 Only used by the client-side TLS.
4663 tls_read(void * ct_ctx, uschar *buff, size_t len)
4665 SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl
4666 : state_server.lib_state.lib_ssl;
4670 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
4671 buff, (unsigned int)len);
4674 inbytes = SSL_read(ssl, CS buff, len);
4675 error = SSL_get_error(ssl, inbytes);
4677 if (error == SSL_ERROR_ZERO_RETURN)
4679 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
4682 else if (error != SSL_ERROR_NONE)
4692 /*************************************************
4693 * Write bytes down TLS channel *
4694 *************************************************/
4698 ct_ctx client context pointer, or NULL for the one global server context
4701 more further data expected soon
4703 Returns: the number of bytes after a successful write,
4704 -1 after a failed write
4706 Used by both server-side and client-side TLS. Calling with len zero and more unset
4707 will flush buffered writes; buff can be null for this case.
4711 tls_write(void * ct_ctx, const uschar * buff, size_t len, BOOL more)
4714 int outbytes, error;
4716 ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl
4717 : state_server.lib_state.lib_ssl;
4718 static gstring * server_corked = NULL;
4719 gstring ** corkedp = ct_ctx
4720 ? &((exim_openssl_client_tls_ctx *)ct_ctx)->corked : &server_corked;
4721 gstring * corked = *corkedp;
4723 DEBUG(D_tls) debug_printf("%s(%p, %lu%s)\n", __FUNCTION__,
4724 buff, (unsigned long)len, more ? ", more" : "");
4726 /* Lacking a CORK or MSG_MORE facility (such as GnuTLS has) we copy data when
4727 "more" is notified. This hack is only ok if small amounts are involved AND only
4728 one stream does it, in one context (i.e. no store reset). Currently it is used
4729 for the responses to the received SMTP MAIL , RCPT, DATA sequence, only.
4730 We support callouts done by the server process by using a separate client
4731 context for the stashed information. */
4732 /* + if PIPE_COMMAND, banner & ehlo-resp for smmtp-on-connect. Suspect there's
4733 a store reset there, so use POOL_PERM. */
4734 /* + if CHUNKING, cmds EHLO,MAIL,RCPT(s),BDAT */
4738 if (!len) buff = US &error; /* dummy just so that string_catn is ok */
4740 int save_pool = store_pool;
4741 store_pool = POOL_PERM;
4743 corked = string_catn(corked, buff, len);
4745 store_pool = save_pool;
4752 buff = CUS corked->s;
4757 for (int left = len; left > 0;)
4759 DEBUG(D_tls) debug_printf("SSL_write(%p, %p, %d)\n", ssl, buff, left);
4761 outbytes = SSL_write(ssl, CS buff, left);
4762 error = SSL_get_error(ssl, outbytes);
4763 DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
4766 case SSL_ERROR_NONE: /* the usual case */
4772 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
4773 log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
4776 case SSL_ERROR_ZERO_RETURN:
4777 log_write(0, LOG_MAIN, "SSL channel closed on write");
4780 case SSL_ERROR_SYSCALL:
4781 if (ct_ctx || errno != ECONNRESET || !f.smtp_in_quit)
4782 log_write(0, LOG_MAIN, "SSL_write: (from %s) syscall: %s",
4783 sender_fullhost ? sender_fullhost : US"<unknown>",
4785 else if (LOGGING(protocol_detail))
4786 log_write(0, LOG_MAIN, "[%s] after QUIT, client reset TCP before"
4787 " SMTP response and TLS close\n", sender_host_address);
4789 DEBUG(D_tls) debug_printf("[%s] SSL_write: after QUIT,"
4790 " client reset TCP before TLS close\n", sender_host_address);
4794 log_write(0, LOG_MAIN, "SSL_write error %d", error);
4805 ct_ctx client TLS context pointer, or NULL for the one global server context
4809 tls_shutdown_wr(void * ct_ctx)
4811 exim_openssl_client_tls_ctx * o_ctx = ct_ctx;
4812 SSL ** sslp = o_ctx ? &o_ctx->ssl : (SSL **) &state_server.lib_state.lib_ssl;
4813 int * fdp = o_ctx ? &tls_out.active.sock : &tls_in.active.sock;
4816 if (*fdp < 0) return; /* TLS was not active */
4818 tls_write(ct_ctx, NULL, 0, FALSE); /* flush write buffer */
4820 HDEBUG(D_transport|D_tls|D_acl|D_v) debug_printf_indent(" SMTP(TLS shutdown)>>\n");
4821 rc = SSL_shutdown(*sslp);
4822 if (rc < 0) DEBUG(D_tls)
4824 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
4825 debug_printf("SSL_shutdown: %s\n", ssl_errstring);
4829 /*************************************************
4830 * Close down a TLS session *
4831 *************************************************/
4833 /* This is also called from within a delivery subprocess forked from the
4834 daemon, to shut down the TLS library, without actually doing a shutdown (which
4835 would tamper with the SSL session in the parent process).
4838 ct_ctx client TLS context pointer, or NULL for the one global server context
4839 do_shutdown 0 no data-flush or TLS close-alert
4840 1 if TLS close-alert is to be sent,
4841 2 if also response to be waited for
4845 Used by both server-side and client-side TLS.
4849 tls_close(void * ct_ctx, int do_shutdown)
4851 exim_openssl_client_tls_ctx * o_ctx = ct_ctx;
4852 SSL ** sslp = o_ctx ? &o_ctx->ssl : (SSL **) &state_server.lib_state.lib_ssl;
4853 int * fdp = o_ctx ? &tls_out.active.sock : &tls_in.active.sock;
4855 if (*fdp < 0) return; /* TLS was not active */
4857 if (do_shutdown > TLS_NO_SHUTDOWN)
4860 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
4861 do_shutdown > TLS_SHUTDOWN_NOWAIT ? " (with response-wait)" : "");
4863 tls_write(ct_ctx, NULL, 0, FALSE); /* flush write buffer */
4865 if ( ( do_shutdown >= TLS_SHUTDOWN_WONLY
4866 || (rc = SSL_shutdown(*sslp)) == 0 /* send "close notify" alert */
4868 && do_shutdown > TLS_SHUTDOWN_NOWAIT
4871 #ifdef EXIM_TCP_CORK
4872 (void) setsockopt(*fdp, IPPROTO_TCP, EXIM_TCP_CORK, US &off, sizeof(off));
4875 rc = SSL_shutdown(*sslp); /* wait for response */
4879 if (rc < 0) DEBUG(D_tls)
4881 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
4882 debug_printf("SSL_shutdown: %s\n", ssl_errstring);
4886 if (!o_ctx) /* server side */
4888 #ifndef DISABLE_OCSP
4889 sk_X509_pop_free(state_server.u_ocsp.server.verify_stack, X509_free);
4890 state_server.u_ocsp.server.verify_stack = NULL;
4893 receive_getc = smtp_getc;
4894 receive_getbuf = smtp_getbuf;
4895 receive_get_cache = smtp_get_cache;
4896 receive_hasc = smtp_hasc;
4897 receive_ungetc = smtp_ungetc;
4898 receive_feof = smtp_feof;
4899 receive_ferror = smtp_ferror;
4900 tls_in.active.tls_ctx = NULL;
4902 /* Leave bits, peercert, cipher, peerdn, certificate_verified set, for logging */
4913 /*************************************************
4914 * Let tls_require_ciphers be checked at startup *
4915 *************************************************/
4917 /* The tls_require_ciphers option, if set, must be something which the
4920 Returns: NULL on success, or error message
4924 tls_validate_require_cipher(void)
4927 uschar * expciphers, * err;
4931 if (!(tls_require_ciphers && *tls_require_ciphers))
4934 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
4936 return US"failed to expand tls_require_ciphers";
4938 if (!(expciphers && *expciphers))
4941 normalise_ciphers(&expciphers, tls_require_ciphers);
4944 if (lib_ctx_new(&ctx, NULL, &err) == OK)
4947 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
4949 if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
4951 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
4952 err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed: %s",
4953 expciphers, ssl_errstring);
4964 /*************************************************
4965 * Report the library versions. *
4966 *************************************************/
4968 /* There have historically been some issues with binary compatibility in
4969 OpenSSL libraries; if Exim (like many other applications) is built against
4970 one version of OpenSSL but the run-time linker picks up another version,
4971 it can result in serious failures, including crashing with a SIGSEGV. So
4972 report the version found by the compiler and the run-time version.
4974 Note: some OS vendors backport security fixes without changing the version
4975 number/string, and the version date remains unchanged. The _build_ date
4976 will change, so we can more usefully assist with version diagnosis by also
4977 reporting the build date.
4979 Arguments: string to append to
4984 tls_version_report(gstring * g)
4986 return string_fmt_append(g,
4987 "Library version: OpenSSL: Compile: %s\n"
4990 OPENSSL_VERSION_TEXT,
4991 SSLeay_version(SSLEAY_VERSION),
4992 SSLeay_version(SSLEAY_BUILT_ON));
4993 /* third line is 38 characters for the %s and the line is 73 chars long;
4994 the OpenSSL output includes a "built on: " prefix already. */
5000 /*************************************************
5001 * Random number generation *
5002 *************************************************/
5004 /* Pseudo-random number generation. The result is not expected to be
5005 cryptographically strong but not so weak that someone will shoot themselves
5006 in the foot using it as a nonce in input in some email header scheme or
5007 whatever weirdness they'll twist this into. The result should handle fork()
5008 and avoid repeating sequences. OpenSSL handles that for us.
5012 Returns a random number in range [0, max-1]
5016 vaguely_random_number(int max)
5020 static pid_t pidlast = 0;
5022 uschar smallbuf[sizeof(r)];
5028 if (pidnow != pidlast)
5030 /* Although OpenSSL documents that "OpenSSL makes sure that the PRNG state
5031 is unique for each thread", this doesn't apparently apply across processes,
5032 so our own warning from vaguely_random_number_fallback() applies here too.
5033 Fix per PostgreSQL. */
5039 /* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
5043 gettimeofday(&r.tv, NULL);
5046 RAND_seed(US (&r), sizeof(r));
5048 /* We're after pseudo-random, not random; if we still don't have enough data
5049 in the internal PRNG then our options are limited. We could sleep and hope
5050 for entropy to come along (prayer technique) but if the system is so depleted
5051 in the first place then something is likely to just keep taking it. Instead,
5052 we'll just take whatever little bit of pseudo-random we can still manage to
5055 needed_len = sizeof(r);
5056 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
5057 asked for a number less than 10. */
5058 for (r = max, i = 0; r; ++i)
5064 #ifdef EXIM_HAVE_RAND_PSEUDO
5065 /* We do not care if crypto-strong */
5066 i = RAND_pseudo_bytes(smallbuf, needed_len);
5068 i = RAND_bytes(smallbuf, needed_len);
5074 debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
5075 return vaguely_random_number_fallback(max);
5079 for (uschar * p = smallbuf; needed_len; --needed_len, ++p)
5082 /* We don't particularly care about weighted results; if someone wants
5083 smooth distribution and cares enough then they should submit a patch then. */
5090 /*************************************************
5091 * OpenSSL option parse *
5092 *************************************************/
5094 /* Parse one option for tls_openssl_options_parse below
5097 name one option name
5098 value place to store a value for it
5099 Returns success or failure in parsing
5105 tls_openssl_one_option_parse(uschar *name, long *value)
5108 int last = exim_openssl_options_size;
5109 while (last > first)
5111 int middle = (first + last)/2;
5112 int c = Ustrcmp(name, exim_openssl_options[middle].name);
5115 *value = exim_openssl_options[middle].value;
5129 /*************************************************
5130 * OpenSSL option parsing logic *
5131 *************************************************/
5133 /* OpenSSL has a number of compatibility options which an administrator might
5134 reasonably wish to set. Interpret a list similarly to decode_bits(), so that
5135 we look like log_selector.
5138 option_spec the administrator-supplied string of options
5139 results ptr to long storage for the options bitmap
5140 Returns success or failure
5144 tls_openssl_options_parse(uschar *option_spec, long *results)
5147 uschar * exp, * end;
5148 BOOL adding, item_parsed;
5150 /* Server: send no (<= TLS1.2) session tickets */
5151 result = SSL_OP_NO_TICKET;
5153 /* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
5154 from default because it increases BEAST susceptibility. */
5155 #ifdef SSL_OP_NO_SSLv2
5156 result |= SSL_OP_NO_SSLv2;
5158 #ifdef SSL_OP_NO_SSLv3
5159 result |= SSL_OP_NO_SSLv3;
5161 #ifdef SSL_OP_SINGLE_DH_USE
5162 result |= SSL_OP_SINGLE_DH_USE;
5164 #ifdef SSL_OP_NO_RENEGOTIATION
5165 result |= SSL_OP_NO_RENEGOTIATION;
5174 if (!expand_check(option_spec, US"openssl_options", &exp, &end))
5177 for (uschar * s = exp; *s; /**/)
5179 if (!Uskip_whitespace(&s))
5181 if (*s != '+' && *s != '-')
5183 DEBUG(D_tls) debug_printf("malformed openssl option setting: "
5184 "+ or - expected but found \"%s\"\n", s);
5187 adding = *s++ == '+';
5189 Uskip_nonwhite(&end);
5190 item_parsed = tls_openssl_one_option_parse(string_copyn(s, end-s), &item);
5193 DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
5196 DEBUG(D_tls) debug_printf("openssl option, %s %08lx: %08lx (%s)\n",
5197 adding ? "adding to " : "removing from", result, item, s);
5211 /* For ATRN provider: transfer the tls_in context to tls_out */
5214 tls_state_in_to_out(int newfd, const uschar * ipaddr, int port)
5216 exim_openssl_client_tls_ctx * exim_client_ctx;
5217 int old_pool = store_pool;
5219 state_server.is_server = FALSE;
5220 state_server.tlsp = &tls_out;
5221 client_static_state = &state_server;
5223 store_pool = POOL_PERM;
5224 exim_client_ctx = store_get(sizeof(exim_openssl_client_tls_ctx), GET_UNTAINTED);
5225 exim_client_ctx->ctx = client_static_state->lib_state.lib_ctx;
5226 exim_client_ctx->ssl = client_static_state->lib_state.lib_ssl;
5227 exim_client_ctx->corked = NULL;
5228 store_pool = old_pool;
5230 SSL_set_fd(exim_client_ctx->ssl, newfd);
5233 tls_out.active.sock = newfd;
5234 tls_out.active.tls_ctx = exim_client_ctx;
5236 memset(&tls_in, 0, sizeof(tls_in));
5239 /* For ATRN customer: transfer the tls_out context to tls_in */
5242 tls_state_out_to_in(int newfd, const uschar * ipaddr, int port)
5244 exim_openssl_client_tls_ctx * exim_client_ctx = tls_out.active.tls_ctx;
5246 if (!ssl_xfer_buffer) ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
5247 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
5248 ssl_xfer_eof = ssl_xfer_error = FALSE;
5250 state_server.is_server = TRUE;
5251 state_server.tlsp = &tls_in;
5252 state_server.lib_state.lib_ctx = exim_client_ctx->ctx;
5253 state_server.lib_state.lib_ssl = exim_client_ctx->ssl;
5255 SSL_set_fd(state_server.lib_state.lib_ssl, newfd);
5258 tls_in.on_connect = FALSE;
5259 tls_in.active.sock = newfd;
5260 tls_in.active.tls_ctx = NULL;
5262 memset(&tls_out, 0, sizeof(tls_out));
5267 #endif /*!MACRO_PREDEF*/
5270 /* End of tls-openssl.c */