Copyright updates:
[exim.git] / src / src / tls-openssl.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2019 */
6 /* Copyright (c) The Exim Maintainers 2020 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
9 /* Portions Copyright (c) The OpenSSL Project 1999 */
10
11 /* This module provides the TLS (aka SSL) support for Exim using the OpenSSL
12 library. It is #included into the tls.c file when that library is used. The
13 code herein is based on a patch that was originally contributed by Steve
14 Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
15
16 No cryptographic code is included in Exim. All this module does is to call
17 functions from the OpenSSL library. */
18
19
20 /* Heading stuff */
21
22 #include <openssl/lhash.h>
23 #include <openssl/ssl.h>
24 #include <openssl/err.h>
25 #include <openssl/rand.h>
26 #ifndef OPENSSL_NO_ECDH
27 # include <openssl/ec.h>
28 #endif
29 #ifndef DISABLE_OCSP
30 # include <openssl/ocsp.h>
31 #endif
32 #ifdef SUPPORT_DANE
33 # include "danessl.h"
34 #endif
35
36
37 #ifndef DISABLE_OCSP
38 # define EXIM_OCSP_SKEW_SECONDS (300L)
39 # define EXIM_OCSP_MAX_AGE (-1L)
40 #endif
41
42 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
43 # define EXIM_HAVE_OPENSSL_TLSEXT
44 #endif
45 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
46 # define EXIM_HAVE_RSA_GENKEY_EX
47 #endif
48 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
49 # define EXIM_HAVE_OCSP_RESP_COUNT
50 # define OPENSSL_AUTO_SHA256
51 #else
52 # define EXIM_HAVE_EPHEM_RSA_KEX
53 # define EXIM_HAVE_RAND_PSEUDO
54 #endif
55 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
56 # define EXIM_HAVE_SHA256
57 #endif
58
59 /* X509_check_host provides sane certificate hostname checking, but was added
60 to OpenSSL late, after other projects forked off the code-base.  So in
61 addition to guarding against the base version number, beware that LibreSSL
62 does not (at this time) support this function.
63
64 If LibreSSL gains a different API, perhaps via libtls, then we'll probably
65 opt to disentangle and ask a LibreSSL user to provide glue for a third
66 crypto provider for libtls instead of continuing to tie the OpenSSL glue
67 into even twistier knots.  If LibreSSL gains the same API, we can just
68 change this guard and punt the issue for a while longer. */
69
70 #ifndef LIBRESSL_VERSION_NUMBER
71 # if OPENSSL_VERSION_NUMBER >= 0x010100000L
72 #  define EXIM_HAVE_OPENSSL_CHECKHOST
73 #  define EXIM_HAVE_OPENSSL_DH_BITS
74 #  define EXIM_HAVE_OPENSSL_TLS_METHOD
75 #  define EXIM_HAVE_OPENSSL_KEYLOG
76 #  define EXIM_HAVE_OPENSSL_CIPHER_GET_ID
77 #  define EXIM_HAVE_SESSION_TICKET
78 #  define EXIM_HAVE_OPESSL_TRACE
79 #  define EXIM_HAVE_OPESSL_GET0_SERIAL
80 #  ifndef DISABLE_OCSP
81 #   define EXIM_HAVE_OCSP
82 #  endif
83 # else
84 #  define EXIM_NEED_OPENSSL_INIT
85 # endif
86 # if OPENSSL_VERSION_NUMBER >= 0x010000000L \
87     && (OPENSSL_VERSION_NUMBER & 0x0000ff000L) >= 0x000002000L
88 #  define EXIM_HAVE_OPENSSL_CHECKHOST
89 # endif
90 #endif
91
92 #if !defined(LIBRESSL_VERSION_NUMBER) \
93     || LIBRESSL_VERSION_NUMBER >= 0x20010000L
94 # if !defined(OPENSSL_NO_ECDH)
95 #  if OPENSSL_VERSION_NUMBER >= 0x0090800fL
96 #   define EXIM_HAVE_ECDH
97 #  endif
98 #  if OPENSSL_VERSION_NUMBER >= 0x10002000L
99 #   define EXIM_HAVE_OPENSSL_EC_NIST2NID
100 #  endif
101 # endif
102 #endif
103
104 #ifndef LIBRESSL_VERSION_NUMBER
105 # if OPENSSL_VERSION_NUMBER >= 0x010101000L
106 #  define OPENSSL_HAVE_KEYLOG_CB
107 #  define OPENSSL_HAVE_NUM_TICKETS
108 #  define EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
109 # else
110 #  define OPENSSL_BAD_SRVR_OURCERT
111 # endif
112 #endif
113
114 #if !defined(EXIM_HAVE_OPENSSL_TLSEXT) && !defined(DISABLE_OCSP)
115 # warning "OpenSSL library version too old; define DISABLE_OCSP in Makefile"
116 # define DISABLE_OCSP
117 #endif
118
119 #ifdef EXPERIMENTAL_TLS_RESUME
120 # if OPENSSL_VERSION_NUMBER < 0x0101010L
121 #  error OpenSSL version too old for session-resumption
122 # endif
123 #endif
124
125 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
126 # include <openssl/x509v3.h>
127 #endif
128
129 #ifndef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
130 # ifndef EXIM_HAVE_OPENSSL_CIPHER_GET_ID
131 #  define SSL_CIPHER_get_id(c) (c->id)
132 # endif
133 # ifndef MACRO_PREDEF
134 #  include "tls-cipher-stdname.c"
135 # endif
136 #endif
137
138 /*************************************************
139 *        OpenSSL option parse                    *
140 *************************************************/
141
142 typedef struct exim_openssl_option {
143   uschar *name;
144   long    value;
145 } exim_openssl_option;
146 /* We could use a macro to expand, but we need the ifdef and not all the
147 options document which version they were introduced in.  Policylet: include
148 all options unless explicitly for DTLS, let the administrator choose which
149 to apply.
150
151 This list is current as of:
152   ==>  1.1.1c  <==
153
154 XXX could we autobuild this list, as with predefined-macros?
155 Seems just parsing ssl.h for SSL_OP_.* would be enough (except to exclude DTLS).
156 Also allow a numeric literal?
157 */
158 static exim_openssl_option exim_openssl_options[] = {
159 /* KEEP SORTED ALPHABETICALLY! */
160 #ifdef SSL_OP_ALL
161   { US"all", (long) SSL_OP_ALL },
162 #endif
163 #ifdef SSL_OP_ALLOW_NO_DHE_KEX
164   { US"allow_no_dhe_kex", SSL_OP_ALLOW_NO_DHE_KEX },
165 #endif
166 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
167   { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
168 #endif
169 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
170   { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
171 #endif
172 #ifdef SSL_OP_CRYPTOPRO_TLSEXT_BUG
173   { US"cryptopro_tlsext_bug", SSL_OP_CRYPTOPRO_TLSEXT_BUG },
174 #endif
175 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
176   { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
177 #endif
178 #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
179   { US"enable_middlebox_compat", SSL_OP_ENABLE_MIDDLEBOX_COMPAT },
180 #endif
181 #ifdef SSL_OP_EPHEMERAL_RSA
182   { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
183 #endif
184 #ifdef SSL_OP_LEGACY_SERVER_CONNECT
185   { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
186 #endif
187 #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
188   { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
189 #endif
190 #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
191   { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
192 #endif
193 #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
194   { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
195 #endif
196 #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
197   { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
198 #endif
199 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
200   { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
201 #endif
202 #ifdef SSL_OP_NO_ANTI_REPLAY
203   { US"no_anti_replay", SSL_OP_NO_ANTI_REPLAY },
204 #endif
205 #ifdef SSL_OP_NO_COMPRESSION
206   { US"no_compression", SSL_OP_NO_COMPRESSION },
207 #endif
208 #ifdef SSL_OP_NO_ENCRYPT_THEN_MAC
209   { US"no_encrypt_then_mac", SSL_OP_NO_ENCRYPT_THEN_MAC },
210 #endif
211 #ifdef SSL_OP_NO_RENEGOTIATION
212   { US"no_renegotiation", SSL_OP_NO_RENEGOTIATION },
213 #endif
214 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
215   { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
216 #endif
217 #ifdef SSL_OP_NO_SSLv2
218   { US"no_sslv2", SSL_OP_NO_SSLv2 },
219 #endif
220 #ifdef SSL_OP_NO_SSLv3
221   { US"no_sslv3", SSL_OP_NO_SSLv3 },
222 #endif
223 #ifdef SSL_OP_NO_TICKET
224   { US"no_ticket", SSL_OP_NO_TICKET },
225 #endif
226 #ifdef SSL_OP_NO_TLSv1
227   { US"no_tlsv1", SSL_OP_NO_TLSv1 },
228 #endif
229 #ifdef SSL_OP_NO_TLSv1_1
230 #if SSL_OP_NO_TLSv1_1 == 0x00000400L
231   /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
232 #warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
233 #else
234   { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
235 #endif
236 #endif
237 #ifdef SSL_OP_NO_TLSv1_2
238   { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
239 #endif
240 #ifdef SSL_OP_NO_TLSv1_3
241   { US"no_tlsv1_3", SSL_OP_NO_TLSv1_3 },
242 #endif
243 #ifdef SSL_OP_PRIORITIZE_CHACHA
244   { US"prioritize_chacha", SSL_OP_PRIORITIZE_CHACHA },
245 #endif
246 #ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
247   { US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
248 #endif
249 #ifdef SSL_OP_SINGLE_DH_USE
250   { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
251 #endif
252 #ifdef SSL_OP_SINGLE_ECDH_USE
253   { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
254 #endif
255 #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
256   { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
257 #endif
258 #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
259   { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
260 #endif
261 #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
262   { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
263 #endif
264 #ifdef SSL_OP_TLS_D5_BUG
265   { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
266 #endif
267 #ifdef SSL_OP_TLS_ROLLBACK_BUG
268   { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
269 #endif
270 #ifdef SSL_OP_TLSEXT_PADDING
271   { US"tlsext_padding", SSL_OP_TLSEXT_PADDING },
272 #endif
273 };
274
275 #ifndef MACRO_PREDEF
276 static int exim_openssl_options_size = nelem(exim_openssl_options);
277 #endif
278
279 #ifdef MACRO_PREDEF
280 void
281 options_tls(void)
282 {
283 uschar buf[64];
284
285 for (struct exim_openssl_option * o = exim_openssl_options;
286      o < exim_openssl_options + nelem(exim_openssl_options); o++)
287   {
288   /* Trailing X is workaround for problem with _OPT_OPENSSL_NO_TLSV1
289   being a ".ifdef _OPT_OPENSSL_NO_TLSV1_3" match */
290
291   spf(buf, sizeof(buf), US"_OPT_OPENSSL_%T_X", o->name);
292   builtin_macro_create(buf);
293   }
294
295 # ifdef EXPERIMENTAL_TLS_RESUME
296 builtin_macro_create_var(US"_RESUME_DECODE", RESUME_DECODE_STRING );
297 # endif
298 # ifdef SSL_OP_NO_TLSv1_3
299 builtin_macro_create(US"_HAVE_TLS1_3");
300 # endif
301 # ifdef OPENSSL_BAD_SRVR_OURCERT
302 builtin_macro_create(US"_TLS_BAD_MULTICERT_IN_OURCERT");
303 # endif
304 # ifdef EXIM_HAVE_OCSP
305 builtin_macro_create(US"_HAVE_TLS_OCSP");
306 builtin_macro_create(US"_HAVE_TLS_OCSP_LIST");
307 # endif
308 }
309 #else
310
311 /******************************************************************************/
312
313 /* Structure for collecting random data for seeding. */
314
315 typedef struct randstuff {
316   struct timeval tv;
317   pid_t          p;
318 } randstuff;
319
320 /* Local static variables */
321
322 static BOOL client_verify_callback_called = FALSE;
323 static BOOL server_verify_callback_called = FALSE;
324 static const uschar *sid_ctx = US"exim";
325
326 /* We have three different contexts to care about.
327
328 Simple case: client, `client_ctx`
329  As a client, we can be doing a callout or cut-through delivery while receiving
330  a message.  So we have a client context, which should have options initialised
331  from the SMTP Transport.  We may also concurrently want to make TLS connections
332  to utility daemons, so client-contexts are allocated and passed around in call
333  args rather than using a gobal.
334
335 Server:
336  There are two cases: with and without ServerNameIndication from the client.
337  Given TLS SNI, we can be using different keys, certs and various other
338  configuration settings, because they're re-expanded with $tls_sni set.  This
339  allows vhosting with TLS.  This SNI is sent in the handshake.
340  A client might not send SNI, so we need a fallback, and an initial setup too.
341  So as a server, we start out using `server_ctx`.
342  If SNI is sent by the client, then we as server, mid-negotiation, try to clone
343  `server_sni` from `server_ctx` and then initialise settings by re-expanding
344  configuration.
345 */
346
347 typedef struct {
348   SSL_CTX *     ctx;
349   SSL *         ssl;
350   gstring *     corked;
351 } exim_openssl_client_tls_ctx;
352
353 static SSL_CTX *server_ctx = NULL;
354 static SSL     *server_ssl = NULL;
355
356 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
357 static SSL_CTX *server_sni = NULL;
358 #endif
359
360 static char ssl_errstring[256];
361
362 static int  ssl_session_timeout = 7200;         /* Two hours */
363 static BOOL client_verify_optional = FALSE;
364 static BOOL server_verify_optional = FALSE;
365
366 static BOOL reexpand_tls_files_for_sni = FALSE;
367
368
369 typedef struct ocsp_resp {
370   struct ocsp_resp *    next;
371   OCSP_RESPONSE *       resp;
372 } ocsp_resplist;
373
374 typedef struct tls_ext_ctx_cb {
375   tls_support * tlsp;
376   uschar *certificate;
377   uschar *privatekey;
378   BOOL is_server;
379 #ifndef DISABLE_OCSP
380   STACK_OF(X509) *verify_stack;         /* chain for verifying the proof */
381   union {
382     struct {
383       uschar        *file;
384       const uschar  *file_expanded;
385       ocsp_resplist *olist;
386     } server;
387     struct {
388       X509_STORE    *verify_store;      /* non-null if status requested */
389       BOOL          verify_required;
390     } client;
391   } u_ocsp;
392 #endif
393   uschar *dhparam;
394   /* these are cached from first expand */
395   uschar *server_cipher_list;
396   /* only passed down to tls_error: */
397   host_item *host;
398   const uschar * verify_cert_hostnames;
399 #ifndef DISABLE_EVENT
400   uschar * event_action;
401 #endif
402 } tls_ext_ctx_cb;
403
404 /* should figure out a cleanup of API to handle state preserved per
405 implementation, for various reasons, which can be void * in the APIs.
406 For now, we hack around it. */
407 tls_ext_ctx_cb *client_static_cbinfo = NULL;    /*XXX should not use static; multiple concurrent clients! */
408 tls_ext_ctx_cb *server_static_cbinfo = NULL;
409
410 static int
411 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
412     int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr );
413
414 /* Callbacks */
415 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
416 static int tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg);
417 #endif
418 #ifndef DISABLE_OCSP
419 static int tls_server_stapling_cb(SSL *s, void *arg);
420 #endif
421
422
423
424 /* Daemon-called, before every connection, key create/rotate */
425 #ifdef EXPERIMENTAL_TLS_RESUME
426 static void tk_init(void);
427 static int tls_exdata_idx = -1;
428 #endif
429
430 void
431 tls_daemon_init(void)
432 {
433 #ifdef EXPERIMENTAL_TLS_RESUME
434 tk_init();
435 #endif
436 return;
437 }
438
439
440 /*************************************************
441 *               Handle TLS error                 *
442 *************************************************/
443
444 /* Called from lots of places when errors occur before actually starting to do
445 the TLS handshake, that is, while the session is still in clear. Always returns
446 DEFER for a server and FAIL for a client so that most calls can use "return
447 tls_error(...)" to do this processing and then give an appropriate return. A
448 single function is used for both server and client, because it is called from
449 some shared functions.
450
451 Argument:
452   prefix    text to include in the logged error
453   host      NULL if setting up a server;
454             the connected host if setting up a client
455   msg       error message or NULL if we should ask OpenSSL
456   errstr    pointer to output error message
457
458 Returns:    OK/DEFER/FAIL
459 */
460
461 static int
462 tls_error(uschar * prefix, const host_item * host, uschar * msg, uschar ** errstr)
463 {
464 if (!msg)
465   {
466   ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
467   msg = US ssl_errstring;
468   }
469
470 msg = string_sprintf("(%s): %s", prefix, msg);
471 DEBUG(D_tls) debug_printf("TLS error '%s'\n", msg);
472 if (errstr) *errstr = msg;
473 return host ? FAIL : DEFER;
474 }
475
476
477
478 /*************************************************
479 *        Callback to generate RSA key            *
480 *************************************************/
481
482 /*
483 Arguments:
484   s          SSL connection (not used)
485   export     not used
486   keylength  keylength
487
488 Returns:     pointer to generated key
489 */
490
491 static RSA *
492 rsa_callback(SSL *s, int export, int keylength)
493 {
494 RSA *rsa_key;
495 #ifdef EXIM_HAVE_RSA_GENKEY_EX
496 BIGNUM *bn = BN_new();
497 #endif
498
499 export = export;     /* Shut picky compilers up */
500 DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
501
502 #ifdef EXIM_HAVE_RSA_GENKEY_EX
503 if (  !BN_set_word(bn, (unsigned long)RSA_F4)
504    || !(rsa_key = RSA_new())
505    || !RSA_generate_key_ex(rsa_key, keylength, bn, NULL)
506    )
507 #else
508 if (!(rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL)))
509 #endif
510
511   {
512   ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
513   log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
514     ssl_errstring);
515   return NULL;
516   }
517 return rsa_key;
518 }
519
520
521
522 /* Extreme debug
523 #ifndef DISABLE_OCSP
524 void
525 x509_store_dump_cert_s_names(X509_STORE * store)
526 {
527 STACK_OF(X509_OBJECT) * roots= store->objs;
528 static uschar name[256];
529
530 for (int i= 0; i < sk_X509_OBJECT_num(roots); i++)
531   {
532   X509_OBJECT * tmp_obj= sk_X509_OBJECT_value(roots, i);
533   if(tmp_obj->type == X509_LU_X509)
534     {
535     X509_NAME * sn = X509_get_subject_name(tmp_obj->data.x509);
536     if (X509_NAME_oneline(sn, CS name, sizeof(name)))
537       {
538       name[sizeof(name)-1] = '\0';
539       debug_printf(" %s\n", name);
540       }
541     }
542   }
543 }
544 #endif
545 */
546
547
548 #ifndef DISABLE_EVENT
549 static int
550 verify_event(tls_support * tlsp, X509 * cert, int depth, const uschar * dn,
551   BOOL *calledp, const BOOL *optionalp, const uschar * what)
552 {
553 uschar * ev;
554 uschar * yield;
555 X509 * old_cert;
556
557 ev = tlsp == &tls_out ? client_static_cbinfo->event_action : event_action;
558 if (ev)
559   {
560   DEBUG(D_tls) debug_printf("verify_event: %s %d\n", what, depth);
561   old_cert = tlsp->peercert;
562   tlsp->peercert = X509_dup(cert);
563   /* NB we do not bother setting peerdn */
564   if ((yield = event_raise(ev, US"tls:cert", string_sprintf("%d", depth))))
565     {
566     log_write(0, LOG_MAIN, "[%s] %s verify denied by event-action: "
567                 "depth=%d cert=%s: %s",
568               tlsp == &tls_out ? deliver_host_address : sender_host_address,
569               what, depth, dn, yield);
570     *calledp = TRUE;
571     if (!*optionalp)
572       {
573       if (old_cert) tlsp->peercert = old_cert;  /* restore 1st failing cert */
574       return 1;                     /* reject (leaving peercert set) */
575       }
576     DEBUG(D_tls) debug_printf("Event-action verify failure overridden "
577       "(host in tls_try_verify_hosts)\n");
578     tlsp->verify_override = TRUE;
579     }
580   X509_free(tlsp->peercert);
581   tlsp->peercert = old_cert;
582   }
583 return 0;
584 }
585 #endif
586
587 /*************************************************
588 *        Callback for verification               *
589 *************************************************/
590
591 /* The SSL library does certificate verification if set up to do so. This
592 callback has the current yes/no state is in "state". If verification succeeded,
593 we set the certificate-verified flag. If verification failed, what happens
594 depends on whether the client is required to present a verifiable certificate
595 or not.
596
597 If verification is optional, we change the state to yes, but still log the
598 verification error. For some reason (it really would help to have proper
599 documentation of OpenSSL), this callback function then gets called again, this
600 time with state = 1.  We must take care not to set the private verified flag on
601 the second time through.
602
603 Note: this function is not called if the client fails to present a certificate
604 when asked. We get here only if a certificate has been received. Handling of
605 optional verification for this case is done when requesting SSL to verify, by
606 setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
607
608 May be called multiple times for different issues with a certificate, even
609 for a given "depth" in the certificate chain.
610
611 Arguments:
612   preverify_ok current yes/no state as 1/0
613   x509ctx      certificate information.
614   tlsp         per-direction (client vs. server) support data
615   calledp      has-been-called flag
616   optionalp    verification-is-optional flag
617
618 Returns:     0 if verification should fail, otherwise 1
619 */
620
621 static int
622 verify_callback(int preverify_ok, X509_STORE_CTX * x509ctx,
623   tls_support * tlsp, BOOL * calledp, BOOL * optionalp)
624 {
625 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
626 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
627 uschar dn[256];
628
629 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
630   {
631   DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
632   log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
633     tlsp == &tls_out ? deliver_host_address : sender_host_address);
634   return 0;
635   }
636 dn[sizeof(dn)-1] = '\0';
637
638 tlsp->verify_override = FALSE;
639 if (preverify_ok == 0)
640   {
641   uschar * extra = verify_mode ? string_sprintf(" (during %c-verify for [%s])",
642       *verify_mode, sender_host_address)
643     : US"";
644   log_write(0, LOG_MAIN, "[%s] SSL verify error%s: depth=%d error=%s cert=%s",
645     tlsp == &tls_out ? deliver_host_address : sender_host_address,
646     extra, depth,
647     X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509ctx)), dn);
648   *calledp = TRUE;
649   if (!*optionalp)
650     {
651     if (!tlsp->peercert)
652       tlsp->peercert = X509_dup(cert);  /* record failing cert */
653     return 0;                           /* reject */
654     }
655   DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
656     "tls_try_verify_hosts)\n");
657   tlsp->verify_override = TRUE;
658   }
659
660 else if (depth != 0)
661   {
662   DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d SN=%s\n", depth, dn);
663 #ifndef DISABLE_OCSP
664   if (tlsp == &tls_out && client_static_cbinfo->u_ocsp.client.verify_store)
665     {   /* client, wanting stapling  */
666     /* Add the server cert's signing chain as the one
667     for the verification of the OCSP stapled information. */
668
669     if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
670                              cert))
671       ERR_clear_error();
672     sk_X509_push(client_static_cbinfo->verify_stack, cert);
673     }
674 #endif
675 #ifndef DISABLE_EVENT
676     if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
677       return 0;                         /* reject, with peercert set */
678 #endif
679   }
680 else
681   {
682   const uschar * verify_cert_hostnames;
683
684   if (  tlsp == &tls_out
685      && ((verify_cert_hostnames = client_static_cbinfo->verify_cert_hostnames)))
686         /* client, wanting hostname check */
687     {
688
689 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
690 # ifndef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
691 #  define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0
692 # endif
693 # ifndef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
694 #  define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0
695 # endif
696     int sep = 0;
697     const uschar * list = verify_cert_hostnames;
698     uschar * name;
699     int rc;
700     while ((name = string_nextinlist(&list, &sep, NULL, 0)))
701       if ((rc = X509_check_host(cert, CCS name, 0,
702                   X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
703                   | X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS,
704                   NULL)))
705         {
706         if (rc < 0)
707           {
708           log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
709             tlsp == &tls_out ? deliver_host_address : sender_host_address);
710           name = NULL;
711           }
712         break;
713         }
714     if (!name)
715 #else
716     if (!tls_is_name_for_cert(verify_cert_hostnames, cert))
717 #endif
718       {
719       uschar * extra = verify_mode
720         ? string_sprintf(" (during %c-verify for [%s])",
721           *verify_mode, sender_host_address)
722         : US"";
723       log_write(0, LOG_MAIN,
724         "[%s] SSL verify error%s: certificate name mismatch: DN=\"%s\" H=\"%s\"",
725         tlsp == &tls_out ? deliver_host_address : sender_host_address,
726         extra, dn, verify_cert_hostnames);
727       *calledp = TRUE;
728       if (!*optionalp)
729         {
730         if (!tlsp->peercert)
731           tlsp->peercert = X509_dup(cert);      /* record failing cert */
732         return 0;                               /* reject */
733         }
734       DEBUG(D_tls) debug_printf("SSL verify name failure overridden (host in "
735         "tls_try_verify_hosts)\n");
736       tlsp->verify_override = TRUE;
737       }
738     }
739
740 #ifndef DISABLE_EVENT
741   if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
742     return 0;                           /* reject, with peercert set */
743 #endif
744
745   DEBUG(D_tls) debug_printf("SSL%s verify ok: depth=0 SN=%s\n",
746     *calledp ? "" : " authenticated", dn);
747   *calledp = TRUE;
748   }
749
750 return 1;   /* accept, at least for this level */
751 }
752
753 static int
754 verify_callback_client(int preverify_ok, X509_STORE_CTX *x509ctx)
755 {
756 return verify_callback(preverify_ok, x509ctx, &tls_out,
757   &client_verify_callback_called, &client_verify_optional);
758 }
759
760 static int
761 verify_callback_server(int preverify_ok, X509_STORE_CTX *x509ctx)
762 {
763 return verify_callback(preverify_ok, x509ctx, &tls_in,
764   &server_verify_callback_called, &server_verify_optional);
765 }
766
767
768 #ifdef SUPPORT_DANE
769
770 /* This gets called *by* the dane library verify callback, which interposes
771 itself.
772 */
773 static int
774 verify_callback_client_dane(int preverify_ok, X509_STORE_CTX * x509ctx)
775 {
776 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
777 uschar dn[256];
778 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
779 #ifndef DISABLE_EVENT
780 BOOL dummy_called, optional = FALSE;
781 #endif
782
783 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
784   {
785   DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
786   log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
787     deliver_host_address);
788   return 0;
789   }
790 dn[sizeof(dn)-1] = '\0';
791
792 DEBUG(D_tls) debug_printf("verify_callback_client_dane: %s depth %d %s\n",
793   preverify_ok ? "ok":"BAD", depth, dn);
794
795 #ifndef DISABLE_EVENT
796   if (verify_event(&tls_out, cert, depth, dn,
797           &dummy_called, &optional, US"DANE"))
798     return 0;                           /* reject, with peercert set */
799 #endif
800
801 if (preverify_ok == 1)
802   {
803   tls_out.dane_verified = TRUE;
804 #ifndef DISABLE_OCSP
805   if (client_static_cbinfo->u_ocsp.client.verify_store)
806     {   /* client, wanting stapling  */
807     /* Add the server cert's signing chain as the one
808     for the verification of the OCSP stapled information. */
809
810     if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
811                              cert))
812       ERR_clear_error();
813     sk_X509_push(client_static_cbinfo->verify_stack, cert);
814     }
815 #endif
816   }
817 else
818   {
819   int err = X509_STORE_CTX_get_error(x509ctx);
820   DEBUG(D_tls)
821     debug_printf(" - err %d '%s'\n", err, X509_verify_cert_error_string(err));
822   if (err == X509_V_ERR_APPLICATION_VERIFICATION)
823     preverify_ok = 1;
824   }
825 return preverify_ok;
826 }
827
828 #endif  /*SUPPORT_DANE*/
829
830
831 /*************************************************
832 *           Information callback                 *
833 *************************************************/
834
835 /* The SSL library functions call this from time to time to indicate what they
836 are doing. We copy the string to the debugging output when TLS debugging has
837 been requested.
838
839 Arguments:
840   s         the SSL connection
841   where
842   ret
843
844 Returns:    nothing
845 */
846
847 static void
848 info_callback(SSL *s, int where, int ret)
849 {
850 DEBUG(D_tls)
851   {
852   const uschar * str;
853
854   if (where & SSL_ST_CONNECT)
855      str = US"SSL_connect";
856   else if (where & SSL_ST_ACCEPT)
857      str = US"SSL_accept";
858   else
859      str = US"SSL info (undefined)";
860
861   if (where & SSL_CB_LOOP)
862      debug_printf("%s: %s\n", str, SSL_state_string_long(s));
863   else if (where & SSL_CB_ALERT)
864     debug_printf("SSL3 alert %s:%s:%s\n",
865           str = where & SSL_CB_READ ? US"read" : US"write",
866           SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
867   else if (where & SSL_CB_EXIT)
868      if (ret == 0)
869         debug_printf("%s: failed in %s\n", str, SSL_state_string_long(s));
870      else if (ret < 0)
871         debug_printf("%s: error in %s\n", str, SSL_state_string_long(s));
872   else if (where & SSL_CB_HANDSHAKE_START)
873      debug_printf("%s: hshake start: %s\n", str, SSL_state_string_long(s));
874   else if (where & SSL_CB_HANDSHAKE_DONE)
875      debug_printf("%s: hshake done: %s\n", str, SSL_state_string_long(s));
876   }
877 }
878
879 #ifdef OPENSSL_HAVE_KEYLOG_CB
880 static void
881 keylog_callback(const SSL *ssl, const char *line)
882 {
883 char * filename;
884 FILE * fp;
885 DEBUG(D_tls) debug_printf("%.200s\n", line);
886 if (!(filename = getenv("SSLKEYLOGFILE"))) return;
887 if (!(fp = fopen(filename, "a"))) return;
888 fprintf(fp, "%s\n", line);
889 fclose(fp);
890 }
891 #endif
892
893
894 #ifdef EXPERIMENTAL_TLS_RESUME
895 /* Manage the keysets used for encrypting the session tickets, on the server. */
896
897 typedef struct {                        /* Session ticket encryption key */
898   uschar        name[16];
899
900   const EVP_CIPHER *    aes_cipher;
901   uschar                aes_key[32];    /* size needed depends on cipher. aes_128 implies 128/8 = 16? */
902   const EVP_MD *        hmac_hash;
903   uschar                hmac_key[16];
904   time_t                renew;
905   time_t                expire;
906 } exim_stek;
907
908 static exim_stek exim_tk;       /* current key */
909 static exim_stek exim_tk_old;   /* previous key */
910
911 static void
912 tk_init(void)
913 {
914 time_t t = time(NULL);
915
916 if (exim_tk.name[0])
917   {
918   if (exim_tk.renew >= t) return;
919   exim_tk_old = exim_tk;
920   }
921
922 if (f.running_in_test_harness) ssl_session_timeout = 6;
923
924 DEBUG(D_tls) debug_printf("OpenSSL: %s STEK\n", exim_tk.name[0] ? "rotating" : "creating");
925 if (RAND_bytes(exim_tk.aes_key, sizeof(exim_tk.aes_key)) <= 0) return;
926 if (RAND_bytes(exim_tk.hmac_key, sizeof(exim_tk.hmac_key)) <= 0) return;
927 if (RAND_bytes(exim_tk.name+1, sizeof(exim_tk.name)-1) <= 0) return;
928
929 exim_tk.name[0] = 'E';
930 exim_tk.aes_cipher = EVP_aes_256_cbc();
931 exim_tk.hmac_hash = EVP_sha256();
932 exim_tk.expire = t + ssl_session_timeout;
933 exim_tk.renew = t + ssl_session_timeout/2;
934 }
935
936 static exim_stek *
937 tk_current(void)
938 {
939 if (!exim_tk.name[0]) return NULL;
940 return &exim_tk;
941 }
942
943 static exim_stek *
944 tk_find(const uschar * name)
945 {
946 return memcmp(name, exim_tk.name, sizeof(exim_tk.name)) == 0 ? &exim_tk
947   : memcmp(name, exim_tk_old.name, sizeof(exim_tk_old.name)) == 0 ? &exim_tk_old
948   : NULL;
949 }
950
951 /* Callback for session tickets, on server */
952 static int
953 ticket_key_callback(SSL * ssl, uschar key_name[16],
954   uschar * iv, EVP_CIPHER_CTX * ctx, HMAC_CTX * hctx, int enc)
955 {
956 tls_support * tlsp = server_static_cbinfo->tlsp;
957 exim_stek * key;
958
959 if (enc)
960   {
961   DEBUG(D_tls) debug_printf("ticket_key_callback: create new session\n");
962   tlsp->resumption |= RESUME_CLIENT_REQUESTED;
963
964   if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0)
965     return -1; /* insufficient random */
966
967   if (!(key = tk_current()))    /* current key doesn't exist or isn't valid */
968      return 0;                  /* key couldn't be created */
969   memcpy(key_name, key->name, 16);
970   DEBUG(D_tls) debug_printf("STEK expire " TIME_T_FMT "\n", key->expire - time(NULL));
971
972   /*XXX will want these dependent on the ssl session strength */
973   HMAC_Init_ex(hctx, key->hmac_key, sizeof(key->hmac_key),
974                 key->hmac_hash, NULL);
975   EVP_EncryptInit_ex(ctx, key->aes_cipher, NULL, key->aes_key, iv);
976
977   DEBUG(D_tls) debug_printf("ticket created\n");
978   return 1;
979   }
980 else
981   {
982   time_t now = time(NULL);
983
984   DEBUG(D_tls) debug_printf("ticket_key_callback: retrieve session\n");
985   tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
986
987   if (!(key = tk_find(key_name)) || key->expire < now)
988     {
989     DEBUG(D_tls)
990       {
991       debug_printf("ticket not usable (%s)\n", key ? "expired" : "not found");
992       if (key) debug_printf("STEK expire " TIME_T_FMT "\n", key->expire - now);
993       }
994     return 0;
995     }
996
997   HMAC_Init_ex(hctx, key->hmac_key, sizeof(key->hmac_key),
998                 key->hmac_hash, NULL);
999   EVP_DecryptInit_ex(ctx, key->aes_cipher, NULL, key->aes_key, iv);
1000
1001   DEBUG(D_tls) debug_printf("ticket usable, STEK expire " TIME_T_FMT "\n", key->expire - now);
1002
1003   /* The ticket lifetime and renewal are the same as the STEK lifetime and
1004   renewal, which is overenthusiastic.  A factor of, say, 3x longer STEK would
1005   be better.  To do that we'd have to encode ticket lifetime in the name as
1006   we don't yet see the restored session.  Could check posthandshake for TLS1.3
1007   and trigger a new ticket then, but cannot do that for TLS1.2 */
1008   return key->renew < now ? 2 : 1;
1009   }
1010 }
1011 #endif
1012
1013
1014
1015 /*************************************************
1016 *                Initialize for DH               *
1017 *************************************************/
1018
1019 /* If dhparam is set, expand it, and load up the parameters for DH encryption.
1020
1021 Arguments:
1022   sctx      The current SSL CTX (inbound or outbound)
1023   dhparam   DH parameter file or fixed parameter identity string
1024   host      connected host, if client; NULL if server
1025   errstr    error string pointer
1026
1027 Returns:    TRUE if OK (nothing to set up, or setup worked)
1028 */
1029
1030 static BOOL
1031 init_dh(SSL_CTX *sctx, uschar *dhparam, const host_item *host, uschar ** errstr)
1032 {
1033 BIO *bio;
1034 DH *dh;
1035 uschar *dhexpanded;
1036 const char *pem;
1037 int dh_bitsize;
1038
1039 if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded, errstr))
1040   return FALSE;
1041
1042 if (!dhexpanded || !*dhexpanded)
1043   bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
1044 else if (dhexpanded[0] == '/')
1045   {
1046   if (!(bio = BIO_new_file(CS dhexpanded, "r")))
1047     {
1048     tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
1049           host, US strerror(errno), errstr);
1050     return FALSE;
1051     }
1052   }
1053 else
1054   {
1055   if (Ustrcmp(dhexpanded, "none") == 0)
1056     {
1057     DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
1058     return TRUE;
1059     }
1060
1061   if (!(pem = std_dh_prime_named(dhexpanded)))
1062     {
1063     tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
1064         host, US strerror(errno), errstr);
1065     return FALSE;
1066     }
1067   bio = BIO_new_mem_buf(CS pem, -1);
1068   }
1069
1070 if (!(dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)))
1071   {
1072   BIO_free(bio);
1073   tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
1074       host, NULL, errstr);
1075   return FALSE;
1076   }
1077
1078 /* note: our default limit of 2236 is not a multiple of 8; the limit comes from
1079  * an NSS limit, and the GnuTLS APIs handle bit-sizes fine, so we went with
1080  * 2236.  But older OpenSSL can only report in bytes (octets), not bits.
1081  * If someone wants to dance at the edge, then they can raise the limit or use
1082  * current libraries. */
1083 #ifdef EXIM_HAVE_OPENSSL_DH_BITS
1084 /* Added in commit 26c79d5641d; `git describe --contains` says OpenSSL_1_1_0-pre1~1022
1085  * This predates OpenSSL_1_1_0 (before a, b, ...) so is in all 1.1.0 */
1086 dh_bitsize = DH_bits(dh);
1087 #else
1088 dh_bitsize = 8 * DH_size(dh);
1089 #endif
1090
1091 /* Even if it is larger, we silently return success rather than cause things
1092  * to fail out, so that a too-large DH will not knock out all TLS; it's a
1093  * debatable choice. */
1094 if (dh_bitsize > tls_dh_max_bits)
1095   {
1096   DEBUG(D_tls)
1097     debug_printf("dhparams file %d bits, is > tls_dh_max_bits limit of %d\n",
1098         dh_bitsize, tls_dh_max_bits);
1099   }
1100 else
1101   {
1102   SSL_CTX_set_tmp_dh(sctx, dh);
1103   DEBUG(D_tls)
1104     debug_printf("Diffie-Hellman initialized from %s with %d-bit prime\n",
1105       dhexpanded ? dhexpanded : US"default", dh_bitsize);
1106   }
1107
1108 DH_free(dh);
1109 BIO_free(bio);
1110
1111 return TRUE;
1112 }
1113
1114
1115
1116
1117 /*************************************************
1118 *               Initialize for ECDH              *
1119 *************************************************/
1120
1121 /* Load parameters for ECDH encryption.
1122
1123 For now, we stick to NIST P-256 because: it's simple and easy to configure;
1124 it avoids any patent issues that might bite redistributors; despite events in
1125 the news and concerns over curve choices, we're not cryptographers, we're not
1126 pretending to be, and this is "good enough" to be better than no support,
1127 protecting against most adversaries.  Given another year or two, there might
1128 be sufficient clarity about a "right" way forward to let us make an informed
1129 decision, instead of a knee-jerk reaction.
1130
1131 Longer-term, we should look at supporting both various named curves and
1132 external files generated with "openssl ecparam", much as we do for init_dh().
1133 We should also support "none" as a value, to explicitly avoid initialisation.
1134
1135 Patches welcome.
1136
1137 Arguments:
1138   sctx      The current SSL CTX (inbound or outbound)
1139   host      connected host, if client; NULL if server
1140   errstr    error string pointer
1141
1142 Returns:    TRUE if OK (nothing to set up, or setup worked)
1143 */
1144
1145 static BOOL
1146 init_ecdh(SSL_CTX * sctx, host_item * host, uschar ** errstr)
1147 {
1148 #ifdef OPENSSL_NO_ECDH
1149 return TRUE;
1150 #else
1151
1152 EC_KEY * ecdh;
1153 uschar * exp_curve;
1154 int nid;
1155 BOOL rv;
1156
1157 if (host)       /* No ECDH setup for clients, only for servers */
1158   return TRUE;
1159
1160 # ifndef EXIM_HAVE_ECDH
1161 DEBUG(D_tls)
1162   debug_printf("No OpenSSL API to define ECDH parameters, skipping\n");
1163 return TRUE;
1164 # else
1165
1166 if (!expand_check(tls_eccurve, US"tls_eccurve", &exp_curve, errstr))
1167   return FALSE;
1168 if (!exp_curve || !*exp_curve)
1169   return TRUE;
1170
1171 /* "auto" needs to be handled carefully.
1172  * OpenSSL <  1.0.2: we do not select anything, but fallback to prime256v1
1173  * OpenSSL <  1.1.0: we have to call SSL_CTX_set_ecdh_auto
1174  *                   (openssl/ssl.h defines SSL_CTRL_SET_ECDH_AUTO)
1175  * OpenSSL >= 1.1.0: we do not set anything, the libray does autoselection
1176  *                   https://github.com/openssl/openssl/commit/fe6ef2472db933f01b59cad82aa925736935984b
1177  */
1178 if (Ustrcmp(exp_curve, "auto") == 0)
1179   {
1180 #if OPENSSL_VERSION_NUMBER < 0x10002000L
1181   DEBUG(D_tls) debug_printf(
1182     "ECDH OpenSSL < 1.0.2: temp key parameter settings: overriding \"auto\" with \"prime256v1\"\n");
1183   exp_curve = US"prime256v1";
1184 #else
1185 # if defined SSL_CTRL_SET_ECDH_AUTO
1186   DEBUG(D_tls) debug_printf(
1187     "ECDH OpenSSL 1.0.2+ temp key parameter settings: autoselection\n");
1188   SSL_CTX_set_ecdh_auto(sctx, 1);
1189   return TRUE;
1190 # else
1191   DEBUG(D_tls) debug_printf(
1192     "ECDH OpenSSL 1.1.0+ temp key parameter settings: default selection\n");
1193   return TRUE;
1194 # endif
1195 #endif
1196   }
1197
1198 DEBUG(D_tls) debug_printf("ECDH: curve '%s'\n", exp_curve);
1199 if (  (nid = OBJ_sn2nid       (CCS exp_curve)) == NID_undef
1200 #   ifdef EXIM_HAVE_OPENSSL_EC_NIST2NID
1201    && (nid = EC_curve_nist2nid(CCS exp_curve)) == NID_undef
1202 #   endif
1203    )
1204   {
1205   tls_error(string_sprintf("Unknown curve name tls_eccurve '%s'", exp_curve),
1206     host, NULL, errstr);
1207   return FALSE;
1208   }
1209
1210 if (!(ecdh = EC_KEY_new_by_curve_name(nid)))
1211   {
1212   tls_error(US"Unable to create ec curve", host, NULL, errstr);
1213   return FALSE;
1214   }
1215
1216 /* The "tmp" in the name here refers to setting a temporary key
1217 not to the stability of the interface. */
1218
1219 if ((rv = SSL_CTX_set_tmp_ecdh(sctx, ecdh) == 0))
1220   tls_error(string_sprintf("Error enabling '%s' curve", exp_curve), host, NULL, errstr);
1221 else
1222   DEBUG(D_tls) debug_printf("ECDH: enabled '%s' curve\n", exp_curve);
1223
1224 EC_KEY_free(ecdh);
1225 return !rv;
1226
1227 # endif /*EXIM_HAVE_ECDH*/
1228 #endif /*OPENSSL_NO_ECDH*/
1229 }
1230
1231
1232
1233
1234 #ifndef DISABLE_OCSP
1235 /*************************************************
1236 *       Load OCSP information into state         *
1237 *************************************************/
1238 /* Called to load the server OCSP response from the given file into memory, once
1239 caller has determined this is needed.  Checks validity.  Debugs a message
1240 if invalid.
1241
1242 ASSUMES: single response, for single cert.
1243
1244 Arguments:
1245   sctx            the SSL_CTX* to update
1246   cbinfo          various parts of session state
1247   filename        the filename putatively holding an OCSP response
1248   is_pem          file is PEM format; otherwise is DER
1249
1250 */
1251
1252 static void
1253 ocsp_load_response(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo,
1254   const uschar * filename, BOOL is_pem)
1255 {
1256 BIO * bio;
1257 OCSP_RESPONSE * resp;
1258 OCSP_BASICRESP * basic_response;
1259 OCSP_SINGLERESP * single_response;
1260 ASN1_GENERALIZEDTIME * rev, * thisupd, * nextupd;
1261 STACK_OF(X509) * sk;
1262 unsigned long verify_flags;
1263 int status, reason, i;
1264
1265 DEBUG(D_tls)
1266   debug_printf("tls_ocsp_file (%s)  '%s'\n", is_pem ? "PEM" : "DER", filename);
1267
1268 if (!(bio = BIO_new_file(CS filename, "rb")))
1269   {
1270   DEBUG(D_tls) debug_printf("Failed to open OCSP response file \"%s\"\n",
1271       filename);
1272   return;
1273   }
1274
1275 if (is_pem)
1276   {
1277   uschar * data, * freep;
1278   char * dummy;
1279   long len;
1280   if (!PEM_read_bio(bio, &dummy, &dummy, &data, &len))
1281     {
1282     DEBUG(D_tls) debug_printf("Failed to read PEM file \"%s\"\n",
1283         filename);
1284     return;
1285     }
1286 debug_printf("read pem file\n");
1287   freep = data;
1288   resp = d2i_OCSP_RESPONSE(NULL, CUSS &data, len);
1289   OPENSSL_free(freep);
1290   }
1291 else
1292   resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
1293 BIO_free(bio);
1294
1295 if (!resp)
1296   {
1297   DEBUG(D_tls) debug_printf("Error reading OCSP response.\n");
1298   return;
1299   }
1300
1301 if ((status = OCSP_response_status(resp)) != OCSP_RESPONSE_STATUS_SUCCESSFUL)
1302   {
1303   DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n",
1304       OCSP_response_status_str(status), status);
1305   goto bad;
1306   }
1307
1308 #ifdef notdef
1309   {
1310   BIO * bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
1311   OCSP_RESPONSE_print(bp, resp, 0);  /* extreme debug: stapling content */
1312   BIO_free(bp);
1313   }
1314 #endif
1315
1316 if (!(basic_response = OCSP_response_get1_basic(resp)))
1317   {
1318   DEBUG(D_tls)
1319     debug_printf("OCSP response parse error: unable to extract basic response.\n");
1320   goto bad;
1321   }
1322
1323 sk = cbinfo->verify_stack;
1324 verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */
1325
1326 /* May need to expose ability to adjust those flags?
1327 OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
1328 OCSP_TRUSTOTHER OCSP_NOINTERN */
1329
1330 /* This does a full verify on the OCSP proof before we load it for serving
1331 up; possibly overkill - just date-checks might be nice enough.
1332
1333 OCSP_basic_verify takes a "store" arg, but does not
1334 use it for the chain verification, which is all we do
1335 when OCSP_NOVERIFY is set.  The content from the wire
1336 "basic_response" and a cert-stack "sk" are all that is used.
1337
1338 We have a stack, loaded in setup_certs() if tls_verify_certificates
1339 was a file (not a directory, or "system").  It is unfortunate we
1340 cannot used the connection context store, as that would neatly
1341 handle the "system" case too, but there seems to be no library
1342 function for getting a stack from a store.
1343 [ In OpenSSL 1.1 - ?  X509_STORE_CTX_get0_chain(ctx) ? ]
1344 We do not free the stack since it could be needed a second time for
1345 SNI handling.
1346
1347 Separately we might try to replace using OCSP_basic_verify() - which seems to not
1348 be a public interface into the OpenSSL library (there's no manual entry) -
1349 But what with?  We also use OCSP_basic_verify in the client stapling callback.
1350 And there we NEED it; we must verify that status... unless the
1351 library does it for us anyway?  */
1352
1353 if ((i = OCSP_basic_verify(basic_response, sk, NULL, verify_flags)) < 0)
1354   {
1355   DEBUG(D_tls)
1356     {
1357     ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1358     debug_printf("OCSP response verify failure: %s\n", US ssl_errstring);
1359     }
1360   goto bad;
1361   }
1362
1363 /* Here's the simplifying assumption: there's only one response, for the
1364 one certificate we use, and nothing for anything else in a chain.  If this
1365 proves false, we need to extract a cert id from our issued cert
1366 (tls_certificate) and use that for OCSP_resp_find_status() (which finds the
1367 right cert in the stack and then calls OCSP_single_get0_status()).
1368
1369 I'm hoping to avoid reworking a bunch more of how we handle state here.
1370
1371 XXX that will change when we add support for (TLS1.3) whole-chain stapling
1372 */
1373
1374 if (!(single_response = OCSP_resp_get0(basic_response, 0)))
1375   {
1376   DEBUG(D_tls)
1377     debug_printf("Unable to get first response from OCSP basic response.\n");
1378   goto bad;
1379   }
1380
1381 status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
1382 if (status != V_OCSP_CERTSTATUS_GOOD)
1383   {
1384   DEBUG(D_tls) debug_printf("OCSP response bad cert status: %s (%d) %s (%d)\n",
1385       OCSP_cert_status_str(status), status,
1386       OCSP_crl_reason_str(reason), reason);
1387   goto bad;
1388   }
1389
1390 if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1391   {
1392   DEBUG(D_tls) debug_printf("OCSP status invalid times.\n");
1393   goto bad;
1394   }
1395
1396 supply_response:
1397   /* Add the resp to the list used by tls_server_stapling_cb() */
1398   {
1399   ocsp_resplist ** op = &cbinfo->u_ocsp.server.olist, * oentry;
1400   while (oentry = *op)
1401     op = &oentry->next;
1402   *op = oentry = store_get(sizeof(ocsp_resplist), FALSE);
1403   oentry->next = NULL;
1404   oentry->resp = resp;
1405   }
1406 return;
1407
1408 bad:
1409   if (f.running_in_test_harness)
1410     {
1411     extern char ** environ;
1412     if (environ) for (uschar ** p = USS environ; *p; p++)
1413       if (Ustrncmp(*p, "EXIM_TESTHARNESS_DISABLE_OCSPVALIDITYCHECK", 42) == 0)
1414         {
1415         DEBUG(D_tls) debug_printf("Supplying known bad OCSP response\n");
1416         goto supply_response;
1417         }
1418     }
1419 return;
1420 }
1421
1422
1423 static void
1424 ocsp_free_response_list(tls_ext_ctx_cb * cbinfo)
1425 {
1426 for (ocsp_resplist * olist = cbinfo->u_ocsp.server.olist; olist;
1427      olist = olist->next)
1428   OCSP_RESPONSE_free(olist->resp);
1429 cbinfo->u_ocsp.server.olist = NULL;
1430 }
1431 #endif  /*!DISABLE_OCSP*/
1432
1433
1434
1435
1436 /* Create and install a selfsigned certificate, for use in server mode */
1437
1438 static int
1439 tls_install_selfsign(SSL_CTX * sctx, uschar ** errstr)
1440 {
1441 X509 * x509 = NULL;
1442 EVP_PKEY * pkey;
1443 RSA * rsa;
1444 X509_NAME * name;
1445 uschar * where;
1446
1447 where = US"allocating pkey";
1448 if (!(pkey = EVP_PKEY_new()))
1449   goto err;
1450
1451 where = US"allocating cert";
1452 if (!(x509 = X509_new()))
1453   goto err;
1454
1455 where = US"generating pkey";
1456 if (!(rsa = rsa_callback(NULL, 0, 2048)))
1457   goto err;
1458
1459 where = US"assigning pkey";
1460 if (!EVP_PKEY_assign_RSA(pkey, rsa))
1461   goto err;
1462
1463 X509_set_version(x509, 2);                              /* N+1 - version 3 */
1464 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
1465 X509_gmtime_adj(X509_get_notBefore(x509), 0);
1466 X509_gmtime_adj(X509_get_notAfter(x509), (long)60 * 60);        /* 1 hour */
1467 X509_set_pubkey(x509, pkey);
1468
1469 name = X509_get_subject_name(x509);
1470 X509_NAME_add_entry_by_txt(name, "C",
1471                           MBSTRING_ASC, CUS "UK", -1, -1, 0);
1472 X509_NAME_add_entry_by_txt(name, "O",
1473                           MBSTRING_ASC, CUS "Exim Developers", -1, -1, 0);
1474 X509_NAME_add_entry_by_txt(name, "CN",
1475                           MBSTRING_ASC, CUS smtp_active_hostname, -1, -1, 0);
1476 X509_set_issuer_name(x509, name);
1477
1478 where = US"signing cert";
1479 if (!X509_sign(x509, pkey, EVP_md5()))
1480   goto err;
1481
1482 where = US"installing selfsign cert";
1483 if (!SSL_CTX_use_certificate(sctx, x509))
1484   goto err;
1485
1486 where = US"installing selfsign key";
1487 if (!SSL_CTX_use_PrivateKey(sctx, pkey))
1488   goto err;
1489
1490 return OK;
1491
1492 err:
1493   (void) tls_error(where, NULL, NULL, errstr);
1494   if (x509) X509_free(x509);
1495   if (pkey) EVP_PKEY_free(pkey);
1496   return DEFER;
1497 }
1498
1499
1500
1501
1502 static int
1503 tls_add_certfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1504   uschar ** errstr)
1505 {
1506 DEBUG(D_tls) debug_printf("tls_certificate file '%s'\n", file);
1507 if (!SSL_CTX_use_certificate_chain_file(sctx, CS file))
1508   return tls_error(string_sprintf(
1509     "SSL_CTX_use_certificate_chain_file file=%s", file),
1510       cbinfo->host, NULL, errstr);
1511 return 0;
1512 }
1513
1514 static int
1515 tls_add_pkeyfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1516   uschar ** errstr)
1517 {
1518 DEBUG(D_tls) debug_printf("tls_privatekey file  '%s'\n", file);
1519 if (!SSL_CTX_use_PrivateKey_file(sctx, CS file, SSL_FILETYPE_PEM))
1520   return tls_error(string_sprintf(
1521     "SSL_CTX_use_PrivateKey_file file=%s", file), cbinfo->host, NULL, errstr);
1522 return 0;
1523 }
1524
1525
1526 /*************************************************
1527 *        Expand key and cert file specs          *
1528 *************************************************/
1529
1530 /* Called once during tls_init and possibly again during TLS setup, for a
1531 new context, if Server Name Indication was used and tls_sni was seen in
1532 the certificate string.
1533
1534 Arguments:
1535   sctx            the SSL_CTX* to update
1536   cbinfo          various parts of session state
1537   errstr          error string pointer
1538
1539 Returns:          OK/DEFER/FAIL
1540 */
1541
1542 static int
1543 tls_expand_session_files(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo,
1544   uschar ** errstr)
1545 {
1546 uschar * expanded;
1547
1548 if (!cbinfo->certificate)
1549   {
1550   if (!cbinfo->is_server)               /* client */
1551     return OK;
1552                                         /* server */
1553   if (tls_install_selfsign(sctx, errstr) != OK)
1554     return DEFER;
1555   }
1556 else
1557   {
1558   int err;
1559
1560   if ( !reexpand_tls_files_for_sni
1561      && (  Ustrstr(cbinfo->certificate, US"tls_sni")
1562         || Ustrstr(cbinfo->certificate, US"tls_in_sni")
1563         || Ustrstr(cbinfo->certificate, US"tls_out_sni")
1564      )  )
1565     reexpand_tls_files_for_sni = TRUE;
1566
1567   if (!expand_check(cbinfo->certificate, US"tls_certificate", &expanded, errstr))
1568     return DEFER;
1569
1570   if (expanded)
1571     if (cbinfo->is_server)
1572       {
1573       const uschar * file_list = expanded;
1574       int sep = 0;
1575       uschar * file;
1576 #ifndef DISABLE_OCSP
1577       const uschar * olist = cbinfo->u_ocsp.server.file;
1578       int osep = 0;
1579       uschar * ofile;
1580       BOOL fmt_pem = FALSE;
1581
1582       if (olist)
1583         if (!expand_check(olist, US"tls_ocsp_file", USS &olist, errstr))
1584           return DEFER;
1585       if (olist && !*olist)
1586         olist = NULL;
1587
1588       if (  cbinfo->u_ocsp.server.file_expanded && olist
1589          && (Ustrcmp(olist, cbinfo->u_ocsp.server.file_expanded) == 0))
1590         {
1591         DEBUG(D_tls) debug_printf(" - value unchanged, using existing values\n");
1592         olist = NULL;
1593         }
1594       else
1595         {
1596         ocsp_free_response_list(cbinfo);
1597         cbinfo->u_ocsp.server.file_expanded = olist;
1598         }
1599 #endif
1600
1601       while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1602         {
1603         if ((err = tls_add_certfile(sctx, cbinfo, file, errstr)))
1604           return err;
1605
1606 #ifndef DISABLE_OCSP
1607         if (olist)
1608           if ((ofile = string_nextinlist(&olist, &osep, NULL, 0)))
1609             {
1610             if (Ustrncmp(ofile, US"PEM ", 4) == 0)
1611               {
1612               fmt_pem = TRUE;
1613               ofile += 4;
1614               }
1615             else if (Ustrncmp(ofile, US"DER ", 4) == 0)
1616               {
1617               fmt_pem = FALSE;
1618               ofile += 4;
1619               }
1620             ocsp_load_response(sctx, cbinfo, ofile, fmt_pem);
1621             }
1622           else
1623             DEBUG(D_tls) debug_printf("ran out of ocsp file list\n");
1624 #endif
1625         }
1626       }
1627     else        /* would there ever be a need for multiple client certs? */
1628       if ((err = tls_add_certfile(sctx, cbinfo, expanded, errstr)))
1629         return err;
1630
1631   if (  cbinfo->privatekey
1632      && !expand_check(cbinfo->privatekey, US"tls_privatekey", &expanded, errstr))
1633     return DEFER;
1634
1635   /* If expansion was forced to fail, key_expanded will be NULL. If the result
1636   of the expansion is an empty string, ignore it also, and assume the private
1637   key is in the same file as the certificate. */
1638
1639   if (expanded && *expanded)
1640     if (cbinfo->is_server)
1641       {
1642       const uschar * file_list = expanded;
1643       int sep = 0;
1644       uschar * file;
1645
1646       while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1647         if ((err = tls_add_pkeyfile(sctx, cbinfo, file, errstr)))
1648           return err;
1649       }
1650     else        /* would there ever be a need for multiple client certs? */
1651       if ((err = tls_add_pkeyfile(sctx, cbinfo, expanded, errstr)))
1652         return err;
1653   }
1654
1655 return OK;
1656 }
1657
1658
1659
1660
1661 /*************************************************
1662 *            Callback to handle SNI              *
1663 *************************************************/
1664
1665 /* Called when acting as server during the TLS session setup if a Server Name
1666 Indication extension was sent by the client.
1667
1668 API documentation is OpenSSL s_server.c implementation.
1669
1670 Arguments:
1671   s               SSL* of the current session
1672   ad              unknown (part of OpenSSL API) (unused)
1673   arg             Callback of "our" registered data
1674
1675 Returns:          SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
1676
1677 XXX might need to change to using ClientHello callback,
1678 per https://www.openssl.org/docs/manmaster/man3/SSL_client_hello_cb_fn.html
1679 */
1680
1681 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
1682 static int
1683 tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg)
1684 {
1685 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1686 tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1687 int rc;
1688 int old_pool = store_pool;
1689 uschar * dummy_errstr;
1690
1691 if (!servername)
1692   return SSL_TLSEXT_ERR_OK;
1693
1694 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
1695     reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
1696
1697 /* Make the extension value available for expansion */
1698 store_pool = POOL_PERM;
1699 tls_in.sni = string_copy_taint(US servername, TRUE);
1700 store_pool = old_pool;
1701
1702 if (!reexpand_tls_files_for_sni)
1703   return SSL_TLSEXT_ERR_OK;
1704
1705 /* Can't find an SSL_CTX_clone() or equivalent, so we do it manually;
1706 not confident that memcpy wouldn't break some internal reference counting.
1707 Especially since there's a references struct member, which would be off. */
1708
1709 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1710 if (!(server_sni = SSL_CTX_new(TLS_server_method())))
1711 #else
1712 if (!(server_sni = SSL_CTX_new(SSLv23_server_method())))
1713 #endif
1714   {
1715   ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1716   DEBUG(D_tls) debug_printf("SSL_CTX_new() failed: %s\n", ssl_errstring);
1717   goto bad;
1718   }
1719
1720 /* Not sure how many of these are actually needed, since SSL object
1721 already exists.  Might even need this selfsame callback, for reneg? */
1722
1723 SSL_CTX_set_info_callback(server_sni, SSL_CTX_get_info_callback(server_ctx));
1724 SSL_CTX_set_mode(server_sni, SSL_CTX_get_mode(server_ctx));
1725 SSL_CTX_set_options(server_sni, SSL_CTX_get_options(server_ctx));
1726 SSL_CTX_set_timeout(server_sni, SSL_CTX_get_timeout(server_ctx));
1727 SSL_CTX_set_tlsext_servername_callback(server_sni, tls_servername_cb);
1728 SSL_CTX_set_tlsext_servername_arg(server_sni, cbinfo);
1729
1730 if (  !init_dh(server_sni, cbinfo->dhparam, NULL, &dummy_errstr)
1731    || !init_ecdh(server_sni, NULL, &dummy_errstr)
1732    )
1733   goto bad;
1734
1735 if (  cbinfo->server_cipher_list
1736    && !SSL_CTX_set_cipher_list(server_sni, CS cbinfo->server_cipher_list))
1737   goto bad;
1738
1739 #ifndef DISABLE_OCSP
1740 if (cbinfo->u_ocsp.server.file)
1741   {
1742   SSL_CTX_set_tlsext_status_cb(server_sni, tls_server_stapling_cb);
1743   SSL_CTX_set_tlsext_status_arg(server_sni, cbinfo);
1744   }
1745 #endif
1746
1747 if ((rc = setup_certs(server_sni, tls_verify_certificates, tls_crl, NULL, FALSE,
1748                       verify_callback_server, &dummy_errstr)) != OK)
1749   goto bad;
1750
1751 /* do this after setup_certs, because this can require the certs for verifying
1752 OCSP information. */
1753 if ((rc = tls_expand_session_files(server_sni, cbinfo, &dummy_errstr)) != OK)
1754   goto bad;
1755
1756 DEBUG(D_tls) debug_printf("Switching SSL context.\n");
1757 SSL_set_SSL_CTX(s, server_sni);
1758 return SSL_TLSEXT_ERR_OK;
1759
1760 bad: return SSL_TLSEXT_ERR_ALERT_FATAL;
1761 }
1762 #endif /* EXIM_HAVE_OPENSSL_TLSEXT */
1763
1764
1765
1766
1767 #ifndef DISABLE_OCSP
1768
1769 /*************************************************
1770 *        Callback to handle OCSP Stapling        *
1771 *************************************************/
1772
1773 /* Called when acting as server during the TLS session setup if the client
1774 requests OCSP information with a Certificate Status Request.
1775
1776 Documentation via openssl s_server.c and the Apache patch from the OpenSSL
1777 project.
1778
1779 */
1780
1781 static int
1782 tls_server_stapling_cb(SSL *s, void *arg)
1783 {
1784 const tls_ext_ctx_cb * cbinfo = (tls_ext_ctx_cb *) arg;
1785 ocsp_resplist * olist = cbinfo->u_ocsp.server.olist;
1786 uschar * response_der;  /*XXX blob */
1787 int response_der_len;
1788
1789 DEBUG(D_tls)
1790   debug_printf("Received TLS status request (OCSP stapling); %s response list\n",
1791     olist ? "have" : "lack");
1792
1793 tls_in.ocsp = OCSP_NOT_RESP;
1794 if (!olist)
1795   return SSL_TLSEXT_ERR_NOACK;
1796
1797 #ifdef EXIM_HAVE_OPESSL_GET0_SERIAL
1798  {
1799   const X509 * cert_sent = SSL_get_certificate(s);
1800   const ASN1_INTEGER * cert_serial = X509_get0_serialNumber(cert_sent);
1801   const BIGNUM * cert_bn = ASN1_INTEGER_to_BN(cert_serial, NULL);
1802   const X509_NAME * cert_issuer = X509_get_issuer_name(cert_sent);
1803   uschar * chash;
1804   uint chash_len;
1805
1806   for (; olist; olist = olist->next)
1807     {
1808     OCSP_BASICRESP * bs = OCSP_response_get1_basic(olist->resp);
1809     const OCSP_SINGLERESP * single = OCSP_resp_get0(bs, 0);
1810     const OCSP_CERTID * cid = OCSP_SINGLERESP_get0_id(single);
1811     ASN1_INTEGER * res_cert_serial;
1812     const BIGNUM * resp_bn;
1813     ASN1_OCTET_STRING * res_cert_iNameHash;
1814
1815
1816     (void) OCSP_id_get0_info(&res_cert_iNameHash, NULL, NULL, &res_cert_serial,
1817       (OCSP_CERTID *) cid);
1818     resp_bn = ASN1_INTEGER_to_BN(res_cert_serial, NULL);
1819
1820     DEBUG(D_tls)
1821       {
1822       debug_printf("cert serial: %s\n", BN_bn2hex(cert_bn));
1823       debug_printf("resp serial: %s\n", BN_bn2hex(resp_bn));
1824       }
1825
1826     if (BN_cmp(cert_bn, resp_bn) == 0)
1827       {
1828       DEBUG(D_tls) debug_printf("matched serial for ocsp\n");
1829
1830       /*XXX TODO: check the rest of the list for duplicate matches.
1831       If any, need to also check the Issuer Name hash.
1832       Without this, we will provide the wrong status in the case of
1833       duplicate id. */
1834
1835       break;
1836       }
1837     DEBUG(D_tls) debug_printf("not match serial for ocsp\n");
1838     }
1839   if (!olist)
1840     {
1841     DEBUG(D_tls) debug_printf("failed to find match for ocsp\n");
1842     return SSL_TLSEXT_ERR_NOACK;
1843     }
1844  }
1845 #else
1846 if (olist->next)
1847   {
1848   DEBUG(D_tls) debug_printf("OpenSSL version too early to support multi-leaf OCSP\n");
1849   return SSL_TLSEXT_ERR_NOACK;
1850   }
1851 #endif
1852
1853 /*XXX could we do the i2d earlier, rather than during the callback? */
1854 response_der = NULL;
1855 response_der_len = i2d_OCSP_RESPONSE(olist->resp, &response_der);
1856 if (response_der_len <= 0)
1857   return SSL_TLSEXT_ERR_NOACK;
1858
1859 SSL_set_tlsext_status_ocsp_resp(server_ssl, response_der, response_der_len);
1860 tls_in.ocsp = OCSP_VFIED;
1861 return SSL_TLSEXT_ERR_OK;
1862 }
1863
1864
1865 static void
1866 time_print(BIO * bp, const char * str, ASN1_GENERALIZEDTIME * time)
1867 {
1868 BIO_printf(bp, "\t%s: ", str);
1869 ASN1_GENERALIZEDTIME_print(bp, time);
1870 BIO_puts(bp, "\n");
1871 }
1872
1873 static int
1874 tls_client_stapling_cb(SSL *s, void *arg)
1875 {
1876 tls_ext_ctx_cb * cbinfo = arg;
1877 const unsigned char * p;
1878 int len;
1879 OCSP_RESPONSE * rsp;
1880 OCSP_BASICRESP * bs;
1881 int i;
1882
1883 DEBUG(D_tls) debug_printf("Received TLS status callback (OCSP stapling):\n");
1884 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1885 if(!p)
1886  {
1887   /* Expect this when we requested ocsp but got none */
1888   if (cbinfo->u_ocsp.client.verify_required && LOGGING(tls_cipher))
1889     log_write(0, LOG_MAIN, "Required TLS certificate status not received");
1890   else
1891     DEBUG(D_tls) debug_printf(" null\n");
1892   return cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1893  }
1894
1895 if (!(rsp = d2i_OCSP_RESPONSE(NULL, &p, len)))
1896   {
1897   tls_out.ocsp = OCSP_FAILED;   /*XXX should use tlsp-> to permit concurrent outbound */
1898   if (LOGGING(tls_cipher))
1899     log_write(0, LOG_MAIN, "Received TLS cert status response, parse error");
1900   else
1901     DEBUG(D_tls) debug_printf(" parse error\n");
1902   return 0;
1903   }
1904
1905 if (!(bs = OCSP_response_get1_basic(rsp)))
1906   {
1907   tls_out.ocsp = OCSP_FAILED;
1908   if (LOGGING(tls_cipher))
1909     log_write(0, LOG_MAIN, "Received TLS cert status response, error parsing response");
1910   else
1911     DEBUG(D_tls) debug_printf(" error parsing response\n");
1912   OCSP_RESPONSE_free(rsp);
1913   return 0;
1914   }
1915
1916 /* We'd check the nonce here if we'd put one in the request. */
1917 /* However that would defeat cacheability on the server so we don't. */
1918
1919 /* This section of code reworked from OpenSSL apps source;
1920    The OpenSSL Project retains copyright:
1921    Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
1922 */
1923   {
1924     BIO * bp = NULL;
1925 #ifndef EXIM_HAVE_OCSP_RESP_COUNT
1926     STACK_OF(OCSP_SINGLERESP) * sresp = bs->tbsResponseData->responses;
1927 #endif
1928
1929     DEBUG(D_tls) bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
1930
1931     /*OCSP_RESPONSE_print(bp, rsp, 0);   extreme debug: stapling content */
1932
1933     /* Use the chain that verified the server cert to verify the stapled info */
1934     /* DEBUG(D_tls) x509_store_dump_cert_s_names(cbinfo->u_ocsp.client.verify_store); */
1935
1936     if ((i = OCSP_basic_verify(bs, cbinfo->verify_stack,
1937               cbinfo->u_ocsp.client.verify_store, OCSP_NOEXPLICIT)) <= 0)
1938       if (ERR_peek_error())
1939         {
1940         tls_out.ocsp = OCSP_FAILED;
1941         if (LOGGING(tls_cipher)) log_write(0, LOG_MAIN,
1942                 "Received TLS cert status response, itself unverifiable: %s",
1943                 ERR_reason_error_string(ERR_peek_error()));
1944         BIO_printf(bp, "OCSP response verify failure\n");
1945         ERR_print_errors(bp);
1946         OCSP_RESPONSE_print(bp, rsp, 0);
1947         goto failed;
1948         }
1949       else
1950         DEBUG(D_tls) debug_printf("no explicit trust for OCSP signing"
1951           " in the root CA certificate; ignoring\n");
1952
1953     DEBUG(D_tls) debug_printf("OCSP response well-formed and signed OK\n");
1954
1955     /*XXX So we have a good stapled OCSP status.  How do we know
1956     it is for the cert of interest?  OpenSSL 1.1.0 has a routine
1957     OCSP_resp_find_status() which matches on a cert id, which presumably
1958     we should use. Making an id needs OCSP_cert_id_new(), which takes
1959     issuerName, issuerKey, serialNumber.  Are they all in the cert?
1960
1961     For now, carry on blindly accepting the resp. */
1962
1963     for (int idx =
1964 #ifdef EXIM_HAVE_OCSP_RESP_COUNT
1965             OCSP_resp_count(bs) - 1;
1966 #else
1967             sk_OCSP_SINGLERESP_num(sresp) - 1;
1968 #endif
1969          idx >= 0; idx--)
1970       {
1971       OCSP_SINGLERESP * single = OCSP_resp_get0(bs, idx);
1972       int status, reason;
1973       ASN1_GENERALIZEDTIME * rev, * thisupd, * nextupd;
1974
1975   /*XXX so I can see putting a loop in here to handle a rsp with >1 singleresp
1976   - but what happens with a GnuTLS-style input?
1977
1978   we could do with a debug label for each singleresp
1979   - it has a certID with a serialNumber, but I see no API to get that
1980   */
1981       status = OCSP_single_get0_status(single, &reason, &rev,
1982                   &thisupd, &nextupd);
1983
1984       DEBUG(D_tls) time_print(bp, "This OCSP Update", thisupd);
1985       DEBUG(D_tls) if(nextupd) time_print(bp, "Next OCSP Update", nextupd);
1986       if (!OCSP_check_validity(thisupd, nextupd,
1987             EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1988         {
1989         tls_out.ocsp = OCSP_FAILED;
1990         DEBUG(D_tls) ERR_print_errors(bp);
1991         log_write(0, LOG_MAIN, "Server OSCP dates invalid");
1992         goto failed;
1993         }
1994
1995       DEBUG(D_tls) BIO_printf(bp, "Certificate status: %s\n",
1996                     OCSP_cert_status_str(status));
1997       switch(status)
1998         {
1999         case V_OCSP_CERTSTATUS_GOOD:
2000           continue;     /* the idx loop */
2001         case V_OCSP_CERTSTATUS_REVOKED:
2002           log_write(0, LOG_MAIN, "Server certificate revoked%s%s",
2003               reason != -1 ? "; reason: " : "",
2004               reason != -1 ? OCSP_crl_reason_str(reason) : "");
2005           DEBUG(D_tls) time_print(bp, "Revocation Time", rev);
2006           break;
2007         default:
2008           log_write(0, LOG_MAIN,
2009               "Server certificate status unknown, in OCSP stapling");
2010           break;
2011         }
2012
2013       goto failed;
2014       }
2015
2016     i = 1;
2017     tls_out.ocsp = OCSP_VFIED;
2018     goto good;
2019
2020   failed:
2021     tls_out.ocsp = OCSP_FAILED;
2022     i = cbinfo->u_ocsp.client.verify_required ? 0 : 1;
2023   good:
2024     BIO_free(bp);
2025   }
2026
2027 OCSP_RESPONSE_free(rsp);
2028 return i;
2029 }
2030 #endif  /*!DISABLE_OCSP*/
2031
2032
2033 /*************************************************
2034 *            Initialize for TLS                  *
2035 *************************************************/
2036
2037 static void
2038 tls_openssl_init(void)
2039 {
2040 #ifdef EXIM_NEED_OPENSSL_INIT
2041 SSL_load_error_strings();          /* basic set up */
2042 OpenSSL_add_ssl_algorithms();
2043 #endif
2044
2045 #if defined(EXIM_HAVE_SHA256) && !defined(OPENSSL_AUTO_SHA256)
2046 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
2047 list of available digests. */
2048 EVP_add_digest(EVP_sha256());
2049 #endif
2050 }
2051
2052
2053
2054 /* Called from both server and client code, to do preliminary initialization
2055 of the library.  We allocate and return a context structure.
2056
2057 Arguments:
2058   ctxp            returned SSL context
2059   host            connected host, if client; NULL if server
2060   dhparam         DH parameter file
2061   certificate     certificate file
2062   privatekey      private key
2063   ocsp_file       file of stapling info (server); flag for require ocsp (client)
2064   addr            address if client; NULL if server (for some randomness)
2065   cbp             place to put allocated callback context
2066   errstr          error string pointer
2067
2068 Returns:          OK/DEFER/FAIL
2069 */
2070
2071 static int
2072 tls_init(SSL_CTX **ctxp, host_item *host, uschar *dhparam, uschar *certificate,
2073   uschar *privatekey,
2074 #ifndef DISABLE_OCSP
2075   uschar *ocsp_file,
2076 #endif
2077   address_item *addr, tls_ext_ctx_cb ** cbp,
2078   tls_support * tlsp,
2079   uschar ** errstr)
2080 {
2081 SSL_CTX * ctx;
2082 long init_options;
2083 int rc;
2084 tls_ext_ctx_cb * cbinfo;
2085
2086 cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
2087 cbinfo->tlsp = tlsp;
2088 cbinfo->certificate = certificate;
2089 cbinfo->privatekey = privatekey;
2090 cbinfo->is_server = host==NULL;
2091 #ifndef DISABLE_OCSP
2092 cbinfo->verify_stack = NULL;
2093 if (!host)
2094   {
2095   cbinfo->u_ocsp.server.file = ocsp_file;
2096   cbinfo->u_ocsp.server.file_expanded = NULL;
2097   cbinfo->u_ocsp.server.olist = NULL;
2098   }
2099 else
2100   cbinfo->u_ocsp.client.verify_store = NULL;
2101 #endif
2102 cbinfo->dhparam = dhparam;
2103 cbinfo->server_cipher_list = NULL;
2104 cbinfo->host = host;
2105 #ifndef DISABLE_EVENT
2106 cbinfo->event_action = NULL;
2107 #endif
2108
2109 tls_openssl_init();
2110
2111 /* Create a context.
2112 The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
2113 negotiation in the different methods; as far as I can tell, the only
2114 *_{server,client}_method which allows negotiation is SSLv23, which exists even
2115 when OpenSSL is built without SSLv2 support.
2116 By disabling with openssl_options, we can let admins re-enable with the
2117 existing knob. */
2118
2119 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
2120 if (!(ctx = SSL_CTX_new(host ? TLS_client_method() : TLS_server_method())))
2121 #else
2122 if (!(ctx = SSL_CTX_new(host ? SSLv23_client_method() : SSLv23_server_method())))
2123 #endif
2124   return tls_error(US"SSL_CTX_new", host, NULL, errstr);
2125
2126 /* It turns out that we need to seed the random number generator this early in
2127 order to get the full complement of ciphers to work. It took me roughly a day
2128 of work to discover this by experiment.
2129
2130 On systems that have /dev/urandom, SSL may automatically seed itself from
2131 there. Otherwise, we have to make something up as best we can. Double check
2132 afterwards. */
2133
2134 if (!RAND_status())
2135   {
2136   randstuff r;
2137   gettimeofday(&r.tv, NULL);
2138   r.p = getpid();
2139
2140   RAND_seed(US (&r), sizeof(r));
2141   RAND_seed(US big_buffer, big_buffer_size);
2142   if (addr != NULL) RAND_seed(US addr, sizeof(addr));
2143
2144   if (!RAND_status())
2145     return tls_error(US"RAND_status", host,
2146       US"unable to seed random number generator", errstr);
2147   }
2148
2149 /* Set up the information callback, which outputs if debugging is at a suitable
2150 level. */
2151
2152 DEBUG(D_tls)
2153   {
2154   SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
2155 #if defined(EXIM_HAVE_OPESSL_TRACE) && !defined(OPENSSL_NO_SSL_TRACE)
2156   /* this needs a debug build of OpenSSL */
2157   SSL_CTX_set_msg_callback(ctx, (void (*)())SSL_trace);
2158 #endif
2159 #ifdef OPENSSL_HAVE_KEYLOG_CB
2160   SSL_CTX_set_keylog_callback(ctx, (void (*)())keylog_callback);
2161 #endif
2162   }
2163
2164 /* Automatically re-try reads/writes after renegotiation. */
2165 (void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
2166
2167 /* Apply administrator-supplied work-arounds.
2168 Historically we applied just one requested option,
2169 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
2170 moved to an administrator-controlled list of options to specify and
2171 grandfathered in the first one as the default value for "openssl_options".
2172
2173 No OpenSSL version number checks: the options we accept depend upon the
2174 availability of the option value macros from OpenSSL.  */
2175
2176 if (!tls_openssl_options_parse(openssl_options, &init_options))
2177   return tls_error(US"openssl_options parsing failed", host, NULL, errstr);
2178
2179 #ifdef EXPERIMENTAL_TLS_RESUME
2180 tlsp->resumption = RESUME_SUPPORTED;
2181 #endif
2182 if (init_options)
2183   {
2184 #ifdef EXPERIMENTAL_TLS_RESUME
2185   /* Should the server offer session resumption? */
2186   if (!host && verify_check_host(&tls_resumption_hosts) == OK)
2187     {
2188     DEBUG(D_tls) debug_printf("tls_resumption_hosts overrides openssl_options\n");
2189     init_options &= ~SSL_OP_NO_TICKET;
2190     tlsp->resumption |= RESUME_SERVER_TICKET; /* server will give ticket on request */
2191     tlsp->host_resumable = TRUE;
2192     }
2193 #endif
2194
2195   DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
2196   if (!(SSL_CTX_set_options(ctx, init_options)))
2197     return tls_error(string_sprintf(
2198           "SSL_CTX_set_option(%#lx)", init_options), host, NULL, errstr);
2199   }
2200 else
2201   DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
2202
2203 /* We'd like to disable session cache unconditionally, but foolish Outlook
2204 Express clients then give up the first TLS connection and make a second one
2205 (which works).  Only when there is an IMAP service on the same machine.
2206 Presumably OE is trying to use the cache for A on B.  Leave it enabled for
2207 now, until we work out a decent way of presenting control to the config.  It
2208 will never be used because we use a new context every time. */
2209 #ifdef notdef
2210 (void) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2211 #endif
2212
2213 /* Initialize with DH parameters if supplied */
2214 /* Initialize ECDH temp key parameter selection */
2215
2216 if (  !init_dh(ctx, dhparam, host, errstr)
2217    || !init_ecdh(ctx, host, errstr)
2218    )
2219   return DEFER;
2220
2221 /* Set up certificate and key (and perhaps OCSP info) */
2222
2223 if ((rc = tls_expand_session_files(ctx, cbinfo, errstr)) != OK)
2224   return rc;
2225
2226 /* If we need to handle SNI or OCSP, do so */
2227
2228 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
2229 # ifndef DISABLE_OCSP
2230   if (!(cbinfo->verify_stack = sk_X509_new_null()))
2231     {
2232     DEBUG(D_tls) debug_printf("failed to create stack for stapling verify\n");
2233     return FAIL;
2234     }
2235 # endif
2236
2237 if (!host)              /* server */
2238   {
2239 # ifndef DISABLE_OCSP
2240   /* We check u_ocsp.server.file, not server.olist, because we care about if
2241   the option exists, not what the current expansion might be, as SNI might
2242   change the certificate and OCSP file in use between now and the time the
2243   callback is invoked. */
2244   if (cbinfo->u_ocsp.server.file)
2245     {
2246     SSL_CTX_set_tlsext_status_cb(ctx, tls_server_stapling_cb);
2247     SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
2248     }
2249 # endif
2250   /* We always do this, so that $tls_sni is available even if not used in
2251   tls_certificate */
2252   SSL_CTX_set_tlsext_servername_callback(ctx, tls_servername_cb);
2253   SSL_CTX_set_tlsext_servername_arg(ctx, cbinfo);
2254   }
2255 # ifndef DISABLE_OCSP
2256 else                    /* client */
2257   if(ocsp_file)         /* wanting stapling */
2258     {
2259     if (!(cbinfo->u_ocsp.client.verify_store = X509_STORE_new()))
2260       {
2261       DEBUG(D_tls) debug_printf("failed to create store for stapling verify\n");
2262       return FAIL;
2263       }
2264     SSL_CTX_set_tlsext_status_cb(ctx, tls_client_stapling_cb);
2265     SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
2266     }
2267 # endif
2268 #endif
2269
2270 cbinfo->verify_cert_hostnames = NULL;
2271
2272 #ifdef EXIM_HAVE_EPHEM_RSA_KEX
2273 /* Set up the RSA callback */
2274 SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
2275 #endif
2276
2277 /* Finally, set the session cache timeout, and we are done.
2278 The period appears to be also used for (server-generated) session tickets */
2279
2280 SSL_CTX_set_timeout(ctx, ssl_session_timeout);
2281 DEBUG(D_tls) debug_printf("Initialized TLS\n");
2282
2283 *cbp = cbinfo;
2284 *ctxp = ctx;
2285
2286 return OK;
2287 }
2288
2289
2290
2291
2292 /*************************************************
2293 *           Get name of cipher in use            *
2294 *************************************************/
2295
2296 /*
2297 Argument:   pointer to an SSL structure for the connection
2298             pointer to number of bits for cipher
2299 Returns:    pointer to allocated string in perm-pool
2300 */
2301
2302 static uschar *
2303 construct_cipher_name(SSL * ssl, const uschar * ver, int * bits)
2304 {
2305 int pool = store_pool;
2306 /* With OpenSSL 1.0.0a, 'c' needs to be const but the documentation doesn't
2307 yet reflect that.  It should be a safe change anyway, even 0.9.8 versions have
2308 the accessor functions use const in the prototype. */
2309
2310 const SSL_CIPHER * c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
2311 uschar * s;
2312
2313 SSL_CIPHER_get_bits(c, bits);
2314
2315 store_pool = POOL_PERM;
2316 s = string_sprintf("%s:%s:%u", ver, SSL_CIPHER_get_name(c), *bits);
2317 store_pool = pool;
2318 DEBUG(D_tls) debug_printf("Cipher: %s\n", s);
2319 return s;
2320 }
2321
2322
2323 /* Get IETF-standard name for ciphersuite.
2324 Argument:   pointer to an SSL structure for the connection
2325 Returns:    pointer to string
2326 */
2327
2328 static const uschar *
2329 cipher_stdname_ssl(SSL * ssl)
2330 {
2331 #ifdef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
2332 return CUS SSL_CIPHER_standard_name(SSL_get_current_cipher(ssl));
2333 #else
2334 ushort id = 0xffff & SSL_CIPHER_get_id(SSL_get_current_cipher(ssl));
2335 return cipher_stdname(id >> 8, id & 0xff);
2336 #endif
2337 }
2338
2339
2340 static const uschar *
2341 tlsver_name(SSL * ssl)
2342 {
2343 uschar * s, * p;
2344 int pool = store_pool;
2345
2346 store_pool = POOL_PERM;
2347 s = string_copy(US SSL_get_version(ssl));
2348 store_pool = pool;
2349 if ((p = Ustrchr(s, 'v')))      /* TLSv1.2 -> TLS1.2 */
2350   for (;; p++) if (!(*p = p[1])) break;
2351 return CUS s;
2352 }
2353
2354
2355 static void
2356 peer_cert(SSL * ssl, tls_support * tlsp, uschar * peerdn, unsigned siz)
2357 {
2358 /*XXX we might consider a list-of-certs variable for the cert chain.
2359 SSL_get_peer_cert_chain(SSL*).  We'd need a new variable type and support
2360 in list-handling functions, also consider the difference between the entire
2361 chain and the elements sent by the peer. */
2362
2363 tlsp->peerdn = NULL;
2364
2365 /* Will have already noted peercert on a verify fail; possibly not the leaf */
2366 if (!tlsp->peercert)
2367   tlsp->peercert = SSL_get_peer_certificate(ssl);
2368 /* Beware anonymous ciphers which lead to server_cert being NULL */
2369 if (tlsp->peercert)
2370   if (!X509_NAME_oneline(X509_get_subject_name(tlsp->peercert), CS peerdn, siz))
2371     { DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n"); }
2372   else
2373     {
2374     int oldpool = store_pool;
2375
2376     peerdn[siz-1] = '\0';               /* paranoia */
2377     store_pool = POOL_PERM;
2378     tlsp->peerdn = string_copy(peerdn);
2379     store_pool = oldpool;
2380
2381     /* We used to set CV in the cert-verify callbacks (either plain or dane)
2382     but they don't get called on session-resumption.  So use the official
2383     interface, which uses the resumed value.  Unfortunately this claims verified
2384     when it actually failed but we're in try-verify mode, due to us wanting the
2385     knowlege that it failed so needing to have the callback and forcing a
2386     permissive return.  If we don't force it, the TLS startup is failed.
2387     The extra bit of information is set in verify_override in the cb, stashed
2388     for resumption next to the TLS session, and used here. */
2389
2390     if (!tlsp->verify_override)
2391       tlsp->certificate_verified =
2392 #ifdef SUPPORT_DANE
2393         tlsp->dane_verified ||
2394 #endif
2395         SSL_get_verify_result(ssl) == X509_V_OK;
2396     }
2397 }
2398
2399
2400
2401
2402
2403 /*************************************************
2404 *        Set up for verifying certificates       *
2405 *************************************************/
2406
2407 #ifndef DISABLE_OCSP
2408 /* Load certs from file, return TRUE on success */
2409
2410 static BOOL
2411 chain_from_pem_file(const uschar * file, STACK_OF(X509) * verify_stack)
2412 {
2413 BIO * bp;
2414 X509 * x;
2415
2416 while (sk_X509_num(verify_stack) > 0)
2417   X509_free(sk_X509_pop(verify_stack));
2418
2419 if (!(bp = BIO_new_file(CS file, "r"))) return FALSE;
2420 while ((x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
2421   sk_X509_push(verify_stack, x);
2422 BIO_free(bp);
2423 return TRUE;
2424 }
2425 #endif
2426
2427
2428
2429 /* Called by both client and server startup; on the server possibly
2430 repeated after a Server Name Indication.
2431
2432 Arguments:
2433   sctx          SSL_CTX* to initialise
2434   certs         certs file or NULL
2435   crl           CRL file or NULL
2436   host          NULL in a server; the remote host in a client
2437   optional      TRUE if called from a server for a host in tls_try_verify_hosts;
2438                 otherwise passed as FALSE
2439   cert_vfy_cb   Callback function for certificate verification
2440   errstr        error string pointer
2441
2442 Returns:        OK/DEFER/FAIL
2443 */
2444
2445 static int
2446 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
2447     int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr)
2448 {
2449 uschar *expcerts, *expcrl;
2450
2451 if (!expand_check(certs, US"tls_verify_certificates", &expcerts, errstr))
2452   return DEFER;
2453 DEBUG(D_tls) debug_printf("tls_verify_certificates: %s\n", expcerts);
2454
2455 if (expcerts && *expcerts)
2456   {
2457   /* Tell the library to use its compiled-in location for the system default
2458   CA bundle. Then add the ones specified in the config, if any. */
2459
2460   if (!SSL_CTX_set_default_verify_paths(sctx))
2461     return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL, errstr);
2462
2463   if (Ustrcmp(expcerts, "system") != 0)
2464     {
2465     struct stat statbuf;
2466
2467     if (Ustat(expcerts, &statbuf) < 0)
2468       {
2469       log_write(0, LOG_MAIN|LOG_PANIC,
2470         "failed to stat %s for certificates", expcerts);
2471       return DEFER;
2472       }
2473     else
2474       {
2475       uschar *file, *dir;
2476       if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
2477         { file = NULL; dir = expcerts; }
2478       else
2479         {
2480         file = expcerts; dir = NULL;
2481 #ifndef DISABLE_OCSP
2482         /* In the server if we will be offering an OCSP proof, load chain from
2483         file for verifying the OCSP proof at load time. */
2484
2485 /*XXX Glitch!   The file here is tls_verify_certs: the chain for verifying the client cert.
2486 This is inconsistent with the need to verify the OCSP proof of the server cert.
2487 */
2488
2489         if (  !host
2490            && statbuf.st_size > 0
2491            && server_static_cbinfo->u_ocsp.server.file
2492            && !chain_from_pem_file(file, server_static_cbinfo->verify_stack)
2493            )
2494           {
2495           log_write(0, LOG_MAIN|LOG_PANIC,
2496             "failed to load cert chain from %s", file);
2497           return DEFER;
2498           }
2499 #endif
2500         }
2501
2502       /* If a certificate file is empty, the load function fails with an
2503       unhelpful error message. If we skip it, we get the correct behaviour (no
2504       certificates are recognized, but the error message is still misleading (it
2505       says no certificate was supplied).  But this is better. */
2506
2507       if (  (!file || statbuf.st_size > 0)
2508          && !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
2509         return tls_error(US"SSL_CTX_load_verify_locations", host, NULL, errstr);
2510
2511       /* On the server load the list of CAs for which we will accept certs, for
2512       sending to the client.  This is only for the one-file
2513       tls_verify_certificates variant.
2514       If a list isn't loaded into the server, but some verify locations are set,
2515       the server end appears to make a wildcard request for client certs.
2516       Meanwhile, the client library as default behaviour *ignores* the list
2517       we send over the wire - see man SSL_CTX_set_client_cert_cb.
2518       Because of this, and that the dir variant is likely only used for
2519       the public-CA bundle (not for a private CA), not worth fixing.  */
2520
2521       if (file)
2522         {
2523         STACK_OF(X509_NAME) * names = SSL_load_client_CA_file(CS file);
2524
2525         if (!host) SSL_CTX_set_client_CA_list(sctx, names);
2526         DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n",
2527                                     sk_X509_NAME_num(names));
2528         }
2529       }
2530     }
2531
2532   /* Handle a certificate revocation list. */
2533
2534 #if OPENSSL_VERSION_NUMBER > 0x00907000L
2535
2536   /* This bit of code is now the version supplied by Lars Mainka. (I have
2537   merely reformatted it into the Exim code style.)
2538
2539   "From here I changed the code to add support for multiple crl's
2540   in pem format in one file or to support hashed directory entries in
2541   pem format instead of a file. This method now uses the library function
2542   X509_STORE_load_locations to add the CRL location to the SSL context.
2543   OpenSSL will then handle the verify against CA certs and CRLs by
2544   itself in the verify callback." */
2545
2546   if (!expand_check(crl, US"tls_crl", &expcrl, errstr)) return DEFER;
2547   if (expcrl && *expcrl)
2548     {
2549     struct stat statbufcrl;
2550     if (Ustat(expcrl, &statbufcrl) < 0)
2551       {
2552       log_write(0, LOG_MAIN|LOG_PANIC,
2553         "failed to stat %s for certificates revocation lists", expcrl);
2554       return DEFER;
2555       }
2556     else
2557       {
2558       /* is it a file or directory? */
2559       uschar *file, *dir;
2560       X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
2561       if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
2562         {
2563         file = NULL;
2564         dir = expcrl;
2565         DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
2566         }
2567       else
2568         {
2569         file = expcrl;
2570         dir = NULL;
2571         DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
2572         }
2573       if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
2574         return tls_error(US"X509_STORE_load_locations", host, NULL, errstr);
2575
2576       /* setting the flags to check against the complete crl chain */
2577
2578       X509_STORE_set_flags(cvstore,
2579         X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2580       }
2581     }
2582
2583 #endif  /* OPENSSL_VERSION_NUMBER > 0x00907000L */
2584
2585   /* If verification is optional, don't fail if no certificate */
2586
2587   SSL_CTX_set_verify(sctx,
2588     SSL_VERIFY_PEER | (optional ? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
2589     cert_vfy_cb);
2590   }
2591
2592 return OK;
2593 }
2594
2595
2596
2597 /*************************************************
2598 *       Start a TLS session in a server          *
2599 *************************************************/
2600
2601 /* This is called when Exim is running as a server, after having received
2602 the STARTTLS command. It must respond to that command, and then negotiate
2603 a TLS session.
2604
2605 Arguments:
2606   require_ciphers   allowed ciphers
2607   errstr            pointer to error message
2608
2609 Returns:            OK on success
2610                     DEFER for errors before the start of the negotiation
2611                     FAIL for errors during the negotiation; the server can't
2612                       continue running.
2613 */
2614
2615 int
2616 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
2617 {
2618 int rc;
2619 uschar * expciphers;
2620 tls_ext_ctx_cb * cbinfo;
2621 static uschar peerdn[256];
2622
2623 /* Check for previous activation */
2624
2625 if (tls_in.active.sock >= 0)
2626   {
2627   tls_error(US"STARTTLS received after TLS started", NULL, US"", errstr);
2628   smtp_printf("554 Already in TLS\r\n", FALSE);
2629   return FAIL;
2630   }
2631
2632 /* Initialize the SSL library. If it fails, it will already have logged
2633 the error. */
2634
2635 rc = tls_init(&server_ctx, NULL, tls_dhparam, tls_certificate, tls_privatekey,
2636 #ifndef DISABLE_OCSP
2637     tls_ocsp_file,
2638 #endif
2639     NULL, &server_static_cbinfo, &tls_in, errstr);
2640 if (rc != OK) return rc;
2641 cbinfo = server_static_cbinfo;
2642
2643 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers, errstr))
2644   return FAIL;
2645
2646 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2647 were historically separated by underscores. So that I can use either form in my
2648 tests, and also for general convenience, we turn underscores into hyphens here.
2649
2650 XXX SSL_CTX_set_cipher_list() is replaced by SSL_CTX_set_ciphersuites()
2651 for TLS 1.3 .  Since we do not call it at present we get the default list:
2652 TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
2653 */
2654
2655 if (expciphers)
2656   {
2657   for (uschar * s = expciphers; *s; s++ ) if (*s == '_') *s = '-';
2658   DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
2659   if (!SSL_CTX_set_cipher_list(server_ctx, CS expciphers))
2660     return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL, errstr);
2661   cbinfo->server_cipher_list = expciphers;
2662   }
2663
2664 /* If this is a host for which certificate verification is mandatory or
2665 optional, set up appropriately. */
2666
2667 tls_in.certificate_verified = FALSE;
2668 #ifdef SUPPORT_DANE
2669 tls_in.dane_verified = FALSE;
2670 #endif
2671 server_verify_callback_called = FALSE;
2672
2673 if (verify_check_host(&tls_verify_hosts) == OK)
2674   {
2675   rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
2676                         FALSE, verify_callback_server, errstr);
2677   if (rc != OK) return rc;
2678   server_verify_optional = FALSE;
2679   }
2680 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2681   {
2682   rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
2683                         TRUE, verify_callback_server, errstr);
2684   if (rc != OK) return rc;
2685   server_verify_optional = TRUE;
2686   }
2687
2688 #ifdef EXPERIMENTAL_TLS_RESUME
2689 SSL_CTX_set_tlsext_ticket_key_cb(server_ctx, ticket_key_callback);
2690 /* despite working, appears to always return failure, so ignoring */
2691 #endif
2692 #ifdef OPENSSL_HAVE_NUM_TICKETS
2693 # ifdef EXPERIMENTAL_TLS_RESUME
2694 SSL_CTX_set_num_tickets(server_ctx, tls_in.host_resumable ? 1 : 0);
2695 # else
2696 SSL_CTX_set_num_tickets(server_ctx, 0); /* send no TLS1.3 stateful-tickets */
2697 # endif
2698 #endif
2699
2700
2701 /* Prepare for new connection */
2702
2703 if (!(server_ssl = SSL_new(server_ctx)))
2704   return tls_error(US"SSL_new", NULL, NULL, errstr);
2705
2706 /* Warning: we used to SSL_clear(ssl) here, it was removed.
2707  *
2708  * With the SSL_clear(), we get strange interoperability bugs with
2709  * OpenSSL 1.0.1b and TLS1.1/1.2.  It looks as though this may be a bug in
2710  * OpenSSL itself, as a clear should not lead to inability to follow protocols.
2711  *
2712  * The SSL_clear() call is to let an existing SSL* be reused, typically after
2713  * session shutdown.  In this case, we have a brand new object and there's no
2714  * obvious reason to immediately clear it.  I'm guessing that this was
2715  * originally added because of incomplete initialisation which the clear fixed,
2716  * in some historic release.
2717  */
2718
2719 /* Set context and tell client to go ahead, except in the case of TLS startup
2720 on connection, where outputting anything now upsets the clients and tends to
2721 make them disconnect. We need to have an explicit fflush() here, to force out
2722 the response. Other smtp_printf() calls do not need it, because in non-TLS
2723 mode, the fflush() happens when smtp_getc() is called. */
2724
2725 SSL_set_session_id_context(server_ssl, sid_ctx, Ustrlen(sid_ctx));
2726 if (!tls_in.on_connect)
2727   {
2728   smtp_printf("220 TLS go ahead\r\n", FALSE);
2729   fflush(smtp_out);
2730   }
2731
2732 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2733 that the OpenSSL library doesn't. */
2734
2735 SSL_set_wfd(server_ssl, fileno(smtp_out));
2736 SSL_set_rfd(server_ssl, fileno(smtp_in));
2737 SSL_set_accept_state(server_ssl);
2738
2739 DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
2740
2741 sigalrm_seen = FALSE;
2742 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2743 rc = SSL_accept(server_ssl);
2744 ALARM_CLR(0);
2745
2746 if (rc <= 0)
2747   {
2748   int error = SSL_get_error(server_ssl, rc);
2749   switch(error)
2750     {
2751     case SSL_ERROR_NONE:
2752       break;
2753
2754     case SSL_ERROR_ZERO_RETURN:
2755       DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2756       (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
2757
2758       if (SSL_get_shutdown(server_ssl) == SSL_RECEIVED_SHUTDOWN)
2759             SSL_shutdown(server_ssl);
2760
2761       tls_close(NULL, TLS_NO_SHUTDOWN);
2762       return FAIL;
2763
2764     /* Handle genuine errors */
2765     case SSL_ERROR_SSL:
2766       {
2767       uschar * s = US"SSL_accept";
2768       int r = ERR_GET_REASON(ERR_peek_error());
2769       if (  r == SSL_R_WRONG_VERSION_NUMBER
2770 #ifdef SSL_R_VERSION_TOO_LOW
2771          || r == SSL_R_VERSION_TOO_LOW
2772 #endif
2773          || r == SSL_R_UNKNOWN_PROTOCOL || r == SSL_R_UNSUPPORTED_PROTOCOL)
2774         s = string_sprintf("%s (%s)", s, SSL_get_version(server_ssl));
2775       (void) tls_error(s, NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
2776       return FAIL;
2777       }
2778
2779     default:
2780       DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
2781       if (error == SSL_ERROR_SYSCALL)
2782         {
2783         if (!errno)
2784           {
2785           *errstr = US"SSL_accept: TCP connection closed by peer";
2786           return FAIL;
2787           }
2788         DEBUG(D_tls) debug_printf(" - syscall %s\n", strerror(errno));
2789         }
2790       (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
2791       return FAIL;
2792     }
2793   }
2794
2795 DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
2796 ERR_clear_error();      /* Even success can leave errors in the stack. Seen with
2797                         anon-authentication ciphersuite negotiated. */
2798
2799 #ifdef EXPERIMENTAL_TLS_RESUME
2800 if (SSL_session_reused(server_ssl))
2801   {
2802   tls_in.resumption |= RESUME_USED;
2803   DEBUG(D_tls) debug_printf("Session reused\n");
2804   }
2805 #endif
2806
2807 /* TLS has been set up. Record data for the connection,
2808 adjust the input functions to read via TLS, and initialize things. */
2809
2810 #ifdef SSL_get_extms_support
2811 tls_in.ext_master_secret = SSL_get_extms_support(server_ssl) == 1;
2812 #endif
2813 peer_cert(server_ssl, &tls_in, peerdn, sizeof(peerdn));
2814
2815 tls_in.ver = tlsver_name(server_ssl);
2816 tls_in.cipher = construct_cipher_name(server_ssl, tls_in.ver, &tls_in.bits);
2817 tls_in.cipher_stdname = cipher_stdname_ssl(server_ssl);
2818
2819 DEBUG(D_tls)
2820   {
2821   uschar buf[2048];
2822   if (SSL_get_shared_ciphers(server_ssl, CS buf, sizeof(buf)))
2823     debug_printf("Shared ciphers: %s\n", buf);
2824
2825 #ifdef EXIM_HAVE_OPENSSL_KEYLOG
2826   {
2827   BIO * bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
2828   SSL_SESSION_print_keylog(bp, SSL_get_session(server_ssl));
2829   BIO_free(bp);
2830   }
2831 #endif
2832
2833 #ifdef EXIM_HAVE_SESSION_TICKET
2834   {
2835   SSL_SESSION * ss = SSL_get_session(server_ssl);
2836   if (SSL_SESSION_has_ticket(ss))       /* 1.1.0 */
2837     debug_printf("The session has a ticket, life %lu seconds\n",
2838       SSL_SESSION_get_ticket_lifetime_hint(ss));
2839   }
2840 #endif
2841   }
2842
2843 /* Record the certificate we presented */
2844   {
2845   X509 * crt = SSL_get_certificate(server_ssl);
2846   tls_in.ourcert = crt ? X509_dup(crt) : NULL;
2847   }
2848
2849 /* Channel-binding info for authenticators
2850 See description in https://paquier.xyz/postgresql-2/channel-binding-openssl/ */
2851   {
2852   uschar c, * s;
2853   size_t len = SSL_get_peer_finished(server_ssl, &c, 0);
2854   int old_pool = store_pool;
2855
2856   SSL_get_peer_finished(server_ssl, s = store_get((int)len, FALSE), len);
2857   store_pool = POOL_PERM;
2858     tls_in.channelbinding = b64encode_taint(CUS s, (int)len, FALSE);
2859   store_pool = old_pool;
2860   DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage %p\n", tls_in.channelbinding);
2861   }
2862
2863 /* Only used by the server-side tls (tls_in), including tls_getc.
2864    Client-side (tls_out) reads (seem to?) go via
2865    smtp_read_response()/ip_recv().
2866    Hence no need to duplicate for _in and _out.
2867  */
2868 if (!ssl_xfer_buffer) ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2869 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
2870 ssl_xfer_eof = ssl_xfer_error = FALSE;
2871
2872 receive_getc = tls_getc;
2873 receive_getbuf = tls_getbuf;
2874 receive_get_cache = tls_get_cache;
2875 receive_ungetc = tls_ungetc;
2876 receive_feof = tls_feof;
2877 receive_ferror = tls_ferror;
2878 receive_smtp_buffered = tls_smtp_buffered;
2879
2880 tls_in.active.sock = fileno(smtp_out);
2881 tls_in.active.tls_ctx = NULL;   /* not using explicit ctx for server-side */
2882 return OK;
2883 }
2884
2885
2886
2887
2888 static int
2889 tls_client_basic_ctx_init(SSL_CTX * ctx,
2890     host_item * host, smtp_transport_options_block * ob, tls_ext_ctx_cb * cbinfo,
2891     uschar ** errstr)
2892 {
2893 int rc;
2894 /* stick to the old behaviour for compatibility if tls_verify_certificates is
2895    set but both tls_verify_hosts and tls_try_verify_hosts is not set. Check only
2896    the specified host patterns if one of them is defined */
2897
2898 if (  (  !ob->tls_verify_hosts
2899       && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2900       )
2901    || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
2902    )
2903   client_verify_optional = FALSE;
2904 else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
2905   client_verify_optional = TRUE;
2906 else
2907   return OK;
2908
2909 if ((rc = setup_certs(ctx, ob->tls_verify_certificates,
2910       ob->tls_crl, host, client_verify_optional, verify_callback_client,
2911       errstr)) != OK)
2912   return rc;
2913
2914 if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
2915   {
2916   cbinfo->verify_cert_hostnames =
2917 #ifdef SUPPORT_I18N
2918     string_domain_utf8_to_alabel(host->name, NULL);
2919 #else
2920     host->name;
2921 #endif
2922   DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
2923                     cbinfo->verify_cert_hostnames);
2924   }
2925 return OK;
2926 }
2927
2928
2929 #ifdef SUPPORT_DANE
2930 static int
2931 dane_tlsa_load(SSL * ssl, host_item * host, dns_answer * dnsa, uschar ** errstr)
2932 {
2933 dns_scan dnss;
2934 const char * hostnames[2] = { CS host->name, NULL };
2935 int found = 0;
2936
2937 if (DANESSL_init(ssl, NULL, hostnames) != 1)
2938   return tls_error(US"hostnames load", host, NULL, errstr);
2939
2940 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
2941      rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2942     ) if (rr->type == T_TLSA && rr->size > 3)
2943   {
2944   const uschar * p = rr->data;
2945   uint8_t usage, selector, mtype;
2946   const char * mdname;
2947
2948   usage = *p++;
2949
2950   /* Only DANE-TA(2) and DANE-EE(3) are supported */
2951   if (usage != 2 && usage != 3) continue;
2952
2953   selector = *p++;
2954   mtype = *p++;
2955
2956   switch (mtype)
2957     {
2958     default: continue;  /* Only match-types 0, 1, 2 are supported */
2959     case 0:  mdname = NULL; break;
2960     case 1:  mdname = "sha256"; break;
2961     case 2:  mdname = "sha512"; break;
2962     }
2963
2964   found++;
2965   switch (DANESSL_add_tlsa(ssl, usage, selector, mdname, p, rr->size - 3))
2966     {
2967     default:
2968       return tls_error(US"tlsa load", host, NULL, errstr);
2969     case 0:     /* action not taken */
2970     case 1:     break;
2971     }
2972
2973   tls_out.tlsa_usage |= 1<<usage;
2974   }
2975
2976 if (found)
2977   return OK;
2978
2979 log_write(0, LOG_MAIN, "DANE error: No usable TLSA records");
2980 return DEFER;
2981 }
2982 #endif  /*SUPPORT_DANE*/
2983
2984
2985
2986 #ifdef EXPERIMENTAL_TLS_RESUME
2987 /* On the client, get any stashed session for the given IP from hints db
2988 and apply it to the ssl-connection for attempted resumption. */
2989
2990 static void
2991 tls_retrieve_session(tls_support * tlsp, SSL * ssl, const uschar * key)
2992 {
2993 tlsp->resumption |= RESUME_SUPPORTED;
2994 if (tlsp->host_resumable)
2995   {
2996   dbdata_tls_session * dt;
2997   int len;
2998   open_db dbblock, * dbm_file;
2999
3000   tlsp->resumption |= RESUME_CLIENT_REQUESTED;
3001   DEBUG(D_tls) debug_printf("checking for resumable session for %s\n", key);
3002   if ((dbm_file = dbfn_open(US"tls", O_RDWR, &dbblock, FALSE, FALSE)))
3003     {
3004     /* key for the db is the IP */
3005     if ((dt = dbfn_read_with_length(dbm_file, key, &len)))
3006       {
3007       SSL_SESSION * ss = NULL;
3008       const uschar * sess_asn1 = dt->session;
3009
3010       len -= sizeof(dbdata_tls_session);
3011       if (!(d2i_SSL_SESSION(&ss, &sess_asn1, (long)len)))
3012         {
3013         DEBUG(D_tls)
3014           {
3015           ERR_error_string_n(ERR_get_error(),
3016             ssl_errstring, sizeof(ssl_errstring));
3017           debug_printf("decoding session: %s\n", ssl_errstring);
3018           }
3019         }
3020 #ifdef EXIM_HAVE_SESSION_TICKET
3021       else if ( SSL_SESSION_get_ticket_lifetime_hint(ss) + dt->time_stamp
3022                < time(NULL))
3023         {
3024         DEBUG(D_tls) debug_printf("session expired\n");
3025         dbfn_delete(dbm_file, key);
3026         }
3027 #endif
3028       else if (!SSL_set_session(ssl, ss))
3029         {
3030         DEBUG(D_tls)
3031           {
3032           ERR_error_string_n(ERR_get_error(),
3033             ssl_errstring, sizeof(ssl_errstring));
3034           debug_printf("applying session to ssl: %s\n", ssl_errstring);
3035           }
3036         }
3037       else
3038         {
3039         DEBUG(D_tls) debug_printf("good session\n");
3040         tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
3041         tlsp->verify_override = dt->verify_override;
3042         tlsp->ocsp = dt->ocsp;
3043         }
3044       }
3045     else
3046       DEBUG(D_tls) debug_printf("no session record\n");
3047     dbfn_close(dbm_file);
3048     }
3049   }
3050 }
3051
3052
3053 /* On the client, save the session for later resumption */
3054
3055 static int
3056 tls_save_session_cb(SSL * ssl, SSL_SESSION * ss)
3057 {
3058 tls_ext_ctx_cb * cbinfo = SSL_get_ex_data(ssl, tls_exdata_idx);
3059 tls_support * tlsp;
3060
3061 DEBUG(D_tls) debug_printf("tls_save_session_cb\n");
3062
3063 if (!cbinfo || !(tlsp = cbinfo->tlsp)->host_resumable) return 0;
3064
3065 # ifdef OPENSSL_HAVE_NUM_TICKETS
3066 if (SSL_SESSION_is_resumable(ss))       /* 1.1.1 */
3067 # endif
3068   {
3069   int len = i2d_SSL_SESSION(ss, NULL);
3070   int dlen = sizeof(dbdata_tls_session) + len;
3071   dbdata_tls_session * dt = store_get(dlen, TRUE);
3072   uschar * s = dt->session;
3073   open_db dbblock, * dbm_file;
3074
3075   DEBUG(D_tls) debug_printf("session is resumable\n");
3076   tlsp->resumption |= RESUME_SERVER_TICKET;     /* server gave us a ticket */
3077
3078   dt->verify_override = tlsp->verify_override;
3079   dt->ocsp = tlsp->ocsp;
3080   (void) i2d_SSL_SESSION(ss, &s);               /* s gets bumped to end */
3081
3082   if ((dbm_file = dbfn_open(US"tls", O_RDWR, &dbblock, FALSE, FALSE)))
3083     {
3084     const uschar * key = cbinfo->host->address;
3085     dbfn_delete(dbm_file, key);
3086     dbfn_write(dbm_file, key, dt, dlen);
3087     dbfn_close(dbm_file);
3088     DEBUG(D_tls) debug_printf("wrote session (len %u) to db\n",
3089                   (unsigned)dlen);
3090     }
3091   }
3092 return 1;
3093 }
3094
3095
3096 static void
3097 tls_client_ctx_resume_prehandshake(
3098   exim_openssl_client_tls_ctx * exim_client_ctx, tls_support * tlsp,
3099   smtp_transport_options_block * ob, host_item * host)
3100 {
3101 /* Should the client request a session resumption ticket? */
3102 if (verify_check_given_host(CUSS &ob->tls_resumption_hosts, host) == OK)
3103   {
3104   tlsp->host_resumable = TRUE;
3105
3106   SSL_CTX_set_session_cache_mode(exim_client_ctx->ctx,
3107         SSL_SESS_CACHE_CLIENT
3108         | SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_NO_AUTO_CLEAR);
3109   SSL_CTX_sess_set_new_cb(exim_client_ctx->ctx, tls_save_session_cb);
3110   }
3111 }
3112
3113 static BOOL
3114 tls_client_ssl_resume_prehandshake(SSL * ssl, tls_support * tlsp,
3115   host_item * host, uschar ** errstr)
3116 {
3117 if (tlsp->host_resumable)
3118   {
3119   DEBUG(D_tls)
3120     debug_printf("tls_resumption_hosts overrides openssl_options, enabling tickets\n");
3121   SSL_clear_options(ssl, SSL_OP_NO_TICKET);
3122
3123   tls_exdata_idx = SSL_get_ex_new_index(0, 0, 0, 0, 0);
3124   if (!SSL_set_ex_data(ssl, tls_exdata_idx, client_static_cbinfo))
3125     {
3126     tls_error(US"set ex_data", host, NULL, errstr);
3127     return FALSE;
3128     }
3129   debug_printf("tls_exdata_idx %d cbinfo %p\n", tls_exdata_idx, client_static_cbinfo);
3130   }
3131
3132 tlsp->resumption = RESUME_SUPPORTED;
3133 /* Pick up a previous session, saved on an old ticket */
3134 tls_retrieve_session(tlsp, ssl, host->address);
3135 return TRUE;
3136 }
3137
3138 static void
3139 tls_client_resume_posthandshake(exim_openssl_client_tls_ctx * exim_client_ctx,
3140   tls_support * tlsp)
3141 {
3142 if (SSL_session_reused(exim_client_ctx->ssl))
3143   {
3144   DEBUG(D_tls) debug_printf("The session was reused\n");
3145   tlsp->resumption |= RESUME_USED;
3146   }
3147 }
3148 #endif  /* EXPERIMENTAL_TLS_RESUME */
3149
3150
3151 /*************************************************
3152 *    Start a TLS session in a client             *
3153 *************************************************/
3154
3155 /* Called from the smtp transport after STARTTLS has been accepted.
3156
3157 Arguments:
3158   cctx          connection context
3159   conn_args     connection details
3160   cookie        datum for randomness; can be NULL
3161   tlsp          record details of TLS channel configuration here; must be non-NULL
3162   errstr        error string pointer
3163
3164 Returns:        TRUE for success with TLS session context set in connection context,
3165                 FALSE on error
3166 */
3167
3168 BOOL
3169 tls_client_start(client_conn_ctx * cctx, smtp_connect_args * conn_args,
3170   void * cookie, tls_support * tlsp, uschar ** errstr)
3171 {
3172 host_item * host = conn_args->host;             /* for msgs and option-tests */
3173 transport_instance * tb = conn_args->tblock;    /* always smtp or NULL */
3174 smtp_transport_options_block * ob = tb
3175   ? (smtp_transport_options_block *)tb->options_block
3176   : &smtp_transport_option_defaults;
3177 exim_openssl_client_tls_ctx * exim_client_ctx;
3178 uschar * expciphers;
3179 int rc;
3180 static uschar peerdn[256];
3181
3182 #ifndef DISABLE_OCSP
3183 BOOL request_ocsp = FALSE;
3184 BOOL require_ocsp = FALSE;
3185 #endif
3186
3187 rc = store_pool;
3188 store_pool = POOL_PERM;
3189 exim_client_ctx = store_get(sizeof(exim_openssl_client_tls_ctx), FALSE);
3190 exim_client_ctx->corked = NULL;
3191 store_pool = rc;
3192
3193 #ifdef SUPPORT_DANE
3194 tlsp->tlsa_usage = 0;
3195 #endif
3196
3197 #ifndef DISABLE_OCSP
3198   {
3199 # ifdef SUPPORT_DANE
3200   if (  conn_args->dane
3201      && ob->hosts_request_ocsp[0] == '*'
3202      && ob->hosts_request_ocsp[1] == '\0'
3203      )
3204     {
3205     /* Unchanged from default.  Use a safer one under DANE */
3206     request_ocsp = TRUE;
3207     ob->hosts_request_ocsp = US"${if or { {= {0}{$tls_out_tlsa_usage}} "
3208                                       "   {= {4}{$tls_out_tlsa_usage}} } "
3209                                  " {*}{}}";
3210     }
3211 # endif
3212
3213   if ((require_ocsp =
3214         verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK))
3215     request_ocsp = TRUE;
3216   else
3217 # ifdef SUPPORT_DANE
3218     if (!request_ocsp)
3219 # endif
3220       request_ocsp =
3221         verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
3222   }
3223 #endif
3224
3225 rc = tls_init(&exim_client_ctx->ctx, host, NULL,
3226     ob->tls_certificate, ob->tls_privatekey,
3227 #ifndef DISABLE_OCSP
3228     (void *)(long)request_ocsp,
3229 #endif
3230     cookie, &client_static_cbinfo, tlsp, errstr);
3231 if (rc != OK) return FALSE;
3232
3233 tlsp->certificate_verified = FALSE;
3234 client_verify_callback_called = FALSE;
3235
3236 expciphers = NULL;
3237 #ifdef SUPPORT_DANE
3238 if (conn_args->dane)
3239   {
3240   /* We fall back to tls_require_ciphers if unset, empty or forced failure, but
3241   other failures should be treated as problems. */
3242   if (ob->dane_require_tls_ciphers &&
3243       !expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
3244         &expciphers, errstr))
3245     return FALSE;
3246   if (expciphers && *expciphers == '\0')
3247     expciphers = NULL;
3248   }
3249 #endif
3250 if (!expciphers &&
3251     !expand_check(ob->tls_require_ciphers, US"tls_require_ciphers",
3252       &expciphers, errstr))
3253   return FALSE;
3254
3255 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
3256 are separated by underscores. So that I can use either form in my tests, and
3257 also for general convenience, we turn underscores into hyphens here. */
3258
3259 if (expciphers)
3260   {
3261   uschar *s = expciphers;
3262   while (*s) { if (*s == '_') *s = '-'; s++; }
3263   DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
3264   if (!SSL_CTX_set_cipher_list(exim_client_ctx->ctx, CS expciphers))
3265     {
3266     tls_error(US"SSL_CTX_set_cipher_list", host, NULL, errstr);
3267     return FALSE;
3268     }
3269   }
3270
3271 #ifdef SUPPORT_DANE
3272 if (conn_args->dane)
3273   {
3274   SSL_CTX_set_verify(exim_client_ctx->ctx,
3275     SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
3276     verify_callback_client_dane);
3277
3278   if (!DANESSL_library_init())
3279     {
3280     tls_error(US"library init", host, NULL, errstr);
3281     return FALSE;
3282     }
3283   if (DANESSL_CTX_init(exim_client_ctx->ctx) <= 0)
3284     {
3285     tls_error(US"context init", host, NULL, errstr);
3286     return FALSE;
3287     }
3288   }
3289 else
3290
3291 #endif
3292
3293   if (tls_client_basic_ctx_init(exim_client_ctx->ctx, host, ob,
3294         client_static_cbinfo, errstr) != OK)
3295     return FALSE;
3296
3297 #ifdef EXPERIMENTAL_TLS_RESUME
3298 tls_client_ctx_resume_prehandshake(exim_client_ctx, tlsp, ob, host);
3299 #endif
3300
3301
3302 if (!(exim_client_ctx->ssl = SSL_new(exim_client_ctx->ctx)))
3303   {
3304   tls_error(US"SSL_new", host, NULL, errstr);
3305   return FALSE;
3306   }
3307 SSL_set_session_id_context(exim_client_ctx->ssl, sid_ctx, Ustrlen(sid_ctx));
3308
3309 SSL_set_fd(exim_client_ctx->ssl, cctx->sock);
3310 SSL_set_connect_state(exim_client_ctx->ssl);
3311
3312 if (ob->tls_sni)
3313   {
3314   if (!expand_check(ob->tls_sni, US"tls_sni", &tlsp->sni, errstr))
3315     return FALSE;
3316   if (!tlsp->sni)
3317     {
3318     DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n");
3319     }
3320   else if (!Ustrlen(tlsp->sni))
3321     tlsp->sni = NULL;
3322   else
3323     {
3324 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
3325     DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tlsp->sni);
3326     SSL_set_tlsext_host_name(exim_client_ctx->ssl, tlsp->sni);
3327 #else
3328     log_write(0, LOG_MAIN, "SNI unusable with this OpenSSL library version; ignoring \"%s\"\n",
3329           tlsp->sni);
3330 #endif
3331     }
3332   }
3333
3334 #ifdef SUPPORT_DANE
3335 if (conn_args->dane)
3336   if (dane_tlsa_load(exim_client_ctx->ssl, host, &conn_args->tlsa_dnsa, errstr) != OK)
3337     return FALSE;
3338 #endif
3339
3340 #ifndef DISABLE_OCSP
3341 /* Request certificate status at connection-time.  If the server
3342 does OCSP stapling we will get the callback (set in tls_init()) */
3343 # ifdef SUPPORT_DANE
3344 if (request_ocsp)
3345   {
3346   const uschar * s;
3347   if (  ((s = ob->hosts_require_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
3348      || ((s = ob->hosts_request_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
3349      )
3350     {   /* Re-eval now $tls_out_tlsa_usage is populated.  If
3351         this means we avoid the OCSP request, we wasted the setup
3352         cost in tls_init(). */
3353     require_ocsp = verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
3354     request_ocsp = require_ocsp
3355       || verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
3356     }
3357   }
3358 # endif
3359
3360 if (request_ocsp)
3361   {
3362   SSL_set_tlsext_status_type(exim_client_ctx->ssl, TLSEXT_STATUSTYPE_ocsp);
3363   client_static_cbinfo->u_ocsp.client.verify_required = require_ocsp;
3364   tlsp->ocsp = OCSP_NOT_RESP;
3365   }
3366 #endif
3367
3368 #ifdef EXPERIMENTAL_TLS_RESUME
3369 if (!tls_client_ssl_resume_prehandshake(exim_client_ctx->ssl, tlsp, host,
3370       errstr))
3371   return FALSE;
3372 #endif
3373
3374 #ifndef DISABLE_EVENT
3375 client_static_cbinfo->event_action = tb ? tb->event_action : NULL;
3376 #endif
3377
3378 /* There doesn't seem to be a built-in timeout on connection. */
3379
3380 DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
3381 sigalrm_seen = FALSE;
3382 ALARM(ob->command_timeout);
3383 rc = SSL_connect(exim_client_ctx->ssl);
3384 ALARM_CLR(0);
3385
3386 #ifdef SUPPORT_DANE
3387 if (conn_args->dane)
3388   DANESSL_cleanup(exim_client_ctx->ssl);
3389 #endif
3390
3391 if (rc <= 0)
3392   {
3393   tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL, errstr);
3394   return FALSE;
3395   }
3396
3397 DEBUG(D_tls)
3398   {
3399   debug_printf("SSL_connect succeeded\n");
3400 #ifdef EXIM_HAVE_OPENSSL_KEYLOG
3401   {
3402   BIO * bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
3403   SSL_SESSION_print_keylog(bp, SSL_get_session(exim_client_ctx->ssl));
3404   BIO_free(bp);
3405   }
3406 #endif
3407   }
3408
3409 #ifdef EXPERIMENTAL_TLS_RESUME
3410 tls_client_resume_posthandshake(exim_client_ctx, tlsp);
3411 #endif
3412
3413 #ifdef SSL_get_extms_support
3414 tlsp->ext_master_secret = SSL_get_extms_support(exim_client_ctx->ssl) == 1;
3415 #endif
3416 peer_cert(exim_client_ctx->ssl, tlsp, peerdn, sizeof(peerdn));
3417
3418 tlsp->ver = tlsver_name(exim_client_ctx->ssl);
3419 tlsp->cipher = construct_cipher_name(exim_client_ctx->ssl, tlsp->ver, &tlsp->bits);
3420 tlsp->cipher_stdname = cipher_stdname_ssl(exim_client_ctx->ssl);
3421
3422 /* Record the certificate we presented */
3423   {
3424   X509 * crt = SSL_get_certificate(exim_client_ctx->ssl);
3425   tlsp->ourcert = crt ? X509_dup(crt) : NULL;
3426   }
3427
3428 /*XXX will this work with continued-TLS? */
3429 /* Channel-binding info for authenticators */
3430   {
3431   uschar c, * s;
3432   size_t len = SSL_get_finished(exim_client_ctx->ssl, &c, 0);
3433   int old_pool = store_pool;
3434
3435   SSL_get_finished(exim_client_ctx->ssl, s = store_get((int)len, TRUE), len);
3436   store_pool = POOL_PERM;
3437     tlsp->channelbinding = b64encode_taint(CUS s, (int)len, TRUE);
3438   store_pool = old_pool;
3439   DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage %p %p\n", tlsp->channelbinding, tlsp);
3440   }
3441
3442 tlsp->active.sock = cctx->sock;
3443 tlsp->active.tls_ctx = exim_client_ctx;
3444 cctx->tls_ctx = exim_client_ctx;
3445 return TRUE;
3446 }
3447
3448
3449
3450
3451
3452 static BOOL
3453 tls_refill(unsigned lim)
3454 {
3455 int error;
3456 int inbytes;
3457
3458 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", server_ssl,
3459   ssl_xfer_buffer, ssl_xfer_buffer_size);
3460
3461 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
3462 inbytes = SSL_read(server_ssl, CS ssl_xfer_buffer,
3463                   MIN(ssl_xfer_buffer_size, lim));
3464 error = SSL_get_error(server_ssl, inbytes);
3465 if (smtp_receive_timeout > 0) ALARM_CLR(0);
3466
3467 if (had_command_timeout)                /* set by signal handler */
3468   smtp_command_timeout_exit();          /* does not return */
3469 if (had_command_sigterm)
3470   smtp_command_sigterm_exit();
3471 if (had_data_timeout)
3472   smtp_data_timeout_exit();
3473 if (had_data_sigint)
3474   smtp_data_sigint_exit();
3475
3476 /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
3477 closed down, not that the socket itself has been closed down. Revert to
3478 non-SSL handling. */
3479
3480 switch(error)
3481   {
3482   case SSL_ERROR_NONE:
3483     break;
3484
3485   case SSL_ERROR_ZERO_RETURN:
3486     DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
3487
3488     if (SSL_get_shutdown(server_ssl) == SSL_RECEIVED_SHUTDOWN)
3489           SSL_shutdown(server_ssl);
3490
3491     tls_close(NULL, TLS_NO_SHUTDOWN);
3492     return FALSE;
3493
3494   /* Handle genuine errors */
3495   case SSL_ERROR_SSL:
3496     ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3497     log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
3498     ssl_xfer_error = TRUE;
3499     return FALSE;
3500
3501   default:
3502     DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
3503     DEBUG(D_tls) if (error == SSL_ERROR_SYSCALL)
3504       debug_printf(" - syscall %s\n", strerror(errno));
3505     ssl_xfer_error = TRUE;
3506     return FALSE;
3507   }
3508
3509 #ifndef DISABLE_DKIM
3510 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
3511 #endif
3512 ssl_xfer_buffer_hwm = inbytes;
3513 ssl_xfer_buffer_lwm = 0;
3514 return TRUE;
3515 }
3516
3517
3518 /*************************************************
3519 *            TLS version of getc                 *
3520 *************************************************/
3521
3522 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
3523 it refills the buffer via the SSL reading function.
3524
3525 Arguments:  lim         Maximum amount to read/buffer
3526 Returns:    the next character or EOF
3527
3528 Only used by the server-side TLS.
3529 */
3530
3531 int
3532 tls_getc(unsigned lim)
3533 {
3534 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
3535   if (!tls_refill(lim))
3536     return ssl_xfer_error ? EOF : smtp_getc(lim);
3537
3538 /* Something in the buffer; return next uschar */
3539
3540 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
3541 }
3542
3543 uschar *
3544 tls_getbuf(unsigned * len)
3545 {
3546 unsigned size;
3547 uschar * buf;
3548
3549 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
3550   if (!tls_refill(*len))
3551     {
3552     if (!ssl_xfer_error) return smtp_getbuf(len);
3553     *len = 0;
3554     return NULL;
3555     }
3556
3557 if ((size = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm) > *len)
3558   size = *len;
3559 buf = &ssl_xfer_buffer[ssl_xfer_buffer_lwm];
3560 ssl_xfer_buffer_lwm += size;
3561 *len = size;
3562 return buf;
3563 }
3564
3565
3566 void
3567 tls_get_cache()
3568 {
3569 #ifndef DISABLE_DKIM
3570 int n = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm;
3571 if (n > 0)
3572   dkim_exim_verify_feed(ssl_xfer_buffer+ssl_xfer_buffer_lwm, n);
3573 #endif
3574 }
3575
3576
3577 BOOL
3578 tls_could_read(void)
3579 {
3580 return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm || SSL_pending(server_ssl) > 0;
3581 }
3582
3583
3584 /*************************************************
3585 *          Read bytes from TLS channel           *
3586 *************************************************/
3587
3588 /*
3589 Arguments:
3590   ct_ctx    client context pointer, or NULL for the one global server context
3591   buff      buffer of data
3592   len       size of buffer
3593
3594 Returns:    the number of bytes read
3595             -1 after a failed read, including EOF
3596
3597 Only used by the client-side TLS.
3598 */
3599
3600 int
3601 tls_read(void * ct_ctx, uschar *buff, size_t len)
3602 {
3603 SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
3604 int inbytes;
3605 int error;
3606
3607 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
3608   buff, (unsigned int)len);
3609
3610 inbytes = SSL_read(ssl, CS buff, len);
3611 error = SSL_get_error(ssl, inbytes);
3612
3613 if (error == SSL_ERROR_ZERO_RETURN)
3614   {
3615   DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
3616   return -1;
3617   }
3618 else if (error != SSL_ERROR_NONE)
3619   return -1;
3620
3621 return inbytes;
3622 }
3623
3624
3625
3626
3627
3628 /*************************************************
3629 *         Write bytes down TLS channel           *
3630 *************************************************/
3631
3632 /*
3633 Arguments:
3634   ct_ctx    client context pointer, or NULL for the one global server context
3635   buff      buffer of data
3636   len       number of bytes
3637   more      further data expected soon
3638
3639 Returns:    the number of bytes after a successful write,
3640             -1 after a failed write
3641
3642 Used by both server-side and client-side TLS.  Calling with len zero and more unset
3643 will flush buffered writes; buff can be null for this case.
3644 */
3645
3646 int
3647 tls_write(void * ct_ctx, const uschar * buff, size_t len, BOOL more)
3648 {
3649 size_t olen = len;
3650 int outbytes, error;
3651 SSL * ssl = ct_ctx
3652   ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
3653 static gstring * server_corked = NULL;
3654 gstring ** corkedp = ct_ctx
3655   ? &((exim_openssl_client_tls_ctx *)ct_ctx)->corked : &server_corked;
3656 gstring * corked = *corkedp;
3657
3658 DEBUG(D_tls) debug_printf("%s(%p, %lu%s)\n", __FUNCTION__,
3659   buff, (unsigned long)len, more ? ", more" : "");
3660
3661 /* Lacking a CORK or MSG_MORE facility (such as GnuTLS has) we copy data when
3662 "more" is notified.  This hack is only ok if small amounts are involved AND only
3663 one stream does it, in one context (i.e. no store reset).  Currently it is used
3664 for the responses to the received SMTP MAIL , RCPT, DATA sequence, only.
3665 We support callouts done by the server process by using a separate client
3666 context for the stashed information. */
3667 /* + if PIPE_COMMAND, banner & ehlo-resp for smmtp-on-connect. Suspect there's
3668 a store reset there, so use POOL_PERM. */
3669 /* + if CHUNKING, cmds EHLO,MAIL,RCPT(s),BDAT */
3670
3671 if ((more || corked))
3672   {
3673   if (!len) buff = US &error;   /* dummy just so that string_catn is ok */
3674
3675 #ifndef DISABLE_PIPE_CONNECT
3676   int save_pool = store_pool;
3677   store_pool = POOL_PERM;
3678 #endif
3679
3680   corked = string_catn(corked, buff, len);
3681
3682 #ifndef DISABLE_PIPE_CONNECT
3683   store_pool = save_pool;
3684 #endif
3685
3686   if (more)
3687     {
3688     *corkedp = corked;
3689     return len;
3690     }
3691   buff = CUS corked->s;
3692   len = corked->ptr;
3693   *corkedp = NULL;
3694   }
3695
3696 for (int left = len; left > 0;)
3697   {
3698   DEBUG(D_tls) debug_printf("SSL_write(%p, %p, %d)\n", ssl, buff, left);
3699   outbytes = SSL_write(ssl, CS buff, left);
3700   error = SSL_get_error(ssl, outbytes);
3701   DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
3702   switch (error)
3703     {
3704     case SSL_ERROR_NONE:        /* the usual case */
3705       left -= outbytes;
3706       buff += outbytes;
3707       break;
3708
3709     case SSL_ERROR_SSL:
3710       ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3711       log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
3712       return -1;
3713
3714     case SSL_ERROR_ZERO_RETURN:
3715       log_write(0, LOG_MAIN, "SSL channel closed on write");
3716       return -1;
3717
3718     case SSL_ERROR_SYSCALL:
3719       log_write(0, LOG_MAIN, "SSL_write: (from %s) syscall: %s",
3720         sender_fullhost ? sender_fullhost : US"<unknown>",
3721         strerror(errno));
3722       return -1;
3723
3724     default:
3725       log_write(0, LOG_MAIN, "SSL_write error %d", error);
3726       return -1;
3727     }
3728   }
3729 return olen;
3730 }
3731
3732
3733
3734 /*************************************************
3735 *         Close down a TLS session               *
3736 *************************************************/
3737
3738 /* This is also called from within a delivery subprocess forked from the
3739 daemon, to shut down the TLS library, without actually doing a shutdown (which
3740 would tamper with the SSL session in the parent process).
3741
3742 Arguments:
3743   ct_ctx        client TLS context pointer, or NULL for the one global server context
3744   shutdown      1 if TLS close-alert is to be sent,
3745                 2 if also response to be waited for
3746
3747 Returns:     nothing
3748
3749 Used by both server-side and client-side TLS.
3750 */
3751
3752 void
3753 tls_close(void * ct_ctx, int shutdown)
3754 {
3755 exim_openssl_client_tls_ctx * o_ctx = ct_ctx;
3756 SSL_CTX **ctxp = o_ctx ? &o_ctx->ctx : &server_ctx;
3757 SSL **sslp =     o_ctx ? &o_ctx->ssl : &server_ssl;
3758 int *fdp = o_ctx ? &tls_out.active.sock : &tls_in.active.sock;
3759
3760 if (*fdp < 0) return;  /* TLS was not active */
3761
3762 if (shutdown)
3763   {
3764   int rc;
3765   DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
3766     shutdown > 1 ? " (with response-wait)" : "");
3767
3768   if (  (rc = SSL_shutdown(*sslp)) == 0 /* send "close notify" alert */
3769      && shutdown > 1)
3770     {
3771     ALARM(2);
3772     rc = SSL_shutdown(*sslp);           /* wait for response */
3773     ALARM_CLR(0);
3774     }
3775
3776   if (rc < 0) DEBUG(D_tls)
3777     {
3778     ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3779     debug_printf("SSL_shutdown: %s\n", ssl_errstring);
3780     }
3781   }
3782
3783 if (!o_ctx)             /* server side */
3784   {
3785 #ifndef DISABLE_OCSP
3786   sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
3787   server_static_cbinfo->verify_stack = NULL;
3788 #endif
3789
3790   receive_getc =        smtp_getc;
3791   receive_getbuf =      smtp_getbuf;
3792   receive_get_cache =   smtp_get_cache;
3793   receive_ungetc =      smtp_ungetc;
3794   receive_feof =        smtp_feof;
3795   receive_ferror =      smtp_ferror;
3796   receive_smtp_buffered = smtp_buffered;
3797   tls_in.active.tls_ctx = NULL;
3798   tls_in.sni = NULL;
3799   /* Leave bits, peercert, cipher, peerdn, certificate_verified set, for logging */
3800   }
3801
3802 SSL_CTX_free(*ctxp);
3803 SSL_free(*sslp);
3804 *ctxp = NULL;
3805 *sslp = NULL;
3806 *fdp = -1;
3807 }
3808
3809
3810
3811
3812 /*************************************************
3813 *  Let tls_require_ciphers be checked at startup *
3814 *************************************************/
3815
3816 /* The tls_require_ciphers option, if set, must be something which the
3817 library can parse.
3818
3819 Returns:     NULL on success, or error message
3820 */
3821
3822 uschar *
3823 tls_validate_require_cipher(void)
3824 {
3825 SSL_CTX *ctx;
3826 uschar *s, *expciphers, *err;
3827
3828 tls_openssl_init();
3829
3830 if (!(tls_require_ciphers && *tls_require_ciphers))
3831   return NULL;
3832
3833 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3834                   &err))
3835   return US"failed to expand tls_require_ciphers";
3836
3837 if (!(expciphers && *expciphers))
3838   return NULL;
3839
3840 /* normalisation ripped from above */
3841 s = expciphers;
3842 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
3843
3844 err = NULL;
3845
3846 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
3847 if (!(ctx = SSL_CTX_new(TLS_server_method())))
3848 #else
3849 if (!(ctx = SSL_CTX_new(SSLv23_server_method())))
3850 #endif
3851   {
3852   ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3853   return string_sprintf("SSL_CTX_new() failed: %s", ssl_errstring);
3854   }
3855
3856 DEBUG(D_tls)
3857   debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3858
3859 if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
3860   {
3861   ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3862   err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed: %s",
3863                       expciphers, ssl_errstring);
3864   }
3865
3866 SSL_CTX_free(ctx);
3867
3868 return err;
3869 }
3870
3871
3872
3873
3874 /*************************************************
3875 *         Report the library versions.           *
3876 *************************************************/
3877
3878 /* There have historically been some issues with binary compatibility in
3879 OpenSSL libraries; if Exim (like many other applications) is built against
3880 one version of OpenSSL but the run-time linker picks up another version,
3881 it can result in serious failures, including crashing with a SIGSEGV.  So
3882 report the version found by the compiler and the run-time version.
3883
3884 Note: some OS vendors backport security fixes without changing the version
3885 number/string, and the version date remains unchanged.  The _build_ date
3886 will change, so we can more usefully assist with version diagnosis by also
3887 reporting the build date.
3888
3889 Arguments:   a FILE* to print the results to
3890 Returns:     nothing
3891 */
3892
3893 void
3894 tls_version_report(FILE *f)
3895 {
3896 fprintf(f, "Library version: OpenSSL: Compile: %s\n"
3897            "                          Runtime: %s\n"
3898            "                                 : %s\n",
3899            OPENSSL_VERSION_TEXT,
3900            SSLeay_version(SSLEAY_VERSION),
3901            SSLeay_version(SSLEAY_BUILT_ON));
3902 /* third line is 38 characters for the %s and the line is 73 chars long;
3903 the OpenSSL output includes a "built on: " prefix already. */
3904 }
3905
3906
3907
3908
3909 /*************************************************
3910 *            Random number generation            *
3911 *************************************************/
3912
3913 /* Pseudo-random number generation.  The result is not expected to be
3914 cryptographically strong but not so weak that someone will shoot themselves
3915 in the foot using it as a nonce in input in some email header scheme or
3916 whatever weirdness they'll twist this into.  The result should handle fork()
3917 and avoid repeating sequences.  OpenSSL handles that for us.
3918
3919 Arguments:
3920   max       range maximum
3921 Returns     a random number in range [0, max-1]
3922 */
3923
3924 int
3925 vaguely_random_number(int max)
3926 {
3927 unsigned int r;
3928 int i, needed_len;
3929 static pid_t pidlast = 0;
3930 pid_t pidnow;
3931 uschar smallbuf[sizeof(r)];
3932
3933 if (max <= 1)
3934   return 0;
3935
3936 pidnow = getpid();
3937 if (pidnow != pidlast)
3938   {
3939   /* Although OpenSSL documents that "OpenSSL makes sure that the PRNG state
3940   is unique for each thread", this doesn't apparently apply across processes,
3941   so our own warning from vaguely_random_number_fallback() applies here too.
3942   Fix per PostgreSQL. */
3943   if (pidlast != 0)
3944     RAND_cleanup();
3945   pidlast = pidnow;
3946   }
3947
3948 /* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
3949 if (!RAND_status())
3950   {
3951   randstuff r;
3952   gettimeofday(&r.tv, NULL);
3953   r.p = getpid();
3954
3955   RAND_seed(US (&r), sizeof(r));
3956   }
3957 /* We're after pseudo-random, not random; if we still don't have enough data
3958 in the internal PRNG then our options are limited.  We could sleep and hope
3959 for entropy to come along (prayer technique) but if the system is so depleted
3960 in the first place then something is likely to just keep taking it.  Instead,
3961 we'll just take whatever little bit of pseudo-random we can still manage to
3962 get. */
3963
3964 needed_len = sizeof(r);
3965 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
3966 asked for a number less than 10. */
3967 for (r = max, i = 0; r; ++i)
3968   r >>= 1;
3969 i = (i + 7) / 8;
3970 if (i < needed_len)
3971   needed_len = i;
3972
3973 #ifdef EXIM_HAVE_RAND_PSEUDO
3974 /* We do not care if crypto-strong */
3975 i = RAND_pseudo_bytes(smallbuf, needed_len);
3976 #else
3977 i = RAND_bytes(smallbuf, needed_len);
3978 #endif
3979
3980 if (i < 0)
3981   {
3982   DEBUG(D_all)
3983     debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
3984   return vaguely_random_number_fallback(max);
3985   }
3986
3987 r = 0;
3988 for (uschar * p = smallbuf; needed_len; --needed_len, ++p)
3989   r = 256 * r + *p;
3990
3991 /* We don't particularly care about weighted results; if someone wants
3992 smooth distribution and cares enough then they should submit a patch then. */
3993 return r % max;
3994 }
3995
3996
3997
3998
3999 /*************************************************
4000 *        OpenSSL option parse                    *
4001 *************************************************/
4002
4003 /* Parse one option for tls_openssl_options_parse below
4004
4005 Arguments:
4006   name    one option name
4007   value   place to store a value for it
4008 Returns   success or failure in parsing
4009 */
4010
4011
4012
4013 static BOOL
4014 tls_openssl_one_option_parse(uschar *name, long *value)
4015 {
4016 int first = 0;
4017 int last = exim_openssl_options_size;
4018 while (last > first)
4019   {
4020   int middle = (first + last)/2;
4021   int c = Ustrcmp(name, exim_openssl_options[middle].name);
4022   if (c == 0)
4023     {
4024     *value = exim_openssl_options[middle].value;
4025     return TRUE;
4026     }
4027   else if (c > 0)
4028     first = middle + 1;
4029   else
4030     last = middle;
4031   }
4032 return FALSE;
4033 }
4034
4035
4036
4037
4038 /*************************************************
4039 *        OpenSSL option parsing logic            *
4040 *************************************************/
4041
4042 /* OpenSSL has a number of compatibility options which an administrator might
4043 reasonably wish to set.  Interpret a list similarly to decode_bits(), so that
4044 we look like log_selector.
4045
4046 Arguments:
4047   option_spec  the administrator-supplied string of options
4048   results      ptr to long storage for the options bitmap
4049 Returns        success or failure
4050 */
4051
4052 BOOL
4053 tls_openssl_options_parse(uschar *option_spec, long *results)
4054 {
4055 long result, item;
4056 uschar * exp, * end;
4057 uschar keep_c;
4058 BOOL adding, item_parsed;
4059
4060 /* Server: send no (<= TLS1.2) session tickets */
4061 result = SSL_OP_NO_TICKET;
4062
4063 /* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
4064 from default because it increases BEAST susceptibility. */
4065 #ifdef SSL_OP_NO_SSLv2
4066 result |= SSL_OP_NO_SSLv2;
4067 #endif
4068 #ifdef SSL_OP_NO_SSLv3
4069 result |= SSL_OP_NO_SSLv3;
4070 #endif
4071 #ifdef SSL_OP_SINGLE_DH_USE
4072 result |= SSL_OP_SINGLE_DH_USE;
4073 #endif
4074 #ifdef SSL_OP_NO_RENEGOTIATION
4075 result |= SSL_OP_NO_RENEGOTIATION;
4076 #endif
4077
4078 if (!option_spec)
4079   {
4080   *results = result;
4081   return TRUE;
4082   }
4083
4084 if (!expand_check(option_spec, US"openssl_options", &exp, &end))
4085   return FALSE;
4086
4087 for (uschar * s = exp; *s; /**/)
4088   {
4089   while (isspace(*s)) ++s;
4090   if (*s == '\0')
4091     break;
4092   if (*s != '+' && *s != '-')
4093     {
4094     DEBUG(D_tls) debug_printf("malformed openssl option setting: "
4095         "+ or - expected but found \"%s\"\n", s);
4096     return FALSE;
4097     }
4098   adding = *s++ == '+';
4099   for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
4100   keep_c = *end;
4101   *end = '\0';
4102   item_parsed = tls_openssl_one_option_parse(s, &item);
4103   *end = keep_c;
4104   if (!item_parsed)
4105     {
4106     DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
4107     return FALSE;
4108     }
4109   DEBUG(D_tls) debug_printf("openssl option, %s %08lx: %08lx (%s)\n",
4110       adding ? "adding to    " : "removing from", result, item, s);
4111   if (adding)
4112     result |= item;
4113   else
4114     result &= ~item;
4115   s = end;
4116   }
4117
4118 *results = result;
4119 return TRUE;
4120 }
4121
4122 #endif  /*!MACRO_PREDEF*/
4123 /* vi: aw ai sw=2
4124 */
4125 /* End of tls-openssl.c */