Copyright year updates.
[exim.git] / src / src / tls-openssl.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 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 /* 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 Returns:            OK on success
1011                     DEFER for errors before the start of the negotiation
1012                     FAIL for errors during the negotation; the server can't
1013                       continue running.
1014 */
1015
1016 int
1017 tls_server_start(const uschar *require_ciphers)
1018 {
1019 int rc;
1020 uschar *expciphers;
1021 tls_ext_ctx_cb *cbinfo;
1022
1023 /* Check for previous activation */
1024
1025 if (tls_active >= 0)
1026   {
1027   tls_error(US"STARTTLS received after TLS started", NULL, US"");
1028   smtp_printf("554 Already in TLS\r\n");
1029   return FAIL;
1030   }
1031
1032 /* Initialize the SSL library. If it fails, it will already have logged
1033 the error. */
1034
1035 rc = tls_init(NULL, tls_dhparam, tls_certificate, tls_privatekey,
1036 #ifdef EXPERIMENTAL_OCSP
1037     tls_ocsp_file,
1038 #endif
1039     NULL);
1040 if (rc != OK) return rc;
1041 cbinfo = static_cbinfo;
1042
1043 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers))
1044   return FAIL;
1045
1046 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
1047 were historically separated by underscores. So that I can use either form in my
1048 tests, and also for general convenience, we turn underscores into hyphens here.
1049 */
1050
1051 if (expciphers != NULL)
1052   {
1053   uschar *s = expciphers;
1054   while (*s != 0) { if (*s == '_') *s = '-'; s++; }
1055   DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
1056   if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
1057     return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL);
1058   cbinfo->server_cipher_list = expciphers;
1059   }
1060
1061 /* If this is a host for which certificate verification is mandatory or
1062 optional, set up appropriately. */
1063
1064 tls_certificate_verified = FALSE;
1065 verify_callback_called = FALSE;
1066
1067 if (verify_check_host(&tls_verify_hosts) == OK)
1068   {
1069   rc = setup_certs(ctx, tls_verify_certificates, tls_crl, NULL, FALSE);
1070   if (rc != OK) return rc;
1071   verify_optional = FALSE;
1072   }
1073 else if (verify_check_host(&tls_try_verify_hosts) == OK)
1074   {
1075   rc = setup_certs(ctx, tls_verify_certificates, tls_crl, NULL, TRUE);
1076   if (rc != OK) return rc;
1077   verify_optional = TRUE;
1078   }
1079
1080 /* Prepare for new connection */
1081
1082 if ((ssl = SSL_new(ctx)) == NULL) return tls_error(US"SSL_new", NULL, NULL);
1083
1084 /* Warning: we used to SSL_clear(ssl) here, it was removed.
1085  *
1086  * With the SSL_clear(), we get strange interoperability bugs with
1087  * OpenSSL 1.0.1b and TLS1.1/1.2.  It looks as though this may be a bug in
1088  * OpenSSL itself, as a clear should not lead to inability to follow protocols.
1089  *
1090  * The SSL_clear() call is to let an existing SSL* be reused, typically after
1091  * session shutdown.  In this case, we have a brand new object and there's no
1092  * obvious reason to immediately clear it.  I'm guessing that this was
1093  * originally added because of incomplete initialisation which the clear fixed,
1094  * in some historic release.
1095  */
1096
1097 /* Set context and tell client to go ahead, except in the case of TLS startup
1098 on connection, where outputting anything now upsets the clients and tends to
1099 make them disconnect. We need to have an explicit fflush() here, to force out
1100 the response. Other smtp_printf() calls do not need it, because in non-TLS
1101 mode, the fflush() happens when smtp_getc() is called. */
1102
1103 SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
1104 if (!tls_on_connect)
1105   {
1106   smtp_printf("220 TLS go ahead\r\n");
1107   fflush(smtp_out);
1108   }
1109
1110 /* Now negotiate the TLS session. We put our own timer on it, since it seems
1111 that the OpenSSL library doesn't. */
1112
1113 SSL_set_wfd(ssl, fileno(smtp_out));
1114 SSL_set_rfd(ssl, fileno(smtp_in));
1115 SSL_set_accept_state(ssl);
1116
1117 DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
1118
1119 sigalrm_seen = FALSE;
1120 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1121 rc = SSL_accept(ssl);
1122 alarm(0);
1123
1124 if (rc <= 0)
1125   {
1126   tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL);
1127   if (ERR_get_error() == 0)
1128     log_write(0, LOG_MAIN,
1129         "TLS client disconnected cleanly (rejected our certificate?)");
1130   return FAIL;
1131   }
1132
1133 DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
1134
1135 /* TLS has been set up. Adjust the input functions to read via TLS,
1136 and initialize things. */
1137
1138 construct_cipher_name(ssl);
1139
1140 DEBUG(D_tls)
1141   {
1142   uschar buf[2048];
1143   if (SSL_get_shared_ciphers(ssl, CS buf, sizeof(buf)) != NULL)
1144     debug_printf("Shared ciphers: %s\n", buf);
1145   }
1146
1147
1148 ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1149 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
1150 ssl_xfer_eof = ssl_xfer_error = 0;
1151
1152 receive_getc = tls_getc;
1153 receive_ungetc = tls_ungetc;
1154 receive_feof = tls_feof;
1155 receive_ferror = tls_ferror;
1156 receive_smtp_buffered = tls_smtp_buffered;
1157
1158 tls_active = fileno(smtp_out);
1159 return OK;
1160 }
1161
1162
1163
1164
1165
1166 /*************************************************
1167 *    Start a TLS session in a client             *
1168 *************************************************/
1169
1170 /* Called from the smtp transport after STARTTLS has been accepted.
1171
1172 Argument:
1173   fd               the fd of the connection
1174   host             connected host (for messages)
1175   addr             the first address
1176   dhparam          DH parameter file
1177   certificate      certificate file
1178   privatekey       private key file
1179   sni              TLS SNI to send to remote host
1180   verify_certs     file for certificate verify
1181   crl              file containing CRL
1182   require_ciphers  list of allowed ciphers
1183   timeout          startup timeout
1184
1185 Returns:           OK on success
1186                    FAIL otherwise - note that tls_error() will not give DEFER
1187                      because this is not a server
1188 */
1189
1190 int
1191 tls_client_start(int fd, host_item *host, address_item *addr, uschar *dhparam,
1192   uschar *certificate, uschar *privatekey, uschar *sni,
1193   uschar *verify_certs, uschar *crl,
1194   uschar *require_ciphers, int timeout)
1195 {
1196 static uschar txt[256];
1197 uschar *expciphers;
1198 X509* server_cert;
1199 int rc;
1200
1201 rc = tls_init(host, dhparam, certificate, privatekey,
1202 #ifdef EXPERIMENTAL_OCSP
1203     NULL,
1204 #endif
1205     addr);
1206 if (rc != OK) return rc;
1207
1208 tls_certificate_verified = FALSE;
1209 verify_callback_called = FALSE;
1210
1211 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers))
1212   return FAIL;
1213
1214 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
1215 are separated by underscores. So that I can use either form in my tests, and
1216 also for general convenience, we turn underscores into hyphens here. */
1217
1218 if (expciphers != NULL)
1219   {
1220   uschar *s = expciphers;
1221   while (*s != 0) { if (*s == '_') *s = '-'; s++; }
1222   DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
1223   if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
1224     return tls_error(US"SSL_CTX_set_cipher_list", host, NULL);
1225   }
1226
1227 rc = setup_certs(ctx, verify_certs, crl, host, FALSE);
1228 if (rc != OK) return rc;
1229
1230 if ((ssl = SSL_new(ctx)) == NULL) return tls_error(US"SSL_new", host, NULL);
1231 SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
1232 SSL_set_fd(ssl, fd);
1233 SSL_set_connect_state(ssl);
1234
1235 if (sni)
1236   {
1237   if (!expand_check(sni, US"tls_sni", &tls_sni))
1238     return FAIL;
1239   if (!Ustrlen(tls_sni))
1240     tls_sni = NULL;
1241   else
1242     {
1243     DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tls_sni);
1244     SSL_set_tlsext_host_name(ssl, tls_sni);
1245     }
1246   }
1247
1248 /* There doesn't seem to be a built-in timeout on connection. */
1249
1250 DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
1251 sigalrm_seen = FALSE;
1252 alarm(timeout);
1253 rc = SSL_connect(ssl);
1254 alarm(0);
1255
1256 if (rc <= 0)
1257   return tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL);
1258
1259 DEBUG(D_tls) debug_printf("SSL_connect succeeded\n");
1260
1261 /* Beware anonymous ciphers which lead to server_cert being NULL */
1262 server_cert = SSL_get_peer_certificate (ssl);
1263 if (server_cert)
1264   {
1265   tls_peerdn = US X509_NAME_oneline(X509_get_subject_name(server_cert),
1266     CS txt, sizeof(txt));
1267   tls_peerdn = txt;
1268   }
1269 else
1270   tls_peerdn = NULL;
1271
1272 construct_cipher_name(ssl);   /* Sets tls_cipher */
1273
1274 tls_active = fd;
1275 return OK;
1276 }
1277
1278
1279
1280
1281
1282 /*************************************************
1283 *            TLS version of getc                 *
1284 *************************************************/
1285
1286 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
1287 it refills the buffer via the SSL reading function.
1288
1289 Arguments:  none
1290 Returns:    the next character or EOF
1291 */
1292
1293 int
1294 tls_getc(void)
1295 {
1296 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
1297   {
1298   int error;
1299   int inbytes;
1300
1301   DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
1302     ssl_xfer_buffer, ssl_xfer_buffer_size);
1303
1304   if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1305   inbytes = SSL_read(ssl, CS ssl_xfer_buffer, ssl_xfer_buffer_size);
1306   error = SSL_get_error(ssl, inbytes);
1307   alarm(0);
1308
1309   /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
1310   closed down, not that the socket itself has been closed down. Revert to
1311   non-SSL handling. */
1312
1313   if (error == SSL_ERROR_ZERO_RETURN)
1314     {
1315     DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
1316
1317     receive_getc = smtp_getc;
1318     receive_ungetc = smtp_ungetc;
1319     receive_feof = smtp_feof;
1320     receive_ferror = smtp_ferror;
1321     receive_smtp_buffered = smtp_buffered;
1322
1323     SSL_free(ssl);
1324     ssl = NULL;
1325     tls_active = -1;
1326     tls_bits = 0;
1327     tls_cipher = NULL;
1328     tls_peerdn = NULL;
1329     tls_sni = NULL;
1330
1331     return smtp_getc();
1332     }
1333
1334   /* Handle genuine errors */
1335
1336   else if (error == SSL_ERROR_SSL)
1337     {
1338     ERR_error_string(ERR_get_error(), ssl_errstring);
1339     log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
1340     ssl_xfer_error = 1;
1341     return EOF;
1342     }
1343
1344   else if (error != SSL_ERROR_NONE)
1345     {
1346     DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
1347     ssl_xfer_error = 1;
1348     return EOF;
1349     }
1350
1351 #ifndef DISABLE_DKIM
1352   dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
1353 #endif
1354   ssl_xfer_buffer_hwm = inbytes;
1355   ssl_xfer_buffer_lwm = 0;
1356   }
1357
1358 /* Something in the buffer; return next uschar */
1359
1360 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
1361 }
1362
1363
1364
1365 /*************************************************
1366 *          Read bytes from TLS channel           *
1367 *************************************************/
1368
1369 /*
1370 Arguments:
1371   buff      buffer of data
1372   len       size of buffer
1373
1374 Returns:    the number of bytes read
1375             -1 after a failed read
1376 */
1377
1378 int
1379 tls_read(uschar *buff, size_t len)
1380 {
1381 int inbytes;
1382 int error;
1383
1384 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
1385   buff, (unsigned int)len);
1386
1387 inbytes = SSL_read(ssl, CS buff, len);
1388 error = SSL_get_error(ssl, inbytes);
1389
1390 if (error == SSL_ERROR_ZERO_RETURN)
1391   {
1392   DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
1393   return -1;
1394   }
1395 else if (error != SSL_ERROR_NONE)
1396   {
1397   return -1;
1398   }
1399
1400 return inbytes;
1401 }
1402
1403
1404
1405
1406
1407 /*************************************************
1408 *         Write bytes down TLS channel           *
1409 *************************************************/
1410
1411 /*
1412 Arguments:
1413   buff      buffer of data
1414   len       number of bytes
1415
1416 Returns:    the number of bytes after a successful write,
1417             -1 after a failed write
1418 */
1419
1420 int
1421 tls_write(const uschar *buff, size_t len)
1422 {
1423 int outbytes;
1424 int error;
1425 int left = len;
1426
1427 DEBUG(D_tls) debug_printf("tls_do_write(%p, %d)\n", buff, left);
1428 while (left > 0)
1429   {
1430   DEBUG(D_tls) debug_printf("SSL_write(SSL, %p, %d)\n", buff, left);
1431   outbytes = SSL_write(ssl, CS buff, left);
1432   error = SSL_get_error(ssl, outbytes);
1433   DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
1434   switch (error)
1435     {
1436     case SSL_ERROR_SSL:
1437     ERR_error_string(ERR_get_error(), ssl_errstring);
1438     log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
1439     return -1;
1440
1441     case SSL_ERROR_NONE:
1442     left -= outbytes;
1443     buff += outbytes;
1444     break;
1445
1446     case SSL_ERROR_ZERO_RETURN:
1447     log_write(0, LOG_MAIN, "SSL channel closed on write");
1448     return -1;
1449
1450     default:
1451     log_write(0, LOG_MAIN, "SSL_write error %d", error);
1452     return -1;
1453     }
1454   }
1455 return len;
1456 }
1457
1458
1459
1460 /*************************************************
1461 *         Close down a TLS session               *
1462 *************************************************/
1463
1464 /* This is also called from within a delivery subprocess forked from the
1465 daemon, to shut down the TLS library, without actually doing a shutdown (which
1466 would tamper with the SSL session in the parent process).
1467
1468 Arguments:   TRUE if SSL_shutdown is to be called
1469 Returns:     nothing
1470 */
1471
1472 void
1473 tls_close(BOOL shutdown)
1474 {
1475 if (tls_active < 0) return;  /* TLS was not active */
1476
1477 if (shutdown)
1478   {
1479   DEBUG(D_tls) debug_printf("tls_close(): shutting down SSL\n");
1480   SSL_shutdown(ssl);
1481   }
1482
1483 SSL_free(ssl);
1484 ssl = NULL;
1485
1486 tls_active = -1;
1487 }
1488
1489
1490
1491
1492 /*************************************************
1493 *         Report the library versions.           *
1494 *************************************************/
1495
1496 /* There have historically been some issues with binary compatibility in
1497 OpenSSL libraries; if Exim (like many other applications) is built against
1498 one version of OpenSSL but the run-time linker picks up another version,
1499 it can result in serious failures, including crashing with a SIGSEGV.  So
1500 report the version found by the compiler and the run-time version.
1501
1502 Arguments:   a FILE* to print the results to
1503 Returns:     nothing
1504 */
1505
1506 void
1507 tls_version_report(FILE *f)
1508 {
1509 fprintf(f, "Library version: OpenSSL: Compile: %s\n"
1510            "                          Runtime: %s\n",
1511            OPENSSL_VERSION_TEXT,
1512            SSLeay_version(SSLEAY_VERSION));
1513 }
1514
1515
1516
1517
1518 /*************************************************
1519 *            Random number generation            *
1520 *************************************************/
1521
1522 /* Pseudo-random number generation.  The result is not expected to be
1523 cryptographically strong but not so weak that someone will shoot themselves
1524 in the foot using it as a nonce in input in some email header scheme or
1525 whatever weirdness they'll twist this into.  The result should handle fork()
1526 and avoid repeating sequences.  OpenSSL handles that for us.
1527
1528 Arguments:
1529   max       range maximum
1530 Returns     a random number in range [0, max-1]
1531 */
1532
1533 int
1534 vaguely_random_number(int max)
1535 {
1536 unsigned int r;
1537 int i, needed_len;
1538 uschar *p;
1539 uschar smallbuf[sizeof(r)];
1540
1541 if (max <= 1)
1542   return 0;
1543
1544 /* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
1545 if (!RAND_status())
1546   {
1547   randstuff r;
1548   gettimeofday(&r.tv, NULL);
1549   r.p = getpid();
1550
1551   RAND_seed((uschar *)(&r), sizeof(r));
1552   }
1553 /* We're after pseudo-random, not random; if we still don't have enough data
1554 in the internal PRNG then our options are limited.  We could sleep and hope
1555 for entropy to come along (prayer technique) but if the system is so depleted
1556 in the first place then something is likely to just keep taking it.  Instead,
1557 we'll just take whatever little bit of pseudo-random we can still manage to
1558 get. */
1559
1560 needed_len = sizeof(r);
1561 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
1562 asked for a number less than 10. */
1563 for (r = max, i = 0; r; ++i)
1564   r >>= 1;
1565 i = (i + 7) / 8;
1566 if (i < needed_len)
1567   needed_len = i;
1568
1569 /* We do not care if crypto-strong */
1570 i = RAND_pseudo_bytes(smallbuf, needed_len);
1571 if (i < 0)
1572   {
1573   DEBUG(D_all)
1574     debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
1575   return vaguely_random_number_fallback(max);
1576   }
1577
1578 r = 0;
1579 for (p = smallbuf; needed_len; --needed_len, ++p)
1580   {
1581   r *= 256;
1582   r += *p;
1583   }
1584
1585 /* We don't particularly care about weighted results; if someone wants
1586 smooth distribution and cares enough then they should submit a patch then. */
1587 return r % max;
1588 }
1589
1590
1591
1592
1593 /*************************************************
1594 *        OpenSSL option parse                    *
1595 *************************************************/
1596
1597 /* Parse one option for tls_openssl_options_parse below
1598
1599 Arguments:
1600   name    one option name
1601   value   place to store a value for it
1602 Returns   success or failure in parsing
1603 */
1604
1605 struct exim_openssl_option {
1606   uschar *name;
1607   long    value;
1608 };
1609 /* We could use a macro to expand, but we need the ifdef and not all the
1610 options document which version they were introduced in.  Policylet: include
1611 all options unless explicitly for DTLS, let the administrator choose which
1612 to apply.
1613
1614 This list is current as of:
1615   ==>  1.0.1b  <==  */
1616 static struct exim_openssl_option exim_openssl_options[] = {
1617 /* KEEP SORTED ALPHABETICALLY! */
1618 #ifdef SSL_OP_ALL
1619   { US"all", SSL_OP_ALL },
1620 #endif
1621 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
1622   { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
1623 #endif
1624 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
1625   { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
1626 #endif
1627 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
1628   { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
1629 #endif
1630 #ifdef SSL_OP_EPHEMERAL_RSA
1631   { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
1632 #endif
1633 #ifdef SSL_OP_LEGACY_SERVER_CONNECT
1634   { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
1635 #endif
1636 #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
1637   { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
1638 #endif
1639 #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
1640   { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
1641 #endif
1642 #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
1643   { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
1644 #endif
1645 #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
1646   { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
1647 #endif
1648 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
1649   { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
1650 #endif
1651 #ifdef SSL_OP_NO_COMPRESSION
1652   { US"no_compression", SSL_OP_NO_COMPRESSION },
1653 #endif
1654 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1655   { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
1656 #endif
1657 #ifdef SSL_OP_NO_SSLv2
1658   { US"no_sslv2", SSL_OP_NO_SSLv2 },
1659 #endif
1660 #ifdef SSL_OP_NO_SSLv3
1661   { US"no_sslv3", SSL_OP_NO_SSLv3 },
1662 #endif
1663 #ifdef SSL_OP_NO_TICKET
1664   { US"no_ticket", SSL_OP_NO_TICKET },
1665 #endif
1666 #ifdef SSL_OP_NO_TLSv1
1667   { US"no_tlsv1", SSL_OP_NO_TLSv1 },
1668 #endif
1669 #ifdef SSL_OP_NO_TLSv1_1
1670 #if SSL_OP_NO_TLSv1_1 == 0x00000400L
1671   /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
1672 #warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
1673 #else
1674   { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
1675 #endif
1676 #endif
1677 #ifdef SSL_OP_NO_TLSv1_2
1678   { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
1679 #endif
1680 #ifdef SSL_OP_SINGLE_DH_USE
1681   { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
1682 #endif
1683 #ifdef SSL_OP_SINGLE_ECDH_USE
1684   { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
1685 #endif
1686 #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
1687   { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
1688 #endif
1689 #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
1690   { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
1691 #endif
1692 #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
1693   { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
1694 #endif
1695 #ifdef SSL_OP_TLS_D5_BUG
1696   { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
1697 #endif
1698 #ifdef SSL_OP_TLS_ROLLBACK_BUG
1699   { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
1700 #endif
1701 };
1702 static int exim_openssl_options_size =
1703   sizeof(exim_openssl_options)/sizeof(struct exim_openssl_option);
1704
1705
1706 static BOOL
1707 tls_openssl_one_option_parse(uschar *name, long *value)
1708 {
1709 int first = 0;
1710 int last = exim_openssl_options_size;
1711 while (last > first)
1712   {
1713   int middle = (first + last)/2;
1714   int c = Ustrcmp(name, exim_openssl_options[middle].name);
1715   if (c == 0)
1716     {
1717     *value = exim_openssl_options[middle].value;
1718     return TRUE;
1719     }
1720   else if (c > 0)
1721     first = middle + 1;
1722   else
1723     last = middle;
1724   }
1725 return FALSE;
1726 }
1727
1728
1729
1730
1731 /*************************************************
1732 *        OpenSSL option parsing logic            *
1733 *************************************************/
1734
1735 /* OpenSSL has a number of compatibility options which an administrator might
1736 reasonably wish to set.  Interpret a list similarly to decode_bits(), so that
1737 we look like log_selector.
1738
1739 Arguments:
1740   option_spec  the administrator-supplied string of options
1741   results      ptr to long storage for the options bitmap
1742 Returns        success or failure
1743 */
1744
1745 BOOL
1746 tls_openssl_options_parse(uschar *option_spec, long *results)
1747 {
1748 long result, item;
1749 uschar *s, *end;
1750 uschar keep_c;
1751 BOOL adding, item_parsed;
1752
1753 result = 0L;
1754 /* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
1755  * from default because it increases BEAST susceptibility. */
1756
1757 if (option_spec == NULL)
1758   {
1759   *results = result;
1760   return TRUE;
1761   }
1762
1763 for (s=option_spec; *s != '\0'; /**/)
1764   {
1765   while (isspace(*s)) ++s;
1766   if (*s == '\0')
1767     break;
1768   if (*s != '+' && *s != '-')
1769     {
1770     DEBUG(D_tls) debug_printf("malformed openssl option setting: "
1771         "+ or - expected but found \"%s\"\n", s);
1772     return FALSE;
1773     }
1774   adding = *s++ == '+';
1775   for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
1776   keep_c = *end;
1777   *end = '\0';
1778   item_parsed = tls_openssl_one_option_parse(s, &item);
1779   if (!item_parsed)
1780     {
1781     DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
1782     return FALSE;
1783     }
1784   DEBUG(D_tls) debug_printf("openssl option, %s from %lx: %lx (%s)\n",
1785       adding ? "adding" : "removing", result, item, s);
1786   if (adding)
1787     result |= item;
1788   else
1789     result &= ~item;
1790   *end = keep_c;
1791   s = end;
1792   }
1793
1794 *results = result;
1795 return TRUE;
1796 }
1797
1798 /* End of tls-openssl.c */