Delivery: quieten smtp transport conn reuse vs. delivery race. Bug 1810
[exim.git] / src / src / tls-openssl.c
... / ...
CommitLineData
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
5/* Copyright (c) University of Cambridge 1995 - 2016 */
6/* See the file NOTICE for conditions of use and distribution. */
7
8/* Portions Copyright (c) The OpenSSL Project 1999 */
9
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>
25#ifndef OPENSSL_NO_ECDH
26# include <openssl/ec.h>
27#endif
28#ifndef DISABLE_OCSP
29# include <openssl/ocsp.h>
30#endif
31#ifdef EXPERIMENTAL_DANE
32# include <danessl.h>
33#endif
34
35
36#ifndef DISABLE_OCSP
37# define EXIM_OCSP_SKEW_SECONDS (300L)
38# define EXIM_OCSP_MAX_AGE (-1L)
39#endif
40
41#if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
42# define EXIM_HAVE_OPENSSL_TLSEXT
43#endif
44#if OPENSSL_VERSION_NUMBER >= 0x00908000L
45# define EXIM_HAVE_RSA_GENKEY_EX
46#endif
47#if OPENSSL_VERSION_NUMBER >= 0x10100000L
48# define EXIM_HAVE_OCSP_RESP_COUNT
49#else
50# define EXIM_HAVE_EPHEM_RSA_KEX
51# define EXIM_HAVE_RAND_PSEUDO
52#endif
53#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
54# define EXIM_HAVE_SHA256
55#endif
56
57/*
58 * X509_check_host provides sane certificate hostname checking, but was added
59 * to OpenSSL late, after other projects forked off the code-base. So in
60 * addition to guarding against the base version number, beware that LibreSSL
61 * does not (at this time) support this function.
62 *
63 * If LibreSSL gains a different API, perhaps via libtls, then we'll probably
64 * opt to disentangle and ask a LibreSSL user to provide glue for a third
65 * crypto provider for libtls instead of continuing to tie the OpenSSL glue
66 * into even twistier knots. If LibreSSL gains the same API, we can just
67 * change this guard and punt the issue for a while longer.
68 */
69#ifndef LIBRESSL_VERSION_NUMBER
70# if OPENSSL_VERSION_NUMBER >= 0x010100000L
71# define EXIM_HAVE_OPENSSL_CHECKHOST
72# endif
73# if OPENSSL_VERSION_NUMBER >= 0x010000000L \
74 && (OPENSSL_VERSION_NUMBER & 0x0000ff000L) >= 0x000002000L
75# define EXIM_HAVE_OPENSSL_CHECKHOST
76# endif
77#endif
78
79#if !defined(LIBRESSL_VERSION_NUMBER) \
80 || LIBRESSL_VERSION_NUMBER >= 0x20010000L
81# if !defined(OPENSSL_NO_ECDH)
82# if OPENSSL_VERSION_NUMBER >= 0x0090800fL
83# define EXIM_HAVE_ECDH
84# endif
85# if OPENSSL_VERSION_NUMBER >= 0x10002000L
86# if OPENSSL_VERSION_NUMBER < 0x10100000L
87# define EXIM_HAVE_OPENSSL_ECDH_AUTO
88# endif
89# define EXIM_HAVE_OPENSSL_EC_NIST2NID
90# endif
91# endif
92#endif
93
94#if !defined(EXIM_HAVE_OPENSSL_TLSEXT) && !defined(DISABLE_OCSP)
95# warning "OpenSSL library version too old; define DISABLE_OCSP in Makefile"
96# define DISABLE_OCSP
97#endif
98
99/* Structure for collecting random data for seeding. */
100
101typedef struct randstuff {
102 struct timeval tv;
103 pid_t p;
104} randstuff;
105
106/* Local static variables */
107
108static BOOL client_verify_callback_called = FALSE;
109static BOOL server_verify_callback_called = FALSE;
110static const uschar *sid_ctx = US"exim";
111
112/* We have three different contexts to care about.
113
114Simple case: client, `client_ctx`
115 As a client, we can be doing a callout or cut-through delivery while receiving
116 a message. So we have a client context, which should have options initialised
117 from the SMTP Transport.
118
119Server:
120 There are two cases: with and without ServerNameIndication from the client.
121 Given TLS SNI, we can be using different keys, certs and various other
122 configuration settings, because they're re-expanded with $tls_sni set. This
123 allows vhosting with TLS. This SNI is sent in the handshake.
124 A client might not send SNI, so we need a fallback, and an initial setup too.
125 So as a server, we start out using `server_ctx`.
126 If SNI is sent by the client, then we as server, mid-negotiation, try to clone
127 `server_sni` from `server_ctx` and then initialise settings by re-expanding
128 configuration.
129*/
130
131static SSL_CTX *client_ctx = NULL;
132static SSL_CTX *server_ctx = NULL;
133static SSL *client_ssl = NULL;
134static SSL *server_ssl = NULL;
135
136#ifdef EXIM_HAVE_OPENSSL_TLSEXT
137static SSL_CTX *server_sni = NULL;
138#endif
139
140static char ssl_errstring[256];
141
142static int ssl_session_timeout = 200;
143static BOOL client_verify_optional = FALSE;
144static BOOL server_verify_optional = FALSE;
145
146static BOOL reexpand_tls_files_for_sni = FALSE;
147
148
149typedef struct tls_ext_ctx_cb {
150 uschar *certificate;
151 uschar *privatekey;
152#ifndef DISABLE_OCSP
153 BOOL is_server;
154 union {
155 struct {
156 uschar *file;
157 uschar *file_expanded;
158 OCSP_RESPONSE *response;
159 } server;
160 struct {
161 X509_STORE *verify_store; /* non-null if status requested */
162 BOOL verify_required;
163 } client;
164 } u_ocsp;
165#endif
166 uschar *dhparam;
167 /* these are cached from first expand */
168 uschar *server_cipher_list;
169 /* only passed down to tls_error: */
170 host_item *host;
171 const uschar * verify_cert_hostnames;
172#ifndef DISABLE_EVENT
173 uschar * event_action;
174#endif
175} tls_ext_ctx_cb;
176
177/* should figure out a cleanup of API to handle state preserved per
178implementation, for various reasons, which can be void * in the APIs.
179For now, we hack around it. */
180tls_ext_ctx_cb *client_static_cbinfo = NULL;
181tls_ext_ctx_cb *server_static_cbinfo = NULL;
182
183static int
184setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
185 int (*cert_vfy_cb)(int, X509_STORE_CTX *) );
186
187/* Callbacks */
188#ifdef EXIM_HAVE_OPENSSL_TLSEXT
189static int tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg);
190#endif
191#ifndef DISABLE_OCSP
192static int tls_server_stapling_cb(SSL *s, void *arg);
193#endif
194
195
196/*************************************************
197* Handle TLS error *
198*************************************************/
199
200/* Called from lots of places when errors occur before actually starting to do
201the TLS handshake, that is, while the session is still in clear. Always returns
202DEFER for a server and FAIL for a client so that most calls can use "return
203tls_error(...)" to do this processing and then give an appropriate return. A
204single function is used for both server and client, because it is called from
205some shared functions.
206
207Argument:
208 prefix text to include in the logged error
209 host NULL if setting up a server;
210 the connected host if setting up a client
211 msg error message or NULL if we should ask OpenSSL
212
213Returns: OK/DEFER/FAIL
214*/
215
216static int
217tls_error(uschar * prefix, const host_item * host, uschar * msg)
218{
219if (!msg)
220 {
221 ERR_error_string(ERR_get_error(), ssl_errstring);
222 msg = (uschar *)ssl_errstring;
223 }
224
225if (host)
226 {
227 log_write(0, LOG_MAIN, "H=%s [%s] TLS error on connection (%s): %s",
228 host->name, host->address, prefix, msg);
229 return FAIL;
230 }
231else
232 {
233 uschar *conn_info = smtp_get_connection_info();
234 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
235 conn_info += 5;
236 /* I'd like to get separated H= here, but too hard for now */
237 log_write(0, LOG_MAIN, "TLS error on %s (%s): %s",
238 conn_info, prefix, msg);
239 return DEFER;
240 }
241}
242
243
244
245#ifdef EXIM_HAVE_EPHEM_RSA_KEX
246/*************************************************
247* Callback to generate RSA key *
248*************************************************/
249
250/*
251Arguments:
252 s SSL connection
253 export not used
254 keylength keylength
255
256Returns: pointer to generated key
257*/
258
259static RSA *
260rsa_callback(SSL *s, int export, int keylength)
261{
262RSA *rsa_key;
263#ifdef EXIM_HAVE_RSA_GENKEY_EX
264BIGNUM *bn = BN_new();
265#endif
266
267export = export; /* Shut picky compilers up */
268DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
269
270#ifdef EXIM_HAVE_RSA_GENKEY_EX
271if ( !BN_set_word(bn, (unsigned long)RSA_F4)
272 || !(rsa_key = RSA_new())
273 || !RSA_generate_key_ex(rsa_key, keylength, bn, NULL)
274 )
275#else
276rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL);
277if (rsa_key == NULL)
278#endif
279
280 {
281 ERR_error_string(ERR_get_error(), ssl_errstring);
282 log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
283 ssl_errstring);
284 return NULL;
285 }
286return rsa_key;
287}
288#endif
289
290
291
292/* Extreme debug
293#ifndef DISABLE_OCSP
294void
295x509_store_dump_cert_s_names(X509_STORE * store)
296{
297STACK_OF(X509_OBJECT) * roots= store->objs;
298int i;
299static uschar name[256];
300
301for(i= 0; i<sk_X509_OBJECT_num(roots); i++)
302 {
303 X509_OBJECT * tmp_obj= sk_X509_OBJECT_value(roots, i);
304 if(tmp_obj->type == X509_LU_X509)
305 {
306 X509 * current_cert= tmp_obj->data.x509;
307 X509_NAME_oneline(X509_get_subject_name(current_cert), CS name, sizeof(name));
308 name[sizeof(name)-1] = '\0';
309 debug_printf(" %s\n", name);
310 }
311 }
312}
313#endif
314*/
315
316
317#ifndef DISABLE_EVENT
318static int
319verify_event(tls_support * tlsp, X509 * cert, int depth, const uschar * dn,
320 BOOL *calledp, const BOOL *optionalp, const uschar * what)
321{
322uschar * ev;
323uschar * yield;
324X509 * old_cert;
325
326ev = tlsp == &tls_out ? client_static_cbinfo->event_action : event_action;
327if (ev)
328 {
329 DEBUG(D_tls) debug_printf("verify_event: %s %d\n", what, depth);
330 old_cert = tlsp->peercert;
331 tlsp->peercert = X509_dup(cert);
332 /* NB we do not bother setting peerdn */
333 if ((yield = event_raise(ev, US"tls:cert", string_sprintf("%d", depth))))
334 {
335 log_write(0, LOG_MAIN, "[%s] %s verify denied by event-action: "
336 "depth=%d cert=%s: %s",
337 tlsp == &tls_out ? deliver_host_address : sender_host_address,
338 what, depth, dn, yield);
339 *calledp = TRUE;
340 if (!*optionalp)
341 {
342 if (old_cert) tlsp->peercert = old_cert; /* restore 1st failing cert */
343 return 1; /* reject (leaving peercert set) */
344 }
345 DEBUG(D_tls) debug_printf("Event-action verify failure overridden "
346 "(host in tls_try_verify_hosts)\n");
347 }
348 X509_free(tlsp->peercert);
349 tlsp->peercert = old_cert;
350 }
351return 0;
352}
353#endif
354
355/*************************************************
356* Callback for verification *
357*************************************************/
358
359/* The SSL library does certificate verification if set up to do so. This
360callback has the current yes/no state is in "state". If verification succeeded,
361we set the certificate-verified flag. If verification failed, what happens
362depends on whether the client is required to present a verifiable certificate
363or not.
364
365If verification is optional, we change the state to yes, but still log the
366verification error. For some reason (it really would help to have proper
367documentation of OpenSSL), this callback function then gets called again, this
368time with state = 1. We must take care not to set the private verified flag on
369the second time through.
370
371Note: this function is not called if the client fails to present a certificate
372when asked. We get here only if a certificate has been received. Handling of
373optional verification for this case is done when requesting SSL to verify, by
374setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
375
376May be called multiple times for different issues with a certificate, even
377for a given "depth" in the certificate chain.
378
379Arguments:
380 preverify_ok current yes/no state as 1/0
381 x509ctx certificate information.
382 tlsp per-direction (client vs. server) support data
383 calledp has-been-called flag
384 optionalp verification-is-optional flag
385
386Returns: 0 if verification should fail, otherwise 1
387*/
388
389static int
390verify_callback(int preverify_ok, X509_STORE_CTX *x509ctx,
391 tls_support *tlsp, BOOL *calledp, BOOL *optionalp)
392{
393X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
394int depth = X509_STORE_CTX_get_error_depth(x509ctx);
395uschar dn[256];
396
397X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn));
398dn[sizeof(dn)-1] = '\0';
399
400if (preverify_ok == 0)
401 {
402 log_write(0, LOG_MAIN, "[%s] SSL verify error: depth=%d error=%s cert=%s",
403 tlsp == &tls_out ? deliver_host_address : sender_host_address,
404 depth,
405 X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509ctx)),
406 dn);
407 *calledp = TRUE;
408 if (!*optionalp)
409 {
410 if (!tlsp->peercert)
411 tlsp->peercert = X509_dup(cert); /* record failing cert */
412 return 0; /* reject */
413 }
414 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
415 "tls_try_verify_hosts)\n");
416 }
417
418else if (depth != 0)
419 {
420 DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d SN=%s\n", depth, dn);
421#ifndef DISABLE_OCSP
422 if (tlsp == &tls_out && client_static_cbinfo->u_ocsp.client.verify_store)
423 { /* client, wanting stapling */
424 /* Add the server cert's signing chain as the one
425 for the verification of the OCSP stapled information. */
426
427 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
428 cert))
429 ERR_clear_error();
430 }
431#endif
432#ifndef DISABLE_EVENT
433 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
434 return 0; /* reject, with peercert set */
435#endif
436 }
437else
438 {
439 const uschar * verify_cert_hostnames;
440
441 if ( tlsp == &tls_out
442 && ((verify_cert_hostnames = client_static_cbinfo->verify_cert_hostnames)))
443 /* client, wanting hostname check */
444 {
445
446#ifdef EXIM_HAVE_OPENSSL_CHECKHOST
447# ifndef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
448# define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0
449# endif
450# ifndef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
451# define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0
452# endif
453 int sep = 0;
454 const uschar * list = verify_cert_hostnames;
455 uschar * name;
456 int rc;
457 while ((name = string_nextinlist(&list, &sep, NULL, 0)))
458 if ((rc = X509_check_host(cert, CCS name, 0,
459 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
460 | X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS,
461 NULL)))
462 {
463 if (rc < 0)
464 {
465 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
466 tlsp == &tls_out ? deliver_host_address : sender_host_address);
467 name = NULL;
468 }
469 break;
470 }
471 if (!name)
472#else
473 if (!tls_is_name_for_cert(verify_cert_hostnames, cert))
474#endif
475 {
476 log_write(0, LOG_MAIN,
477 "[%s] SSL verify error: certificate name mismatch: \"%s\"",
478 tlsp == &tls_out ? deliver_host_address : sender_host_address,
479 dn);
480 *calledp = TRUE;
481 if (!*optionalp)
482 {
483 if (!tlsp->peercert)
484 tlsp->peercert = X509_dup(cert); /* record failing cert */
485 return 0; /* reject */
486 }
487 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
488 "tls_try_verify_hosts)\n");
489 }
490 }
491
492#ifndef DISABLE_EVENT
493 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
494 return 0; /* reject, with peercert set */
495#endif
496
497 DEBUG(D_tls) debug_printf("SSL%s verify ok: depth=0 SN=%s\n",
498 *calledp ? "" : " authenticated", dn);
499 if (!*calledp) tlsp->certificate_verified = TRUE;
500 *calledp = TRUE;
501 }
502
503return 1; /* accept, at least for this level */
504}
505
506static int
507verify_callback_client(int preverify_ok, X509_STORE_CTX *x509ctx)
508{
509return verify_callback(preverify_ok, x509ctx, &tls_out,
510 &client_verify_callback_called, &client_verify_optional);
511}
512
513static int
514verify_callback_server(int preverify_ok, X509_STORE_CTX *x509ctx)
515{
516return verify_callback(preverify_ok, x509ctx, &tls_in,
517 &server_verify_callback_called, &server_verify_optional);
518}
519
520
521#ifdef EXPERIMENTAL_DANE
522
523/* This gets called *by* the dane library verify callback, which interposes
524itself.
525*/
526static int
527verify_callback_client_dane(int preverify_ok, X509_STORE_CTX * x509ctx)
528{
529X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
530uschar dn[256];
531#ifndef DISABLE_EVENT
532int depth = X509_STORE_CTX_get_error_depth(x509ctx);
533BOOL dummy_called, optional = FALSE;
534#endif
535
536X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn));
537dn[sizeof(dn)-1] = '\0';
538
539DEBUG(D_tls) debug_printf("verify_callback_client_dane: %s depth %d %s\n",
540 preverify_ok ? "ok":"BAD", depth, dn);
541
542#ifndef DISABLE_EVENT
543 if (verify_event(&tls_out, cert, depth, dn,
544 &dummy_called, &optional, US"DANE"))
545 return 0; /* reject, with peercert set */
546#endif
547
548if (preverify_ok == 1)
549 tls_out.dane_verified =
550 tls_out.certificate_verified = TRUE;
551else
552 {
553 int err = X509_STORE_CTX_get_error(x509ctx);
554 DEBUG(D_tls)
555 debug_printf(" - err %d '%s'\n", err, X509_verify_cert_error_string(err));
556 if (err == X509_V_ERR_APPLICATION_VERIFICATION)
557 preverify_ok = 1;
558 }
559return preverify_ok;
560}
561
562#endif /*EXPERIMENTAL_DANE*/
563
564
565/*************************************************
566* Information callback *
567*************************************************/
568
569/* The SSL library functions call this from time to time to indicate what they
570are doing. We copy the string to the debugging output when TLS debugging has
571been requested.
572
573Arguments:
574 s the SSL connection
575 where
576 ret
577
578Returns: nothing
579*/
580
581static void
582info_callback(SSL *s, int where, int ret)
583{
584where = where;
585ret = ret;
586DEBUG(D_tls) debug_printf("SSL info: %s\n", SSL_state_string_long(s));
587}
588
589
590
591/*************************************************
592* Initialize for DH *
593*************************************************/
594
595/* If dhparam is set, expand it, and load up the parameters for DH encryption.
596
597Arguments:
598 sctx The current SSL CTX (inbound or outbound)
599 dhparam DH parameter file or fixed parameter identity string
600 host connected host, if client; NULL if server
601
602Returns: TRUE if OK (nothing to set up, or setup worked)
603*/
604
605static BOOL
606init_dh(SSL_CTX *sctx, uschar *dhparam, const host_item *host)
607{
608BIO *bio;
609DH *dh;
610uschar *dhexpanded;
611const char *pem;
612
613if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded))
614 return FALSE;
615
616if (!dhexpanded || !*dhexpanded)
617 bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
618else if (dhexpanded[0] == '/')
619 {
620 if (!(bio = BIO_new_file(CS dhexpanded, "r")))
621 {
622 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
623 host, US strerror(errno));
624 return FALSE;
625 }
626 }
627else
628 {
629 if (Ustrcmp(dhexpanded, "none") == 0)
630 {
631 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
632 return TRUE;
633 }
634
635 if (!(pem = std_dh_prime_named(dhexpanded)))
636 {
637 tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
638 host, US strerror(errno));
639 return FALSE;
640 }
641 bio = BIO_new_mem_buf(CS pem, -1);
642 }
643
644if (!(dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)))
645 {
646 BIO_free(bio);
647 tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
648 host, NULL);
649 return FALSE;
650 }
651
652/* Even if it is larger, we silently return success rather than cause things
653 * to fail out, so that a too-large DH will not knock out all TLS; it's a
654 * debatable choice. */
655if ((8*DH_size(dh)) > tls_dh_max_bits)
656 {
657 DEBUG(D_tls)
658 debug_printf("dhparams file %d bits, is > tls_dh_max_bits limit of %d",
659 8*DH_size(dh), tls_dh_max_bits);
660 }
661else
662 {
663 SSL_CTX_set_tmp_dh(sctx, dh);
664 DEBUG(D_tls)
665 debug_printf("Diffie-Hellman initialized from %s with %d-bit prime\n",
666 dhexpanded ? dhexpanded : US"default", 8*DH_size(dh));
667 }
668
669DH_free(dh);
670BIO_free(bio);
671
672return TRUE;
673}
674
675
676
677
678/*************************************************
679* Initialize for ECDH *
680*************************************************/
681
682/* Load parameters for ECDH encryption.
683
684For now, we stick to NIST P-256 because: it's simple and easy to configure;
685it avoids any patent issues that might bite redistributors; despite events in
686the news and concerns over curve choices, we're not cryptographers, we're not
687pretending to be, and this is "good enough" to be better than no support,
688protecting against most adversaries. Given another year or two, there might
689be sufficient clarity about a "right" way forward to let us make an informed
690decision, instead of a knee-jerk reaction.
691
692Longer-term, we should look at supporting both various named curves and
693external files generated with "openssl ecparam", much as we do for init_dh().
694We should also support "none" as a value, to explicitly avoid initialisation.
695
696Patches welcome.
697
698Arguments:
699 sctx The current SSL CTX (inbound or outbound)
700 host connected host, if client; NULL if server
701
702Returns: TRUE if OK (nothing to set up, or setup worked)
703*/
704
705static BOOL
706init_ecdh(SSL_CTX * sctx, host_item * host)
707{
708#ifdef OPENSSL_NO_ECDH
709return TRUE;
710#else
711
712EC_KEY * ecdh;
713uschar * exp_curve;
714int nid;
715BOOL rv;
716
717if (host) /* No ECDH setup for clients, only for servers */
718 return TRUE;
719
720# ifndef EXIM_HAVE_ECDH
721DEBUG(D_tls)
722 debug_printf("No OpenSSL API to define ECDH parameters, skipping\n");
723return TRUE;
724# else
725
726if (!expand_check(tls_eccurve, US"tls_eccurve", &exp_curve))
727 return FALSE;
728if (!exp_curve || !*exp_curve)
729 return TRUE;
730
731# ifdef EXIM_HAVE_OPENSSL_ECDH_AUTO
732/* check if new enough library to support auto ECDH temp key parameter selection */
733if (Ustrcmp(exp_curve, "auto") == 0)
734 {
735 DEBUG(D_tls) debug_printf(
736 "ECDH temp key parameter settings: OpenSSL 1.2+ autoselection\n");
737 SSL_CTX_set_ecdh_auto(sctx, 1);
738 return TRUE;
739 }
740# endif
741
742DEBUG(D_tls) debug_printf("ECDH: curve '%s'\n", exp_curve);
743if ( (nid = OBJ_sn2nid (CCS exp_curve)) == NID_undef
744# ifdef EXIM_HAVE_OPENSSL_EC_NIST2NID
745 && (nid = EC_curve_nist2nid(CCS exp_curve)) == NID_undef
746# endif
747 )
748 {
749 tls_error(string_sprintf("Unknown curve name tls_eccurve '%s'",
750 exp_curve),
751 host, NULL);
752 return FALSE;
753 }
754
755if (!(ecdh = EC_KEY_new_by_curve_name(nid)))
756 {
757 tls_error(US"Unable to create ec curve", host, NULL);
758 return FALSE;
759 }
760
761/* The "tmp" in the name here refers to setting a temporary key
762not to the stability of the interface. */
763
764if ((rv = SSL_CTX_set_tmp_ecdh(sctx, ecdh) == 0))
765 tls_error(string_sprintf("Error enabling '%s' curve", exp_curve), host, NULL);
766else
767 DEBUG(D_tls) debug_printf("ECDH: enabled '%s' curve\n", exp_curve);
768
769EC_KEY_free(ecdh);
770return !rv;
771
772# endif /*EXIM_HAVE_ECDH*/
773#endif /*OPENSSL_NO_ECDH*/
774}
775
776
777
778
779#ifndef DISABLE_OCSP
780/*************************************************
781* Load OCSP information into state *
782*************************************************/
783
784/* Called to load the server OCSP response from the given file into memory, once
785caller has determined this is needed. Checks validity. Debugs a message
786if invalid.
787
788ASSUMES: single response, for single cert.
789
790Arguments:
791 sctx the SSL_CTX* to update
792 cbinfo various parts of session state
793 expanded the filename putatively holding an OCSP response
794
795*/
796
797static void
798ocsp_load_response(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo, const uschar *expanded)
799{
800BIO *bio;
801OCSP_RESPONSE *resp;
802OCSP_BASICRESP *basic_response;
803OCSP_SINGLERESP *single_response;
804ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
805X509_STORE *store;
806unsigned long verify_flags;
807int status, reason, i;
808
809cbinfo->u_ocsp.server.file_expanded = string_copy(expanded);
810if (cbinfo->u_ocsp.server.response)
811 {
812 OCSP_RESPONSE_free(cbinfo->u_ocsp.server.response);
813 cbinfo->u_ocsp.server.response = NULL;
814 }
815
816bio = BIO_new_file(CS cbinfo->u_ocsp.server.file_expanded, "rb");
817if (!bio)
818 {
819 DEBUG(D_tls) debug_printf("Failed to open OCSP response file \"%s\"\n",
820 cbinfo->u_ocsp.server.file_expanded);
821 return;
822 }
823
824resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
825BIO_free(bio);
826if (!resp)
827 {
828 DEBUG(D_tls) debug_printf("Error reading OCSP response.\n");
829 return;
830 }
831
832status = OCSP_response_status(resp);
833if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL)
834 {
835 DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n",
836 OCSP_response_status_str(status), status);
837 goto bad;
838 }
839
840basic_response = OCSP_response_get1_basic(resp);
841if (!basic_response)
842 {
843 DEBUG(D_tls)
844 debug_printf("OCSP response parse error: unable to extract basic response.\n");
845 goto bad;
846 }
847
848store = SSL_CTX_get_cert_store(sctx);
849verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */
850
851/* May need to expose ability to adjust those flags?
852OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
853OCSP_TRUSTOTHER OCSP_NOINTERN */
854
855i = OCSP_basic_verify(basic_response, NULL, store, verify_flags);
856if (i <= 0)
857 {
858 DEBUG(D_tls) {
859 ERR_error_string(ERR_get_error(), ssl_errstring);
860 debug_printf("OCSP response verify failure: %s\n", US ssl_errstring);
861 }
862 goto bad;
863 }
864
865/* Here's the simplifying assumption: there's only one response, for the
866one certificate we use, and nothing for anything else in a chain. If this
867proves false, we need to extract a cert id from our issued cert
868(tls_certificate) and use that for OCSP_resp_find_status() (which finds the
869right cert in the stack and then calls OCSP_single_get0_status()).
870
871I'm hoping to avoid reworking a bunch more of how we handle state here. */
872single_response = OCSP_resp_get0(basic_response, 0);
873if (!single_response)
874 {
875 DEBUG(D_tls)
876 debug_printf("Unable to get first response from OCSP basic response.\n");
877 goto bad;
878 }
879
880status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
881if (status != V_OCSP_CERTSTATUS_GOOD)
882 {
883 DEBUG(D_tls) debug_printf("OCSP response bad cert status: %s (%d) %s (%d)\n",
884 OCSP_cert_status_str(status), status,
885 OCSP_crl_reason_str(reason), reason);
886 goto bad;
887 }
888
889if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
890 {
891 DEBUG(D_tls) debug_printf("OCSP status invalid times.\n");
892 goto bad;
893 }
894
895supply_response:
896 cbinfo->u_ocsp.server.response = resp;
897return;
898
899bad:
900 if (running_in_test_harness)
901 {
902 extern char ** environ;
903 uschar ** p;
904 if (environ) for (p = USS environ; *p != NULL; p++)
905 if (Ustrncmp(*p, "EXIM_TESTHARNESS_DISABLE_OCSPVALIDITYCHECK", 42) == 0)
906 {
907 DEBUG(D_tls) debug_printf("Supplying known bad OCSP response\n");
908 goto supply_response;
909 }
910 }
911return;
912}
913#endif /*!DISABLE_OCSP*/
914
915
916
917
918/*************************************************
919* Expand key and cert file specs *
920*************************************************/
921
922/* Called once during tls_init and possibly again during TLS setup, for a
923new context, if Server Name Indication was used and tls_sni was seen in
924the certificate string.
925
926Arguments:
927 sctx the SSL_CTX* to update
928 cbinfo various parts of session state
929
930Returns: OK/DEFER/FAIL
931*/
932
933static int
934tls_expand_session_files(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo)
935{
936uschar *expanded;
937
938if (cbinfo->certificate == NULL)
939 return OK;
940
941if (Ustrstr(cbinfo->certificate, US"tls_sni") ||
942 Ustrstr(cbinfo->certificate, US"tls_in_sni") ||
943 Ustrstr(cbinfo->certificate, US"tls_out_sni")
944 )
945 reexpand_tls_files_for_sni = TRUE;
946
947if (!expand_check(cbinfo->certificate, US"tls_certificate", &expanded))
948 return DEFER;
949
950if (expanded != NULL)
951 {
952 DEBUG(D_tls) debug_printf("tls_certificate file %s\n", expanded);
953 if (!SSL_CTX_use_certificate_chain_file(sctx, CS expanded))
954 return tls_error(string_sprintf(
955 "SSL_CTX_use_certificate_chain_file file=%s", expanded),
956 cbinfo->host, NULL);
957 }
958
959if (cbinfo->privatekey != NULL &&
960 !expand_check(cbinfo->privatekey, US"tls_privatekey", &expanded))
961 return DEFER;
962
963/* If expansion was forced to fail, key_expanded will be NULL. If the result
964of the expansion is an empty string, ignore it also, and assume the private
965key is in the same file as the certificate. */
966
967if (expanded && *expanded)
968 {
969 DEBUG(D_tls) debug_printf("tls_privatekey file %s\n", expanded);
970 if (!SSL_CTX_use_PrivateKey_file(sctx, CS expanded, SSL_FILETYPE_PEM))
971 return tls_error(string_sprintf(
972 "SSL_CTX_use_PrivateKey_file file=%s", expanded), cbinfo->host, NULL);
973 }
974
975#ifndef DISABLE_OCSP
976if (cbinfo->is_server && cbinfo->u_ocsp.server.file)
977 {
978 if (!expand_check(cbinfo->u_ocsp.server.file, US"tls_ocsp_file", &expanded))
979 return DEFER;
980
981 if (expanded && *expanded)
982 {
983 DEBUG(D_tls) debug_printf("tls_ocsp_file %s\n", expanded);
984 if ( cbinfo->u_ocsp.server.file_expanded
985 && (Ustrcmp(expanded, cbinfo->u_ocsp.server.file_expanded) == 0))
986 {
987 DEBUG(D_tls) debug_printf(" - value unchanged, using existing values\n");
988 }
989 else
990 {
991 ocsp_load_response(sctx, cbinfo, expanded);
992 }
993 }
994 }
995#endif
996
997return OK;
998}
999
1000
1001
1002
1003/*************************************************
1004* Callback to handle SNI *
1005*************************************************/
1006
1007/* Called when acting as server during the TLS session setup if a Server Name
1008Indication extension was sent by the client.
1009
1010API documentation is OpenSSL s_server.c implementation.
1011
1012Arguments:
1013 s SSL* of the current session
1014 ad unknown (part of OpenSSL API) (unused)
1015 arg Callback of "our" registered data
1016
1017Returns: SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
1018*/
1019
1020#ifdef EXIM_HAVE_OPENSSL_TLSEXT
1021static int
1022tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg)
1023{
1024const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1025tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1026int rc;
1027int old_pool = store_pool;
1028
1029if (!servername)
1030 return SSL_TLSEXT_ERR_OK;
1031
1032DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
1033 reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
1034
1035/* Make the extension value available for expansion */
1036store_pool = POOL_PERM;
1037tls_in.sni = string_copy(US servername);
1038store_pool = old_pool;
1039
1040if (!reexpand_tls_files_for_sni)
1041 return SSL_TLSEXT_ERR_OK;
1042
1043/* Can't find an SSL_CTX_clone() or equivalent, so we do it manually;
1044not confident that memcpy wouldn't break some internal reference counting.
1045Especially since there's a references struct member, which would be off. */
1046
1047if (!(server_sni = SSL_CTX_new(SSLv23_server_method())))
1048 {
1049 ERR_error_string(ERR_get_error(), ssl_errstring);
1050 DEBUG(D_tls) debug_printf("SSL_CTX_new() failed: %s\n", ssl_errstring);
1051 return SSL_TLSEXT_ERR_NOACK;
1052 }
1053
1054/* Not sure how many of these are actually needed, since SSL object
1055already exists. Might even need this selfsame callback, for reneg? */
1056
1057SSL_CTX_set_info_callback(server_sni, SSL_CTX_get_info_callback(server_ctx));
1058SSL_CTX_set_mode(server_sni, SSL_CTX_get_mode(server_ctx));
1059SSL_CTX_set_options(server_sni, SSL_CTX_get_options(server_ctx));
1060SSL_CTX_set_timeout(server_sni, SSL_CTX_get_timeout(server_ctx));
1061SSL_CTX_set_tlsext_servername_callback(server_sni, tls_servername_cb);
1062SSL_CTX_set_tlsext_servername_arg(server_sni, cbinfo);
1063
1064if ( !init_dh(server_sni, cbinfo->dhparam, NULL)
1065 || !init_ecdh(server_sni, NULL)
1066 )
1067 return SSL_TLSEXT_ERR_NOACK;
1068
1069if (cbinfo->server_cipher_list)
1070 SSL_CTX_set_cipher_list(server_sni, CS cbinfo->server_cipher_list);
1071#ifndef DISABLE_OCSP
1072if (cbinfo->u_ocsp.server.file)
1073 {
1074 SSL_CTX_set_tlsext_status_cb(server_sni, tls_server_stapling_cb);
1075 SSL_CTX_set_tlsext_status_arg(server_sni, cbinfo);
1076 }
1077#endif
1078
1079rc = setup_certs(server_sni, tls_verify_certificates, tls_crl, NULL, FALSE, verify_callback_server);
1080if (rc != OK) return SSL_TLSEXT_ERR_NOACK;
1081
1082/* do this after setup_certs, because this can require the certs for verifying
1083OCSP information. */
1084if ((rc = tls_expand_session_files(server_sni, cbinfo)) != OK)
1085 return SSL_TLSEXT_ERR_NOACK;
1086
1087DEBUG(D_tls) debug_printf("Switching SSL context.\n");
1088SSL_set_SSL_CTX(s, server_sni);
1089
1090return SSL_TLSEXT_ERR_OK;
1091}
1092#endif /* EXIM_HAVE_OPENSSL_TLSEXT */
1093
1094
1095
1096
1097#ifndef DISABLE_OCSP
1098
1099/*************************************************
1100* Callback to handle OCSP Stapling *
1101*************************************************/
1102
1103/* Called when acting as server during the TLS session setup if the client
1104requests OCSP information with a Certificate Status Request.
1105
1106Documentation via openssl s_server.c and the Apache patch from the OpenSSL
1107project.
1108
1109*/
1110
1111static int
1112tls_server_stapling_cb(SSL *s, void *arg)
1113{
1114const tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1115uschar *response_der;
1116int response_der_len;
1117
1118DEBUG(D_tls)
1119 debug_printf("Received TLS status request (OCSP stapling); %s response\n",
1120 cbinfo->u_ocsp.server.response ? "have" : "lack");
1121
1122tls_in.ocsp = OCSP_NOT_RESP;
1123if (!cbinfo->u_ocsp.server.response)
1124 return SSL_TLSEXT_ERR_NOACK;
1125
1126response_der = NULL;
1127response_der_len = i2d_OCSP_RESPONSE(cbinfo->u_ocsp.server.response,
1128 &response_der);
1129if (response_der_len <= 0)
1130 return SSL_TLSEXT_ERR_NOACK;
1131
1132SSL_set_tlsext_status_ocsp_resp(server_ssl, response_der, response_der_len);
1133tls_in.ocsp = OCSP_VFIED;
1134return SSL_TLSEXT_ERR_OK;
1135}
1136
1137
1138static void
1139time_print(BIO * bp, const char * str, ASN1_GENERALIZEDTIME * time)
1140{
1141BIO_printf(bp, "\t%s: ", str);
1142ASN1_GENERALIZEDTIME_print(bp, time);
1143BIO_puts(bp, "\n");
1144}
1145
1146static int
1147tls_client_stapling_cb(SSL *s, void *arg)
1148{
1149tls_ext_ctx_cb * cbinfo = arg;
1150const unsigned char * p;
1151int len;
1152OCSP_RESPONSE * rsp;
1153OCSP_BASICRESP * bs;
1154int i;
1155
1156DEBUG(D_tls) debug_printf("Received TLS status response (OCSP stapling):");
1157len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1158if(!p)
1159 {
1160 /* Expect this when we requested ocsp but got none */
1161 if (cbinfo->u_ocsp.client.verify_required && LOGGING(tls_cipher))
1162 log_write(0, LOG_MAIN, "Received TLS status callback, null content");
1163 else
1164 DEBUG(D_tls) debug_printf(" null\n");
1165 return cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1166 }
1167
1168if(!(rsp = d2i_OCSP_RESPONSE(NULL, &p, len)))
1169 {
1170 tls_out.ocsp = OCSP_FAILED;
1171 if (LOGGING(tls_cipher))
1172 log_write(0, LOG_MAIN, "Received TLS cert status response, parse error");
1173 else
1174 DEBUG(D_tls) debug_printf(" parse error\n");
1175 return 0;
1176 }
1177
1178if(!(bs = OCSP_response_get1_basic(rsp)))
1179 {
1180 tls_out.ocsp = OCSP_FAILED;
1181 if (LOGGING(tls_cipher))
1182 log_write(0, LOG_MAIN, "Received TLS cert status response, error parsing response");
1183 else
1184 DEBUG(D_tls) debug_printf(" error parsing response\n");
1185 OCSP_RESPONSE_free(rsp);
1186 return 0;
1187 }
1188
1189/* We'd check the nonce here if we'd put one in the request. */
1190/* However that would defeat cacheability on the server so we don't. */
1191
1192/* This section of code reworked from OpenSSL apps source;
1193 The OpenSSL Project retains copyright:
1194 Copyright (c) 1999 The OpenSSL Project. All rights reserved.
1195*/
1196 {
1197 BIO * bp = NULL;
1198 int status, reason;
1199 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1200
1201 DEBUG(D_tls) bp = BIO_new_fp(stderr, BIO_NOCLOSE);
1202
1203 /*OCSP_RESPONSE_print(bp, rsp, 0); extreme debug: stapling content */
1204
1205 /* Use the chain that verified the server cert to verify the stapled info */
1206 /* DEBUG(D_tls) x509_store_dump_cert_s_names(cbinfo->u_ocsp.client.verify_store); */
1207
1208 if ((i = OCSP_basic_verify(bs, NULL,
1209 cbinfo->u_ocsp.client.verify_store, 0)) <= 0)
1210 {
1211 tls_out.ocsp = OCSP_FAILED;
1212 if (LOGGING(tls_cipher))
1213 log_write(0, LOG_MAIN, "Received TLS cert status response, itself unverifiable");
1214 BIO_printf(bp, "OCSP response verify failure\n");
1215 ERR_print_errors(bp);
1216 goto failed;
1217 }
1218
1219 BIO_printf(bp, "OCSP response well-formed and signed OK\n");
1220
1221 /*XXX So we have a good stapled OCSP status. How do we know
1222 it is for the cert of interest? OpenSSL 1.1.0 has a routine
1223 OCSP_resp_find_status() which matches on a cert id, which presumably
1224 we should use. Making an id needs OCSP_cert_id_new(), which takes
1225 issuerName, issuerKey, serialNumber. Are they all in the cert?
1226
1227 For now, carry on blindly accepting the resp. */
1228
1229 {
1230 OCSP_SINGLERESP * single;
1231
1232#ifdef EXIM_HAVE_OCSP_RESP_COUNT
1233 if (OCSP_resp_count(bs) != 1)
1234#else
1235 STACK_OF(OCSP_SINGLERESP) * sresp = bs->tbsResponseData->responses;
1236 if (sk_OCSP_SINGLERESP_num(sresp) != 1)
1237#endif
1238 {
1239 tls_out.ocsp = OCSP_FAILED;
1240 log_write(0, LOG_MAIN, "OCSP stapling "
1241 "with multiple responses not handled");
1242 goto failed;
1243 }
1244 single = OCSP_resp_get0(bs, 0);
1245 status = OCSP_single_get0_status(single, &reason, &rev,
1246 &thisupd, &nextupd);
1247 }
1248
1249 DEBUG(D_tls) time_print(bp, "This OCSP Update", thisupd);
1250 DEBUG(D_tls) if(nextupd) time_print(bp, "Next OCSP Update", nextupd);
1251 if (!OCSP_check_validity(thisupd, nextupd,
1252 EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1253 {
1254 tls_out.ocsp = OCSP_FAILED;
1255 DEBUG(D_tls) ERR_print_errors(bp);
1256 log_write(0, LOG_MAIN, "Server OSCP dates invalid");
1257 }
1258 else
1259 {
1260 DEBUG(D_tls) BIO_printf(bp, "Certificate status: %s\n",
1261 OCSP_cert_status_str(status));
1262 switch(status)
1263 {
1264 case V_OCSP_CERTSTATUS_GOOD:
1265 tls_out.ocsp = OCSP_VFIED;
1266 i = 1;
1267 goto good;
1268 case V_OCSP_CERTSTATUS_REVOKED:
1269 tls_out.ocsp = OCSP_FAILED;
1270 log_write(0, LOG_MAIN, "Server certificate revoked%s%s",
1271 reason != -1 ? "; reason: " : "",
1272 reason != -1 ? OCSP_crl_reason_str(reason) : "");
1273 DEBUG(D_tls) time_print(bp, "Revocation Time", rev);
1274 break;
1275 default:
1276 tls_out.ocsp = OCSP_FAILED;
1277 log_write(0, LOG_MAIN,
1278 "Server certificate status unknown, in OCSP stapling");
1279 break;
1280 }
1281 }
1282 failed:
1283 i = cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1284 good:
1285 BIO_free(bp);
1286 }
1287
1288OCSP_RESPONSE_free(rsp);
1289return i;
1290}
1291#endif /*!DISABLE_OCSP*/
1292
1293
1294/*************************************************
1295* Initialize for TLS *
1296*************************************************/
1297
1298/* Called from both server and client code, to do preliminary initialization
1299of the library. We allocate and return a context structure.
1300
1301Arguments:
1302 ctxp returned SSL context
1303 host connected host, if client; NULL if server
1304 dhparam DH parameter file
1305 certificate certificate file
1306 privatekey private key
1307 ocsp_file file of stapling info (server); flag for require ocsp (client)
1308 addr address if client; NULL if server (for some randomness)
1309 cbp place to put allocated callback context
1310
1311Returns: OK/DEFER/FAIL
1312*/
1313
1314static int
1315tls_init(SSL_CTX **ctxp, host_item *host, uschar *dhparam, uschar *certificate,
1316 uschar *privatekey,
1317#ifndef DISABLE_OCSP
1318 uschar *ocsp_file,
1319#endif
1320 address_item *addr, tls_ext_ctx_cb ** cbp)
1321{
1322long init_options;
1323int rc;
1324BOOL okay;
1325tls_ext_ctx_cb * cbinfo;
1326
1327cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
1328cbinfo->certificate = certificate;
1329cbinfo->privatekey = privatekey;
1330#ifndef DISABLE_OCSP
1331if ((cbinfo->is_server = host==NULL))
1332 {
1333 cbinfo->u_ocsp.server.file = ocsp_file;
1334 cbinfo->u_ocsp.server.file_expanded = NULL;
1335 cbinfo->u_ocsp.server.response = NULL;
1336 }
1337else
1338 cbinfo->u_ocsp.client.verify_store = NULL;
1339#endif
1340cbinfo->dhparam = dhparam;
1341cbinfo->server_cipher_list = NULL;
1342cbinfo->host = host;
1343#ifndef DISABLE_EVENT
1344cbinfo->event_action = NULL;
1345#endif
1346
1347SSL_load_error_strings(); /* basic set up */
1348OpenSSL_add_ssl_algorithms();
1349
1350#ifdef EXIM_HAVE_SHA256
1351/* SHA256 is becoming ever more popular. This makes sure it gets added to the
1352list of available digests. */
1353EVP_add_digest(EVP_sha256());
1354#endif
1355
1356/* Create a context.
1357The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
1358negotiation in the different methods; as far as I can tell, the only
1359*_{server,client}_method which allows negotiation is SSLv23, which exists even
1360when OpenSSL is built without SSLv2 support.
1361By disabling with openssl_options, we can let admins re-enable with the
1362existing knob. */
1363
1364*ctxp = SSL_CTX_new(host ? SSLv23_client_method() : SSLv23_server_method());
1365
1366if (!*ctxp) return tls_error(US"SSL_CTX_new", host, NULL);
1367
1368/* It turns out that we need to seed the random number generator this early in
1369order to get the full complement of ciphers to work. It took me roughly a day
1370of work to discover this by experiment.
1371
1372On systems that have /dev/urandom, SSL may automatically seed itself from
1373there. Otherwise, we have to make something up as best we can. Double check
1374afterwards. */
1375
1376if (!RAND_status())
1377 {
1378 randstuff r;
1379 gettimeofday(&r.tv, NULL);
1380 r.p = getpid();
1381
1382 RAND_seed((uschar *)(&r), sizeof(r));
1383 RAND_seed((uschar *)big_buffer, big_buffer_size);
1384 if (addr != NULL) RAND_seed((uschar *)addr, sizeof(addr));
1385
1386 if (!RAND_status())
1387 return tls_error(US"RAND_status", host,
1388 US"unable to seed random number generator");
1389 }
1390
1391/* Set up the information callback, which outputs if debugging is at a suitable
1392level. */
1393
1394DEBUG(D_tls) SSL_CTX_set_info_callback(*ctxp, (void (*)())info_callback);
1395
1396/* Automatically re-try reads/writes after renegotiation. */
1397(void) SSL_CTX_set_mode(*ctxp, SSL_MODE_AUTO_RETRY);
1398
1399/* Apply administrator-supplied work-arounds.
1400Historically we applied just one requested option,
1401SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
1402moved to an administrator-controlled list of options to specify and
1403grandfathered in the first one as the default value for "openssl_options".
1404
1405No OpenSSL version number checks: the options we accept depend upon the
1406availability of the option value macros from OpenSSL. */
1407
1408okay = tls_openssl_options_parse(openssl_options, &init_options);
1409if (!okay)
1410 return tls_error(US"openssl_options parsing failed", host, NULL);
1411
1412if (init_options)
1413 {
1414 DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
1415 if (!(SSL_CTX_set_options(*ctxp, init_options)))
1416 return tls_error(string_sprintf(
1417 "SSL_CTX_set_option(%#lx)", init_options), host, NULL);
1418 }
1419else
1420 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
1421
1422/* Initialize with DH parameters if supplied */
1423/* Initialize ECDH temp key parameter selection */
1424
1425if ( !init_dh(*ctxp, dhparam, host)
1426 || !init_ecdh(*ctxp, host)
1427 )
1428 return DEFER;
1429
1430/* Set up certificate and key (and perhaps OCSP info) */
1431
1432rc = tls_expand_session_files(*ctxp, cbinfo);
1433if (rc != OK) return rc;
1434
1435/* If we need to handle SNI, do so */
1436#ifdef EXIM_HAVE_OPENSSL_TLSEXT
1437if (host == NULL) /* server */
1438 {
1439# ifndef DISABLE_OCSP
1440 /* We check u_ocsp.server.file, not server.response, because we care about if
1441 the option exists, not what the current expansion might be, as SNI might
1442 change the certificate and OCSP file in use between now and the time the
1443 callback is invoked. */
1444 if (cbinfo->u_ocsp.server.file)
1445 {
1446 SSL_CTX_set_tlsext_status_cb(server_ctx, tls_server_stapling_cb);
1447 SSL_CTX_set_tlsext_status_arg(server_ctx, cbinfo);
1448 }
1449# endif
1450 /* We always do this, so that $tls_sni is available even if not used in
1451 tls_certificate */
1452 SSL_CTX_set_tlsext_servername_callback(*ctxp, tls_servername_cb);
1453 SSL_CTX_set_tlsext_servername_arg(*ctxp, cbinfo);
1454 }
1455# ifndef DISABLE_OCSP
1456else /* client */
1457 if(ocsp_file) /* wanting stapling */
1458 {
1459 if (!(cbinfo->u_ocsp.client.verify_store = X509_STORE_new()))
1460 {
1461 DEBUG(D_tls) debug_printf("failed to create store for stapling verify\n");
1462 return FAIL;
1463 }
1464 SSL_CTX_set_tlsext_status_cb(*ctxp, tls_client_stapling_cb);
1465 SSL_CTX_set_tlsext_status_arg(*ctxp, cbinfo);
1466 }
1467# endif
1468#endif
1469
1470cbinfo->verify_cert_hostnames = NULL;
1471
1472#ifdef EXIM_HAVE_EPHEM_RSA_KEX
1473/* Set up the RSA callback */
1474SSL_CTX_set_tmp_rsa_callback(*ctxp, rsa_callback);
1475#endif
1476
1477/* Finally, set the timeout, and we are done */
1478
1479SSL_CTX_set_timeout(*ctxp, ssl_session_timeout);
1480DEBUG(D_tls) debug_printf("Initialized TLS\n");
1481
1482*cbp = cbinfo;
1483
1484return OK;
1485}
1486
1487
1488
1489
1490/*************************************************
1491* Get name of cipher in use *
1492*************************************************/
1493
1494/*
1495Argument: pointer to an SSL structure for the connection
1496 buffer to use for answer
1497 size of buffer
1498 pointer to number of bits for cipher
1499Returns: nothing
1500*/
1501
1502static void
1503construct_cipher_name(SSL *ssl, uschar *cipherbuf, int bsize, int *bits)
1504{
1505/* With OpenSSL 1.0.0a, this needs to be const but the documentation doesn't
1506yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
1507the accessor functions use const in the prototype. */
1508const SSL_CIPHER *c;
1509const uschar *ver;
1510
1511ver = (const uschar *)SSL_get_version(ssl);
1512
1513c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
1514SSL_CIPHER_get_bits(c, bits);
1515
1516string_format(cipherbuf, bsize, "%s:%s:%u", ver,
1517 SSL_CIPHER_get_name(c), *bits);
1518
1519DEBUG(D_tls) debug_printf("Cipher: %s\n", cipherbuf);
1520}
1521
1522
1523static void
1524peer_cert(SSL * ssl, tls_support * tlsp, uschar * peerdn, unsigned bsize)
1525{
1526/*XXX we might consider a list-of-certs variable for the cert chain.
1527SSL_get_peer_cert_chain(SSL*). We'd need a new variable type and support
1528in list-handling functions, also consider the difference between the entire
1529chain and the elements sent by the peer. */
1530
1531/* Will have already noted peercert on a verify fail; possibly not the leaf */
1532if (!tlsp->peercert)
1533 tlsp->peercert = SSL_get_peer_certificate(ssl);
1534/* Beware anonymous ciphers which lead to server_cert being NULL */
1535if (tlsp->peercert)
1536 {
1537 X509_NAME_oneline(X509_get_subject_name(tlsp->peercert), CS peerdn, bsize);
1538 peerdn[bsize-1] = '\0';
1539 tlsp->peerdn = peerdn; /*XXX a static buffer... */
1540 }
1541else
1542 tlsp->peerdn = NULL;
1543}
1544
1545
1546
1547
1548
1549/*************************************************
1550* Set up for verifying certificates *
1551*************************************************/
1552
1553/* Called by both client and server startup
1554
1555Arguments:
1556 sctx SSL_CTX* to initialise
1557 certs certs file or NULL
1558 crl CRL file or NULL
1559 host NULL in a server; the remote host in a client
1560 optional TRUE if called from a server for a host in tls_try_verify_hosts;
1561 otherwise passed as FALSE
1562 cert_vfy_cb Callback function for certificate verification
1563
1564Returns: OK/DEFER/FAIL
1565*/
1566
1567static int
1568setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
1569 int (*cert_vfy_cb)(int, X509_STORE_CTX *) )
1570{
1571uschar *expcerts, *expcrl;
1572
1573if (!expand_check(certs, US"tls_verify_certificates", &expcerts))
1574 return DEFER;
1575
1576if (expcerts && *expcerts)
1577 {
1578 /* Tell the library to use its compiled-in location for the system default
1579 CA bundle. Then add the ones specified in the config, if any. */
1580
1581 if (!SSL_CTX_set_default_verify_paths(sctx))
1582 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL);
1583
1584 if (Ustrcmp(expcerts, "system") != 0)
1585 {
1586 struct stat statbuf;
1587
1588 if (Ustat(expcerts, &statbuf) < 0)
1589 {
1590 log_write(0, LOG_MAIN|LOG_PANIC,
1591 "failed to stat %s for certificates", expcerts);
1592 return DEFER;
1593 }
1594 else
1595 {
1596 uschar *file, *dir;
1597 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
1598 { file = NULL; dir = expcerts; }
1599 else
1600 { file = expcerts; dir = NULL; }
1601
1602 /* If a certificate file is empty, the next function fails with an
1603 unhelpful error message. If we skip it, we get the correct behaviour (no
1604 certificates are recognized, but the error message is still misleading (it
1605 says no certificate was supplied.) But this is better. */
1606
1607 if ( (!file || statbuf.st_size > 0)
1608 && !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
1609 return tls_error(US"SSL_CTX_load_verify_locations", host, NULL);
1610
1611 /* Load the list of CAs for which we will accept certs, for sending
1612 to the client. This is only for the one-file tls_verify_certificates
1613 variant.
1614 If a list isn't loaded into the server, but
1615 some verify locations are set, the server end appears to make
1616 a wildcard reqest for client certs.
1617 Meanwhile, the client library as default behaviour *ignores* the list
1618 we send over the wire - see man SSL_CTX_set_client_cert_cb.
1619 Because of this, and that the dir variant is likely only used for
1620 the public-CA bundle (not for a private CA), not worth fixing.
1621 */
1622 if (file)
1623 {
1624 STACK_OF(X509_NAME) * names = SSL_load_client_CA_file(CS file);
1625
1626 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n",
1627 sk_X509_NAME_num(names));
1628 SSL_CTX_set_client_CA_list(sctx, names);
1629 }
1630 }
1631 }
1632
1633 /* Handle a certificate revocation list. */
1634
1635#if OPENSSL_VERSION_NUMBER > 0x00907000L
1636
1637 /* This bit of code is now the version supplied by Lars Mainka. (I have
1638 merely reformatted it into the Exim code style.)
1639
1640 "From here I changed the code to add support for multiple crl's
1641 in pem format in one file or to support hashed directory entries in
1642 pem format instead of a file. This method now uses the library function
1643 X509_STORE_load_locations to add the CRL location to the SSL context.
1644 OpenSSL will then handle the verify against CA certs and CRLs by
1645 itself in the verify callback." */
1646
1647 if (!expand_check(crl, US"tls_crl", &expcrl)) return DEFER;
1648 if (expcrl && *expcrl)
1649 {
1650 struct stat statbufcrl;
1651 if (Ustat(expcrl, &statbufcrl) < 0)
1652 {
1653 log_write(0, LOG_MAIN|LOG_PANIC,
1654 "failed to stat %s for certificates revocation lists", expcrl);
1655 return DEFER;
1656 }
1657 else
1658 {
1659 /* is it a file or directory? */
1660 uschar *file, *dir;
1661 X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
1662 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
1663 {
1664 file = NULL;
1665 dir = expcrl;
1666 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
1667 }
1668 else
1669 {
1670 file = expcrl;
1671 dir = NULL;
1672 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
1673 }
1674 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
1675 return tls_error(US"X509_STORE_load_locations", host, NULL);
1676
1677 /* setting the flags to check against the complete crl chain */
1678
1679 X509_STORE_set_flags(cvstore,
1680 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1681 }
1682 }
1683
1684#endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
1685
1686 /* If verification is optional, don't fail if no certificate */
1687
1688 SSL_CTX_set_verify(sctx,
1689 SSL_VERIFY_PEER | (optional? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
1690 cert_vfy_cb);
1691 }
1692
1693return OK;
1694}
1695
1696
1697
1698/*************************************************
1699* Start a TLS session in a server *
1700*************************************************/
1701
1702/* This is called when Exim is running as a server, after having received
1703the STARTTLS command. It must respond to that command, and then negotiate
1704a TLS session.
1705
1706Arguments:
1707 require_ciphers allowed ciphers
1708
1709Returns: OK on success
1710 DEFER for errors before the start of the negotiation
1711 FAIL for errors during the negotation; the server can't
1712 continue running.
1713*/
1714
1715int
1716tls_server_start(const uschar *require_ciphers)
1717{
1718int rc;
1719uschar *expciphers;
1720tls_ext_ctx_cb *cbinfo;
1721static uschar peerdn[256];
1722static uschar cipherbuf[256];
1723
1724/* Check for previous activation */
1725
1726if (tls_in.active >= 0)
1727 {
1728 tls_error(US"STARTTLS received after TLS started", NULL, US"");
1729 smtp_printf("554 Already in TLS\r\n");
1730 return FAIL;
1731 }
1732
1733/* Initialize the SSL library. If it fails, it will already have logged
1734the error. */
1735
1736rc = tls_init(&server_ctx, NULL, tls_dhparam, tls_certificate, tls_privatekey,
1737#ifndef DISABLE_OCSP
1738 tls_ocsp_file,
1739#endif
1740 NULL, &server_static_cbinfo);
1741if (rc != OK) return rc;
1742cbinfo = server_static_cbinfo;
1743
1744if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers))
1745 return FAIL;
1746
1747/* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
1748were historically separated by underscores. So that I can use either form in my
1749tests, and also for general convenience, we turn underscores into hyphens here.
1750*/
1751
1752if (expciphers != NULL)
1753 {
1754 uschar *s = expciphers;
1755 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
1756 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
1757 if (!SSL_CTX_set_cipher_list(server_ctx, CS expciphers))
1758 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL);
1759 cbinfo->server_cipher_list = expciphers;
1760 }
1761
1762/* If this is a host for which certificate verification is mandatory or
1763optional, set up appropriately. */
1764
1765tls_in.certificate_verified = FALSE;
1766#ifdef EXPERIMENTAL_DANE
1767tls_in.dane_verified = FALSE;
1768#endif
1769server_verify_callback_called = FALSE;
1770
1771if (verify_check_host(&tls_verify_hosts) == OK)
1772 {
1773 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
1774 FALSE, verify_callback_server);
1775 if (rc != OK) return rc;
1776 server_verify_optional = FALSE;
1777 }
1778else if (verify_check_host(&tls_try_verify_hosts) == OK)
1779 {
1780 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
1781 TRUE, verify_callback_server);
1782 if (rc != OK) return rc;
1783 server_verify_optional = TRUE;
1784 }
1785
1786/* Prepare for new connection */
1787
1788if ((server_ssl = SSL_new(server_ctx)) == NULL) return tls_error(US"SSL_new", NULL, NULL);
1789
1790/* Warning: we used to SSL_clear(ssl) here, it was removed.
1791 *
1792 * With the SSL_clear(), we get strange interoperability bugs with
1793 * OpenSSL 1.0.1b and TLS1.1/1.2. It looks as though this may be a bug in
1794 * OpenSSL itself, as a clear should not lead to inability to follow protocols.
1795 *
1796 * The SSL_clear() call is to let an existing SSL* be reused, typically after
1797 * session shutdown. In this case, we have a brand new object and there's no
1798 * obvious reason to immediately clear it. I'm guessing that this was
1799 * originally added because of incomplete initialisation which the clear fixed,
1800 * in some historic release.
1801 */
1802
1803/* Set context and tell client to go ahead, except in the case of TLS startup
1804on connection, where outputting anything now upsets the clients and tends to
1805make them disconnect. We need to have an explicit fflush() here, to force out
1806the response. Other smtp_printf() calls do not need it, because in non-TLS
1807mode, the fflush() happens when smtp_getc() is called. */
1808
1809SSL_set_session_id_context(server_ssl, sid_ctx, Ustrlen(sid_ctx));
1810if (!tls_in.on_connect)
1811 {
1812 smtp_printf("220 TLS go ahead\r\n");
1813 fflush(smtp_out);
1814 }
1815
1816/* Now negotiate the TLS session. We put our own timer on it, since it seems
1817that the OpenSSL library doesn't. */
1818
1819SSL_set_wfd(server_ssl, fileno(smtp_out));
1820SSL_set_rfd(server_ssl, fileno(smtp_in));
1821SSL_set_accept_state(server_ssl);
1822
1823DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
1824
1825sigalrm_seen = FALSE;
1826if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1827rc = SSL_accept(server_ssl);
1828alarm(0);
1829
1830if (rc <= 0)
1831 {
1832 tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL);
1833 if (ERR_get_error() == 0)
1834 log_write(0, LOG_MAIN,
1835 "TLS client disconnected cleanly (rejected our certificate?)");
1836 return FAIL;
1837 }
1838
1839DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
1840
1841/* TLS has been set up. Adjust the input functions to read via TLS,
1842and initialize things. */
1843
1844peer_cert(server_ssl, &tls_in, peerdn, sizeof(peerdn));
1845
1846construct_cipher_name(server_ssl, cipherbuf, sizeof(cipherbuf), &tls_in.bits);
1847tls_in.cipher = cipherbuf;
1848
1849DEBUG(D_tls)
1850 {
1851 uschar buf[2048];
1852 if (SSL_get_shared_ciphers(server_ssl, CS buf, sizeof(buf)) != NULL)
1853 debug_printf("Shared ciphers: %s\n", buf);
1854 }
1855
1856/* Record the certificate we presented */
1857 {
1858 X509 * crt = SSL_get_certificate(server_ssl);
1859 tls_in.ourcert = crt ? X509_dup(crt) : NULL;
1860 }
1861
1862/* Only used by the server-side tls (tls_in), including tls_getc.
1863 Client-side (tls_out) reads (seem to?) go via
1864 smtp_read_response()/ip_recv().
1865 Hence no need to duplicate for _in and _out.
1866 */
1867ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1868ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
1869ssl_xfer_eof = ssl_xfer_error = 0;
1870
1871receive_getc = tls_getc;
1872receive_ungetc = tls_ungetc;
1873receive_feof = tls_feof;
1874receive_ferror = tls_ferror;
1875receive_smtp_buffered = tls_smtp_buffered;
1876
1877tls_in.active = fileno(smtp_out);
1878return OK;
1879}
1880
1881
1882
1883
1884static int
1885tls_client_basic_ctx_init(SSL_CTX * ctx,
1886 host_item * host, smtp_transport_options_block * ob, tls_ext_ctx_cb * cbinfo
1887 )
1888{
1889int rc;
1890/* stick to the old behaviour for compatibility if tls_verify_certificates is
1891 set but both tls_verify_hosts and tls_try_verify_hosts is not set. Check only
1892 the specified host patterns if one of them is defined */
1893
1894if ( ( !ob->tls_verify_hosts
1895 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
1896 )
1897 || (verify_check_given_host(&ob->tls_verify_hosts, host) == OK)
1898 )
1899 client_verify_optional = FALSE;
1900else if (verify_check_given_host(&ob->tls_try_verify_hosts, host) == OK)
1901 client_verify_optional = TRUE;
1902else
1903 return OK;
1904
1905if ((rc = setup_certs(ctx, ob->tls_verify_certificates,
1906 ob->tls_crl, host, client_verify_optional, verify_callback_client)) != OK)
1907 return rc;
1908
1909if (verify_check_given_host(&ob->tls_verify_cert_hostnames, host) == OK)
1910 {
1911 cbinfo->verify_cert_hostnames =
1912#ifdef SUPPORT_I18N
1913 string_domain_utf8_to_alabel(host->name, NULL);
1914#else
1915 host->name;
1916#endif
1917 DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
1918 cbinfo->verify_cert_hostnames);
1919 }
1920return OK;
1921}
1922
1923
1924#ifdef EXPERIMENTAL_DANE
1925static int
1926dane_tlsa_load(SSL * ssl, host_item * host, dns_answer * dnsa)
1927{
1928dns_record * rr;
1929dns_scan dnss;
1930const char * hostnames[2] = { CS host->name, NULL };
1931int found = 0;
1932
1933if (DANESSL_init(ssl, NULL, hostnames) != 1)
1934 return tls_error(US"hostnames load", host, NULL);
1935
1936for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
1937 rr;
1938 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
1939 ) if (rr->type == T_TLSA)
1940 {
1941 uschar * p = rr->data;
1942 uint8_t usage, selector, mtype;
1943 const char * mdname;
1944
1945 usage = *p++;
1946
1947 /* Only DANE-TA(2) and DANE-EE(3) are supported */
1948 if (usage != 2 && usage != 3) continue;
1949
1950 selector = *p++;
1951 mtype = *p++;
1952
1953 switch (mtype)
1954 {
1955 default: continue; /* Only match-types 0, 1, 2 are supported */
1956 case 0: mdname = NULL; break;
1957 case 1: mdname = "sha256"; break;
1958 case 2: mdname = "sha512"; break;
1959 }
1960
1961 found++;
1962 switch (DANESSL_add_tlsa(ssl, usage, selector, mdname, p, rr->size - 3))
1963 {
1964 default:
1965 return tls_error(US"tlsa load", host, NULL);
1966 case 0: /* action not taken */
1967 case 1: break;
1968 }
1969
1970 tls_out.tlsa_usage |= 1<<usage;
1971 }
1972
1973if (found)
1974 return OK;
1975
1976log_write(0, LOG_MAIN, "DANE error: No usable TLSA records");
1977return DEFER;
1978}
1979#endif /*EXPERIMENTAL_DANE*/
1980
1981
1982
1983/*************************************************
1984* Start a TLS session in a client *
1985*************************************************/
1986
1987/* Called from the smtp transport after STARTTLS has been accepted.
1988
1989Argument:
1990 fd the fd of the connection
1991 host connected host (for messages)
1992 addr the first address
1993 tb transport (always smtp)
1994 tlsa_dnsa tlsa lookup, if DANE, else null
1995
1996Returns: OK on success
1997 FAIL otherwise - note that tls_error() will not give DEFER
1998 because this is not a server
1999*/
2000
2001int
2002tls_client_start(int fd, host_item *host, address_item *addr,
2003 transport_instance *tb
2004#ifdef EXPERIMENTAL_DANE
2005 , dns_answer * tlsa_dnsa
2006#endif
2007 )
2008{
2009smtp_transport_options_block * ob =
2010 (smtp_transport_options_block *)tb->options_block;
2011static uschar peerdn[256];
2012uschar * expciphers;
2013int rc;
2014static uschar cipherbuf[256];
2015
2016#ifndef DISABLE_OCSP
2017BOOL request_ocsp = FALSE;
2018BOOL require_ocsp = FALSE;
2019#endif
2020
2021#ifdef EXPERIMENTAL_DANE
2022tls_out.tlsa_usage = 0;
2023#endif
2024
2025#ifndef DISABLE_OCSP
2026 {
2027# ifdef EXPERIMENTAL_DANE
2028 if ( tlsa_dnsa
2029 && ob->hosts_request_ocsp[0] == '*'
2030 && ob->hosts_request_ocsp[1] == '\0'
2031 )
2032 {
2033 /* Unchanged from default. Use a safer one under DANE */
2034 request_ocsp = TRUE;
2035 ob->hosts_request_ocsp = US"${if or { {= {0}{$tls_out_tlsa_usage}} "
2036 " {= {4}{$tls_out_tlsa_usage}} } "
2037 " {*}{}}";
2038 }
2039# endif
2040
2041 if ((require_ocsp =
2042 verify_check_given_host(&ob->hosts_require_ocsp, host) == OK))
2043 request_ocsp = TRUE;
2044 else
2045# ifdef EXPERIMENTAL_DANE
2046 if (!request_ocsp)
2047# endif
2048 request_ocsp =
2049 verify_check_given_host(&ob->hosts_request_ocsp, host) == OK;
2050 }
2051#endif
2052
2053rc = tls_init(&client_ctx, host, NULL,
2054 ob->tls_certificate, ob->tls_privatekey,
2055#ifndef DISABLE_OCSP
2056 (void *)(long)request_ocsp,
2057#endif
2058 addr, &client_static_cbinfo);
2059if (rc != OK) return rc;
2060
2061tls_out.certificate_verified = FALSE;
2062client_verify_callback_called = FALSE;
2063
2064if (!expand_check(ob->tls_require_ciphers, US"tls_require_ciphers",
2065 &expciphers))
2066 return FAIL;
2067
2068/* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2069are separated by underscores. So that I can use either form in my tests, and
2070also for general convenience, we turn underscores into hyphens here. */
2071
2072if (expciphers != NULL)
2073 {
2074 uschar *s = expciphers;
2075 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
2076 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
2077 if (!SSL_CTX_set_cipher_list(client_ctx, CS expciphers))
2078 return tls_error(US"SSL_CTX_set_cipher_list", host, NULL);
2079 }
2080
2081#ifdef EXPERIMENTAL_DANE
2082if (tlsa_dnsa)
2083 {
2084 SSL_CTX_set_verify(client_ctx,
2085 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2086 verify_callback_client_dane);
2087
2088 if (!DANESSL_library_init())
2089 return tls_error(US"library init", host, NULL);
2090 if (DANESSL_CTX_init(client_ctx) <= 0)
2091 return tls_error(US"context init", host, NULL);
2092 }
2093else
2094
2095#endif
2096
2097 if ((rc = tls_client_basic_ctx_init(client_ctx, host, ob, client_static_cbinfo))
2098 != OK)
2099 return rc;
2100
2101if ((client_ssl = SSL_new(client_ctx)) == NULL)
2102 return tls_error(US"SSL_new", host, NULL);
2103SSL_set_session_id_context(client_ssl, sid_ctx, Ustrlen(sid_ctx));
2104SSL_set_fd(client_ssl, fd);
2105SSL_set_connect_state(client_ssl);
2106
2107if (ob->tls_sni)
2108 {
2109 if (!expand_check(ob->tls_sni, US"tls_sni", &tls_out.sni))
2110 return FAIL;
2111 if (tls_out.sni == NULL)
2112 {
2113 DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n");
2114 }
2115 else if (!Ustrlen(tls_out.sni))
2116 tls_out.sni = NULL;
2117 else
2118 {
2119#ifdef EXIM_HAVE_OPENSSL_TLSEXT
2120 DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tls_out.sni);
2121 SSL_set_tlsext_host_name(client_ssl, tls_out.sni);
2122#else
2123 log_write(0, LOG_MAIN, "SNI unusable with this OpenSSL library version; ignoring \"%s\"\n",
2124 tls_out.sni);
2125#endif
2126 }
2127 }
2128
2129#ifdef EXPERIMENTAL_DANE
2130if (tlsa_dnsa)
2131 if ((rc = dane_tlsa_load(client_ssl, host, tlsa_dnsa)) != OK)
2132 return rc;
2133#endif
2134
2135#ifndef DISABLE_OCSP
2136/* Request certificate status at connection-time. If the server
2137does OCSP stapling we will get the callback (set in tls_init()) */
2138# ifdef EXPERIMENTAL_DANE
2139if (request_ocsp)
2140 {
2141 const uschar * s;
2142 if ( ((s = ob->hosts_require_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
2143 || ((s = ob->hosts_request_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
2144 )
2145 { /* Re-eval now $tls_out_tlsa_usage is populated. If
2146 this means we avoid the OCSP request, we wasted the setup
2147 cost in tls_init(). */
2148 require_ocsp = verify_check_given_host(&ob->hosts_require_ocsp, host) == OK;
2149 request_ocsp = require_ocsp
2150 || verify_check_given_host(&ob->hosts_request_ocsp, host) == OK;
2151 }
2152 }
2153# endif
2154
2155if (request_ocsp)
2156 {
2157 SSL_set_tlsext_status_type(client_ssl, TLSEXT_STATUSTYPE_ocsp);
2158 client_static_cbinfo->u_ocsp.client.verify_required = require_ocsp;
2159 tls_out.ocsp = OCSP_NOT_RESP;
2160 }
2161#endif
2162
2163#ifndef DISABLE_EVENT
2164client_static_cbinfo->event_action = tb->event_action;
2165#endif
2166
2167/* There doesn't seem to be a built-in timeout on connection. */
2168
2169DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
2170sigalrm_seen = FALSE;
2171alarm(ob->command_timeout);
2172rc = SSL_connect(client_ssl);
2173alarm(0);
2174
2175#ifdef EXPERIMENTAL_DANE
2176if (tlsa_dnsa)
2177 DANESSL_cleanup(client_ssl);
2178#endif
2179
2180if (rc <= 0)
2181 return tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL);
2182
2183DEBUG(D_tls) debug_printf("SSL_connect succeeded\n");
2184
2185peer_cert(client_ssl, &tls_out, peerdn, sizeof(peerdn));
2186
2187construct_cipher_name(client_ssl, cipherbuf, sizeof(cipherbuf), &tls_out.bits);
2188tls_out.cipher = cipherbuf;
2189
2190/* Record the certificate we presented */
2191 {
2192 X509 * crt = SSL_get_certificate(client_ssl);
2193 tls_out.ourcert = crt ? X509_dup(crt) : NULL;
2194 }
2195
2196tls_out.active = fd;
2197return OK;
2198}
2199
2200
2201
2202
2203
2204/*************************************************
2205* TLS version of getc *
2206*************************************************/
2207
2208/* This gets the next byte from the TLS input buffer. If the buffer is empty,
2209it refills the buffer via the SSL reading function.
2210
2211Arguments: none
2212Returns: the next character or EOF
2213
2214Only used by the server-side TLS.
2215*/
2216
2217int
2218tls_getc(void)
2219{
2220if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
2221 {
2222 int error;
2223 int inbytes;
2224
2225 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", server_ssl,
2226 ssl_xfer_buffer, ssl_xfer_buffer_size);
2227
2228 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2229 inbytes = SSL_read(server_ssl, CS ssl_xfer_buffer, ssl_xfer_buffer_size);
2230 error = SSL_get_error(server_ssl, inbytes);
2231 alarm(0);
2232
2233 /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
2234 closed down, not that the socket itself has been closed down. Revert to
2235 non-SSL handling. */
2236
2237 if (error == SSL_ERROR_ZERO_RETURN)
2238 {
2239 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2240
2241 receive_getc = smtp_getc;
2242 receive_ungetc = smtp_ungetc;
2243 receive_feof = smtp_feof;
2244 receive_ferror = smtp_ferror;
2245 receive_smtp_buffered = smtp_buffered;
2246
2247 SSL_free(server_ssl);
2248 server_ssl = NULL;
2249 tls_in.active = -1;
2250 tls_in.bits = 0;
2251 tls_in.cipher = NULL;
2252 tls_in.peerdn = NULL;
2253 tls_in.sni = NULL;
2254
2255 return smtp_getc();
2256 }
2257
2258 /* Handle genuine errors */
2259
2260 else if (error == SSL_ERROR_SSL)
2261 {
2262 ERR_error_string(ERR_get_error(), ssl_errstring);
2263 log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
2264 ssl_xfer_error = 1;
2265 return EOF;
2266 }
2267
2268 else if (error != SSL_ERROR_NONE)
2269 {
2270 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
2271 ssl_xfer_error = 1;
2272 return EOF;
2273 }
2274
2275#ifndef DISABLE_DKIM
2276 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
2277#endif
2278 ssl_xfer_buffer_hwm = inbytes;
2279 ssl_xfer_buffer_lwm = 0;
2280 }
2281
2282/* Something in the buffer; return next uschar */
2283
2284return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
2285}
2286
2287
2288
2289/*************************************************
2290* Read bytes from TLS channel *
2291*************************************************/
2292
2293/*
2294Arguments:
2295 buff buffer of data
2296 len size of buffer
2297
2298Returns: the number of bytes read
2299 -1 after a failed read
2300
2301Only used by the client-side TLS.
2302*/
2303
2304int
2305tls_read(BOOL is_server, uschar *buff, size_t len)
2306{
2307SSL *ssl = is_server ? server_ssl : client_ssl;
2308int inbytes;
2309int error;
2310
2311DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
2312 buff, (unsigned int)len);
2313
2314inbytes = SSL_read(ssl, CS buff, len);
2315error = SSL_get_error(ssl, inbytes);
2316
2317if (error == SSL_ERROR_ZERO_RETURN)
2318 {
2319 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2320 return -1;
2321 }
2322else if (error != SSL_ERROR_NONE)
2323 {
2324 return -1;
2325 }
2326
2327return inbytes;
2328}
2329
2330
2331
2332
2333
2334/*************************************************
2335* Write bytes down TLS channel *
2336*************************************************/
2337
2338/*
2339Arguments:
2340 is_server channel specifier
2341 buff buffer of data
2342 len number of bytes
2343
2344Returns: the number of bytes after a successful write,
2345 -1 after a failed write
2346
2347Used by both server-side and client-side TLS.
2348*/
2349
2350int
2351tls_write(BOOL is_server, const uschar *buff, size_t len)
2352{
2353int outbytes;
2354int error;
2355int left = len;
2356SSL *ssl = is_server ? server_ssl : client_ssl;
2357
2358DEBUG(D_tls) debug_printf("tls_do_write(%p, %d)\n", buff, left);
2359while (left > 0)
2360 {
2361 DEBUG(D_tls) debug_printf("SSL_write(SSL, %p, %d)\n", buff, left);
2362 outbytes = SSL_write(ssl, CS buff, left);
2363 error = SSL_get_error(ssl, outbytes);
2364 DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
2365 switch (error)
2366 {
2367 case SSL_ERROR_SSL:
2368 ERR_error_string(ERR_get_error(), ssl_errstring);
2369 log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
2370 return -1;
2371
2372 case SSL_ERROR_NONE:
2373 left -= outbytes;
2374 buff += outbytes;
2375 break;
2376
2377 case SSL_ERROR_ZERO_RETURN:
2378 log_write(0, LOG_MAIN, "SSL channel closed on write");
2379 return -1;
2380
2381 case SSL_ERROR_SYSCALL:
2382 log_write(0, LOG_MAIN, "SSL_write: (from %s) syscall: %s",
2383 sender_fullhost ? sender_fullhost : US"<unknown>",
2384 strerror(errno));
2385 return -1;
2386
2387 default:
2388 log_write(0, LOG_MAIN, "SSL_write error %d", error);
2389 return -1;
2390 }
2391 }
2392return len;
2393}
2394
2395
2396
2397/*************************************************
2398* Close down a TLS session *
2399*************************************************/
2400
2401/* This is also called from within a delivery subprocess forked from the
2402daemon, to shut down the TLS library, without actually doing a shutdown (which
2403would tamper with the SSL session in the parent process).
2404
2405Arguments: TRUE if SSL_shutdown is to be called
2406Returns: nothing
2407
2408Used by both server-side and client-side TLS.
2409*/
2410
2411void
2412tls_close(BOOL is_server, BOOL shutdown)
2413{
2414SSL **sslp = is_server ? &server_ssl : &client_ssl;
2415int *fdp = is_server ? &tls_in.active : &tls_out.active;
2416
2417if (*fdp < 0) return; /* TLS was not active */
2418
2419if (shutdown)
2420 {
2421 DEBUG(D_tls) debug_printf("tls_close(): shutting down SSL\n");
2422 SSL_shutdown(*sslp);
2423 }
2424
2425SSL_free(*sslp);
2426*sslp = NULL;
2427
2428*fdp = -1;
2429}
2430
2431
2432
2433
2434/*************************************************
2435* Let tls_require_ciphers be checked at startup *
2436*************************************************/
2437
2438/* The tls_require_ciphers option, if set, must be something which the
2439library can parse.
2440
2441Returns: NULL on success, or error message
2442*/
2443
2444uschar *
2445tls_validate_require_cipher(void)
2446{
2447SSL_CTX *ctx;
2448uschar *s, *expciphers, *err;
2449
2450/* this duplicates from tls_init(), we need a better "init just global
2451state, for no specific purpose" singleton function of our own */
2452
2453SSL_load_error_strings();
2454OpenSSL_add_ssl_algorithms();
2455#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
2456/* SHA256 is becoming ever more popular. This makes sure it gets added to the
2457list of available digests. */
2458EVP_add_digest(EVP_sha256());
2459#endif
2460
2461if (!(tls_require_ciphers && *tls_require_ciphers))
2462 return NULL;
2463
2464if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers))
2465 return US"failed to expand tls_require_ciphers";
2466
2467if (!(expciphers && *expciphers))
2468 return NULL;
2469
2470/* normalisation ripped from above */
2471s = expciphers;
2472while (*s != 0) { if (*s == '_') *s = '-'; s++; }
2473
2474err = NULL;
2475
2476ctx = SSL_CTX_new(SSLv23_server_method());
2477if (!ctx)
2478 {
2479 ERR_error_string(ERR_get_error(), ssl_errstring);
2480 return string_sprintf("SSL_CTX_new() failed: %s", ssl_errstring);
2481 }
2482
2483DEBUG(D_tls)
2484 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2485
2486if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
2487 {
2488 ERR_error_string(ERR_get_error(), ssl_errstring);
2489 err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed", expciphers);
2490 }
2491
2492SSL_CTX_free(ctx);
2493
2494return err;
2495}
2496
2497
2498
2499
2500/*************************************************
2501* Report the library versions. *
2502*************************************************/
2503
2504/* There have historically been some issues with binary compatibility in
2505OpenSSL libraries; if Exim (like many other applications) is built against
2506one version of OpenSSL but the run-time linker picks up another version,
2507it can result in serious failures, including crashing with a SIGSEGV. So
2508report the version found by the compiler and the run-time version.
2509
2510Note: some OS vendors backport security fixes without changing the version
2511number/string, and the version date remains unchanged. The _build_ date
2512will change, so we can more usefully assist with version diagnosis by also
2513reporting the build date.
2514
2515Arguments: a FILE* to print the results to
2516Returns: nothing
2517*/
2518
2519void
2520tls_version_report(FILE *f)
2521{
2522fprintf(f, "Library version: OpenSSL: Compile: %s\n"
2523 " Runtime: %s\n"
2524 " : %s\n",
2525 OPENSSL_VERSION_TEXT,
2526 SSLeay_version(SSLEAY_VERSION),
2527 SSLeay_version(SSLEAY_BUILT_ON));
2528/* third line is 38 characters for the %s and the line is 73 chars long;
2529the OpenSSL output includes a "built on: " prefix already. */
2530}
2531
2532
2533
2534
2535/*************************************************
2536* Random number generation *
2537*************************************************/
2538
2539/* Pseudo-random number generation. The result is not expected to be
2540cryptographically strong but not so weak that someone will shoot themselves
2541in the foot using it as a nonce in input in some email header scheme or
2542whatever weirdness they'll twist this into. The result should handle fork()
2543and avoid repeating sequences. OpenSSL handles that for us.
2544
2545Arguments:
2546 max range maximum
2547Returns a random number in range [0, max-1]
2548*/
2549
2550int
2551vaguely_random_number(int max)
2552{
2553unsigned int r;
2554int i, needed_len;
2555static pid_t pidlast = 0;
2556pid_t pidnow;
2557uschar *p;
2558uschar smallbuf[sizeof(r)];
2559
2560if (max <= 1)
2561 return 0;
2562
2563pidnow = getpid();
2564if (pidnow != pidlast)
2565 {
2566 /* Although OpenSSL documents that "OpenSSL makes sure that the PRNG state
2567 is unique for each thread", this doesn't apparently apply across processes,
2568 so our own warning from vaguely_random_number_fallback() applies here too.
2569 Fix per PostgreSQL. */
2570 if (pidlast != 0)
2571 RAND_cleanup();
2572 pidlast = pidnow;
2573 }
2574
2575/* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
2576if (!RAND_status())
2577 {
2578 randstuff r;
2579 gettimeofday(&r.tv, NULL);
2580 r.p = getpid();
2581
2582 RAND_seed((uschar *)(&r), sizeof(r));
2583 }
2584/* We're after pseudo-random, not random; if we still don't have enough data
2585in the internal PRNG then our options are limited. We could sleep and hope
2586for entropy to come along (prayer technique) but if the system is so depleted
2587in the first place then something is likely to just keep taking it. Instead,
2588we'll just take whatever little bit of pseudo-random we can still manage to
2589get. */
2590
2591needed_len = sizeof(r);
2592/* Don't take 8 times more entropy than needed if int is 8 octets and we were
2593asked for a number less than 10. */
2594for (r = max, i = 0; r; ++i)
2595 r >>= 1;
2596i = (i + 7) / 8;
2597if (i < needed_len)
2598 needed_len = i;
2599
2600#ifdef EXIM_HAVE_RAND_PSEUDO
2601/* We do not care if crypto-strong */
2602i = RAND_pseudo_bytes(smallbuf, needed_len);
2603#else
2604i = RAND_bytes(smallbuf, needed_len);
2605#endif
2606
2607if (i < 0)
2608 {
2609 DEBUG(D_all)
2610 debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
2611 return vaguely_random_number_fallback(max);
2612 }
2613
2614r = 0;
2615for (p = smallbuf; needed_len; --needed_len, ++p)
2616 {
2617 r *= 256;
2618 r += *p;
2619 }
2620
2621/* We don't particularly care about weighted results; if someone wants
2622smooth distribution and cares enough then they should submit a patch then. */
2623return r % max;
2624}
2625
2626
2627
2628
2629/*************************************************
2630* OpenSSL option parse *
2631*************************************************/
2632
2633/* Parse one option for tls_openssl_options_parse below
2634
2635Arguments:
2636 name one option name
2637 value place to store a value for it
2638Returns success or failure in parsing
2639*/
2640
2641struct exim_openssl_option {
2642 uschar *name;
2643 long value;
2644};
2645/* We could use a macro to expand, but we need the ifdef and not all the
2646options document which version they were introduced in. Policylet: include
2647all options unless explicitly for DTLS, let the administrator choose which
2648to apply.
2649
2650This list is current as of:
2651 ==> 1.0.1b <==
2652Plus SSL_OP_SAFARI_ECDHE_ECDSA_BUG from 2013-June patch/discussion on openssl-dev
2653*/
2654static struct exim_openssl_option exim_openssl_options[] = {
2655/* KEEP SORTED ALPHABETICALLY! */
2656#ifdef SSL_OP_ALL
2657 { US"all", SSL_OP_ALL },
2658#endif
2659#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
2660 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
2661#endif
2662#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2663 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
2664#endif
2665#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
2666 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
2667#endif
2668#ifdef SSL_OP_EPHEMERAL_RSA
2669 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
2670#endif
2671#ifdef SSL_OP_LEGACY_SERVER_CONNECT
2672 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
2673#endif
2674#ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
2675 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
2676#endif
2677#ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
2678 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
2679#endif
2680#ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
2681 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
2682#endif
2683#ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
2684 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
2685#endif
2686#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
2687 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
2688#endif
2689#ifdef SSL_OP_NO_COMPRESSION
2690 { US"no_compression", SSL_OP_NO_COMPRESSION },
2691#endif
2692#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2693 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
2694#endif
2695#ifdef SSL_OP_NO_SSLv2
2696 { US"no_sslv2", SSL_OP_NO_SSLv2 },
2697#endif
2698#ifdef SSL_OP_NO_SSLv3
2699 { US"no_sslv3", SSL_OP_NO_SSLv3 },
2700#endif
2701#ifdef SSL_OP_NO_TICKET
2702 { US"no_ticket", SSL_OP_NO_TICKET },
2703#endif
2704#ifdef SSL_OP_NO_TLSv1
2705 { US"no_tlsv1", SSL_OP_NO_TLSv1 },
2706#endif
2707#ifdef SSL_OP_NO_TLSv1_1
2708#if SSL_OP_NO_TLSv1_1 == 0x00000400L
2709 /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
2710#warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
2711#else
2712 { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
2713#endif
2714#endif
2715#ifdef SSL_OP_NO_TLSv1_2
2716 { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
2717#endif
2718#ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
2719 { US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
2720#endif
2721#ifdef SSL_OP_SINGLE_DH_USE
2722 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
2723#endif
2724#ifdef SSL_OP_SINGLE_ECDH_USE
2725 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
2726#endif
2727#ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
2728 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
2729#endif
2730#ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
2731 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
2732#endif
2733#ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
2734 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
2735#endif
2736#ifdef SSL_OP_TLS_D5_BUG
2737 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
2738#endif
2739#ifdef SSL_OP_TLS_ROLLBACK_BUG
2740 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
2741#endif
2742};
2743static int exim_openssl_options_size =
2744 sizeof(exim_openssl_options)/sizeof(struct exim_openssl_option);
2745
2746
2747static BOOL
2748tls_openssl_one_option_parse(uschar *name, long *value)
2749{
2750int first = 0;
2751int last = exim_openssl_options_size;
2752while (last > first)
2753 {
2754 int middle = (first + last)/2;
2755 int c = Ustrcmp(name, exim_openssl_options[middle].name);
2756 if (c == 0)
2757 {
2758 *value = exim_openssl_options[middle].value;
2759 return TRUE;
2760 }
2761 else if (c > 0)
2762 first = middle + 1;
2763 else
2764 last = middle;
2765 }
2766return FALSE;
2767}
2768
2769
2770
2771
2772/*************************************************
2773* OpenSSL option parsing logic *
2774*************************************************/
2775
2776/* OpenSSL has a number of compatibility options which an administrator might
2777reasonably wish to set. Interpret a list similarly to decode_bits(), so that
2778we look like log_selector.
2779
2780Arguments:
2781 option_spec the administrator-supplied string of options
2782 results ptr to long storage for the options bitmap
2783Returns success or failure
2784*/
2785
2786BOOL
2787tls_openssl_options_parse(uschar *option_spec, long *results)
2788{
2789long result, item;
2790uschar *s, *end;
2791uschar keep_c;
2792BOOL adding, item_parsed;
2793
2794result = 0L;
2795/* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
2796 * from default because it increases BEAST susceptibility. */
2797#ifdef SSL_OP_NO_SSLv2
2798result |= SSL_OP_NO_SSLv2;
2799#endif
2800#ifdef SSL_OP_SINGLE_DH_USE
2801result |= SSL_OP_SINGLE_DH_USE;
2802#endif
2803
2804if (option_spec == NULL)
2805 {
2806 *results = result;
2807 return TRUE;
2808 }
2809
2810for (s=option_spec; *s != '\0'; /**/)
2811 {
2812 while (isspace(*s)) ++s;
2813 if (*s == '\0')
2814 break;
2815 if (*s != '+' && *s != '-')
2816 {
2817 DEBUG(D_tls) debug_printf("malformed openssl option setting: "
2818 "+ or - expected but found \"%s\"\n", s);
2819 return FALSE;
2820 }
2821 adding = *s++ == '+';
2822 for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
2823 keep_c = *end;
2824 *end = '\0';
2825 item_parsed = tls_openssl_one_option_parse(s, &item);
2826 *end = keep_c;
2827 if (!item_parsed)
2828 {
2829 DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
2830 return FALSE;
2831 }
2832 DEBUG(D_tls) debug_printf("openssl option, %s from %lx: %lx (%s)\n",
2833 adding ? "adding" : "removing", result, item, s);
2834 if (adding)
2835 result |= item;
2836 else
2837 result &= ~item;
2838 s = end;
2839 }
2840
2841*results = result;
2842return TRUE;
2843}
2844
2845/* vi: aw ai sw=2
2846*/
2847/* End of tls-openssl.c */