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