BUGFIX: forced-fail smtp option tls_sni would dereference NULL
[exim.git] / src / src / tls-openssl.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2012 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* This module provides the TLS (aka SSL) support for Exim using the OpenSSL
9 library. It is #included into the tls.c file when that library is used. The
10 code herein is based on a patch that was originally contributed by Steve
11 Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
12
13 No cryptographic code is included in Exim. All this module does is to call
14 functions from the OpenSSL library. */
15
16
17 /* Heading stuff */
18
19 #include <openssl/lhash.h>
20 #include <openssl/ssl.h>
21 #include <openssl/err.h>
22 #include <openssl/rand.h>
23 #ifdef EXPERIMENTAL_OCSP
24 #include <openssl/ocsp.h>
25 #endif
26
27 #ifdef EXPERIMENTAL_OCSP
28 #define EXIM_OCSP_SKEW_SECONDS (300L)
29 #define EXIM_OCSP_MAX_AGE (-1L)
30 #endif
31
32 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
33 #define EXIM_HAVE_OPENSSL_TLSEXT
34 #endif
35
36 /* Structure for collecting random data for seeding. */
37
38 typedef struct randstuff {
39   struct timeval tv;
40   pid_t          p;
41 } randstuff;
42
43 /* Local static variables */
44
45 static BOOL verify_callback_called = FALSE;
46 static const uschar *sid_ctx = US"exim";
47
48 static SSL_CTX *ctx = NULL;
49 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
50 static SSL_CTX *ctx_sni = NULL;
51 #endif
52 static SSL *ssl = NULL;
53
54 static char ssl_errstring[256];
55
56 static int  ssl_session_timeout = 200;
57 static BOOL verify_optional = FALSE;
58
59 static BOOL    reexpand_tls_files_for_sni = FALSE;
60
61
62 typedef struct tls_ext_ctx_cb {
63   uschar *certificate;
64   uschar *privatekey;
65 #ifdef EXPERIMENTAL_OCSP
66   uschar *ocsp_file;
67   uschar *ocsp_file_expanded;
68   OCSP_RESPONSE *ocsp_response;
69 #endif
70   uschar *dhparam;
71   /* these are cached from first expand */
72   uschar *server_cipher_list;
73   /* only passed down to tls_error: */
74   host_item *host;
75 } tls_ext_ctx_cb;
76
77 /* should figure out a cleanup of API to handle state preserved per
78 implementation, for various reasons, which can be void * in the APIs.
79 For now, we hack around it. */
80 tls_ext_ctx_cb *static_cbinfo = NULL;
81
82 static int
83 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional);
84
85 /* Callbacks */
86 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
87 static int tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg);
88 #endif
89 #ifdef EXPERIMENTAL_OCSP
90 static int tls_stapling_cb(SSL *s, void *arg);
91 #endif
92
93
94 /*************************************************
95 *               Handle TLS error                 *
96 *************************************************/
97
98 /* Called from lots of places when errors occur before actually starting to do
99 the TLS handshake, that is, while the session is still in clear. Always returns
100 DEFER for a server and FAIL for a client so that most calls can use "return
101 tls_error(...)" to do this processing and then give an appropriate return. A
102 single function is used for both server and client, because it is called from
103 some shared functions.
104
105 Argument:
106   prefix    text to include in the logged error
107   host      NULL if setting up a server;
108             the connected host if setting up a client
109   msg       error message or NULL if we should ask OpenSSL
110
111 Returns:    OK/DEFER/FAIL
112 */
113
114 static int
115 tls_error(uschar *prefix, host_item *host, uschar *msg)
116 {
117 if (msg == NULL)
118   {
119   ERR_error_string(ERR_get_error(), ssl_errstring);
120   msg = (uschar *)ssl_errstring;
121   }
122
123 if (host == NULL)
124   {
125   uschar *conn_info = smtp_get_connection_info();
126   if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
127     conn_info += 5;
128   log_write(0, LOG_MAIN, "TLS error on %s (%s): %s",
129     conn_info, prefix, msg);
130   return DEFER;
131   }
132 else
133   {
134   log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s): %s",
135     host->name, host->address, prefix, msg);
136   return FAIL;
137   }
138 }
139
140
141
142 /*************************************************
143 *        Callback to generate RSA key            *
144 *************************************************/
145
146 /*
147 Arguments:
148   s          SSL connection
149   export     not used
150   keylength  keylength
151
152 Returns:     pointer to generated key
153 */
154
155 static RSA *
156 rsa_callback(SSL *s, int export, int keylength)
157 {
158 RSA *rsa_key;
159 export = export;     /* Shut picky compilers up */
160 DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
161 rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL);
162 if (rsa_key == NULL)
163   {
164   ERR_error_string(ERR_get_error(), ssl_errstring);
165   log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
166     ssl_errstring);
167   return NULL;
168   }
169 return rsa_key;
170 }
171
172
173
174
175 /*************************************************
176 *        Callback for verification               *
177 *************************************************/
178
179 /* The SSL library does certificate verification if set up to do so. This
180 callback has the current yes/no state is in "state". If verification succeeded,
181 we set up the tls_peerdn string. If verification failed, what happens depends
182 on whether the client is required to present a verifiable certificate or not.
183
184 If verification is optional, we change the state to yes, but still log the
185 verification error. For some reason (it really would help to have proper
186 documentation of OpenSSL), this callback function then gets called again, this
187 time with state = 1. In fact, that's useful, because we can set up the peerdn
188 value, but we must take care not to set the private verified flag on the second
189 time through.
190
191 Note: this function is not called if the client fails to present a certificate
192 when asked. We get here only if a certificate has been received. Handling of
193 optional verification for this case is done when requesting SSL to verify, by
194 setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
195
196 Arguments:
197   state      current yes/no state as 1/0
198   x509ctx    certificate information.
199
200 Returns:     1 if verified, 0 if not
201 */
202
203 static int
204 verify_callback(int state, X509_STORE_CTX *x509ctx)
205 {
206 static uschar txt[256];
207
208 X509_NAME_oneline(X509_get_subject_name(x509ctx->current_cert),
209   CS txt, sizeof(txt));
210
211 if (state == 0)
212   {
213   log_write(0, LOG_MAIN, "SSL verify error: depth=%d error=%s cert=%s",
214     x509ctx->error_depth,
215     X509_verify_cert_error_string(x509ctx->error),
216     txt);
217   tls_certificate_verified = FALSE;
218   verify_callback_called = TRUE;
219   if (!verify_optional) return 0;    /* reject */
220   DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
221     "tls_try_verify_hosts)\n");
222   return 1;                          /* accept */
223   }
224
225 if (x509ctx->error_depth != 0)
226   {
227   DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d cert=%s\n",
228      x509ctx->error_depth, txt);
229   }
230 else
231   {
232   DEBUG(D_tls) debug_printf("SSL%s peer: %s\n",
233     verify_callback_called? "" : " authenticated", txt);
234   tls_peerdn = txt;
235   }
236
237 if (!verify_callback_called) tls_certificate_verified = TRUE;
238 verify_callback_called = TRUE;
239
240 return 1;   /* accept */
241 }
242
243
244
245 /*************************************************
246 *           Information callback                 *
247 *************************************************/
248
249 /* The SSL library functions call this from time to time to indicate what they
250 are doing. We copy the string to the debugging output when TLS debugging has
251 been requested.
252
253 Arguments:
254   s         the SSL connection
255   where
256   ret
257
258 Returns:    nothing
259 */
260
261 static void
262 info_callback(SSL *s, int where, int ret)
263 {
264 where = where;
265 ret = ret;
266 DEBUG(D_tls) debug_printf("SSL info: %s\n", SSL_state_string_long(s));
267 }
268
269
270
271 /*************************************************
272 *                Initialize for DH               *
273 *************************************************/
274
275 /* If dhparam is set, expand it, and load up the parameters for DH encryption.
276
277 Arguments:
278   dhparam   DH parameter file or fixed parameter identity string
279   host      connected host, if client; NULL if server
280
281 Returns:    TRUE if OK (nothing to set up, or setup worked)
282 */
283
284 static BOOL
285 init_dh(SSL_CTX *sctx, uschar *dhparam, host_item *host)
286 {
287 BIO *bio;
288 DH *dh;
289 uschar *dhexpanded;
290 const char *pem;
291
292 if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded))
293   return FALSE;
294
295 if (dhexpanded == NULL || *dhexpanded == '\0')
296   {
297   bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
298   }
299 else if (dhexpanded[0] == '/')
300   {
301   bio = BIO_new_file(CS dhexpanded, "r");
302   if (bio == NULL)
303     {
304     tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
305           host, US strerror(errno));
306     return FALSE;
307     }
308   }
309 else
310   {
311   if (Ustrcmp(dhexpanded, "none") == 0)
312     {
313     DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
314     return TRUE;
315     }
316
317   pem = std_dh_prime_named(dhexpanded);
318   if (!pem)
319     {
320     tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
321         host, US strerror(errno));
322     return FALSE;
323     }
324   bio = BIO_new_mem_buf(CS pem, -1);
325   }
326
327 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
328 if (dh == NULL)
329   {
330   BIO_free(bio);
331   tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
332       host, NULL);
333   return FALSE;
334   }
335
336 /* Even if it is larger, we silently return success rather than cause things
337  * to fail out, so that a too-large DH will not knock out all TLS; it's a
338  * debatable choice. */
339 if ((8*DH_size(dh)) > tls_dh_max_bits)
340   {
341   DEBUG(D_tls)
342     debug_printf("dhparams file %d bits, is > tls_dh_max_bits limit of %d",
343         8*DH_size(dh), tls_dh_max_bits);
344   }
345 else
346   {
347   SSL_CTX_set_tmp_dh(sctx, dh);
348   DEBUG(D_tls)
349     debug_printf("Diffie-Hellman initialized from %s with %d-bit prime\n",
350       dhexpanded ? dhexpanded : US"default", 8*DH_size(dh));
351   }
352
353 DH_free(dh);
354 BIO_free(bio);
355
356 return TRUE;
357 }
358
359
360
361
362 #ifdef EXPERIMENTAL_OCSP
363 /*************************************************
364 *       Load OCSP information into state         *
365 *************************************************/
366
367 /* Called to load the OCSP response from the given file into memory, once
368 caller has determined this is needed.  Checks validity.  Debugs a message
369 if invalid.
370
371 ASSUMES: single response, for single cert.
372
373 Arguments:
374   sctx            the SSL_CTX* to update
375   cbinfo          various parts of session state
376   expanded        the filename putatively holding an OCSP response
377
378 */
379
380 static void
381 ocsp_load_response(SSL_CTX *sctx,
382     tls_ext_ctx_cb *cbinfo,
383     const uschar *expanded)
384 {
385 BIO *bio;
386 OCSP_RESPONSE *resp;
387 OCSP_BASICRESP *basic_response;
388 OCSP_SINGLERESP *single_response;
389 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
390 X509_STORE *store;
391 unsigned long verify_flags;
392 int status, reason, i;
393
394 cbinfo->ocsp_file_expanded = string_copy(expanded);
395 if (cbinfo->ocsp_response)
396   {
397   OCSP_RESPONSE_free(cbinfo->ocsp_response);
398   cbinfo->ocsp_response = NULL;
399   }
400
401 bio = BIO_new_file(CS cbinfo->ocsp_file_expanded, "rb");
402 if (!bio)
403   {
404   DEBUG(D_tls) debug_printf("Failed to open OCSP response file \"%s\"\n",
405       cbinfo->ocsp_file_expanded);
406   return;
407   }
408
409 resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
410 BIO_free(bio);
411 if (!resp)
412   {
413   DEBUG(D_tls) debug_printf("Error reading OCSP response.\n");
414   return;
415   }
416
417 status = OCSP_response_status(resp);
418 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL)
419   {
420   DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n",
421       OCSP_response_status_str(status), status);
422   return;
423   }
424
425 basic_response = OCSP_response_get1_basic(resp);
426 if (!basic_response)
427   {
428   DEBUG(D_tls)
429     debug_printf("OCSP response parse error: unable to extract basic response.\n");
430   return;
431   }
432
433 store = SSL_CTX_get_cert_store(sctx);
434 verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */
435
436 /* May need to expose ability to adjust those flags?
437 OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
438 OCSP_TRUSTOTHER OCSP_NOINTERN */
439
440 i = OCSP_basic_verify(basic_response, NULL, store, verify_flags);
441 if (i <= 0)
442   {
443   DEBUG(D_tls) {
444     ERR_error_string(ERR_get_error(), ssl_errstring);
445     debug_printf("OCSP response verify failure: %s\n", US ssl_errstring);
446   }
447   return;
448   }
449
450 /* Here's the simplifying assumption: there's only one response, for the
451 one certificate we use, and nothing for anything else in a chain.  If this
452 proves false, we need to extract a cert id from our issued cert
453 (tls_certificate) and use that for OCSP_resp_find_status() (which finds the
454 right cert in the stack and then calls OCSP_single_get0_status()).
455
456 I'm hoping to avoid reworking a bunch more of how we handle state here. */
457 single_response = OCSP_resp_get0(basic_response, 0);
458 if (!single_response)
459   {
460   DEBUG(D_tls)
461     debug_printf("Unable to get first response from OCSP basic response.\n");
462   return;
463   }
464
465 status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
466 /* how does this status differ from the one above? */
467 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL)
468   {
469   DEBUG(D_tls) debug_printf("OCSP response not valid (take 2): %s (%d)\n",
470       OCSP_response_status_str(status), status);
471   return;
472   }
473
474 if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
475   {
476   DEBUG(D_tls) debug_printf("OCSP status invalid times.\n");
477   return;
478   }
479
480 cbinfo->ocsp_response = resp;
481 }
482 #endif
483
484
485
486
487 /*************************************************
488 *        Expand key and cert file specs          *
489 *************************************************/
490
491 /* Called once during tls_init and possibly againt during TLS setup, for a
492 new context, if Server Name Indication was used and tls_sni was seen in
493 the certificate string.
494
495 Arguments:
496   sctx            the SSL_CTX* to update
497   cbinfo          various parts of session state
498
499 Returns:          OK/DEFER/FAIL
500 */
501
502 static int
503 tls_expand_session_files(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo)
504 {
505 uschar *expanded;
506
507 if (cbinfo->certificate == NULL)
508   return OK;
509
510 if (Ustrstr(cbinfo->certificate, US"tls_sni"))
511   reexpand_tls_files_for_sni = TRUE;
512
513 if (!expand_check(cbinfo->certificate, US"tls_certificate", &expanded))
514   return DEFER;
515
516 if (expanded != NULL)
517   {
518   DEBUG(D_tls) debug_printf("tls_certificate file %s\n", expanded);
519   if (!SSL_CTX_use_certificate_chain_file(sctx, CS expanded))
520     return tls_error(string_sprintf(
521       "SSL_CTX_use_certificate_chain_file file=%s", expanded),
522         cbinfo->host, NULL);
523   }
524
525 if (cbinfo->privatekey != NULL &&
526     !expand_check(cbinfo->privatekey, US"tls_privatekey", &expanded))
527   return DEFER;
528
529 /* If expansion was forced to fail, key_expanded will be NULL. If the result
530 of the expansion is an empty string, ignore it also, and assume the private
531 key is in the same file as the certificate. */
532
533 if (expanded != NULL && *expanded != 0)
534   {
535   DEBUG(D_tls) debug_printf("tls_privatekey file %s\n", expanded);
536   if (!SSL_CTX_use_PrivateKey_file(sctx, CS expanded, SSL_FILETYPE_PEM))
537     return tls_error(string_sprintf(
538       "SSL_CTX_use_PrivateKey_file file=%s", expanded), cbinfo->host, NULL);
539   }
540
541 #ifdef EXPERIMENTAL_OCSP
542 if (cbinfo->ocsp_file != NULL)
543   {
544   if (!expand_check(cbinfo->ocsp_file, US"tls_ocsp_file", &expanded))
545     return DEFER;
546
547   if (expanded != NULL && *expanded != 0)
548     {
549     DEBUG(D_tls) debug_printf("tls_ocsp_file %s\n", expanded);
550     if (cbinfo->ocsp_file_expanded &&
551         (Ustrcmp(expanded, cbinfo->ocsp_file_expanded) == 0))
552       {
553       DEBUG(D_tls)
554         debug_printf("tls_ocsp_file value unchanged, using existing values.\n");
555       } else {
556         ocsp_load_response(sctx, cbinfo, expanded);
557       }
558     }
559   }
560 #endif
561
562 return OK;
563 }
564
565
566
567
568 /*************************************************
569 *            Callback to handle SNI              *
570 *************************************************/
571
572 /* Called when acting as server during the TLS session setup if a Server Name
573 Indication extension was sent by the client.
574
575 API documentation is OpenSSL s_server.c implementation.
576
577 Arguments:
578   s               SSL* of the current session
579   ad              unknown (part of OpenSSL API) (unused)
580   arg             Callback of "our" registered data
581
582 Returns:          SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
583 */
584
585 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
586 static int
587 tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg)
588 {
589 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
590 tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
591 int rc;
592 int old_pool = store_pool;
593
594 if (!servername)
595   return SSL_TLSEXT_ERR_OK;
596
597 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
598     reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
599
600 /* Make the extension value available for expansion */
601 store_pool = POOL_PERM;
602 tls_sni = string_copy(US servername);
603 store_pool = old_pool;
604
605 if (!reexpand_tls_files_for_sni)
606   return SSL_TLSEXT_ERR_OK;
607
608 /* Can't find an SSL_CTX_clone() or equivalent, so we do it manually;
609 not confident that memcpy wouldn't break some internal reference counting.
610 Especially since there's a references struct member, which would be off. */
611
612 ctx_sni = SSL_CTX_new(SSLv23_server_method());
613 if (!ctx_sni)
614   {
615   ERR_error_string(ERR_get_error(), ssl_errstring);
616   DEBUG(D_tls) debug_printf("SSL_CTX_new() failed: %s\n", ssl_errstring);
617   return SSL_TLSEXT_ERR_NOACK;
618   }
619
620 /* Not sure how many of these are actually needed, since SSL object
621 already exists.  Might even need this selfsame callback, for reneg? */
622
623 SSL_CTX_set_info_callback(ctx_sni, SSL_CTX_get_info_callback(ctx));
624 SSL_CTX_set_mode(ctx_sni, SSL_CTX_get_mode(ctx));
625 SSL_CTX_set_options(ctx_sni, SSL_CTX_get_options(ctx));
626 SSL_CTX_set_timeout(ctx_sni, SSL_CTX_get_timeout(ctx));
627 SSL_CTX_set_tlsext_servername_callback(ctx_sni, tls_servername_cb);
628 SSL_CTX_set_tlsext_servername_arg(ctx_sni, cbinfo);
629 if (cbinfo->server_cipher_list)
630   SSL_CTX_set_cipher_list(ctx_sni, CS cbinfo->server_cipher_list);
631 #ifdef EXPERIMENTAL_OCSP
632 if (cbinfo->ocsp_file)
633   {
634   SSL_CTX_set_tlsext_status_cb(ctx_sni, tls_stapling_cb);
635   SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
636   }
637 #endif
638
639 rc = setup_certs(ctx_sni, tls_verify_certificates, tls_crl, NULL, FALSE);
640 if (rc != OK) return SSL_TLSEXT_ERR_NOACK;
641
642 /* do this after setup_certs, because this can require the certs for verifying
643 OCSP information. */
644 rc = tls_expand_session_files(ctx_sni, cbinfo);
645 if (rc != OK) return SSL_TLSEXT_ERR_NOACK;
646
647 rc = init_dh(ctx_sni, cbinfo->dhparam, NULL);
648 if (rc != OK) return SSL_TLSEXT_ERR_NOACK;
649
650 DEBUG(D_tls) debug_printf("Switching SSL context.\n");
651 SSL_set_SSL_CTX(s, ctx_sni);
652
653 return SSL_TLSEXT_ERR_OK;
654 }
655 #endif /* EXIM_HAVE_OPENSSL_TLSEXT */
656
657
658
659
660 #ifdef EXPERIMENTAL_OCSP
661 /*************************************************
662 *        Callback to handle OCSP Stapling        *
663 *************************************************/
664
665 /* Called when acting as server during the TLS session setup if the client
666 requests OCSP information with a Certificate Status Request.
667
668 Documentation via openssl s_server.c and the Apache patch from the OpenSSL
669 project.
670
671 */
672
673 static int
674 tls_stapling_cb(SSL *s, void *arg)
675 {
676 const tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
677 uschar *response_der;
678 int response_der_len;
679
680 DEBUG(D_tls) debug_printf("Received TLS status request (OCSP stapling); %s response.\n",
681     cbinfo->ocsp_response ? "have" : "lack");
682 if (!cbinfo->ocsp_response)
683   return SSL_TLSEXT_ERR_NOACK;
684
685 response_der = NULL;
686 response_der_len = i2d_OCSP_RESPONSE(cbinfo->ocsp_response, &response_der);
687 if (response_der_len <= 0)
688   return SSL_TLSEXT_ERR_NOACK;
689
690 SSL_set_tlsext_status_ocsp_resp(ssl, response_der, response_der_len);
691 return SSL_TLSEXT_ERR_OK;
692 }
693
694 #endif /* EXPERIMENTAL_OCSP */
695
696
697
698
699 /*************************************************
700 *            Initialize for TLS                  *
701 *************************************************/
702
703 /* Called from both server and client code, to do preliminary initialization of
704 the library.
705
706 Arguments:
707   host            connected host, if client; NULL if server
708   dhparam         DH parameter file
709   certificate     certificate file
710   privatekey      private key
711   addr            address if client; NULL if server (for some randomness)
712
713 Returns:          OK/DEFER/FAIL
714 */
715
716 static int
717 tls_init(host_item *host, uschar *dhparam, uschar *certificate,
718   uschar *privatekey,
719 #ifdef EXPERIMENTAL_OCSP
720   uschar *ocsp_file,
721 #endif
722   address_item *addr)
723 {
724 long init_options;
725 int rc;
726 BOOL okay;
727 tls_ext_ctx_cb *cbinfo;
728
729 cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
730 cbinfo->certificate = certificate;
731 cbinfo->privatekey = privatekey;
732 #ifdef EXPERIMENTAL_OCSP
733 cbinfo->ocsp_file = ocsp_file;
734 #endif
735 cbinfo->dhparam = dhparam;
736 cbinfo->host = host;
737
738 SSL_load_error_strings();          /* basic set up */
739 OpenSSL_add_ssl_algorithms();
740
741 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
742 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
743 list of available digests. */
744 EVP_add_digest(EVP_sha256());
745 #endif
746
747 /* Create a context.
748 The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
749 negotiation in the different methods; as far as I can tell, the only
750 *_{server,client}_method which allows negotiation is SSLv23, which exists even
751 when OpenSSL is built without SSLv2 support.
752 By disabling with openssl_options, we can let admins re-enable with the
753 existing knob. */
754
755 ctx = SSL_CTX_new((host == NULL)?
756   SSLv23_server_method() : SSLv23_client_method());
757
758 if (ctx == NULL) return tls_error(US"SSL_CTX_new", host, NULL);
759
760 /* It turns out that we need to seed the random number generator this early in
761 order to get the full complement of ciphers to work. It took me roughly a day
762 of work to discover this by experiment.
763
764 On systems that have /dev/urandom, SSL may automatically seed itself from
765 there. Otherwise, we have to make something up as best we can. Double check
766 afterwards. */
767
768 if (!RAND_status())
769   {
770   randstuff r;
771   gettimeofday(&r.tv, NULL);
772   r.p = getpid();
773
774   RAND_seed((uschar *)(&r), sizeof(r));
775   RAND_seed((uschar *)big_buffer, big_buffer_size);
776   if (addr != NULL) RAND_seed((uschar *)addr, sizeof(addr));
777
778   if (!RAND_status())
779     return tls_error(US"RAND_status", host,
780       US"unable to seed random number generator");
781   }
782
783 /* Set up the information callback, which outputs if debugging is at a suitable
784 level. */
785
786 SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
787
788 /* Automatically re-try reads/writes after renegotiation. */
789 (void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
790
791 /* Apply administrator-supplied work-arounds.
792 Historically we applied just one requested option,
793 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
794 moved to an administrator-controlled list of options to specify and
795 grandfathered in the first one as the default value for "openssl_options".
796
797 No OpenSSL version number checks: the options we accept depend upon the
798 availability of the option value macros from OpenSSL.  */
799
800 okay = tls_openssl_options_parse(openssl_options, &init_options);
801 if (!okay)
802   return tls_error(US"openssl_options parsing failed", host, NULL);
803
804 if (init_options)
805   {
806   DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
807   if (!(SSL_CTX_set_options(ctx, init_options)))
808     return tls_error(string_sprintf(
809           "SSL_CTX_set_option(%#lx)", init_options), host, NULL);
810   }
811 else
812   DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
813
814 /* Initialize with DH parameters if supplied */
815
816 if (!init_dh(ctx, dhparam, host)) return DEFER;
817
818 /* Set up certificate and key (and perhaps OCSP info) */
819
820 rc = tls_expand_session_files(ctx, cbinfo);
821 if (rc != OK) return rc;
822
823 /* If we need to handle SNI, do so */
824 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
825 if (host == NULL)
826   {
827 #ifdef EXPERIMENTAL_OCSP
828   /* We check ocsp_file, not ocsp_response, because we care about if
829   the option exists, not what the current expansion might be, as SNI might
830   change the certificate and OCSP file in use between now and the time the
831   callback is invoked. */
832   if (cbinfo->ocsp_file)
833     {
834     SSL_CTX_set_tlsext_status_cb(ctx, tls_stapling_cb);
835     SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
836     }
837 #endif
838   /* We always do this, so that $tls_sni is available even if not used in
839   tls_certificate */
840   SSL_CTX_set_tlsext_servername_callback(ctx, tls_servername_cb);
841   SSL_CTX_set_tlsext_servername_arg(ctx, cbinfo);
842   }
843 #endif
844
845 /* Set up the RSA callback */
846
847 SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
848
849 /* Finally, set the timeout, and we are done */
850
851 SSL_CTX_set_timeout(ctx, ssl_session_timeout);
852 DEBUG(D_tls) debug_printf("Initialized TLS\n");
853
854 static_cbinfo = cbinfo;
855
856 return OK;
857 }
858
859
860
861
862 /*************************************************
863 *           Get name of cipher in use            *
864 *************************************************/
865
866 /* The answer is left in a static buffer, and tls_cipher is set to point
867 to it.
868
869 Argument:   pointer to an SSL structure for the connection
870 Returns:    nothing
871 */
872
873 static void
874 construct_cipher_name(SSL *ssl)
875 {
876 static uschar cipherbuf[256];
877 /* With OpenSSL 1.0.0a, this needs to be const but the documentation doesn't
878 yet reflect that.  It should be a safe change anyway, even 0.9.8 versions have
879 the accessor functions use const in the prototype. */
880 const SSL_CIPHER *c;
881 uschar *ver;
882
883 switch (ssl->session->ssl_version)
884   {
885   case SSL2_VERSION:
886   ver = US"SSLv2";
887   break;
888
889   case SSL3_VERSION:
890   ver = US"SSLv3";
891   break;
892
893   case TLS1_VERSION:
894   ver = US"TLSv1";
895   break;
896
897 #ifdef TLS1_1_VERSION
898   case TLS1_1_VERSION:
899   ver = US"TLSv1.1";
900   break;
901 #endif
902
903 #ifdef TLS1_2_VERSION
904   case TLS1_2_VERSION:
905   ver = US"TLSv1.2";
906   break;
907 #endif
908
909   default:
910   ver = US"UNKNOWN";
911   }
912
913 c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
914 SSL_CIPHER_get_bits(c, &tls_bits);
915
916 string_format(cipherbuf, sizeof(cipherbuf), "%s:%s:%u", ver,
917   SSL_CIPHER_get_name(c), tls_bits);
918 tls_cipher = cipherbuf;
919
920 DEBUG(D_tls) debug_printf("Cipher: %s\n", cipherbuf);
921 }
922
923
924
925
926
927 /*************************************************
928 *        Set up for verifying certificates       *
929 *************************************************/
930
931 /* Called by both client and server startup
932
933 Arguments:
934   sctx          SSL_CTX* to initialise
935   certs         certs file or NULL
936   crl           CRL file or NULL
937   host          NULL in a server; the remote host in a client
938   optional      TRUE if called from a server for a host in tls_try_verify_hosts;
939                 otherwise passed as FALSE
940
941 Returns:        OK/DEFER/FAIL
942 */
943
944 static int
945 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional)
946 {
947 uschar *expcerts, *expcrl;
948
949 if (!expand_check(certs, US"tls_verify_certificates", &expcerts))
950   return DEFER;
951
952 if (expcerts != NULL)
953   {
954   struct stat statbuf;
955   if (!SSL_CTX_set_default_verify_paths(sctx))
956     return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL);
957
958   if (Ustat(expcerts, &statbuf) < 0)
959     {
960     log_write(0, LOG_MAIN|LOG_PANIC,
961       "failed to stat %s for certificates", expcerts);
962     return DEFER;
963     }
964   else
965     {
966     uschar *file, *dir;
967     if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
968       { file = NULL; dir = expcerts; }
969     else
970       { file = expcerts; dir = NULL; }
971
972     /* If a certificate file is empty, the next function fails with an
973     unhelpful error message. If we skip it, we get the correct behaviour (no
974     certificates are recognized, but the error message is still misleading (it
975     says no certificate was supplied.) But this is better. */
976
977     if ((file == NULL || statbuf.st_size > 0) &&
978           !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
979       return tls_error(US"SSL_CTX_load_verify_locations", host, NULL);
980
981     if (file != NULL)
982       {
983       SSL_CTX_set_client_CA_list(sctx, SSL_load_client_CA_file(CS file));
984       }
985     }
986
987   /* Handle a certificate revocation list. */
988
989   #if OPENSSL_VERSION_NUMBER > 0x00907000L
990
991   /* This bit of code is now the version supplied by Lars Mainka. (I have
992    * merely reformatted it into the Exim code style.)
993
994    * "From here I changed the code to add support for multiple crl's
995    * in pem format in one file or to support hashed directory entries in
996    * pem format instead of a file. This method now uses the library function
997    * X509_STORE_load_locations to add the CRL location to the SSL context.
998    * OpenSSL will then handle the verify against CA certs and CRLs by
999    * itself in the verify callback." */
1000
1001   if (!expand_check(crl, US"tls_crl", &expcrl)) return DEFER;
1002   if (expcrl != NULL && *expcrl != 0)
1003     {
1004     struct stat statbufcrl;
1005     if (Ustat(expcrl, &statbufcrl) < 0)
1006       {
1007       log_write(0, LOG_MAIN|LOG_PANIC,
1008         "failed to stat %s for certificates revocation lists", expcrl);
1009       return DEFER;
1010       }
1011     else
1012       {
1013       /* is it a file or directory? */
1014       uschar *file, *dir;
1015       X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
1016       if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
1017         {
1018         file = NULL;
1019         dir = expcrl;
1020         DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
1021         }
1022       else
1023         {
1024         file = expcrl;
1025         dir = NULL;
1026         DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
1027         }
1028       if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
1029         return tls_error(US"X509_STORE_load_locations", host, NULL);
1030
1031       /* setting the flags to check against the complete crl chain */
1032
1033       X509_STORE_set_flags(cvstore,
1034         X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1035       }
1036     }
1037
1038   #endif  /* OPENSSL_VERSION_NUMBER > 0x00907000L */
1039
1040   /* If verification is optional, don't fail if no certificate */
1041
1042   SSL_CTX_set_verify(sctx,
1043     SSL_VERIFY_PEER | (optional? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
1044     verify_callback);
1045   }
1046
1047 return OK;
1048 }
1049
1050
1051
1052 /*************************************************
1053 *       Start a TLS session in a server          *
1054 *************************************************/
1055
1056 /* This is called when Exim is running as a server, after having received
1057 the STARTTLS command. It must respond to that command, and then negotiate
1058 a TLS session.
1059
1060 Arguments:
1061   require_ciphers   allowed ciphers
1062
1063 Returns:            OK on success
1064                     DEFER for errors before the start of the negotiation
1065                     FAIL for errors during the negotation; the server can't
1066                       continue running.
1067 */
1068
1069 int
1070 tls_server_start(const uschar *require_ciphers)
1071 {
1072 int rc;
1073 uschar *expciphers;
1074 tls_ext_ctx_cb *cbinfo;
1075
1076 /* Check for previous activation */
1077
1078 if (tls_active >= 0)
1079   {
1080   tls_error(US"STARTTLS received after TLS started", NULL, US"");
1081   smtp_printf("554 Already in TLS\r\n");
1082   return FAIL;
1083   }
1084
1085 /* Initialize the SSL library. If it fails, it will already have logged
1086 the error. */
1087
1088 rc = tls_init(NULL, tls_dhparam, tls_certificate, tls_privatekey,
1089 #ifdef EXPERIMENTAL_OCSP
1090     tls_ocsp_file,
1091 #endif
1092     NULL);
1093 if (rc != OK) return rc;
1094 cbinfo = static_cbinfo;
1095
1096 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers))
1097   return FAIL;
1098
1099 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
1100 were historically separated by underscores. So that I can use either form in my
1101 tests, and also for general convenience, we turn underscores into hyphens here.
1102 */
1103
1104 if (expciphers != NULL)
1105   {
1106   uschar *s = expciphers;
1107   while (*s != 0) { if (*s == '_') *s = '-'; s++; }
1108   DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
1109   if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
1110     return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL);
1111   cbinfo->server_cipher_list = expciphers;
1112   }
1113
1114 /* If this is a host for which certificate verification is mandatory or
1115 optional, set up appropriately. */
1116
1117 tls_certificate_verified = FALSE;
1118 verify_callback_called = FALSE;
1119
1120 if (verify_check_host(&tls_verify_hosts) == OK)
1121   {
1122   rc = setup_certs(ctx, tls_verify_certificates, tls_crl, NULL, FALSE);
1123   if (rc != OK) return rc;
1124   verify_optional = FALSE;
1125   }
1126 else if (verify_check_host(&tls_try_verify_hosts) == OK)
1127   {
1128   rc = setup_certs(ctx, tls_verify_certificates, tls_crl, NULL, TRUE);
1129   if (rc != OK) return rc;
1130   verify_optional = TRUE;
1131   }
1132
1133 /* Prepare for new connection */
1134
1135 if ((ssl = SSL_new(ctx)) == NULL) return tls_error(US"SSL_new", NULL, NULL);
1136
1137 /* Warning: we used to SSL_clear(ssl) here, it was removed.
1138  *
1139  * With the SSL_clear(), we get strange interoperability bugs with
1140  * OpenSSL 1.0.1b and TLS1.1/1.2.  It looks as though this may be a bug in
1141  * OpenSSL itself, as a clear should not lead to inability to follow protocols.
1142  *
1143  * The SSL_clear() call is to let an existing SSL* be reused, typically after
1144  * session shutdown.  In this case, we have a brand new object and there's no
1145  * obvious reason to immediately clear it.  I'm guessing that this was
1146  * originally added because of incomplete initialisation which the clear fixed,
1147  * in some historic release.
1148  */
1149
1150 /* Set context and tell client to go ahead, except in the case of TLS startup
1151 on connection, where outputting anything now upsets the clients and tends to
1152 make them disconnect. We need to have an explicit fflush() here, to force out
1153 the response. Other smtp_printf() calls do not need it, because in non-TLS
1154 mode, the fflush() happens when smtp_getc() is called. */
1155
1156 SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
1157 if (!tls_on_connect)
1158   {
1159   smtp_printf("220 TLS go ahead\r\n");
1160   fflush(smtp_out);
1161   }
1162
1163 /* Now negotiate the TLS session. We put our own timer on it, since it seems
1164 that the OpenSSL library doesn't. */
1165
1166 SSL_set_wfd(ssl, fileno(smtp_out));
1167 SSL_set_rfd(ssl, fileno(smtp_in));
1168 SSL_set_accept_state(ssl);
1169
1170 DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
1171
1172 sigalrm_seen = FALSE;
1173 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1174 rc = SSL_accept(ssl);
1175 alarm(0);
1176
1177 if (rc <= 0)
1178   {
1179   tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL);
1180   if (ERR_get_error() == 0)
1181     log_write(0, LOG_MAIN,
1182         "TLS client disconnected cleanly (rejected our certificate?)");
1183   return FAIL;
1184   }
1185
1186 DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
1187
1188 /* TLS has been set up. Adjust the input functions to read via TLS,
1189 and initialize things. */
1190
1191 construct_cipher_name(ssl);
1192
1193 DEBUG(D_tls)
1194   {
1195   uschar buf[2048];
1196   if (SSL_get_shared_ciphers(ssl, CS buf, sizeof(buf)) != NULL)
1197     debug_printf("Shared ciphers: %s\n", buf);
1198   }
1199
1200
1201 ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1202 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
1203 ssl_xfer_eof = ssl_xfer_error = 0;
1204
1205 receive_getc = tls_getc;
1206 receive_ungetc = tls_ungetc;
1207 receive_feof = tls_feof;
1208 receive_ferror = tls_ferror;
1209 receive_smtp_buffered = tls_smtp_buffered;
1210
1211 tls_active = fileno(smtp_out);
1212 return OK;
1213 }
1214
1215
1216
1217
1218
1219 /*************************************************
1220 *    Start a TLS session in a client             *
1221 *************************************************/
1222
1223 /* Called from the smtp transport after STARTTLS has been accepted.
1224
1225 Argument:
1226   fd               the fd of the connection
1227   host             connected host (for messages)
1228   addr             the first address
1229   dhparam          DH parameter file
1230   certificate      certificate file
1231   privatekey       private key file
1232   sni              TLS SNI to send to remote host
1233   verify_certs     file for certificate verify
1234   crl              file containing CRL
1235   require_ciphers  list of allowed ciphers
1236   timeout          startup timeout
1237
1238 Returns:           OK on success
1239                    FAIL otherwise - note that tls_error() will not give DEFER
1240                      because this is not a server
1241 */
1242
1243 int
1244 tls_client_start(int fd, host_item *host, address_item *addr, uschar *dhparam,
1245   uschar *certificate, uschar *privatekey, uschar *sni,
1246   uschar *verify_certs, uschar *crl,
1247   uschar *require_ciphers, int timeout)
1248 {
1249 static uschar txt[256];
1250 uschar *expciphers;
1251 X509* server_cert;
1252 int rc;
1253
1254 rc = tls_init(host, dhparam, certificate, privatekey,
1255 #ifdef EXPERIMENTAL_OCSP
1256     NULL,
1257 #endif
1258     addr);
1259 if (rc != OK) return rc;
1260
1261 tls_certificate_verified = FALSE;
1262 verify_callback_called = FALSE;
1263
1264 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers))
1265   return FAIL;
1266
1267 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
1268 are separated by underscores. So that I can use either form in my tests, and
1269 also for general convenience, we turn underscores into hyphens here. */
1270
1271 if (expciphers != NULL)
1272   {
1273   uschar *s = expciphers;
1274   while (*s != 0) { if (*s == '_') *s = '-'; s++; }
1275   DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
1276   if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
1277     return tls_error(US"SSL_CTX_set_cipher_list", host, NULL);
1278   }
1279
1280 rc = setup_certs(ctx, verify_certs, crl, host, FALSE);
1281 if (rc != OK) return rc;
1282
1283 if ((ssl = SSL_new(ctx)) == NULL) return tls_error(US"SSL_new", host, NULL);
1284 SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
1285 SSL_set_fd(ssl, fd);
1286 SSL_set_connect_state(ssl);
1287
1288 if (sni)
1289   {
1290   if (!expand_check(sni, US"tls_sni", &tls_sni))
1291     return FAIL;
1292   if (tls_sni == NULL)
1293     {
1294     DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n");
1295     }
1296   else if (!Ustrlen(tls_sni))
1297     tls_sni = NULL;
1298   else
1299     {
1300 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
1301     DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tls_sni);
1302     SSL_set_tlsext_host_name(ssl, tls_sni);
1303 #else
1304     DEBUG(D_tls)
1305       debug_printf("OpenSSL at build-time lacked SNI support, ignoring \"%s\"\n",
1306           tls_sni);
1307 #endif
1308     }
1309   }
1310
1311 /* There doesn't seem to be a built-in timeout on connection. */
1312
1313 DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
1314 sigalrm_seen = FALSE;
1315 alarm(timeout);
1316 rc = SSL_connect(ssl);
1317 alarm(0);
1318
1319 if (rc <= 0)
1320   return tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL);
1321
1322 DEBUG(D_tls) debug_printf("SSL_connect succeeded\n");
1323
1324 /* Beware anonymous ciphers which lead to server_cert being NULL */
1325 server_cert = SSL_get_peer_certificate (ssl);
1326 if (server_cert)
1327   {
1328   tls_peerdn = US X509_NAME_oneline(X509_get_subject_name(server_cert),
1329     CS txt, sizeof(txt));
1330   tls_peerdn = txt;
1331   }
1332 else
1333   tls_peerdn = NULL;
1334
1335 construct_cipher_name(ssl);   /* Sets tls_cipher */
1336
1337 tls_active = fd;
1338 return OK;
1339 }
1340
1341
1342
1343
1344
1345 /*************************************************
1346 *            TLS version of getc                 *
1347 *************************************************/
1348
1349 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
1350 it refills the buffer via the SSL reading function.
1351
1352 Arguments:  none
1353 Returns:    the next character or EOF
1354 */
1355
1356 int
1357 tls_getc(void)
1358 {
1359 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
1360   {
1361   int error;
1362   int inbytes;
1363
1364   DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
1365     ssl_xfer_buffer, ssl_xfer_buffer_size);
1366
1367   if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1368   inbytes = SSL_read(ssl, CS ssl_xfer_buffer, ssl_xfer_buffer_size);
1369   error = SSL_get_error(ssl, inbytes);
1370   alarm(0);
1371
1372   /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
1373   closed down, not that the socket itself has been closed down. Revert to
1374   non-SSL handling. */
1375
1376   if (error == SSL_ERROR_ZERO_RETURN)
1377     {
1378     DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
1379
1380     receive_getc = smtp_getc;
1381     receive_ungetc = smtp_ungetc;
1382     receive_feof = smtp_feof;
1383     receive_ferror = smtp_ferror;
1384     receive_smtp_buffered = smtp_buffered;
1385
1386     SSL_free(ssl);
1387     ssl = NULL;
1388     tls_active = -1;
1389     tls_bits = 0;
1390     tls_cipher = NULL;
1391     tls_peerdn = NULL;
1392     tls_sni = NULL;
1393
1394     return smtp_getc();
1395     }
1396
1397   /* Handle genuine errors */
1398
1399   else if (error == SSL_ERROR_SSL)
1400     {
1401     ERR_error_string(ERR_get_error(), ssl_errstring);
1402     log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
1403     ssl_xfer_error = 1;
1404     return EOF;
1405     }
1406
1407   else if (error != SSL_ERROR_NONE)
1408     {
1409     DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
1410     ssl_xfer_error = 1;
1411     return EOF;
1412     }
1413
1414 #ifndef DISABLE_DKIM
1415   dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
1416 #endif
1417   ssl_xfer_buffer_hwm = inbytes;
1418   ssl_xfer_buffer_lwm = 0;
1419   }
1420
1421 /* Something in the buffer; return next uschar */
1422
1423 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
1424 }
1425
1426
1427
1428 /*************************************************
1429 *          Read bytes from TLS channel           *
1430 *************************************************/
1431
1432 /*
1433 Arguments:
1434   buff      buffer of data
1435   len       size of buffer
1436
1437 Returns:    the number of bytes read
1438             -1 after a failed read
1439 */
1440
1441 int
1442 tls_read(uschar *buff, size_t len)
1443 {
1444 int inbytes;
1445 int error;
1446
1447 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
1448   buff, (unsigned int)len);
1449
1450 inbytes = SSL_read(ssl, CS buff, len);
1451 error = SSL_get_error(ssl, inbytes);
1452
1453 if (error == SSL_ERROR_ZERO_RETURN)
1454   {
1455   DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
1456   return -1;
1457   }
1458 else if (error != SSL_ERROR_NONE)
1459   {
1460   return -1;
1461   }
1462
1463 return inbytes;
1464 }
1465
1466
1467
1468
1469
1470 /*************************************************
1471 *         Write bytes down TLS channel           *
1472 *************************************************/
1473
1474 /*
1475 Arguments:
1476   buff      buffer of data
1477   len       number of bytes
1478
1479 Returns:    the number of bytes after a successful write,
1480             -1 after a failed write
1481 */
1482
1483 int
1484 tls_write(const uschar *buff, size_t len)
1485 {
1486 int outbytes;
1487 int error;
1488 int left = len;
1489
1490 DEBUG(D_tls) debug_printf("tls_do_write(%p, %d)\n", buff, left);
1491 while (left > 0)
1492   {
1493   DEBUG(D_tls) debug_printf("SSL_write(SSL, %p, %d)\n", buff, left);
1494   outbytes = SSL_write(ssl, CS buff, left);
1495   error = SSL_get_error(ssl, outbytes);
1496   DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
1497   switch (error)
1498     {
1499     case SSL_ERROR_SSL:
1500     ERR_error_string(ERR_get_error(), ssl_errstring);
1501     log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
1502     return -1;
1503
1504     case SSL_ERROR_NONE:
1505     left -= outbytes;
1506     buff += outbytes;
1507     break;
1508
1509     case SSL_ERROR_ZERO_RETURN:
1510     log_write(0, LOG_MAIN, "SSL channel closed on write");
1511     return -1;
1512
1513     default:
1514     log_write(0, LOG_MAIN, "SSL_write error %d", error);
1515     return -1;
1516     }
1517   }
1518 return len;
1519 }
1520
1521
1522
1523 /*************************************************
1524 *         Close down a TLS session               *
1525 *************************************************/
1526
1527 /* This is also called from within a delivery subprocess forked from the
1528 daemon, to shut down the TLS library, without actually doing a shutdown (which
1529 would tamper with the SSL session in the parent process).
1530
1531 Arguments:   TRUE if SSL_shutdown is to be called
1532 Returns:     nothing
1533 */
1534
1535 void
1536 tls_close(BOOL shutdown)
1537 {
1538 if (tls_active < 0) return;  /* TLS was not active */
1539
1540 if (shutdown)
1541   {
1542   DEBUG(D_tls) debug_printf("tls_close(): shutting down SSL\n");
1543   SSL_shutdown(ssl);
1544   }
1545
1546 SSL_free(ssl);
1547 ssl = NULL;
1548
1549 tls_active = -1;
1550 }
1551
1552
1553
1554
1555 /*************************************************
1556 *  Let tls_require_ciphers be checked at startup *
1557 *************************************************/
1558
1559 /* The tls_require_ciphers option, if set, must be something which the
1560 library can parse.
1561
1562 Returns:     NULL on success, or error message
1563 */
1564
1565 uschar *
1566 tls_validate_require_cipher(void)
1567 {
1568 SSL_CTX *ctx;
1569 uschar *s, *expciphers, *err;
1570
1571 /* this duplicates from tls_init(), we need a better "init just global
1572 state, for no specific purpose" singleton function of our own */
1573
1574 SSL_load_error_strings();
1575 OpenSSL_add_ssl_algorithms();
1576 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
1577 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
1578 list of available digests. */
1579 EVP_add_digest(EVP_sha256());
1580 #endif
1581
1582 if (!(tls_require_ciphers && *tls_require_ciphers))
1583   return NULL;
1584
1585 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers))
1586   return US"failed to expand tls_require_ciphers";
1587
1588 if (!(expciphers && *expciphers))
1589   return NULL;
1590
1591 /* normalisation ripped from above */
1592 s = expciphers;
1593 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
1594
1595 err = NULL;
1596
1597 ctx = SSL_CTX_new(SSLv23_server_method());
1598 if (!ctx)
1599   {
1600   ERR_error_string(ERR_get_error(), ssl_errstring);
1601   return string_sprintf("SSL_CTX_new() failed: %s", ssl_errstring);
1602   }
1603
1604 DEBUG(D_tls)
1605   debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
1606
1607 if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
1608   {
1609   ERR_error_string(ERR_get_error(), ssl_errstring);
1610   err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed", expciphers);
1611   }
1612
1613 SSL_CTX_free(ctx);
1614
1615 return err;
1616 }
1617
1618
1619
1620
1621 /*************************************************
1622 *         Report the library versions.           *
1623 *************************************************/
1624
1625 /* There have historically been some issues with binary compatibility in
1626 OpenSSL libraries; if Exim (like many other applications) is built against
1627 one version of OpenSSL but the run-time linker picks up another version,
1628 it can result in serious failures, including crashing with a SIGSEGV.  So
1629 report the version found by the compiler and the run-time version.
1630
1631 Arguments:   a FILE* to print the results to
1632 Returns:     nothing
1633 */
1634
1635 void
1636 tls_version_report(FILE *f)
1637 {
1638 fprintf(f, "Library version: OpenSSL: Compile: %s\n"
1639            "                          Runtime: %s\n",
1640            OPENSSL_VERSION_TEXT,
1641            SSLeay_version(SSLEAY_VERSION));
1642 }
1643
1644
1645
1646
1647 /*************************************************
1648 *            Random number generation            *
1649 *************************************************/
1650
1651 /* Pseudo-random number generation.  The result is not expected to be
1652 cryptographically strong but not so weak that someone will shoot themselves
1653 in the foot using it as a nonce in input in some email header scheme or
1654 whatever weirdness they'll twist this into.  The result should handle fork()
1655 and avoid repeating sequences.  OpenSSL handles that for us.
1656
1657 Arguments:
1658   max       range maximum
1659 Returns     a random number in range [0, max-1]
1660 */
1661
1662 int
1663 vaguely_random_number(int max)
1664 {
1665 unsigned int r;
1666 int i, needed_len;
1667 uschar *p;
1668 uschar smallbuf[sizeof(r)];
1669
1670 if (max <= 1)
1671   return 0;
1672
1673 /* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
1674 if (!RAND_status())
1675   {
1676   randstuff r;
1677   gettimeofday(&r.tv, NULL);
1678   r.p = getpid();
1679
1680   RAND_seed((uschar *)(&r), sizeof(r));
1681   }
1682 /* We're after pseudo-random, not random; if we still don't have enough data
1683 in the internal PRNG then our options are limited.  We could sleep and hope
1684 for entropy to come along (prayer technique) but if the system is so depleted
1685 in the first place then something is likely to just keep taking it.  Instead,
1686 we'll just take whatever little bit of pseudo-random we can still manage to
1687 get. */
1688
1689 needed_len = sizeof(r);
1690 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
1691 asked for a number less than 10. */
1692 for (r = max, i = 0; r; ++i)
1693   r >>= 1;
1694 i = (i + 7) / 8;
1695 if (i < needed_len)
1696   needed_len = i;
1697
1698 /* We do not care if crypto-strong */
1699 i = RAND_pseudo_bytes(smallbuf, needed_len);
1700 if (i < 0)
1701   {
1702   DEBUG(D_all)
1703     debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
1704   return vaguely_random_number_fallback(max);
1705   }
1706
1707 r = 0;
1708 for (p = smallbuf; needed_len; --needed_len, ++p)
1709   {
1710   r *= 256;
1711   r += *p;
1712   }
1713
1714 /* We don't particularly care about weighted results; if someone wants
1715 smooth distribution and cares enough then they should submit a patch then. */
1716 return r % max;
1717 }
1718
1719
1720
1721
1722 /*************************************************
1723 *        OpenSSL option parse                    *
1724 *************************************************/
1725
1726 /* Parse one option for tls_openssl_options_parse below
1727
1728 Arguments:
1729   name    one option name
1730   value   place to store a value for it
1731 Returns   success or failure in parsing
1732 */
1733
1734 struct exim_openssl_option {
1735   uschar *name;
1736   long    value;
1737 };
1738 /* We could use a macro to expand, but we need the ifdef and not all the
1739 options document which version they were introduced in.  Policylet: include
1740 all options unless explicitly for DTLS, let the administrator choose which
1741 to apply.
1742
1743 This list is current as of:
1744   ==>  1.0.1b  <==  */
1745 static struct exim_openssl_option exim_openssl_options[] = {
1746 /* KEEP SORTED ALPHABETICALLY! */
1747 #ifdef SSL_OP_ALL
1748   { US"all", SSL_OP_ALL },
1749 #endif
1750 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
1751   { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
1752 #endif
1753 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
1754   { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
1755 #endif
1756 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
1757   { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
1758 #endif
1759 #ifdef SSL_OP_EPHEMERAL_RSA
1760   { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
1761 #endif
1762 #ifdef SSL_OP_LEGACY_SERVER_CONNECT
1763   { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
1764 #endif
1765 #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
1766   { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
1767 #endif
1768 #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
1769   { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
1770 #endif
1771 #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
1772   { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
1773 #endif
1774 #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
1775   { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
1776 #endif
1777 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
1778   { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
1779 #endif
1780 #ifdef SSL_OP_NO_COMPRESSION
1781   { US"no_compression", SSL_OP_NO_COMPRESSION },
1782 #endif
1783 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1784   { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
1785 #endif
1786 #ifdef SSL_OP_NO_SSLv2
1787   { US"no_sslv2", SSL_OP_NO_SSLv2 },
1788 #endif
1789 #ifdef SSL_OP_NO_SSLv3
1790   { US"no_sslv3", SSL_OP_NO_SSLv3 },
1791 #endif
1792 #ifdef SSL_OP_NO_TICKET
1793   { US"no_ticket", SSL_OP_NO_TICKET },
1794 #endif
1795 #ifdef SSL_OP_NO_TLSv1
1796   { US"no_tlsv1", SSL_OP_NO_TLSv1 },
1797 #endif
1798 #ifdef SSL_OP_NO_TLSv1_1
1799 #if SSL_OP_NO_TLSv1_1 == 0x00000400L
1800   /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
1801 #warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
1802 #else
1803   { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
1804 #endif
1805 #endif
1806 #ifdef SSL_OP_NO_TLSv1_2
1807   { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
1808 #endif
1809 #ifdef SSL_OP_SINGLE_DH_USE
1810   { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
1811 #endif
1812 #ifdef SSL_OP_SINGLE_ECDH_USE
1813   { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
1814 #endif
1815 #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
1816   { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
1817 #endif
1818 #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
1819   { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
1820 #endif
1821 #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
1822   { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
1823 #endif
1824 #ifdef SSL_OP_TLS_D5_BUG
1825   { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
1826 #endif
1827 #ifdef SSL_OP_TLS_ROLLBACK_BUG
1828   { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
1829 #endif
1830 };
1831 static int exim_openssl_options_size =
1832   sizeof(exim_openssl_options)/sizeof(struct exim_openssl_option);
1833
1834
1835 static BOOL
1836 tls_openssl_one_option_parse(uschar *name, long *value)
1837 {
1838 int first = 0;
1839 int last = exim_openssl_options_size;
1840 while (last > first)
1841   {
1842   int middle = (first + last)/2;
1843   int c = Ustrcmp(name, exim_openssl_options[middle].name);
1844   if (c == 0)
1845     {
1846     *value = exim_openssl_options[middle].value;
1847     return TRUE;
1848     }
1849   else if (c > 0)
1850     first = middle + 1;
1851   else
1852     last = middle;
1853   }
1854 return FALSE;
1855 }
1856
1857
1858
1859
1860 /*************************************************
1861 *        OpenSSL option parsing logic            *
1862 *************************************************/
1863
1864 /* OpenSSL has a number of compatibility options which an administrator might
1865 reasonably wish to set.  Interpret a list similarly to decode_bits(), so that
1866 we look like log_selector.
1867
1868 Arguments:
1869   option_spec  the administrator-supplied string of options
1870   results      ptr to long storage for the options bitmap
1871 Returns        success or failure
1872 */
1873
1874 BOOL
1875 tls_openssl_options_parse(uschar *option_spec, long *results)
1876 {
1877 long result, item;
1878 uschar *s, *end;
1879 uschar keep_c;
1880 BOOL adding, item_parsed;
1881
1882 result = 0L;
1883 /* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
1884  * from default because it increases BEAST susceptibility. */
1885 #ifdef SSL_OP_NO_SSLv2
1886 result |= SSL_OP_NO_SSLv2;
1887 #endif
1888
1889 if (option_spec == NULL)
1890   {
1891   *results = result;
1892   return TRUE;
1893   }
1894
1895 for (s=option_spec; *s != '\0'; /**/)
1896   {
1897   while (isspace(*s)) ++s;
1898   if (*s == '\0')
1899     break;
1900   if (*s != '+' && *s != '-')
1901     {
1902     DEBUG(D_tls) debug_printf("malformed openssl option setting: "
1903         "+ or - expected but found \"%s\"\n", s);
1904     return FALSE;
1905     }
1906   adding = *s++ == '+';
1907   for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
1908   keep_c = *end;
1909   *end = '\0';
1910   item_parsed = tls_openssl_one_option_parse(s, &item);
1911   if (!item_parsed)
1912     {
1913     DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
1914     return FALSE;
1915     }
1916   DEBUG(D_tls) debug_printf("openssl option, %s from %lx: %lx (%s)\n",
1917       adding ? "adding" : "removing", result, item, s);
1918   if (adding)
1919     result |= item;
1920   else
1921     result &= ~item;
1922   *end = keep_c;
1923   s = end;
1924   }
1925
1926 *results = result;
1927 return TRUE;
1928 }
1929
1930 /* End of tls-openssl.c */