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