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