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