OCSP Stapling support, under EXPERIMENTAL_OCSP.
[exim.git] / src / src / tls-openssl.c
CommitLineData
059ec3d9
PH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
0a49a7a4 5/* Copyright (c) University of Cambridge 1995 - 2009 */
059ec3d9
PH
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
9library. It is #included into the tls.c file when that library is used. The
10code herein is based on a patch that was originally contributed by Steve
11Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
12
13No cryptographic code is included in Exim. All this module does is to call
14functions 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>
3f7eeb86
PP
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
059ec3d9
PH
31
32/* Structure for collecting random data for seeding. */
33
34typedef struct randstuff {
9e3331ea
TK
35 struct timeval tv;
36 pid_t p;
059ec3d9
PH
37} randstuff;
38
39/* Local static variables */
40
41static BOOL verify_callback_called = FALSE;
42static const uschar *sid_ctx = US"exim";
43
44static SSL_CTX *ctx = NULL;
7be682ca 45static SSL_CTX *ctx_sni = NULL;
059ec3d9
PH
46static SSL *ssl = NULL;
47
48static char ssl_errstring[256];
49
50static int ssl_session_timeout = 200;
51static BOOL verify_optional = FALSE;
52
7be682ca 53static BOOL reexpand_tls_files_for_sni = FALSE;
059ec3d9
PH
54
55
7be682ca
PP
56typedef struct tls_ext_ctx_cb {
57 uschar *certificate;
58 uschar *privatekey;
3f7eeb86
PP
59#ifdef EXPERIMENTAL_OCSP
60 uschar *ocsp_file;
61 uschar *ocsp_file_expanded;
62 OCSP_RESPONSE *ocsp_response;
63#endif
7be682ca
PP
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
72implementation, for various reasons, which can be void * in the APIs.
73For now, we hack around it. */
74tls_ext_ctx_cb *static_cbinfo = NULL;
75
76static int
77setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional);
059ec3d9 78
3f7eeb86
PP
79/* Callbacks */
80static int tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg);
81#ifdef EXPERIMENTAL_OCSP
82static int tls_stapling_cb(SSL *s, void *arg);
83#endif
84
059ec3d9
PH
85
86/*************************************************
87* Handle TLS error *
88*************************************************/
89
90/* Called from lots of places when errors occur before actually starting to do
91the TLS handshake, that is, while the session is still in clear. Always returns
92DEFER for a server and FAIL for a client so that most calls can use "return
93tls_error(...)" to do this processing and then give an appropriate return. A
94single function is used for both server and client, because it is called from
95some shared functions.
96
97Argument:
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
7199e1ee 101 msg error message or NULL if we should ask OpenSSL
059ec3d9
PH
102
103Returns: OK/DEFER/FAIL
104*/
105
106static int
7199e1ee 107tls_error(uschar *prefix, host_item *host, uschar *msg)
059ec3d9 108{
7199e1ee
TF
109if (msg == NULL)
110 {
111 ERR_error_string(ERR_get_error(), ssl_errstring);
5ca6d115 112 msg = (uschar *)ssl_errstring;
7199e1ee
TF
113 }
114
059ec3d9
PH
115if (host == NULL)
116 {
7199e1ee 117 uschar *conn_info = smtp_get_connection_info();
5ca6d115 118 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
7199e1ee
TF
119 conn_info += 5;
120 log_write(0, LOG_MAIN, "TLS error on %s (%s): %s",
121 conn_info, prefix, msg);
059ec3d9
PH
122 return DEFER;
123 }
124else
125 {
126 log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s): %s",
7199e1ee 127 host->name, host->address, prefix, msg);
059ec3d9
PH
128 return FAIL;
129 }
130}
131
132
133
134/*************************************************
135* Callback to generate RSA key *
136*************************************************/
137
138/*
139Arguments:
140 s SSL connection
141 export not used
142 keylength keylength
143
144Returns: pointer to generated key
145*/
146
147static RSA *
148rsa_callback(SSL *s, int export, int keylength)
149{
150RSA *rsa_key;
151export = export; /* Shut picky compilers up */
152DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
153rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL);
154if (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 }
161return 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
172callback has the current yes/no state is in "state". If verification succeeded,
173we set up the tls_peerdn string. If verification failed, what happens depends
174on whether the client is required to present a verifiable certificate or not.
175
176If verification is optional, we change the state to yes, but still log the
177verification error. For some reason (it really would help to have proper
178documentation of OpenSSL), this callback function then gets called again, this
179time with state = 1. In fact, that's useful, because we can set up the peerdn
180value, but we must take care not to set the private verified flag on the second
181time through.
182
183Note: this function is not called if the client fails to present a certificate
184when asked. We get here only if a certificate has been received. Handling of
185optional verification for this case is done when requesting SSL to verify, by
186setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
187
188Arguments:
189 state current yes/no state as 1/0
190 x509ctx certificate information.
191
192Returns: 1 if verified, 0 if not
193*/
194
195static int
196verify_callback(int state, X509_STORE_CTX *x509ctx)
197{
198static uschar txt[256];
199
200X509_NAME_oneline(X509_get_subject_name(x509ctx->current_cert),
201 CS txt, sizeof(txt));
202
203if (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
217if (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 }
222else
223 {
224 DEBUG(D_tls) debug_printf("SSL%s peer: %s\n",
225 verify_callback_called? "" : " authenticated", txt);
226 tls_peerdn = txt;
227 }
228
059ec3d9
PH
229if (!verify_callback_called) tls_certificate_verified = TRUE;
230verify_callback_called = TRUE;
231
232return 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
7be682ca
PP
242are doing. We copy the string to the debugging output when TLS debugging has
243been requested.
059ec3d9
PH
244
245Arguments:
246 s the SSL connection
247 where
248 ret
249
250Returns: nothing
251*/
252
253static void
254info_callback(SSL *s, int where, int ret)
255{
256where = where;
257ret = ret;
258DEBUG(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
269Arguments:
270 dhparam DH parameter file
7199e1ee 271 host connected host, if client; NULL if server
059ec3d9
PH
272
273Returns: TRUE if OK (nothing to set up, or setup worked)
274*/
275
276static BOOL
7199e1ee 277init_dh(uschar *dhparam, host_item *host)
059ec3d9
PH
278{
279BOOL yield = TRUE;
280BIO *bio;
281DH *dh;
282uschar *dhexpanded;
283
284if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded))
285 return FALSE;
286
287if (dhexpanded == NULL) return TRUE;
288
289if ((bio = BIO_new_file(CS dhexpanded, "r")) == NULL)
290 {
7199e1ee 291 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
5ca6d115 292 host, (uschar *)strerror(errno));
059ec3d9
PH
293 yield = FALSE;
294 }
295else
296 {
297 if ((dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)) == NULL)
298 {
7199e1ee
TF
299 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
300 host, NULL);
059ec3d9
PH
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
314return yield;
315}
316
317
318
319
3f7eeb86
PP
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
326caller has determined this is needed. Checks validity. Debugs a message
327if invalid.
328
329ASSUMES: single response, for single cert.
330
331Arguments:
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
338static void
339ocsp_load_response(SSL_CTX *sctx,
340 tls_ext_ctx_cb *cbinfo,
341 const uschar *expanded)
342{
343BIO *bio;
344OCSP_RESPONSE *resp;
345OCSP_BASICRESP *basic_response;
346OCSP_SINGLERESP *single_response;
347ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
348X509_STORE *store;
349unsigned long verify_flags;
350int status, reason, i;
351
352cbinfo->ocsp_file_expanded = string_copy(expanded);
353if (cbinfo->ocsp_response)
354 {
355 OCSP_RESPONSE_free(cbinfo->ocsp_response);
356 cbinfo->ocsp_response = NULL;
357 }
358
359bio = BIO_new_file(CS cbinfo->ocsp_file_expanded, "rb");
360if (!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
367resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
368BIO_free(bio);
369if (!resp)
370 {
371 DEBUG(D_tls) debug_printf("Error reading OCSP response.\n");
372 return;
373 }
374
375status = OCSP_response_status(resp);
376if (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
383basic_response = OCSP_response_get1_basic(resp);
384if (!basic_response)
385 {
386 DEBUG(D_tls)
387 debug_printf("OCSP response parse error: unable to extract basic response.\n");
388 return;
389 }
390
391store = SSL_CTX_get_cert_store(sctx);
392verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */
393
394/* May need to expose ability to adjust those flags?
395OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
396OCSP_TRUSTOTHER OCSP_NOINTERN */
397
398i = OCSP_basic_verify(basic_response, NULL, store, verify_flags);
399if (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
409one certificate we use, and nothing for anything else in a chain. If this
410proves 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
412right cert in the stack and then calls OCSP_single_get0_status()).
413
414I'm hoping to avoid reworking a bunch more of how we handle state here. */
415single_response = OCSP_resp_get0(basic_response, 0);
416if (!single_response)
417 {
418 DEBUG(D_tls)
419 debug_printf("Unable to get first response from OCSP basic response.\n");
420 return;
421 }
422
423status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
424/* how does this status differ from the one above? */
425if (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
432if (!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
438cbinfo->ocsp_response = resp;
439}
440#endif
441
442
443
444
7be682ca
PP
445/*************************************************
446* Expand key and cert file specs *
447*************************************************/
448
449/* Called once during tls_init and possibly againt during TLS setup, for a
450new context, if Server Name Indication was used and tls_sni was seen in
451the certificate string.
452
453Arguments:
454 sctx the SSL_CTX* to update
455 cbinfo various parts of session state
456
457Returns: OK/DEFER/FAIL
458*/
459
460static int
3f7eeb86 461tls_expand_session_files(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo)
7be682ca
PP
462{
463uschar *expanded;
464
465if (cbinfo->certificate == NULL)
466 return OK;
467
468if (Ustrstr(cbinfo->certificate, US"tls_sni"))
469 reexpand_tls_files_for_sni = TRUE;
470
471if (!expand_check(cbinfo->certificate, US"tls_certificate", &expanded))
472 return DEFER;
473
474if (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
483if (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
488of the expansion is an empty string, ignore it also, and assume the private
489key is in the same file as the certificate. */
490
491if (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
3f7eeb86
PP
499#ifdef EXPERIMENTAL_OCSP
500if (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
7be682ca
PP
520return 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
531Indication extension was sent by the client.
532
533API documentation is OpenSSL s_server.c implementation.
534
535Arguments:
536 s SSL* of the current session
537 ad unknown (part of OpenSSL API) (unused)
538 arg Callback of "our" registered data
539
540Returns: SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
541*/
542
7be682ca
PP
543static int
544tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg)
545{
546const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3f7eeb86 547tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
7be682ca 548int rc;
3f0945ff 549int old_pool = store_pool;
7be682ca
PP
550
551if (!servername)
552 return SSL_TLSEXT_ERR_OK;
553
3f0945ff 554DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
7be682ca
PP
555 reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
556
557/* Make the extension value available for expansion */
3f0945ff
PP
558store_pool = POOL_PERM;
559tls_sni = string_copy(US servername);
560store_pool = old_pool;
7be682ca
PP
561
562if (!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;
566not confident that memcpy wouldn't break some internal reference counting.
567Especially since there's a references struct member, which would be off. */
568
569ctx_sni = SSL_CTX_new(SSLv23_server_method());
570if (!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
578already exists. Might even need this selfsame callback, for reneg? */
579
580SSL_CTX_set_info_callback(ctx_sni, SSL_CTX_get_info_callback(ctx));
581SSL_CTX_set_mode(ctx_sni, SSL_CTX_get_mode(ctx));
582SSL_CTX_set_options(ctx_sni, SSL_CTX_get_options(ctx));
583SSL_CTX_set_timeout(ctx_sni, SSL_CTX_get_timeout(ctx));
584SSL_CTX_set_tlsext_servername_callback(ctx_sni, tls_servername_cb);
585SSL_CTX_set_tlsext_servername_arg(ctx_sni, cbinfo);
586if (cbinfo->server_cipher_list)
587 SSL_CTX_set_cipher_list(ctx_sni, CS cbinfo->server_cipher_list);
3f7eeb86
PP
588#ifdef EXPERIMENTAL_OCSP
589if (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
7be682ca 595
3f7eeb86 596rc = setup_certs(ctx_sni, tls_verify_certificates, tls_crl, NULL, FALSE);
7be682ca
PP
597if (rc != OK) return SSL_TLSEXT_ERR_NOACK;
598
3f7eeb86
PP
599/* do this after setup_certs, because this can require the certs for verifying
600OCSP information. */
601rc = tls_expand_session_files(ctx_sni, cbinfo);
7be682ca
PP
602if (rc != OK) return SSL_TLSEXT_ERR_NOACK;
603
604DEBUG(D_tls) debug_printf("Switching SSL context.\n");
605SSL_set_SSL_CTX(s, ctx_sni);
606
607return SSL_TLSEXT_ERR_OK;
608}
609
610
611
612
3f7eeb86
PP
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
619requests OCSP information with a Certificate Status Request.
620
621Documentation via openssl s_server.c and the Apache patch from the OpenSSL
622project.
623
624*/
625
626static int
627tls_stapling_cb(SSL *s, void *arg)
628{
629const tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
630uschar *response_der;
631int response_der_len;
632
633DEBUG(D_tls) debug_printf("Received TLS status request (OCSP stapling); %s response.\n",
634 cbinfo->ocsp_response ? "have" : "lack");
635if (!cbinfo->ocsp_response)
636 return SSL_TLSEXT_ERR_NOACK;
637
638response_der = NULL;
639response_der_len = i2d_OCSP_RESPONSE(cbinfo->ocsp_response, &response_der);
640if (response_der_len <= 0)
641 return SSL_TLSEXT_ERR_NOACK;
642
643SSL_set_tlsext_status_ocsp_resp(ssl, response_der, response_der_len);
644return SSL_TLSEXT_ERR_OK;
645}
646
647#endif /* EXPERIMENTAL_OCSP */
648
649
650
651
059ec3d9
PH
652/*************************************************
653* Initialize for TLS *
654*************************************************/
655
656/* Called from both server and client code, to do preliminary initialization of
657the library.
658
659Arguments:
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
666Returns: OK/DEFER/FAIL
667*/
668
669static int
c91535f3 670tls_init(host_item *host, uschar *dhparam, uschar *certificate,
3f7eeb86
PP
671 uschar *privatekey,
672#ifdef EXPERIMENTAL_OCSP
673 uschar *ocsp_file,
674#endif
675 address_item *addr)
059ec3d9 676{
77bb000f 677long init_options;
7be682ca 678int rc;
77bb000f 679BOOL okay;
7be682ca
PP
680tls_ext_ctx_cb *cbinfo;
681
682cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
683cbinfo->certificate = certificate;
684cbinfo->privatekey = privatekey;
3f7eeb86
PP
685#ifdef EXPERIMENTAL_OCSP
686cbinfo->ocsp_file = ocsp_file;
687#endif
7be682ca
PP
688cbinfo->dhparam = dhparam;
689cbinfo->host = host;
77bb000f 690
059ec3d9
PH
691SSL_load_error_strings(); /* basic set up */
692OpenSSL_add_ssl_algorithms();
693
388d6564 694#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
77bb000f 695/* SHA256 is becoming ever more popular. This makes sure it gets added to the
a0475b69
TK
696list of available digests. */
697EVP_add_digest(EVP_sha256());
cf1ef1a9 698#endif
a0475b69 699
059ec3d9
PH
700/* Create a context */
701
702ctx = SSL_CTX_new((host == NULL)?
703 SSLv23_server_method() : SSLv23_client_method());
704
7199e1ee 705if (ctx == NULL) return tls_error(US"SSL_CTX_new", host, NULL);
059ec3d9
PH
706
707/* It turns out that we need to seed the random number generator this early in
708order to get the full complement of ciphers to work. It took me roughly a day
709of work to discover this by experiment.
710
711On systems that have /dev/urandom, SSL may automatically seed itself from
712there. Otherwise, we have to make something up as best we can. Double check
713afterwards. */
714
715if (!RAND_status())
716 {
717 randstuff r;
9e3331ea 718 gettimeofday(&r.tv, NULL);
059ec3d9
PH
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())
7199e1ee 726 return tls_error(US"RAND_status", host,
5ca6d115 727 US"unable to seed random number generator");
059ec3d9
PH
728 }
729
730/* Set up the information callback, which outputs if debugging is at a suitable
731level. */
732
58c01c94 733SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
059ec3d9 734
c80c5570
PP
735/* Automatically re-try reads/writes after renegotiation. */
736(void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
737
77bb000f
PP
738/* Apply administrator-supplied work-arounds.
739Historically we applied just one requested option,
740SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
741moved to an administrator-controlled list of options to specify and
742grandfathered in the first one as the default value for "openssl_options".
059ec3d9 743
77bb000f
PP
744No OpenSSL version number checks: the options we accept depend upon the
745availability of the option value macros from OpenSSL. */
059ec3d9 746
77bb000f
PP
747okay = tls_openssl_options_parse(openssl_options, &init_options);
748if (!okay)
73a46702 749 return tls_error(US"openssl_options parsing failed", host, NULL);
77bb000f
PP
750
751if (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 }
758else
759 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
059ec3d9
PH
760
761/* Initialize with DH parameters if supplied */
762
7199e1ee 763if (!init_dh(dhparam, host)) return DEFER;
059ec3d9 764
3f7eeb86 765/* Set up certificate and key (and perhaps OCSP info) */
059ec3d9 766
7be682ca
PP
767rc = tls_expand_session_files(ctx, cbinfo);
768if (rc != OK) return rc;
c91535f3 769
7be682ca
PP
770/* If we need to handle SNI, do so */
771#if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
3f0945ff
PP
772if (host == NULL)
773 {
3f7eeb86
PP
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
3f0945ff
PP
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 }
7be682ca 790#endif
059ec3d9
PH
791
792/* Set up the RSA callback */
793
794SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
795
796/* Finally, set the timeout, and we are done */
797
798SSL_CTX_set_timeout(ctx, ssl_session_timeout);
799DEBUG(D_tls) debug_printf("Initialized TLS\n");
7be682ca
PP
800
801static_cbinfo = cbinfo;
802
059ec3d9
PH
803return 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
814to it.
815
816Argument: pointer to an SSL structure for the connection
817Returns: nothing
818*/
819
820static void
821construct_cipher_name(SSL *ssl)
822{
823static uschar cipherbuf[256];
57b3a7f5
PP
824/* With OpenSSL 1.0.0a, this needs to be const but the documentation doesn't
825yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
826the accessor functions use const in the prototype. */
827const SSL_CIPHER *c;
059ec3d9 828uschar *ver;
059ec3d9
PH
829
830switch (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
c80c5570
PP
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
059ec3d9
PH
856 default:
857 ver = US"UNKNOWN";
858 }
859
57b3a7f5 860c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
edc33b5f 861SSL_CIPHER_get_bits(c, &tls_bits);
059ec3d9
PH
862
863string_format(cipherbuf, sizeof(cipherbuf), "%s:%s:%u", ver,
edc33b5f 864 SSL_CIPHER_get_name(c), tls_bits);
059ec3d9
PH
865tls_cipher = cipherbuf;
866
867DEBUG(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
880Arguments:
7be682ca 881 sctx SSL_CTX* to initialise
059ec3d9
PH
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
888Returns: OK/DEFER/FAIL
889*/
890
891static int
7be682ca 892setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional)
059ec3d9
PH
893{
894uschar *expcerts, *expcrl;
895
896if (!expand_check(certs, US"tls_verify_certificates", &expcerts))
897 return DEFER;
898
899if (expcerts != NULL)
900 {
901 struct stat statbuf;
7be682ca 902 if (!SSL_CTX_set_default_verify_paths(sctx))
7199e1ee 903 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL);
059ec3d9
PH
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) &&
7be682ca 925 !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
7199e1ee 926 return tls_error(US"SSL_CTX_load_verify_locations", host, NULL);
059ec3d9
PH
927
928 if (file != NULL)
929 {
7be682ca 930 SSL_CTX_set_client_CA_list(sctx, SSL_load_client_CA_file(CS file));
059ec3d9
PH
931 }
932 }
933
934 /* Handle a certificate revocation list. */
935
936 #if OPENSSL_VERSION_NUMBER > 0x00907000L
937
8b417f2c
PH
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
059ec3d9
PH
948 if (!expand_check(crl, US"tls_crl", &expcrl)) return DEFER;
949 if (expcrl != NULL && *expcrl != 0)
950 {
8b417f2c
PH
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
059ec3d9 959 {
8b417f2c
PH
960 /* is it a file or directory? */
961 uschar *file, *dir;
7be682ca 962 X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
8b417f2c 963 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
059ec3d9 964 {
8b417f2c
PH
965 file = NULL;
966 dir = expcrl;
967 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
059ec3d9
PH
968 }
969 else
970 {
8b417f2c
PH
971 file = expcrl;
972 dir = NULL;
973 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
059ec3d9 974 }
8b417f2c 975 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
7199e1ee 976 return tls_error(US"X509_STORE_load_locations", host, NULL);
8b417f2c
PH
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);
059ec3d9 982 }
059ec3d9
PH
983 }
984
985 #endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
986
987 /* If verification is optional, don't fail if no certificate */
988
7be682ca 989 SSL_CTX_set_verify(sctx,
059ec3d9
PH
990 SSL_VERIFY_PEER | (optional? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
991 verify_callback);
992 }
993
994return 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
1004the STARTTLS command. It must respond to that command, and then negotiate
1005a TLS session.
1006
1007Arguments:
1008 require_ciphers allowed ciphers
83da1223
PH
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 ------------------------------------------------------
059ec3d9
PH
1014
1015Returns: 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
1021int
83da1223
PH
1022tls_server_start(uschar *require_ciphers, uschar *require_mac,
1023 uschar *require_kx, uschar *require_proto)
059ec3d9
PH
1024{
1025int rc;
1026uschar *expciphers;
7be682ca 1027tls_ext_ctx_cb *cbinfo;
059ec3d9
PH
1028
1029/* Check for previous activation */
1030
1031if (tls_active >= 0)
1032 {
5ca6d115 1033 tls_error(US"STARTTLS received after TLS started", NULL, US"");
059ec3d9
PH
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
1039the error. */
1040
3f7eeb86
PP
1041rc = tls_init(NULL, tls_dhparam, tls_certificate, tls_privatekey,
1042#ifdef EXPERIMENTAL_OCSP
1043 tls_ocsp_file,
1044#endif
1045 NULL);
059ec3d9 1046if (rc != OK) return rc;
7be682ca 1047cbinfo = static_cbinfo;
059ec3d9
PH
1048
1049if (!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
1053are separated by underscores. So that I can use either form in my tests, and
1054also for general convenience, we turn underscores into hyphens here. */
1055
1056if (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))
7199e1ee 1062 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL);
7be682ca 1063 cbinfo->server_cipher_list = expciphers;
059ec3d9
PH
1064 }
1065
1066/* If this is a host for which certificate verification is mandatory or
1067optional, set up appropriately. */
1068
1069tls_certificate_verified = FALSE;
1070verify_callback_called = FALSE;
1071
1072if (verify_check_host(&tls_verify_hosts) == OK)
1073 {
7be682ca 1074 rc = setup_certs(ctx, tls_verify_certificates, tls_crl, NULL, FALSE);
059ec3d9
PH
1075 if (rc != OK) return rc;
1076 verify_optional = FALSE;
1077 }
1078else if (verify_check_host(&tls_try_verify_hosts) == OK)
1079 {
7be682ca 1080 rc = setup_certs(ctx, tls_verify_certificates, tls_crl, NULL, TRUE);
059ec3d9
PH
1081 if (rc != OK) return rc;
1082 verify_optional = TRUE;
1083 }
1084
1085/* Prepare for new connection */
1086
7199e1ee 1087if ((ssl = SSL_new(ctx)) == NULL) return tls_error(US"SSL_new", NULL, NULL);
da3ad30d
PP
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 */
059ec3d9
PH
1101
1102/* Set context and tell client to go ahead, except in the case of TLS startup
1103on connection, where outputting anything now upsets the clients and tends to
1104make them disconnect. We need to have an explicit fflush() here, to force out
1105the response. Other smtp_printf() calls do not need it, because in non-TLS
1106mode, the fflush() happens when smtp_getc() is called. */
1107
1108SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
1109if (!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
1116that the OpenSSL library doesn't. */
1117
56f5d9bd
PH
1118SSL_set_wfd(ssl, fileno(smtp_out));
1119SSL_set_rfd(ssl, fileno(smtp_in));
059ec3d9
PH
1120SSL_set_accept_state(ssl);
1121
1122DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
1123
1124sigalrm_seen = FALSE;
1125if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1126rc = SSL_accept(ssl);
1127alarm(0);
1128
1129if (rc <= 0)
1130 {
7199e1ee 1131 tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL);
77bb000f
PP
1132 if (ERR_get_error() == 0)
1133 log_write(0, LOG_MAIN,
a053d125 1134 "TLS client disconnected cleanly (rejected our certificate?)");
059ec3d9
PH
1135 return FAIL;
1136 }
1137
1138DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
1139
1140/* TLS has been set up. Adjust the input functions to read via TLS,
1141and initialize things. */
1142
1143construct_cipher_name(ssl);
1144
1145DEBUG(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
1153ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1154ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
1155ssl_xfer_eof = ssl_xfer_error = 0;
1156
1157receive_getc = tls_getc;
1158receive_ungetc = tls_ungetc;
1159receive_feof = tls_feof;
1160receive_ferror = tls_ferror;
58eb016e 1161receive_smtp_buffered = tls_smtp_buffered;
059ec3d9
PH
1162
1163tls_active = fileno(smtp_out);
1164return 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
1177Argument:
1178 fd the fd of the connection
1179 host connected host (for messages)
83da1223 1180 addr the first address
059ec3d9
PH
1181 dhparam DH parameter file
1182 certificate certificate file
1183 privatekey private key file
3f0945ff 1184 sni TLS SNI to send to remote host
059ec3d9
PH
1185 verify_certs file for certificate verify
1186 crl file containing CRL
1187 require_ciphers list of allowed ciphers
83da1223
PH
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
059ec3d9
PH
1194
1195Returns: OK on success
1196 FAIL otherwise - note that tls_error() will not give DEFER
1197 because this is not a server
1198*/
1199
1200int
1201tls_client_start(int fd, host_item *host, address_item *addr, uschar *dhparam,
3f0945ff
PP
1202 uschar *certificate, uschar *privatekey, uschar *sni,
1203 uschar *verify_certs, uschar *crl,
83da1223
PH
1204 uschar *require_ciphers, uschar *require_mac, uschar *require_kx,
1205 uschar *require_proto, int timeout)
059ec3d9
PH
1206{
1207static uschar txt[256];
1208uschar *expciphers;
1209X509* server_cert;
1210int rc;
1211
3f7eeb86
PP
1212rc = tls_init(host, dhparam, certificate, privatekey,
1213#ifdef EXPERIMENTAL_OCSP
1214 NULL,
1215#endif
1216 addr);
059ec3d9
PH
1217if (rc != OK) return rc;
1218
1219tls_certificate_verified = FALSE;
1220verify_callback_called = FALSE;
1221
1222if (!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
1226are separated by underscores. So that I can use either form in my tests, and
1227also for general convenience, we turn underscores into hyphens here. */
1228
1229if (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))
7199e1ee 1235 return tls_error(US"SSL_CTX_set_cipher_list", host, NULL);
059ec3d9
PH
1236 }
1237
7be682ca 1238rc = setup_certs(ctx, verify_certs, crl, host, FALSE);
059ec3d9
PH
1239if (rc != OK) return rc;
1240
7199e1ee 1241if ((ssl = SSL_new(ctx)) == NULL) return tls_error(US"SSL_new", host, NULL);
059ec3d9
PH
1242SSL_set_session_id_context(ssl, sid_ctx, Ustrlen(sid_ctx));
1243SSL_set_fd(ssl, fd);
1244SSL_set_connect_state(ssl);
1245
3f0945ff
PP
1246if (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
059ec3d9
PH
1259/* There doesn't seem to be a built-in timeout on connection. */
1260
1261DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
1262sigalrm_seen = FALSE;
1263alarm(timeout);
1264rc = SSL_connect(ssl);
1265alarm(0);
1266
1267if (rc <= 0)
7199e1ee 1268 return tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL);
059ec3d9
PH
1269
1270DEBUG(D_tls) debug_printf("SSL_connect succeeded\n");
1271
453a6645 1272/* Beware anonymous ciphers which lead to server_cert being NULL */
059ec3d9 1273server_cert = SSL_get_peer_certificate (ssl);
453a6645
PP
1274if (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 }
1280else
1281 tls_peerdn = NULL;
059ec3d9
PH
1282
1283construct_cipher_name(ssl); /* Sets tls_cipher */
1284
1285tls_active = fd;
1286return 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,
1298it refills the buffer via the SSL reading function.
1299
1300Arguments: none
1301Returns: the next character or EOF
1302*/
1303
1304int
1305tls_getc(void)
1306{
1307if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
1308 {
1309 int error;
1310 int inbytes;
1311
c80c5570
PP
1312 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
1313 ssl_xfer_buffer, ssl_xfer_buffer_size);
059ec3d9
PH
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;
58eb016e 1332 receive_smtp_buffered = smtp_buffered;
059ec3d9
PH
1333
1334 SSL_free(ssl);
1335 ssl = NULL;
1336 tls_active = -1;
3f0945ff 1337 tls_bits = 0;
059ec3d9
PH
1338 tls_cipher = NULL;
1339 tls_peerdn = NULL;
3f0945ff 1340 tls_sni = NULL;
059ec3d9
PH
1341
1342 return smtp_getc();
1343 }
1344
1345 /* Handle genuine errors */
1346
ba084640
PP
1347 else if (error == SSL_ERROR_SSL)
1348 {
1349 ERR_error_string(ERR_get_error(), ssl_errstring);
89dd51cd 1350 log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
ba084640
PP
1351 ssl_xfer_error = 1;
1352 return EOF;
1353 }
1354
059ec3d9
PH
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 }
c80c5570 1361
80a47a2c
TK
1362#ifndef DISABLE_DKIM
1363 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
1364#endif
059ec3d9
PH
1365 ssl_xfer_buffer_hwm = inbytes;
1366 ssl_xfer_buffer_lwm = 0;
1367 }
1368
1369/* Something in the buffer; return next uschar */
1370
1371return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
1372}
1373
1374
1375
1376/*************************************************
1377* Read bytes from TLS channel *
1378*************************************************/
1379
1380/*
1381Arguments:
1382 buff buffer of data
1383 len size of buffer
1384
1385Returns: the number of bytes read
1386 -1 after a failed read
1387*/
1388
1389int
1390tls_read(uschar *buff, size_t len)
1391{
1392int inbytes;
1393int error;
1394
c80c5570
PP
1395DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
1396 buff, (unsigned int)len);
059ec3d9
PH
1397
1398inbytes = SSL_read(ssl, CS buff, len);
1399error = SSL_get_error(ssl, inbytes);
1400
1401if (error == SSL_ERROR_ZERO_RETURN)
1402 {
1403 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
1404 return -1;
1405 }
1406else if (error != SSL_ERROR_NONE)
1407 {
1408 return -1;
1409 }
1410
1411return inbytes;
1412}
1413
1414
1415
1416
1417
1418/*************************************************
1419* Write bytes down TLS channel *
1420*************************************************/
1421
1422/*
1423Arguments:
1424 buff buffer of data
1425 len number of bytes
1426
1427Returns: the number of bytes after a successful write,
1428 -1 after a failed write
1429*/
1430
1431int
1432tls_write(const uschar *buff, size_t len)
1433{
1434int outbytes;
1435int error;
1436int left = len;
1437
c80c5570 1438DEBUG(D_tls) debug_printf("tls_do_write(%p, %d)\n", buff, left);
059ec3d9
PH
1439while (left > 0)
1440 {
c80c5570 1441 DEBUG(D_tls) debug_printf("SSL_write(SSL, %p, %d)\n", buff, left);
059ec3d9
PH
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 }
1466return 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
1476daemon, to shut down the TLS library, without actually doing a shutdown (which
1477would tamper with the SSL session in the parent process).
1478
1479Arguments: TRUE if SSL_shutdown is to be called
1480Returns: nothing
1481*/
1482
1483void
1484tls_close(BOOL shutdown)
1485{
1486if (tls_active < 0) return; /* TLS was not active */
1487
1488if (shutdown)
1489 {
1490 DEBUG(D_tls) debug_printf("tls_close(): shutting down SSL\n");
1491 SSL_shutdown(ssl);
1492 }
1493
1494SSL_free(ssl);
1495ssl = NULL;
1496
1497tls_active = -1;
1498}
1499
36f12725
NM
1500
1501
1502
1503/*************************************************
1504* Report the library versions. *
1505*************************************************/
1506
1507/* There have historically been some issues with binary compatibility in
1508OpenSSL libraries; if Exim (like many other applications) is built against
1509one version of OpenSSL but the run-time linker picks up another version,
1510it can result in serious failures, including crashing with a SIGSEGV. So
1511report the version found by the compiler and the run-time version.
1512
1513Arguments: a FILE* to print the results to
1514Returns: nothing
1515*/
1516
1517void
1518tls_version_report(FILE *f)
1519{
754a0503
PP
1520fprintf(f, "Library version: OpenSSL: Compile: %s\n"
1521 " Runtime: %s\n",
1522 OPENSSL_VERSION_TEXT,
1523 SSLeay_version(SSLEAY_VERSION));
36f12725
NM
1524}
1525
9e3331ea
TK
1526
1527
1528
1529/*************************************************
1530* Pseudo-random number generation *
1531*************************************************/
1532
1533/* Pseudo-random number generation. The result is not expected to be
1534cryptographically strong but not so weak that someone will shoot themselves
1535in the foot using it as a nonce in input in some email header scheme or
1536whatever weirdness they'll twist this into. The result should handle fork()
1537and avoid repeating sequences. OpenSSL handles that for us.
1538
1539Arguments:
1540 max range maximum
1541Returns a random number in range [0, max-1]
1542*/
1543
1544int
1545pseudo_random_number(int max)
1546{
1547unsigned int r;
1548int i, needed_len;
1549uschar *p;
1550uschar smallbuf[sizeof(r)];
1551
1552if (max <= 1)
1553 return 0;
1554
1555/* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
1556if (!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
1565in the internal PRNG then our options are limited. We could sleep and hope
1566for entropy to come along (prayer technique) but if the system is so depleted
1567in the first place then something is likely to just keep taking it. Instead,
1568we'll just take whatever little bit of pseudo-random we can still manage to
1569get. */
1570
1571needed_len = sizeof(r);
1572/* Don't take 8 times more entropy than needed if int is 8 octets and we were
1573asked for a number less than 10. */
1574for (r = max, i = 0; r; ++i)
1575 r >>= 1;
1576i = (i + 7) / 8;
1577if (i < needed_len)
1578 needed_len = i;
1579
1580/* We do not care if crypto-strong */
1581(void) RAND_pseudo_bytes(smallbuf, needed_len);
1582r = 0;
1583for (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
1590smooth distribution and cares enough then they should submit a patch then. */
1591return r % max;
1592}
1593
77bb000f
PP
1594
1595
1596
1597/*************************************************
1598* OpenSSL option parse *
1599*************************************************/
1600
1601/* Parse one option for tls_openssl_options_parse below
1602
1603Arguments:
1604 name one option name
1605 value place to store a value for it
1606Returns success or failure in parsing
1607*/
1608
1609struct 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
1614options document which version they were introduced in. Policylet: include
1615all options unless explicitly for DTLS, let the administrator choose which
1616to apply.
1617
1618This list is current as of:
c80c5570 1619 ==> 1.0.1b <== */
77bb000f
PP
1620static struct exim_openssl_option exim_openssl_options[] = {
1621/* KEEP SORTED ALPHABETICALLY! */
1622#ifdef SSL_OP_ALL
73a46702 1623 { US"all", SSL_OP_ALL },
77bb000f
PP
1624#endif
1625#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
73a46702 1626 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
77bb000f
PP
1627#endif
1628#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
73a46702 1629 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
77bb000f
PP
1630#endif
1631#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
73a46702 1632 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
77bb000f
PP
1633#endif
1634#ifdef SSL_OP_EPHEMERAL_RSA
73a46702 1635 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
77bb000f
PP
1636#endif
1637#ifdef SSL_OP_LEGACY_SERVER_CONNECT
73a46702 1638 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
77bb000f
PP
1639#endif
1640#ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
73a46702 1641 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
77bb000f
PP
1642#endif
1643#ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
73a46702 1644 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
77bb000f
PP
1645#endif
1646#ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
73a46702 1647 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
77bb000f
PP
1648#endif
1649#ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
73a46702 1650 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
77bb000f
PP
1651#endif
1652#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
73a46702 1653 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
77bb000f 1654#endif
c80c5570
PP
1655#ifdef SSL_OP_NO_COMPRESSION
1656 { US"no_compression", SSL_OP_NO_COMPRESSION },
1657#endif
77bb000f 1658#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
73a46702 1659 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
77bb000f 1660#endif
c0c7b2da
PP
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
c80c5570
PP
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
77bb000f 1684#ifdef SSL_OP_SINGLE_DH_USE
73a46702 1685 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
77bb000f
PP
1686#endif
1687#ifdef SSL_OP_SINGLE_ECDH_USE
73a46702 1688 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
77bb000f
PP
1689#endif
1690#ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
73a46702 1691 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
77bb000f
PP
1692#endif
1693#ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
73a46702 1694 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
77bb000f
PP
1695#endif
1696#ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
73a46702 1697 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
77bb000f
PP
1698#endif
1699#ifdef SSL_OP_TLS_D5_BUG
73a46702 1700 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
77bb000f
PP
1701#endif
1702#ifdef SSL_OP_TLS_ROLLBACK_BUG
73a46702 1703 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
77bb000f
PP
1704#endif
1705};
1706static int exim_openssl_options_size =
1707 sizeof(exim_openssl_options)/sizeof(struct exim_openssl_option);
1708
c80c5570 1709
77bb000f
PP
1710static BOOL
1711tls_openssl_one_option_parse(uschar *name, long *value)
1712{
1713int first = 0;
1714int last = exim_openssl_options_size;
1715while (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 }
1729return 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
1740reasonably wish to set. Interpret a list similarly to decode_bits(), so that
1741we look like log_selector.
1742
1743Arguments:
1744 option_spec the administrator-supplied string of options
1745 results ptr to long storage for the options bitmap
1746Returns success or failure
1747*/
1748
1749BOOL
1750tls_openssl_options_parse(uschar *option_spec, long *results)
1751{
1752long result, item;
1753uschar *s, *end;
1754uschar keep_c;
1755BOOL adding, item_parsed;
1756
0e944a0d 1757result = 0L;
da3ad30d
PP
1758/* Prior to 4.78 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
1759 * from default because it increases BEAST susceptibility. */
77bb000f
PP
1760
1761if (option_spec == NULL)
1762 {
1763 *results = result;
1764 return TRUE;
1765 }
1766
1767for (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: "
0e944a0d 1775 "+ or - expected but found \"%s\"\n", s);
77bb000f
PP
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 {
0e944a0d 1785 DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
77bb000f
PP
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;
1799return TRUE;
1800}
1801
059ec3d9 1802/* End of tls-openssl.c */