e47df7cb29f3f739eac6982fa2b5f408c3a2b23b
[exim.git] / src / src / tls-openssl.c
1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2019 */
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
11 library. It is #included into the tls.c file when that library is used. The
12 code herein is based on a patch that was originally contributed by Steve
13 Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
14
15 No cryptographic code is included in Exim. All this module does is to call
16 functions 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 SUPPORT_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 /* X509_check_host provides sane certificate hostname checking, but was added
58 to OpenSSL late, after other projects forked off the code-base. So in
59 addition to guarding against the base version number, beware that LibreSSL
60 does not (at this time) support this function.
61
62 If LibreSSL gains a different API, perhaps via libtls, then we'll probably
63 opt to disentangle and ask a LibreSSL user to provide glue for a third
64 crypto provider for libtls instead of continuing to tie the OpenSSL glue
65 into even twistier knots. If LibreSSL gains the same API, we can just
66 change this guard and punt the issue for a while longer. */
67
68 #ifndef LIBRESSL_VERSION_NUMBER
69 # if OPENSSL_VERSION_NUMBER >= 0x010100000L
70 # define EXIM_HAVE_OPENSSL_CHECKHOST
71 # define EXIM_HAVE_OPENSSL_DH_BITS
72 # define EXIM_HAVE_OPENSSL_TLS_METHOD
73 # define EXIM_HAVE_OPENSSL_KEYLOG
74 # define EXIM_HAVE_OPENSSL_CIPHER_GET_ID
75 # define EXIM_HAVE_SESSION_TICKET
76 # define EXIM_HAVE_OPESSL_TRACE
77 # else
78 # define EXIM_NEED_OPENSSL_INIT
79 # endif
80 # if OPENSSL_VERSION_NUMBER >= 0x010000000L \
81 && (OPENSSL_VERSION_NUMBER & 0x0000ff000L) >= 0x000002000L
82 # define EXIM_HAVE_OPENSSL_CHECKHOST
83 # endif
84 #endif
85
86 #if !defined(LIBRESSL_VERSION_NUMBER) \
87 || LIBRESSL_VERSION_NUMBER >= 0x20010000L
88 # if !defined(OPENSSL_NO_ECDH)
89 # if OPENSSL_VERSION_NUMBER >= 0x0090800fL
90 # define EXIM_HAVE_ECDH
91 # endif
92 # if OPENSSL_VERSION_NUMBER >= 0x10002000L
93 # define EXIM_HAVE_OPENSSL_EC_NIST2NID
94 # endif
95 # endif
96 #endif
97
98 #ifndef LIBRESSL_VERSION_NUMBER
99 # if OPENSSL_VERSION_NUMBER >= 0x010101000L
100 # define OPENSSL_HAVE_KEYLOG_CB
101 # define OPENSSL_HAVE_NUM_TICKETS
102 # define EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
103 # endif
104 #endif
105
106 #if !defined(EXIM_HAVE_OPENSSL_TLSEXT) && !defined(DISABLE_OCSP)
107 # warning "OpenSSL library version too old; define DISABLE_OCSP in Makefile"
108 # define DISABLE_OCSP
109 #endif
110
111 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
112 # include <openssl/x509v3.h>
113 #endif
114
115 #ifndef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
116 # ifndef EXIM_HAVE_OPENSSL_CIPHER_GET_ID
117 # define SSL_CIPHER_get_id(c) (c->id)
118 # endif
119 # ifndef MACRO_PREDEF
120 # include "tls-cipher-stdname.c"
121 # endif
122 #endif
123
124 /*************************************************
125 * OpenSSL option parse *
126 *************************************************/
127
128 typedef struct exim_openssl_option {
129 uschar *name;
130 long value;
131 } exim_openssl_option;
132 /* We could use a macro to expand, but we need the ifdef and not all the
133 options document which version they were introduced in. Policylet: include
134 all options unless explicitly for DTLS, let the administrator choose which
135 to apply.
136
137 This list is current as of:
138 ==> 1.0.1b <==
139 Plus SSL_OP_SAFARI_ECDHE_ECDSA_BUG from 2013-June patch/discussion on openssl-dev
140 Plus SSL_OP_NO_TLSv1_3 for 1.1.2-dev
141 */
142 static exim_openssl_option exim_openssl_options[] = {
143 /* KEEP SORTED ALPHABETICALLY! */
144 #ifdef SSL_OP_ALL
145 { US"all", SSL_OP_ALL },
146 #endif
147 #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
148 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
149 #endif
150 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
151 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
152 #endif
153 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
154 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
155 #endif
156 #ifdef SSL_OP_EPHEMERAL_RSA
157 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
158 #endif
159 #ifdef SSL_OP_LEGACY_SERVER_CONNECT
160 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
161 #endif
162 #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
163 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
164 #endif
165 #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
166 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
167 #endif
168 #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
169 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
170 #endif
171 #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
172 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
173 #endif
174 #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
175 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
176 #endif
177 #ifdef SSL_OP_NO_COMPRESSION
178 { US"no_compression", SSL_OP_NO_COMPRESSION },
179 #endif
180 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
181 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
182 #endif
183 #ifdef SSL_OP_NO_SSLv2
184 { US"no_sslv2", SSL_OP_NO_SSLv2 },
185 #endif
186 #ifdef SSL_OP_NO_SSLv3
187 { US"no_sslv3", SSL_OP_NO_SSLv3 },
188 #endif
189 #ifdef SSL_OP_NO_TICKET
190 { US"no_ticket", SSL_OP_NO_TICKET },
191 #endif
192 #ifdef SSL_OP_NO_TLSv1
193 { US"no_tlsv1", SSL_OP_NO_TLSv1 },
194 #endif
195 #ifdef SSL_OP_NO_TLSv1_1
196 #if SSL_OP_NO_TLSv1_1 == 0x00000400L
197 /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
198 #warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
199 #else
200 { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
201 #endif
202 #endif
203 #ifdef SSL_OP_NO_TLSv1_2
204 { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
205 #endif
206 #ifdef SSL_OP_NO_TLSv1_3
207 { US"no_tlsv1_3", SSL_OP_NO_TLSv1_3 },
208 #endif
209 #ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
210 { US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
211 #endif
212 #ifdef SSL_OP_SINGLE_DH_USE
213 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
214 #endif
215 #ifdef SSL_OP_SINGLE_ECDH_USE
216 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
217 #endif
218 #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
219 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
220 #endif
221 #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
222 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
223 #endif
224 #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
225 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
226 #endif
227 #ifdef SSL_OP_TLS_D5_BUG
228 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
229 #endif
230 #ifdef SSL_OP_TLS_ROLLBACK_BUG
231 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
232 #endif
233 };
234
235 #ifndef MACRO_PREDEF
236 static int exim_openssl_options_size = nelem(exim_openssl_options);
237 #endif
238
239 #ifdef MACRO_PREDEF
240 void
241 options_tls(void)
242 {
243 uschar buf[64];
244
245 for (struct exim_openssl_option * o = exim_openssl_options;
246 o < exim_openssl_options + nelem(exim_openssl_options); o++)
247 {
248 /* Trailing X is workaround for problem with _OPT_OPENSSL_NO_TLSV1
249 being a ".ifdef _OPT_OPENSSL_NO_TLSV1_3" match */
250
251 spf(buf, sizeof(buf), US"_OPT_OPENSSL_%T_X", o->name);
252 builtin_macro_create(buf);
253 }
254
255 # ifdef EXPERIMENTAL_TLS_RESUME
256 builtin_macro_create_var(US"_RESUME_DECODE", RESUME_DECODE_STRING );
257 # endif
258 }
259 #else
260
261 /******************************************************************************/
262
263 /* Structure for collecting random data for seeding. */
264
265 typedef struct randstuff {
266 struct timeval tv;
267 pid_t p;
268 } randstuff;
269
270 /* Local static variables */
271
272 static BOOL client_verify_callback_called = FALSE;
273 static BOOL server_verify_callback_called = FALSE;
274 static const uschar *sid_ctx = US"exim";
275
276 /* We have three different contexts to care about.
277
278 Simple case: client, `client_ctx`
279 As a client, we can be doing a callout or cut-through delivery while receiving
280 a message. So we have a client context, which should have options initialised
281 from the SMTP Transport. We may also concurrently want to make TLS connections
282 to utility daemons, so client-contexts are allocated and passed around in call
283 args rather than using a gobal.
284
285 Server:
286 There are two cases: with and without ServerNameIndication from the client.
287 Given TLS SNI, we can be using different keys, certs and various other
288 configuration settings, because they're re-expanded with $tls_sni set. This
289 allows vhosting with TLS. This SNI is sent in the handshake.
290 A client might not send SNI, so we need a fallback, and an initial setup too.
291 So as a server, we start out using `server_ctx`.
292 If SNI is sent by the client, then we as server, mid-negotiation, try to clone
293 `server_sni` from `server_ctx` and then initialise settings by re-expanding
294 configuration.
295 */
296
297 typedef struct {
298 SSL_CTX * ctx;
299 SSL * ssl;
300 gstring * corked;
301 } exim_openssl_client_tls_ctx;
302
303 static SSL_CTX *server_ctx = NULL;
304 static SSL *server_ssl = NULL;
305
306 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
307 static SSL_CTX *server_sni = NULL;
308 #endif
309
310 static char ssl_errstring[256];
311
312 static int ssl_session_timeout = 3600;
313 static BOOL client_verify_optional = FALSE;
314 static BOOL server_verify_optional = FALSE;
315
316 static BOOL reexpand_tls_files_for_sni = FALSE;
317
318
319 typedef struct tls_ext_ctx_cb {
320 tls_support * tlsp;
321 uschar *certificate;
322 uschar *privatekey;
323 BOOL is_server;
324 #ifndef DISABLE_OCSP
325 STACK_OF(X509) *verify_stack; /* chain for verifying the proof */
326 union {
327 struct {
328 uschar *file;
329 uschar *file_expanded;
330 OCSP_RESPONSE *response;
331 } server;
332 struct {
333 X509_STORE *verify_store; /* non-null if status requested */
334 BOOL verify_required;
335 } client;
336 } u_ocsp;
337 #endif
338 uschar *dhparam;
339 /* these are cached from first expand */
340 uschar *server_cipher_list;
341 /* only passed down to tls_error: */
342 host_item *host;
343 const uschar * verify_cert_hostnames;
344 #ifndef DISABLE_EVENT
345 uschar * event_action;
346 #endif
347 } tls_ext_ctx_cb;
348
349 /* should figure out a cleanup of API to handle state preserved per
350 implementation, for various reasons, which can be void * in the APIs.
351 For now, we hack around it. */
352 tls_ext_ctx_cb *client_static_cbinfo = NULL; /*XXX should not use static; multiple concurrent clients! */
353 tls_ext_ctx_cb *server_static_cbinfo = NULL;
354
355 static int
356 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
357 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr );
358
359 /* Callbacks */
360 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
361 static int tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg);
362 #endif
363 #ifndef DISABLE_OCSP
364 static int tls_server_stapling_cb(SSL *s, void *arg);
365 #endif
366
367
368
369 /* Daemon-called key create/rotate */
370 #ifdef EXPERIMENTAL_TLS_RESUME
371 static void tk_init(void);
372 static int tls_exdata_idx = -1;
373 #endif
374
375 void
376 tls_daemon_init(void)
377 {
378 #ifdef EXPERIMENTAL_TLS_RESUME
379 tk_init();
380 #endif
381 return;
382 }
383
384
385 /*************************************************
386 * Handle TLS error *
387 *************************************************/
388
389 /* Called from lots of places when errors occur before actually starting to do
390 the TLS handshake, that is, while the session is still in clear. Always returns
391 DEFER for a server and FAIL for a client so that most calls can use "return
392 tls_error(...)" to do this processing and then give an appropriate return. A
393 single function is used for both server and client, because it is called from
394 some shared functions.
395
396 Argument:
397 prefix text to include in the logged error
398 host NULL if setting up a server;
399 the connected host if setting up a client
400 msg error message or NULL if we should ask OpenSSL
401 errstr pointer to output error message
402
403 Returns: OK/DEFER/FAIL
404 */
405
406 static int
407 tls_error(uschar * prefix, const host_item * host, uschar * msg, uschar ** errstr)
408 {
409 if (!msg)
410 {
411 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
412 msg = US ssl_errstring;
413 }
414
415 msg = string_sprintf("(%s): %s", prefix, msg);
416 DEBUG(D_tls) debug_printf("TLS error '%s'\n", msg);
417 if (errstr) *errstr = msg;
418 return host ? FAIL : DEFER;
419 }
420
421
422
423 /*************************************************
424 * Callback to generate RSA key *
425 *************************************************/
426
427 /*
428 Arguments:
429 s SSL connection (not used)
430 export not used
431 keylength keylength
432
433 Returns: pointer to generated key
434 */
435
436 static RSA *
437 rsa_callback(SSL *s, int export, int keylength)
438 {
439 RSA *rsa_key;
440 #ifdef EXIM_HAVE_RSA_GENKEY_EX
441 BIGNUM *bn = BN_new();
442 #endif
443
444 export = export; /* Shut picky compilers up */
445 DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
446
447 #ifdef EXIM_HAVE_RSA_GENKEY_EX
448 if ( !BN_set_word(bn, (unsigned long)RSA_F4)
449 || !(rsa_key = RSA_new())
450 || !RSA_generate_key_ex(rsa_key, keylength, bn, NULL)
451 )
452 #else
453 if (!(rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL)))
454 #endif
455
456 {
457 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
458 log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
459 ssl_errstring);
460 return NULL;
461 }
462 return rsa_key;
463 }
464
465
466
467 /* Extreme debug
468 #ifndef DISABLE_OCSP
469 void
470 x509_store_dump_cert_s_names(X509_STORE * store)
471 {
472 STACK_OF(X509_OBJECT) * roots= store->objs;
473 static uschar name[256];
474
475 for (int i= 0; i < sk_X509_OBJECT_num(roots); i++)
476 {
477 X509_OBJECT * tmp_obj= sk_X509_OBJECT_value(roots, i);
478 if(tmp_obj->type == X509_LU_X509)
479 {
480 X509_NAME * sn = X509_get_subject_name(tmp_obj->data.x509);
481 if (X509_NAME_oneline(sn, CS name, sizeof(name)))
482 {
483 name[sizeof(name)-1] = '\0';
484 debug_printf(" %s\n", name);
485 }
486 }
487 }
488 }
489 #endif
490 */
491
492
493 #ifndef DISABLE_EVENT
494 static int
495 verify_event(tls_support * tlsp, X509 * cert, int depth, const uschar * dn,
496 BOOL *calledp, const BOOL *optionalp, const uschar * what)
497 {
498 uschar * ev;
499 uschar * yield;
500 X509 * old_cert;
501
502 ev = tlsp == &tls_out ? client_static_cbinfo->event_action : event_action;
503 if (ev)
504 {
505 DEBUG(D_tls) debug_printf("verify_event: %s %d\n", what, depth);
506 old_cert = tlsp->peercert;
507 tlsp->peercert = X509_dup(cert);
508 /* NB we do not bother setting peerdn */
509 if ((yield = event_raise(ev, US"tls:cert", string_sprintf("%d", depth))))
510 {
511 log_write(0, LOG_MAIN, "[%s] %s verify denied by event-action: "
512 "depth=%d cert=%s: %s",
513 tlsp == &tls_out ? deliver_host_address : sender_host_address,
514 what, depth, dn, yield);
515 *calledp = TRUE;
516 if (!*optionalp)
517 {
518 if (old_cert) tlsp->peercert = old_cert; /* restore 1st failing cert */
519 return 1; /* reject (leaving peercert set) */
520 }
521 DEBUG(D_tls) debug_printf("Event-action verify failure overridden "
522 "(host in tls_try_verify_hosts)\n");
523 }
524 X509_free(tlsp->peercert);
525 tlsp->peercert = old_cert;
526 }
527 return 0;
528 }
529 #endif
530
531 /*************************************************
532 * Callback for verification *
533 *************************************************/
534
535 /* The SSL library does certificate verification if set up to do so. This
536 callback has the current yes/no state is in "state". If verification succeeded,
537 we set the certificate-verified flag. If verification failed, what happens
538 depends on whether the client is required to present a verifiable certificate
539 or not.
540
541 If verification is optional, we change the state to yes, but still log the
542 verification error. For some reason (it really would help to have proper
543 documentation of OpenSSL), this callback function then gets called again, this
544 time with state = 1. We must take care not to set the private verified flag on
545 the second time through.
546
547 Note: this function is not called if the client fails to present a certificate
548 when asked. We get here only if a certificate has been received. Handling of
549 optional verification for this case is done when requesting SSL to verify, by
550 setting SSL_VERIFY_FAIL_IF_NO_PEER_CERT in the non-optional case.
551
552 May be called multiple times for different issues with a certificate, even
553 for a given "depth" in the certificate chain.
554
555 Arguments:
556 preverify_ok current yes/no state as 1/0
557 x509ctx certificate information.
558 tlsp per-direction (client vs. server) support data
559 calledp has-been-called flag
560 optionalp verification-is-optional flag
561
562 Returns: 0 if verification should fail, otherwise 1
563 */
564
565 static int
566 verify_callback(int preverify_ok, X509_STORE_CTX * x509ctx,
567 tls_support * tlsp, BOOL * calledp, BOOL * optionalp)
568 {
569 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
570 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
571 uschar dn[256];
572
573 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
574 {
575 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
576 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
577 tlsp == &tls_out ? deliver_host_address : sender_host_address);
578 return 0;
579 }
580 dn[sizeof(dn)-1] = '\0';
581
582 if (preverify_ok == 0)
583 {
584 uschar * extra = verify_mode ? string_sprintf(" (during %c-verify for [%s])",
585 *verify_mode, sender_host_address)
586 : US"";
587 log_write(0, LOG_MAIN, "[%s] SSL verify error%s: depth=%d error=%s cert=%s",
588 tlsp == &tls_out ? deliver_host_address : sender_host_address,
589 extra, depth,
590 X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509ctx)), dn);
591 *calledp = TRUE;
592 if (!*optionalp)
593 {
594 if (!tlsp->peercert)
595 tlsp->peercert = X509_dup(cert); /* record failing cert */
596 return 0; /* reject */
597 }
598 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
599 "tls_try_verify_hosts)\n");
600 }
601
602 else if (depth != 0)
603 {
604 DEBUG(D_tls) debug_printf("SSL verify ok: depth=%d SN=%s\n", depth, dn);
605 #ifndef DISABLE_OCSP
606 if (tlsp == &tls_out && client_static_cbinfo->u_ocsp.client.verify_store)
607 { /* client, wanting stapling */
608 /* Add the server cert's signing chain as the one
609 for the verification of the OCSP stapled information. */
610
611 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
612 cert))
613 ERR_clear_error();
614 sk_X509_push(client_static_cbinfo->verify_stack, cert);
615 }
616 #endif
617 #ifndef DISABLE_EVENT
618 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
619 return 0; /* reject, with peercert set */
620 #endif
621 }
622 else
623 {
624 const uschar * verify_cert_hostnames;
625
626 if ( tlsp == &tls_out
627 && ((verify_cert_hostnames = client_static_cbinfo->verify_cert_hostnames)))
628 /* client, wanting hostname check */
629 {
630
631 #ifdef EXIM_HAVE_OPENSSL_CHECKHOST
632 # ifndef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
633 # define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0
634 # endif
635 # ifndef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
636 # define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0
637 # endif
638 int sep = 0;
639 const uschar * list = verify_cert_hostnames;
640 uschar * name;
641 int rc;
642 while ((name = string_nextinlist(&list, &sep, NULL, 0)))
643 if ((rc = X509_check_host(cert, CCS name, 0,
644 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
645 | X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS,
646 NULL)))
647 {
648 if (rc < 0)
649 {
650 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
651 tlsp == &tls_out ? deliver_host_address : sender_host_address);
652 name = NULL;
653 }
654 break;
655 }
656 if (!name)
657 #else
658 if (!tls_is_name_for_cert(verify_cert_hostnames, cert))
659 #endif
660 {
661 uschar * extra = verify_mode
662 ? string_sprintf(" (during %c-verify for [%s])",
663 *verify_mode, sender_host_address)
664 : US"";
665 log_write(0, LOG_MAIN,
666 "[%s] SSL verify error%s: certificate name mismatch: DN=\"%s\" H=\"%s\"",
667 tlsp == &tls_out ? deliver_host_address : sender_host_address,
668 extra, dn, verify_cert_hostnames);
669 *calledp = TRUE;
670 if (!*optionalp)
671 {
672 if (!tlsp->peercert)
673 tlsp->peercert = X509_dup(cert); /* record failing cert */
674 return 0; /* reject */
675 }
676 DEBUG(D_tls) debug_printf("SSL verify failure overridden (host in "
677 "tls_try_verify_hosts)\n");
678 }
679 }
680
681 #ifndef DISABLE_EVENT
682 if (verify_event(tlsp, cert, depth, dn, calledp, optionalp, US"SSL"))
683 return 0; /* reject, with peercert set */
684 #endif
685
686 DEBUG(D_tls) debug_printf("SSL%s verify ok: depth=0 SN=%s\n",
687 *calledp ? "" : " authenticated", dn);
688 if (!*calledp) tlsp->certificate_verified = TRUE;
689 *calledp = TRUE;
690 }
691
692 return 1; /* accept, at least for this level */
693 }
694
695 static int
696 verify_callback_client(int preverify_ok, X509_STORE_CTX *x509ctx)
697 {
698 return verify_callback(preverify_ok, x509ctx, &tls_out,
699 &client_verify_callback_called, &client_verify_optional);
700 }
701
702 static int
703 verify_callback_server(int preverify_ok, X509_STORE_CTX *x509ctx)
704 {
705 return verify_callback(preverify_ok, x509ctx, &tls_in,
706 &server_verify_callback_called, &server_verify_optional);
707 }
708
709
710 #ifdef SUPPORT_DANE
711
712 /* This gets called *by* the dane library verify callback, which interposes
713 itself.
714 */
715 static int
716 verify_callback_client_dane(int preverify_ok, X509_STORE_CTX * x509ctx)
717 {
718 X509 * cert = X509_STORE_CTX_get_current_cert(x509ctx);
719 uschar dn[256];
720 int depth = X509_STORE_CTX_get_error_depth(x509ctx);
721 #ifndef DISABLE_EVENT
722 BOOL dummy_called, optional = FALSE;
723 #endif
724
725 if (!X509_NAME_oneline(X509_get_subject_name(cert), CS dn, sizeof(dn)))
726 {
727 DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n");
728 log_write(0, LOG_MAIN, "[%s] SSL verify error: internal error",
729 deliver_host_address);
730 return 0;
731 }
732 dn[sizeof(dn)-1] = '\0';
733
734 DEBUG(D_tls) debug_printf("verify_callback_client_dane: %s depth %d %s\n",
735 preverify_ok ? "ok":"BAD", depth, dn);
736
737 #ifndef DISABLE_EVENT
738 if (verify_event(&tls_out, cert, depth, dn,
739 &dummy_called, &optional, US"DANE"))
740 return 0; /* reject, with peercert set */
741 #endif
742
743 if (preverify_ok == 1)
744 {
745 tls_out.dane_verified = tls_out.certificate_verified = TRUE;
746 #ifndef DISABLE_OCSP
747 if (client_static_cbinfo->u_ocsp.client.verify_store)
748 { /* client, wanting stapling */
749 /* Add the server cert's signing chain as the one
750 for the verification of the OCSP stapled information. */
751
752 if (!X509_STORE_add_cert(client_static_cbinfo->u_ocsp.client.verify_store,
753 cert))
754 ERR_clear_error();
755 sk_X509_push(client_static_cbinfo->verify_stack, cert);
756 }
757 #endif
758 }
759 else
760 {
761 int err = X509_STORE_CTX_get_error(x509ctx);
762 DEBUG(D_tls)
763 debug_printf(" - err %d '%s'\n", err, X509_verify_cert_error_string(err));
764 if (err == X509_V_ERR_APPLICATION_VERIFICATION)
765 preverify_ok = 1;
766 }
767 return preverify_ok;
768 }
769
770 #endif /*SUPPORT_DANE*/
771
772
773 /*************************************************
774 * Information callback *
775 *************************************************/
776
777 /* The SSL library functions call this from time to time to indicate what they
778 are doing. We copy the string to the debugging output when TLS debugging has
779 been requested.
780
781 Arguments:
782 s the SSL connection
783 where
784 ret
785
786 Returns: nothing
787 */
788
789 static void
790 info_callback(SSL *s, int where, int ret)
791 {
792 DEBUG(D_tls)
793 {
794 const uschar * str;
795
796 if (where & SSL_ST_CONNECT)
797 str = US"SSL_connect";
798 else if (where & SSL_ST_ACCEPT)
799 str = US"SSL_accept";
800 else
801 str = US"SSL info (undefined)";
802
803 if (where & SSL_CB_LOOP)
804 debug_printf("%s: %s\n", str, SSL_state_string_long(s));
805 else if (where & SSL_CB_ALERT)
806 debug_printf("SSL3 alert %s:%s:%s\n",
807 str = where & SSL_CB_READ ? US"read" : US"write",
808 SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
809 else if (where & SSL_CB_EXIT)
810 if (ret == 0)
811 debug_printf("%s: failed in %s\n", str, SSL_state_string_long(s));
812 else if (ret < 0)
813 debug_printf("%s: error in %s\n", str, SSL_state_string_long(s));
814 else if (where & SSL_CB_HANDSHAKE_START)
815 debug_printf("%s: hshake start: %s\n", str, SSL_state_string_long(s));
816 else if (where & SSL_CB_HANDSHAKE_DONE)
817 debug_printf("%s: hshake done: %s\n", str, SSL_state_string_long(s));
818 }
819 }
820
821 #ifdef OPENSSL_HAVE_KEYLOG_CB
822 static void
823 keylog_callback(const SSL *ssl, const char *line)
824 {
825 DEBUG(D_tls) debug_printf("%.200s\n", line);
826 }
827 #endif
828
829
830 #ifdef EXPERIMENTAL_TLS_RESUME
831 /* Manage the keysets used for encrypting the session tickets, on the server. */
832
833 typedef struct { /* Session ticket encryption key */
834 uschar name[16];
835
836 const EVP_CIPHER * aes_cipher;
837 uschar aes_key[16]; /* size needed depends on cipher. aes_128 implies 128/8 = 16? */
838 const EVP_MD * hmac_hash;
839 uschar hmac_key[16];
840 time_t renew;
841 time_t expire;
842 } exim_stek;
843
844 /*XXX for now just always create/find the one key.
845 Worry about rotation and overlap later. */
846
847 static exim_stek exim_tk;
848 static exim_stek exim_tk_old;
849
850 static void
851 tk_init(void)
852 {
853 if (exim_tk.name[0])
854 {
855 if (exim_tk.renew >= time(NULL)) return;
856 exim_tk_old = exim_tk;
857 }
858
859 if (f.running_in_test_harness) ssl_session_timeout = 6;
860
861 DEBUG(D_tls) debug_printf("OpenSSL: %s STEK\n", exim_tk.name[0] ? "rotating" : "creating");
862 if (RAND_bytes(exim_tk.aes_key, sizeof(exim_tk.aes_key)) <= 0) return;
863 if (RAND_bytes(exim_tk.hmac_key, sizeof(exim_tk.hmac_key)) <= 0) return;
864 if (RAND_bytes(exim_tk.name+1, sizeof(exim_tk.name)-1) <= 0) return;
865
866 exim_tk.name[0] = 'E';
867 exim_tk.aes_cipher = EVP_aes_128_cbc();
868 exim_tk.hmac_hash = EVP_sha256();
869 exim_tk.expire = time(NULL) + ssl_session_timeout;
870 exim_tk.renew = exim_tk.expire - ssl_session_timeout/2;
871 }
872
873 static exim_stek *
874 tk_current(void)
875 {
876 if (!exim_tk.name[0]) return NULL;
877 return &exim_tk;
878 }
879
880 static exim_stek *
881 tk_find(const uschar * name)
882 {
883 return memcmp(name, exim_tk.name, sizeof(exim_tk.name)) == 0 ? &exim_tk
884 : memcmp(name, exim_tk_old.name, sizeof(exim_tk_old.name)) == 0 ? &exim_tk_old
885 : NULL;
886 }
887
888 /* Callback for session tickets, on server */
889 static int
890 ticket_key_callback(SSL * ssl, uschar key_name[16],
891 uschar * iv, EVP_CIPHER_CTX * ctx, HMAC_CTX * hctx, int enc)
892 {
893 tls_support * tlsp = server_static_cbinfo->tlsp;
894 exim_stek * key;
895
896 if (enc)
897 {
898 DEBUG(D_tls) debug_printf("ticket_key_callback: create new session\n");
899 tlsp->resumption |= RESUME_CLIENT_REQUESTED;
900
901 if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0)
902 return -1; /* insufficient random */
903
904 if (!(key = tk_current())) /* current key doesn't exist or isn't valid */
905 return 0; /* key couldn't be created */
906 memcpy(key_name, key->name, 16);
907 DEBUG(D_tls) debug_printf("STEK expire %ld\n", key->expire - time(NULL));
908
909 /*XXX will want these dependent on the ssl session strength */
910 HMAC_Init_ex(hctx, key->hmac_key, sizeof(key->hmac_key),
911 key->hmac_hash, NULL);
912 EVP_EncryptInit_ex(ctx, key->aes_cipher, NULL, key->aes_key, iv);
913
914 DEBUG(D_tls) debug_printf("ticket created\n");
915 return 1;
916 }
917 else
918 {
919 time_t now = time(NULL);
920
921 DEBUG(D_tls) debug_printf("ticket_key_callback: retrieve session\n");
922 tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
923
924 if (!(key = tk_find(key_name)) || key->expire < now)
925 {
926 DEBUG(D_tls)
927 {
928 debug_printf("ticket not usable (%s)\n", key ? "expired" : "not found");
929 if (key) debug_printf("STEK expire %ld\n", key->expire - now);
930 }
931 return 0;
932 }
933
934 HMAC_Init_ex(hctx, key->hmac_key, sizeof(key->hmac_key),
935 key->hmac_hash, NULL);
936 EVP_DecryptInit_ex(ctx, key->aes_cipher, NULL, key->aes_key, iv);
937
938 DEBUG(D_tls) debug_printf("ticket usable, STEK expire %ld\n", key->expire - now);
939 return key->renew < now ? 2 : 1;
940 }
941 }
942 #endif
943
944
945
946 /*************************************************
947 * Initialize for DH *
948 *************************************************/
949
950 /* If dhparam is set, expand it, and load up the parameters for DH encryption.
951
952 Arguments:
953 sctx The current SSL CTX (inbound or outbound)
954 dhparam DH parameter file or fixed parameter identity string
955 host connected host, if client; NULL if server
956 errstr error string pointer
957
958 Returns: TRUE if OK (nothing to set up, or setup worked)
959 */
960
961 static BOOL
962 init_dh(SSL_CTX *sctx, uschar *dhparam, const host_item *host, uschar ** errstr)
963 {
964 BIO *bio;
965 DH *dh;
966 uschar *dhexpanded;
967 const char *pem;
968 int dh_bitsize;
969
970 if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded, errstr))
971 return FALSE;
972
973 if (!dhexpanded || !*dhexpanded)
974 bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
975 else if (dhexpanded[0] == '/')
976 {
977 if (!(bio = BIO_new_file(CS dhexpanded, "r")))
978 {
979 tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
980 host, US strerror(errno), errstr);
981 return FALSE;
982 }
983 }
984 else
985 {
986 if (Ustrcmp(dhexpanded, "none") == 0)
987 {
988 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
989 return TRUE;
990 }
991
992 if (!(pem = std_dh_prime_named(dhexpanded)))
993 {
994 tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
995 host, US strerror(errno), errstr);
996 return FALSE;
997 }
998 bio = BIO_new_mem_buf(CS pem, -1);
999 }
1000
1001 if (!(dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)))
1002 {
1003 BIO_free(bio);
1004 tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
1005 host, NULL, errstr);
1006 return FALSE;
1007 }
1008
1009 /* note: our default limit of 2236 is not a multiple of 8; the limit comes from
1010 * an NSS limit, and the GnuTLS APIs handle bit-sizes fine, so we went with
1011 * 2236. But older OpenSSL can only report in bytes (octets), not bits.
1012 * If someone wants to dance at the edge, then they can raise the limit or use
1013 * current libraries. */
1014 #ifdef EXIM_HAVE_OPENSSL_DH_BITS
1015 /* Added in commit 26c79d5641d; `git describe --contains` says OpenSSL_1_1_0-pre1~1022
1016 * This predates OpenSSL_1_1_0 (before a, b, ...) so is in all 1.1.0 */
1017 dh_bitsize = DH_bits(dh);
1018 #else
1019 dh_bitsize = 8 * DH_size(dh);
1020 #endif
1021
1022 /* Even if it is larger, we silently return success rather than cause things
1023 * to fail out, so that a too-large DH will not knock out all TLS; it's a
1024 * debatable choice. */
1025 if (dh_bitsize > tls_dh_max_bits)
1026 {
1027 DEBUG(D_tls)
1028 debug_printf("dhparams file %d bits, is > tls_dh_max_bits limit of %d\n",
1029 dh_bitsize, tls_dh_max_bits);
1030 }
1031 else
1032 {
1033 SSL_CTX_set_tmp_dh(sctx, dh);
1034 DEBUG(D_tls)
1035 debug_printf("Diffie-Hellman initialized from %s with %d-bit prime\n",
1036 dhexpanded ? dhexpanded : US"default", dh_bitsize);
1037 }
1038
1039 DH_free(dh);
1040 BIO_free(bio);
1041
1042 return TRUE;
1043 }
1044
1045
1046
1047
1048 /*************************************************
1049 * Initialize for ECDH *
1050 *************************************************/
1051
1052 /* Load parameters for ECDH encryption.
1053
1054 For now, we stick to NIST P-256 because: it's simple and easy to configure;
1055 it avoids any patent issues that might bite redistributors; despite events in
1056 the news and concerns over curve choices, we're not cryptographers, we're not
1057 pretending to be, and this is "good enough" to be better than no support,
1058 protecting against most adversaries. Given another year or two, there might
1059 be sufficient clarity about a "right" way forward to let us make an informed
1060 decision, instead of a knee-jerk reaction.
1061
1062 Longer-term, we should look at supporting both various named curves and
1063 external files generated with "openssl ecparam", much as we do for init_dh().
1064 We should also support "none" as a value, to explicitly avoid initialisation.
1065
1066 Patches welcome.
1067
1068 Arguments:
1069 sctx The current SSL CTX (inbound or outbound)
1070 host connected host, if client; NULL if server
1071 errstr error string pointer
1072
1073 Returns: TRUE if OK (nothing to set up, or setup worked)
1074 */
1075
1076 static BOOL
1077 init_ecdh(SSL_CTX * sctx, host_item * host, uschar ** errstr)
1078 {
1079 #ifdef OPENSSL_NO_ECDH
1080 return TRUE;
1081 #else
1082
1083 EC_KEY * ecdh;
1084 uschar * exp_curve;
1085 int nid;
1086 BOOL rv;
1087
1088 if (host) /* No ECDH setup for clients, only for servers */
1089 return TRUE;
1090
1091 # ifndef EXIM_HAVE_ECDH
1092 DEBUG(D_tls)
1093 debug_printf("No OpenSSL API to define ECDH parameters, skipping\n");
1094 return TRUE;
1095 # else
1096
1097 if (!expand_check(tls_eccurve, US"tls_eccurve", &exp_curve, errstr))
1098 return FALSE;
1099 if (!exp_curve || !*exp_curve)
1100 return TRUE;
1101
1102 /* "auto" needs to be handled carefully.
1103 * OpenSSL < 1.0.2: we do not select anything, but fallback to prime256v1
1104 * OpenSSL < 1.1.0: we have to call SSL_CTX_set_ecdh_auto
1105 * (openssl/ssl.h defines SSL_CTRL_SET_ECDH_AUTO)
1106 * OpenSSL >= 1.1.0: we do not set anything, the libray does autoselection
1107 * https://github.com/openssl/openssl/commit/fe6ef2472db933f01b59cad82aa925736935984b
1108 */
1109 if (Ustrcmp(exp_curve, "auto") == 0)
1110 {
1111 #if OPENSSL_VERSION_NUMBER < 0x10002000L
1112 DEBUG(D_tls) debug_printf(
1113 "ECDH OpenSSL < 1.0.2: temp key parameter settings: overriding \"auto\" with \"prime256v1\"\n");
1114 exp_curve = US"prime256v1";
1115 #else
1116 # if defined SSL_CTRL_SET_ECDH_AUTO
1117 DEBUG(D_tls) debug_printf(
1118 "ECDH OpenSSL 1.0.2+ temp key parameter settings: autoselection\n");
1119 SSL_CTX_set_ecdh_auto(sctx, 1);
1120 return TRUE;
1121 # else
1122 DEBUG(D_tls) debug_printf(
1123 "ECDH OpenSSL 1.1.0+ temp key parameter settings: default selection\n");
1124 return TRUE;
1125 # endif
1126 #endif
1127 }
1128
1129 DEBUG(D_tls) debug_printf("ECDH: curve '%s'\n", exp_curve);
1130 if ( (nid = OBJ_sn2nid (CCS exp_curve)) == NID_undef
1131 # ifdef EXIM_HAVE_OPENSSL_EC_NIST2NID
1132 && (nid = EC_curve_nist2nid(CCS exp_curve)) == NID_undef
1133 # endif
1134 )
1135 {
1136 tls_error(string_sprintf("Unknown curve name tls_eccurve '%s'", exp_curve),
1137 host, NULL, errstr);
1138 return FALSE;
1139 }
1140
1141 if (!(ecdh = EC_KEY_new_by_curve_name(nid)))
1142 {
1143 tls_error(US"Unable to create ec curve", host, NULL, errstr);
1144 return FALSE;
1145 }
1146
1147 /* The "tmp" in the name here refers to setting a temporary key
1148 not to the stability of the interface. */
1149
1150 if ((rv = SSL_CTX_set_tmp_ecdh(sctx, ecdh) == 0))
1151 tls_error(string_sprintf("Error enabling '%s' curve", exp_curve), host, NULL, errstr);
1152 else
1153 DEBUG(D_tls) debug_printf("ECDH: enabled '%s' curve\n", exp_curve);
1154
1155 EC_KEY_free(ecdh);
1156 return !rv;
1157
1158 # endif /*EXIM_HAVE_ECDH*/
1159 #endif /*OPENSSL_NO_ECDH*/
1160 }
1161
1162
1163
1164
1165 #ifndef DISABLE_OCSP
1166 /*************************************************
1167 * Load OCSP information into state *
1168 *************************************************/
1169 /* Called to load the server OCSP response from the given file into memory, once
1170 caller has determined this is needed. Checks validity. Debugs a message
1171 if invalid.
1172
1173 ASSUMES: single response, for single cert.
1174
1175 Arguments:
1176 sctx the SSL_CTX* to update
1177 cbinfo various parts of session state
1178 expanded the filename putatively holding an OCSP response
1179
1180 */
1181
1182 static void
1183 ocsp_load_response(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo, const uschar *expanded)
1184 {
1185 BIO * bio;
1186 OCSP_RESPONSE * resp;
1187 OCSP_BASICRESP * basic_response;
1188 OCSP_SINGLERESP * single_response;
1189 ASN1_GENERALIZEDTIME * rev, * thisupd, * nextupd;
1190 STACK_OF(X509) * sk;
1191 unsigned long verify_flags;
1192 int status, reason, i;
1193
1194 cbinfo->u_ocsp.server.file_expanded = string_copy(expanded);
1195 if (cbinfo->u_ocsp.server.response)
1196 {
1197 OCSP_RESPONSE_free(cbinfo->u_ocsp.server.response);
1198 cbinfo->u_ocsp.server.response = NULL;
1199 }
1200
1201 if (!(bio = BIO_new_file(CS cbinfo->u_ocsp.server.file_expanded, "rb")))
1202 {
1203 DEBUG(D_tls) debug_printf("Failed to open OCSP response file \"%s\"\n",
1204 cbinfo->u_ocsp.server.file_expanded);
1205 return;
1206 }
1207
1208 resp = d2i_OCSP_RESPONSE_bio(bio, NULL);
1209 BIO_free(bio);
1210 if (!resp)
1211 {
1212 DEBUG(D_tls) debug_printf("Error reading OCSP response.\n");
1213 return;
1214 }
1215
1216 if ((status = OCSP_response_status(resp)) != OCSP_RESPONSE_STATUS_SUCCESSFUL)
1217 {
1218 DEBUG(D_tls) debug_printf("OCSP response not valid: %s (%d)\n",
1219 OCSP_response_status_str(status), status);
1220 goto bad;
1221 }
1222
1223 if (!(basic_response = OCSP_response_get1_basic(resp)))
1224 {
1225 DEBUG(D_tls)
1226 debug_printf("OCSP response parse error: unable to extract basic response.\n");
1227 goto bad;
1228 }
1229
1230 sk = cbinfo->verify_stack;
1231 verify_flags = OCSP_NOVERIFY; /* check sigs, but not purpose */
1232
1233 /* May need to expose ability to adjust those flags?
1234 OCSP_NOSIGS OCSP_NOVERIFY OCSP_NOCHAIN OCSP_NOCHECKS OCSP_NOEXPLICIT
1235 OCSP_TRUSTOTHER OCSP_NOINTERN */
1236
1237 /* This does a full verify on the OCSP proof before we load it for serving
1238 up; possibly overkill - just date-checks might be nice enough.
1239
1240 OCSP_basic_verify takes a "store" arg, but does not
1241 use it for the chain verification, which is all we do
1242 when OCSP_NOVERIFY is set. The content from the wire
1243 "basic_response" and a cert-stack "sk" are all that is used.
1244
1245 We have a stack, loaded in setup_certs() if tls_verify_certificates
1246 was a file (not a directory, or "system"). It is unfortunate we
1247 cannot used the connection context store, as that would neatly
1248 handle the "system" case too, but there seems to be no library
1249 function for getting a stack from a store.
1250 [ In OpenSSL 1.1 - ? X509_STORE_CTX_get0_chain(ctx) ? ]
1251 We do not free the stack since it could be needed a second time for
1252 SNI handling.
1253
1254 Separately we might try to replace using OCSP_basic_verify() - which seems to not
1255 be a public interface into the OpenSSL library (there's no manual entry) -
1256 But what with? We also use OCSP_basic_verify in the client stapling callback.
1257 And there we NEED it; we must verify that status... unless the
1258 library does it for us anyway? */
1259
1260 if ((i = OCSP_basic_verify(basic_response, sk, NULL, verify_flags)) < 0)
1261 {
1262 DEBUG(D_tls)
1263 {
1264 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1265 debug_printf("OCSP response verify failure: %s\n", US ssl_errstring);
1266 }
1267 goto bad;
1268 }
1269
1270 /* Here's the simplifying assumption: there's only one response, for the
1271 one certificate we use, and nothing for anything else in a chain. If this
1272 proves false, we need to extract a cert id from our issued cert
1273 (tls_certificate) and use that for OCSP_resp_find_status() (which finds the
1274 right cert in the stack and then calls OCSP_single_get0_status()).
1275
1276 I'm hoping to avoid reworking a bunch more of how we handle state here. */
1277
1278 if (!(single_response = OCSP_resp_get0(basic_response, 0)))
1279 {
1280 DEBUG(D_tls)
1281 debug_printf("Unable to get first response from OCSP basic response.\n");
1282 goto bad;
1283 }
1284
1285 status = OCSP_single_get0_status(single_response, &reason, &rev, &thisupd, &nextupd);
1286 if (status != V_OCSP_CERTSTATUS_GOOD)
1287 {
1288 DEBUG(D_tls) debug_printf("OCSP response bad cert status: %s (%d) %s (%d)\n",
1289 OCSP_cert_status_str(status), status,
1290 OCSP_crl_reason_str(reason), reason);
1291 goto bad;
1292 }
1293
1294 if (!OCSP_check_validity(thisupd, nextupd, EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1295 {
1296 DEBUG(D_tls) debug_printf("OCSP status invalid times.\n");
1297 goto bad;
1298 }
1299
1300 supply_response:
1301 cbinfo->u_ocsp.server.response = resp; /*XXX stack?*/
1302 return;
1303
1304 bad:
1305 if (f.running_in_test_harness)
1306 {
1307 extern char ** environ;
1308 if (environ) for (uschar ** p = USS environ; *p; p++)
1309 if (Ustrncmp(*p, "EXIM_TESTHARNESS_DISABLE_OCSPVALIDITYCHECK", 42) == 0)
1310 {
1311 DEBUG(D_tls) debug_printf("Supplying known bad OCSP response\n");
1312 goto supply_response;
1313 }
1314 }
1315 return;
1316 }
1317 #endif /*!DISABLE_OCSP*/
1318
1319
1320
1321
1322 /* Create and install a selfsigned certificate, for use in server mode */
1323
1324 static int
1325 tls_install_selfsign(SSL_CTX * sctx, uschar ** errstr)
1326 {
1327 X509 * x509 = NULL;
1328 EVP_PKEY * pkey;
1329 RSA * rsa;
1330 X509_NAME * name;
1331 uschar * where;
1332
1333 where = US"allocating pkey";
1334 if (!(pkey = EVP_PKEY_new()))
1335 goto err;
1336
1337 where = US"allocating cert";
1338 if (!(x509 = X509_new()))
1339 goto err;
1340
1341 where = US"generating pkey";
1342 if (!(rsa = rsa_callback(NULL, 0, 2048)))
1343 goto err;
1344
1345 where = US"assigning pkey";
1346 if (!EVP_PKEY_assign_RSA(pkey, rsa))
1347 goto err;
1348
1349 X509_set_version(x509, 2); /* N+1 - version 3 */
1350 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
1351 X509_gmtime_adj(X509_get_notBefore(x509), 0);
1352 X509_gmtime_adj(X509_get_notAfter(x509), (long)60 * 60); /* 1 hour */
1353 X509_set_pubkey(x509, pkey);
1354
1355 name = X509_get_subject_name(x509);
1356 X509_NAME_add_entry_by_txt(name, "C",
1357 MBSTRING_ASC, CUS "UK", -1, -1, 0);
1358 X509_NAME_add_entry_by_txt(name, "O",
1359 MBSTRING_ASC, CUS "Exim Developers", -1, -1, 0);
1360 X509_NAME_add_entry_by_txt(name, "CN",
1361 MBSTRING_ASC, CUS smtp_active_hostname, -1, -1, 0);
1362 X509_set_issuer_name(x509, name);
1363
1364 where = US"signing cert";
1365 if (!X509_sign(x509, pkey, EVP_md5()))
1366 goto err;
1367
1368 where = US"installing selfsign cert";
1369 if (!SSL_CTX_use_certificate(sctx, x509))
1370 goto err;
1371
1372 where = US"installing selfsign key";
1373 if (!SSL_CTX_use_PrivateKey(sctx, pkey))
1374 goto err;
1375
1376 return OK;
1377
1378 err:
1379 (void) tls_error(where, NULL, NULL, errstr);
1380 if (x509) X509_free(x509);
1381 if (pkey) EVP_PKEY_free(pkey);
1382 return DEFER;
1383 }
1384
1385
1386
1387
1388 static int
1389 tls_add_certfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1390 uschar ** errstr)
1391 {
1392 DEBUG(D_tls) debug_printf("tls_certificate file %s\n", file);
1393 if (!SSL_CTX_use_certificate_chain_file(sctx, CS file))
1394 return tls_error(string_sprintf(
1395 "SSL_CTX_use_certificate_chain_file file=%s", file),
1396 cbinfo->host, NULL, errstr);
1397 return 0;
1398 }
1399
1400 static int
1401 tls_add_pkeyfile(SSL_CTX * sctx, tls_ext_ctx_cb * cbinfo, uschar * file,
1402 uschar ** errstr)
1403 {
1404 DEBUG(D_tls) debug_printf("tls_privatekey file %s\n", file);
1405 if (!SSL_CTX_use_PrivateKey_file(sctx, CS file, SSL_FILETYPE_PEM))
1406 return tls_error(string_sprintf(
1407 "SSL_CTX_use_PrivateKey_file file=%s", file), cbinfo->host, NULL, errstr);
1408 return 0;
1409 }
1410
1411
1412 /*************************************************
1413 * Expand key and cert file specs *
1414 *************************************************/
1415
1416 /* Called once during tls_init and possibly again during TLS setup, for a
1417 new context, if Server Name Indication was used and tls_sni was seen in
1418 the certificate string.
1419
1420 Arguments:
1421 sctx the SSL_CTX* to update
1422 cbinfo various parts of session state
1423 errstr error string pointer
1424
1425 Returns: OK/DEFER/FAIL
1426 */
1427
1428 static int
1429 tls_expand_session_files(SSL_CTX *sctx, tls_ext_ctx_cb *cbinfo,
1430 uschar ** errstr)
1431 {
1432 uschar *expanded;
1433
1434 if (!cbinfo->certificate)
1435 {
1436 if (!cbinfo->is_server) /* client */
1437 return OK;
1438 /* server */
1439 if (tls_install_selfsign(sctx, errstr) != OK)
1440 return DEFER;
1441 }
1442 else
1443 {
1444 int err;
1445
1446 if (Ustrstr(cbinfo->certificate, US"tls_sni") ||
1447 Ustrstr(cbinfo->certificate, US"tls_in_sni") ||
1448 Ustrstr(cbinfo->certificate, US"tls_out_sni")
1449 )
1450 reexpand_tls_files_for_sni = TRUE;
1451
1452 if (!expand_check(cbinfo->certificate, US"tls_certificate", &expanded, errstr))
1453 return DEFER;
1454
1455 if (expanded)
1456 if (cbinfo->is_server)
1457 {
1458 const uschar * file_list = expanded;
1459 int sep = 0;
1460 uschar * file;
1461
1462 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1463 if ((err = tls_add_certfile(sctx, cbinfo, file, errstr)))
1464 return err;
1465 }
1466 else /* would there ever be a need for multiple client certs? */
1467 if ((err = tls_add_certfile(sctx, cbinfo, expanded, errstr)))
1468 return err;
1469
1470 if ( cbinfo->privatekey
1471 && !expand_check(cbinfo->privatekey, US"tls_privatekey", &expanded, errstr))
1472 return DEFER;
1473
1474 /* If expansion was forced to fail, key_expanded will be NULL. If the result
1475 of the expansion is an empty string, ignore it also, and assume the private
1476 key is in the same file as the certificate. */
1477
1478 if (expanded && *expanded)
1479 if (cbinfo->is_server)
1480 {
1481 const uschar * file_list = expanded;
1482 int sep = 0;
1483 uschar * file;
1484
1485 while (file = string_nextinlist(&file_list, &sep, NULL, 0))
1486 if ((err = tls_add_pkeyfile(sctx, cbinfo, file, errstr)))
1487 return err;
1488 }
1489 else /* would there ever be a need for multiple client certs? */
1490 if ((err = tls_add_pkeyfile(sctx, cbinfo, expanded, errstr)))
1491 return err;
1492 }
1493
1494 #ifndef DISABLE_OCSP
1495 if (cbinfo->is_server && cbinfo->u_ocsp.server.file)
1496 {
1497 /*XXX stack*/
1498 if (!expand_check(cbinfo->u_ocsp.server.file, US"tls_ocsp_file", &expanded, errstr))
1499 return DEFER;
1500
1501 if (expanded && *expanded)
1502 {
1503 DEBUG(D_tls) debug_printf("tls_ocsp_file %s\n", expanded);
1504 if ( cbinfo->u_ocsp.server.file_expanded
1505 && (Ustrcmp(expanded, cbinfo->u_ocsp.server.file_expanded) == 0))
1506 {
1507 DEBUG(D_tls) debug_printf(" - value unchanged, using existing values\n");
1508 }
1509 else
1510 ocsp_load_response(sctx, cbinfo, expanded);
1511 }
1512 }
1513 #endif
1514
1515 return OK;
1516 }
1517
1518
1519
1520
1521 /*************************************************
1522 * Callback to handle SNI *
1523 *************************************************/
1524
1525 /* Called when acting as server during the TLS session setup if a Server Name
1526 Indication extension was sent by the client.
1527
1528 API documentation is OpenSSL s_server.c implementation.
1529
1530 Arguments:
1531 s SSL* of the current session
1532 ad unknown (part of OpenSSL API) (unused)
1533 arg Callback of "our" registered data
1534
1535 Returns: SSL_TLSEXT_ERR_{OK,ALERT_WARNING,ALERT_FATAL,NOACK}
1536
1537 XXX might need to change to using ClientHello callback,
1538 per https://www.openssl.org/docs/manmaster/man3/SSL_client_hello_cb_fn.html
1539 */
1540
1541 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
1542 static int
1543 tls_servername_cb(SSL *s, int *ad ARG_UNUSED, void *arg)
1544 {
1545 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
1546 tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1547 int rc;
1548 int old_pool = store_pool;
1549 uschar * dummy_errstr;
1550
1551 if (!servername)
1552 return SSL_TLSEXT_ERR_OK;
1553
1554 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", servername,
1555 reexpand_tls_files_for_sni ? "" : " (unused for certificate selection)");
1556
1557 /* Make the extension value available for expansion */
1558 store_pool = POOL_PERM;
1559 tls_in.sni = string_copy(US servername);
1560 store_pool = old_pool;
1561
1562 if (!reexpand_tls_files_for_sni)
1563 return SSL_TLSEXT_ERR_OK;
1564
1565 /* Can't find an SSL_CTX_clone() or equivalent, so we do it manually;
1566 not confident that memcpy wouldn't break some internal reference counting.
1567 Especially since there's a references struct member, which would be off. */
1568
1569 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1570 if (!(server_sni = SSL_CTX_new(TLS_server_method())))
1571 #else
1572 if (!(server_sni = SSL_CTX_new(SSLv23_server_method())))
1573 #endif
1574 {
1575 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
1576 DEBUG(D_tls) debug_printf("SSL_CTX_new() failed: %s\n", ssl_errstring);
1577 goto bad;
1578 }
1579
1580 /* Not sure how many of these are actually needed, since SSL object
1581 already exists. Might even need this selfsame callback, for reneg? */
1582
1583 SSL_CTX_set_info_callback(server_sni, SSL_CTX_get_info_callback(server_ctx));
1584 SSL_CTX_set_mode(server_sni, SSL_CTX_get_mode(server_ctx));
1585 SSL_CTX_set_options(server_sni, SSL_CTX_get_options(server_ctx));
1586 SSL_CTX_set_timeout(server_sni, SSL_CTX_get_timeout(server_ctx));
1587 SSL_CTX_set_tlsext_servername_callback(server_sni, tls_servername_cb);
1588 SSL_CTX_set_tlsext_servername_arg(server_sni, cbinfo);
1589
1590 if ( !init_dh(server_sni, cbinfo->dhparam, NULL, &dummy_errstr)
1591 || !init_ecdh(server_sni, NULL, &dummy_errstr)
1592 )
1593 goto bad;
1594
1595 if ( cbinfo->server_cipher_list
1596 && !SSL_CTX_set_cipher_list(server_sni, CS cbinfo->server_cipher_list))
1597 goto bad;
1598
1599 #ifndef DISABLE_OCSP
1600 if (cbinfo->u_ocsp.server.file)
1601 {
1602 SSL_CTX_set_tlsext_status_cb(server_sni, tls_server_stapling_cb);
1603 SSL_CTX_set_tlsext_status_arg(server_sni, cbinfo);
1604 }
1605 #endif
1606
1607 if ((rc = setup_certs(server_sni, tls_verify_certificates, tls_crl, NULL, FALSE,
1608 verify_callback_server, &dummy_errstr)) != OK)
1609 goto bad;
1610
1611 /* do this after setup_certs, because this can require the certs for verifying
1612 OCSP information. */
1613 if ((rc = tls_expand_session_files(server_sni, cbinfo, &dummy_errstr)) != OK)
1614 goto bad;
1615
1616 DEBUG(D_tls) debug_printf("Switching SSL context.\n");
1617 SSL_set_SSL_CTX(s, server_sni);
1618 return SSL_TLSEXT_ERR_OK;
1619
1620 bad: return SSL_TLSEXT_ERR_ALERT_FATAL;
1621 }
1622 #endif /* EXIM_HAVE_OPENSSL_TLSEXT */
1623
1624
1625
1626
1627 #ifndef DISABLE_OCSP
1628
1629 /*************************************************
1630 * Callback to handle OCSP Stapling *
1631 *************************************************/
1632
1633 /* Called when acting as server during the TLS session setup if the client
1634 requests OCSP information with a Certificate Status Request.
1635
1636 Documentation via openssl s_server.c and the Apache patch from the OpenSSL
1637 project.
1638
1639 */
1640
1641 static int
1642 tls_server_stapling_cb(SSL *s, void *arg)
1643 {
1644 const tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
1645 uschar *response_der; /*XXX blob */
1646 int response_der_len;
1647
1648 /*XXX stack: use SSL_get_certificate() to see which cert; from that work
1649 out which ocsp blob to send. Unfortunately, SSL_get_certificate is known
1650 buggy in current OpenSSL; it returns the last cert loaded always rather than
1651 the one actually presented. So we can't support a stack of OCSP proofs at
1652 this time. */
1653
1654 DEBUG(D_tls)
1655 debug_printf("Received TLS status request (OCSP stapling); %s response\n",
1656 cbinfo->u_ocsp.server.response ? "have" : "lack");
1657
1658 tls_in.ocsp = OCSP_NOT_RESP;
1659 if (!cbinfo->u_ocsp.server.response)
1660 return SSL_TLSEXT_ERR_NOACK;
1661
1662 response_der = NULL;
1663 response_der_len = i2d_OCSP_RESPONSE(cbinfo->u_ocsp.server.response, /*XXX stack*/
1664 &response_der);
1665 if (response_der_len <= 0)
1666 return SSL_TLSEXT_ERR_NOACK;
1667
1668 SSL_set_tlsext_status_ocsp_resp(server_ssl, response_der, response_der_len);
1669 tls_in.ocsp = OCSP_VFIED;
1670 return SSL_TLSEXT_ERR_OK;
1671 }
1672
1673
1674 static void
1675 time_print(BIO * bp, const char * str, ASN1_GENERALIZEDTIME * time)
1676 {
1677 BIO_printf(bp, "\t%s: ", str);
1678 ASN1_GENERALIZEDTIME_print(bp, time);
1679 BIO_puts(bp, "\n");
1680 }
1681
1682 static int
1683 tls_client_stapling_cb(SSL *s, void *arg)
1684 {
1685 tls_ext_ctx_cb * cbinfo = arg;
1686 const unsigned char * p;
1687 int len;
1688 OCSP_RESPONSE * rsp;
1689 OCSP_BASICRESP * bs;
1690 int i;
1691
1692 DEBUG(D_tls) debug_printf("Received TLS status response (OCSP stapling):");
1693 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1694 if(!p)
1695 {
1696 /* Expect this when we requested ocsp but got none */
1697 if (cbinfo->u_ocsp.client.verify_required && LOGGING(tls_cipher))
1698 log_write(0, LOG_MAIN, "Received TLS status callback, null content");
1699 else
1700 DEBUG(D_tls) debug_printf(" null\n");
1701 return cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1702 }
1703
1704 if(!(rsp = d2i_OCSP_RESPONSE(NULL, &p, len)))
1705 {
1706 tls_out.ocsp = OCSP_FAILED;
1707 if (LOGGING(tls_cipher))
1708 log_write(0, LOG_MAIN, "Received TLS cert status response, parse error");
1709 else
1710 DEBUG(D_tls) debug_printf(" parse error\n");
1711 return 0;
1712 }
1713
1714 if(!(bs = OCSP_response_get1_basic(rsp)))
1715 {
1716 tls_out.ocsp = OCSP_FAILED;
1717 if (LOGGING(tls_cipher))
1718 log_write(0, LOG_MAIN, "Received TLS cert status response, error parsing response");
1719 else
1720 DEBUG(D_tls) debug_printf(" error parsing response\n");
1721 OCSP_RESPONSE_free(rsp);
1722 return 0;
1723 }
1724
1725 /* We'd check the nonce here if we'd put one in the request. */
1726 /* However that would defeat cacheability on the server so we don't. */
1727
1728 /* This section of code reworked from OpenSSL apps source;
1729 The OpenSSL Project retains copyright:
1730 Copyright (c) 1999 The OpenSSL Project. All rights reserved.
1731 */
1732 {
1733 BIO * bp = NULL;
1734 int status, reason;
1735 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1736
1737 DEBUG(D_tls) bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
1738
1739 /*OCSP_RESPONSE_print(bp, rsp, 0); extreme debug: stapling content */
1740
1741 /* Use the chain that verified the server cert to verify the stapled info */
1742 /* DEBUG(D_tls) x509_store_dump_cert_s_names(cbinfo->u_ocsp.client.verify_store); */
1743
1744 if ((i = OCSP_basic_verify(bs, cbinfo->verify_stack,
1745 cbinfo->u_ocsp.client.verify_store, 0)) <= 0)
1746 {
1747 tls_out.ocsp = OCSP_FAILED;
1748 if (LOGGING(tls_cipher)) log_write(0, LOG_MAIN,
1749 "Received TLS cert status response, itself unverifiable: %s",
1750 ERR_reason_error_string(ERR_peek_error()));
1751 BIO_printf(bp, "OCSP response verify failure\n");
1752 ERR_print_errors(bp);
1753 OCSP_RESPONSE_print(bp, rsp, 0);
1754 goto failed;
1755 }
1756
1757 BIO_printf(bp, "OCSP response well-formed and signed OK\n");
1758
1759 /*XXX So we have a good stapled OCSP status. How do we know
1760 it is for the cert of interest? OpenSSL 1.1.0 has a routine
1761 OCSP_resp_find_status() which matches on a cert id, which presumably
1762 we should use. Making an id needs OCSP_cert_id_new(), which takes
1763 issuerName, issuerKey, serialNumber. Are they all in the cert?
1764
1765 For now, carry on blindly accepting the resp. */
1766
1767 {
1768 OCSP_SINGLERESP * single;
1769
1770 #ifdef EXIM_HAVE_OCSP_RESP_COUNT
1771 if (OCSP_resp_count(bs) != 1)
1772 #else
1773 STACK_OF(OCSP_SINGLERESP) * sresp = bs->tbsResponseData->responses;
1774 if (sk_OCSP_SINGLERESP_num(sresp) != 1)
1775 #endif
1776 {
1777 tls_out.ocsp = OCSP_FAILED;
1778 log_write(0, LOG_MAIN, "OCSP stapling "
1779 "with multiple responses not handled");
1780 goto failed;
1781 }
1782 single = OCSP_resp_get0(bs, 0);
1783 status = OCSP_single_get0_status(single, &reason, &rev,
1784 &thisupd, &nextupd);
1785 }
1786
1787 DEBUG(D_tls) time_print(bp, "This OCSP Update", thisupd);
1788 DEBUG(D_tls) if(nextupd) time_print(bp, "Next OCSP Update", nextupd);
1789 if (!OCSP_check_validity(thisupd, nextupd,
1790 EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
1791 {
1792 tls_out.ocsp = OCSP_FAILED;
1793 DEBUG(D_tls) ERR_print_errors(bp);
1794 log_write(0, LOG_MAIN, "Server OSCP dates invalid");
1795 }
1796 else
1797 {
1798 DEBUG(D_tls) BIO_printf(bp, "Certificate status: %s\n",
1799 OCSP_cert_status_str(status));
1800 switch(status)
1801 {
1802 case V_OCSP_CERTSTATUS_GOOD:
1803 tls_out.ocsp = OCSP_VFIED;
1804 i = 1;
1805 goto good;
1806 case V_OCSP_CERTSTATUS_REVOKED:
1807 tls_out.ocsp = OCSP_FAILED;
1808 log_write(0, LOG_MAIN, "Server certificate revoked%s%s",
1809 reason != -1 ? "; reason: " : "",
1810 reason != -1 ? OCSP_crl_reason_str(reason) : "");
1811 DEBUG(D_tls) time_print(bp, "Revocation Time", rev);
1812 break;
1813 default:
1814 tls_out.ocsp = OCSP_FAILED;
1815 log_write(0, LOG_MAIN,
1816 "Server certificate status unknown, in OCSP stapling");
1817 break;
1818 }
1819 }
1820 failed:
1821 i = cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1822 good:
1823 BIO_free(bp);
1824 }
1825
1826 OCSP_RESPONSE_free(rsp);
1827 return i;
1828 }
1829 #endif /*!DISABLE_OCSP*/
1830
1831
1832 /*************************************************
1833 * Initialize for TLS *
1834 *************************************************/
1835
1836 /* Called from both server and client code, to do preliminary initialization
1837 of the library. We allocate and return a context structure.
1838
1839 Arguments:
1840 ctxp returned SSL context
1841 host connected host, if client; NULL if server
1842 dhparam DH parameter file
1843 certificate certificate file
1844 privatekey private key
1845 ocsp_file file of stapling info (server); flag for require ocsp (client)
1846 addr address if client; NULL if server (for some randomness)
1847 cbp place to put allocated callback context
1848 errstr error string pointer
1849
1850 Returns: OK/DEFER/FAIL
1851 */
1852
1853 static int
1854 tls_init(SSL_CTX **ctxp, host_item *host, uschar *dhparam, uschar *certificate,
1855 uschar *privatekey,
1856 #ifndef DISABLE_OCSP
1857 uschar *ocsp_file, /*XXX stack, in server*/
1858 #endif
1859 address_item *addr, tls_ext_ctx_cb ** cbp,
1860 tls_support * tlsp,
1861 uschar ** errstr)
1862 {
1863 SSL_CTX * ctx;
1864 long init_options;
1865 int rc;
1866 tls_ext_ctx_cb * cbinfo;
1867
1868 cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
1869 cbinfo->tlsp = tlsp;
1870 cbinfo->certificate = certificate;
1871 cbinfo->privatekey = privatekey;
1872 cbinfo->is_server = host==NULL;
1873 #ifndef DISABLE_OCSP
1874 cbinfo->verify_stack = NULL;
1875 if (!host)
1876 {
1877 cbinfo->u_ocsp.server.file = ocsp_file;
1878 cbinfo->u_ocsp.server.file_expanded = NULL;
1879 cbinfo->u_ocsp.server.response = NULL;
1880 }
1881 else
1882 cbinfo->u_ocsp.client.verify_store = NULL;
1883 #endif
1884 cbinfo->dhparam = dhparam;
1885 cbinfo->server_cipher_list = NULL;
1886 cbinfo->host = host;
1887 #ifndef DISABLE_EVENT
1888 cbinfo->event_action = NULL;
1889 #endif
1890
1891 #ifdef EXIM_NEED_OPENSSL_INIT
1892 SSL_load_error_strings(); /* basic set up */
1893 OpenSSL_add_ssl_algorithms();
1894 #endif
1895
1896 #ifdef EXIM_HAVE_SHA256
1897 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
1898 list of available digests. */
1899 EVP_add_digest(EVP_sha256());
1900 #endif
1901
1902 /* Create a context.
1903 The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
1904 negotiation in the different methods; as far as I can tell, the only
1905 *_{server,client}_method which allows negotiation is SSLv23, which exists even
1906 when OpenSSL is built without SSLv2 support.
1907 By disabling with openssl_options, we can let admins re-enable with the
1908 existing knob. */
1909
1910 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1911 if (!(ctx = SSL_CTX_new(host ? TLS_client_method() : TLS_server_method())))
1912 #else
1913 if (!(ctx = SSL_CTX_new(host ? SSLv23_client_method() : SSLv23_server_method())))
1914 #endif
1915 return tls_error(US"SSL_CTX_new", host, NULL, errstr);
1916
1917 /* It turns out that we need to seed the random number generator this early in
1918 order to get the full complement of ciphers to work. It took me roughly a day
1919 of work to discover this by experiment.
1920
1921 On systems that have /dev/urandom, SSL may automatically seed itself from
1922 there. Otherwise, we have to make something up as best we can. Double check
1923 afterwards. */
1924
1925 if (!RAND_status())
1926 {
1927 randstuff r;
1928 gettimeofday(&r.tv, NULL);
1929 r.p = getpid();
1930
1931 RAND_seed(US (&r), sizeof(r));
1932 RAND_seed(US big_buffer, big_buffer_size);
1933 if (addr != NULL) RAND_seed(US addr, sizeof(addr));
1934
1935 if (!RAND_status())
1936 return tls_error(US"RAND_status", host,
1937 US"unable to seed random number generator", errstr);
1938 }
1939
1940 /* Set up the information callback, which outputs if debugging is at a suitable
1941 level. */
1942
1943 DEBUG(D_tls)
1944 {
1945 SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
1946 #if defined(EXIM_HAVE_OPESSL_TRACE) && !defined(OPENSSL_NO_SSL_TRACE)
1947 /* this needs a debug build of OpenSSL */
1948 SSL_CTX_set_msg_callback(ctx, (void (*)())SSL_trace);
1949 #endif
1950 #ifdef OPENSSL_HAVE_KEYLOG_CB
1951 SSL_CTX_set_keylog_callback(ctx, (void (*)())keylog_callback);
1952 #endif
1953 }
1954
1955 /* Automatically re-try reads/writes after renegotiation. */
1956 (void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
1957
1958 /* Apply administrator-supplied work-arounds.
1959 Historically we applied just one requested option,
1960 SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
1961 moved to an administrator-controlled list of options to specify and
1962 grandfathered in the first one as the default value for "openssl_options".
1963
1964 No OpenSSL version number checks: the options we accept depend upon the
1965 availability of the option value macros from OpenSSL. */
1966
1967 if (!tls_openssl_options_parse(openssl_options, &init_options))
1968 return tls_error(US"openssl_options parsing failed", host, NULL, errstr);
1969
1970 #ifdef EXPERIMENTAL_TLS_RESUME
1971 tlsp->resumption = RESUME_SUPPORTED;
1972 #endif
1973 if (init_options)
1974 {
1975 #ifdef EXPERIMENTAL_TLS_RESUME
1976 /* Should the server offer session resumption? */
1977 if (!host && verify_check_host(&tls_resumption_hosts) == OK)
1978 {
1979 DEBUG(D_tls) debug_printf("tls_resumption_hosts overrides openssl_options\n");
1980 init_options &= ~SSL_OP_NO_TICKET;
1981 tlsp->resumption |= RESUME_SERVER_TICKET; /* server will give ticket on request */
1982 tlsp->host_resumable = TRUE;
1983 }
1984 #endif
1985
1986 DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
1987 if (!(SSL_CTX_set_options(ctx, init_options)))
1988 return tls_error(string_sprintf(
1989 "SSL_CTX_set_option(%#lx)", init_options), host, NULL, errstr);
1990 }
1991 else
1992 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
1993
1994 /* We'd like to disable session cache unconditionally, but foolish Outlook
1995 Express clients then give up the first TLS connection and make a second one
1996 (which works). Only when there is an IMAP service on the same machine.
1997 Presumably OE is trying to use the cache for A on B. Leave it enabled for
1998 now, until we work out a decent way of presenting control to the config. It
1999 will never be used because we use a new context every time. */
2000 #ifdef notdef
2001 (void) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2002 #endif
2003
2004 /* Initialize with DH parameters if supplied */
2005 /* Initialize ECDH temp key parameter selection */
2006
2007 if ( !init_dh(ctx, dhparam, host, errstr)
2008 || !init_ecdh(ctx, host, errstr)
2009 )
2010 return DEFER;
2011
2012 /* Set up certificate and key (and perhaps OCSP info) */
2013
2014 if ((rc = tls_expand_session_files(ctx, cbinfo, errstr)) != OK)
2015 return rc;
2016
2017 /* If we need to handle SNI or OCSP, do so */
2018
2019 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
2020 # ifndef DISABLE_OCSP
2021 if (!(cbinfo->verify_stack = sk_X509_new_null()))
2022 {
2023 DEBUG(D_tls) debug_printf("failed to create stack for stapling verify\n");
2024 return FAIL;
2025 }
2026 # endif
2027
2028 if (!host) /* server */
2029 {
2030 # ifndef DISABLE_OCSP
2031 /* We check u_ocsp.server.file, not server.response, because we care about if
2032 the option exists, not what the current expansion might be, as SNI might
2033 change the certificate and OCSP file in use between now and the time the
2034 callback is invoked. */
2035 if (cbinfo->u_ocsp.server.file)
2036 {
2037 SSL_CTX_set_tlsext_status_cb(ctx, tls_server_stapling_cb);
2038 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
2039 }
2040 # endif
2041 /* We always do this, so that $tls_sni is available even if not used in
2042 tls_certificate */
2043 SSL_CTX_set_tlsext_servername_callback(ctx, tls_servername_cb);
2044 SSL_CTX_set_tlsext_servername_arg(ctx, cbinfo);
2045 }
2046 # ifndef DISABLE_OCSP
2047 else /* client */
2048 if(ocsp_file) /* wanting stapling */
2049 {
2050 if (!(cbinfo->u_ocsp.client.verify_store = X509_STORE_new()))
2051 {
2052 DEBUG(D_tls) debug_printf("failed to create store for stapling verify\n");
2053 return FAIL;
2054 }
2055 SSL_CTX_set_tlsext_status_cb(ctx, tls_client_stapling_cb);
2056 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
2057 }
2058 # endif
2059 #endif
2060
2061 cbinfo->verify_cert_hostnames = NULL;
2062
2063 #ifdef EXIM_HAVE_EPHEM_RSA_KEX
2064 /* Set up the RSA callback */
2065 SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
2066 #endif
2067
2068 /* Finally, set the session cache timeout, and we are done.
2069 The period appears to be also used for (server-generated) session tickets */
2070
2071 SSL_CTX_set_timeout(ctx, ssl_session_timeout);
2072 DEBUG(D_tls) debug_printf("Initialized TLS\n");
2073
2074 *cbp = cbinfo;
2075 *ctxp = ctx;
2076
2077 return OK;
2078 }
2079
2080
2081
2082
2083 /*************************************************
2084 * Get name of cipher in use *
2085 *************************************************/
2086
2087 /*
2088 Argument: pointer to an SSL structure for the connection
2089 pointer to number of bits for cipher
2090 Returns: pointer to allocated string in perm-pool
2091 */
2092
2093 static uschar *
2094 construct_cipher_name(SSL * ssl, int * bits)
2095 {
2096 int pool = store_pool;
2097 /* With OpenSSL 1.0.0a, 'c' needs to be const but the documentation doesn't
2098 yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
2099 the accessor functions use const in the prototype. */
2100
2101 const uschar * ver = CUS SSL_get_version(ssl);
2102 const SSL_CIPHER * c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
2103 uschar * s;
2104
2105 SSL_CIPHER_get_bits(c, bits);
2106
2107 store_pool = POOL_PERM;
2108 s = string_sprintf("%s:%s:%u", ver, SSL_CIPHER_get_name(c), *bits);
2109 store_pool = pool;
2110 DEBUG(D_tls) debug_printf("Cipher: %s\n", s);
2111 return s;
2112 }
2113
2114
2115 /* Get IETF-standard name for ciphersuite.
2116 Argument: pointer to an SSL structure for the connection
2117 Returns: pointer to string
2118 */
2119
2120 static const uschar *
2121 cipher_stdname_ssl(SSL * ssl)
2122 {
2123 #ifdef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
2124 return CUS SSL_CIPHER_standard_name(SSL_get_current_cipher(ssl));
2125 #else
2126 ushort id = 0xffff & SSL_CIPHER_get_id(SSL_get_current_cipher(ssl));
2127 return cipher_stdname(id >> 8, id & 0xff);
2128 #endif
2129 }
2130
2131
2132 static void
2133 peer_cert(SSL * ssl, tls_support * tlsp, uschar * peerdn, unsigned siz)
2134 {
2135 /*XXX we might consider a list-of-certs variable for the cert chain.
2136 SSL_get_peer_cert_chain(SSL*). We'd need a new variable type and support
2137 in list-handling functions, also consider the difference between the entire
2138 chain and the elements sent by the peer. */
2139
2140 tlsp->peerdn = NULL;
2141
2142 /* Will have already noted peercert on a verify fail; possibly not the leaf */
2143 if (!tlsp->peercert)
2144 tlsp->peercert = SSL_get_peer_certificate(ssl);
2145 /* Beware anonymous ciphers which lead to server_cert being NULL */
2146 if (tlsp->peercert)
2147 if (!X509_NAME_oneline(X509_get_subject_name(tlsp->peercert), CS peerdn, siz))
2148 { DEBUG(D_tls) debug_printf("X509_NAME_oneline() error\n"); }
2149 else
2150 {
2151 peerdn[siz-1] = '\0';
2152 tlsp->peerdn = peerdn; /*XXX a static buffer... */
2153 }
2154 }
2155
2156
2157
2158
2159
2160 /*************************************************
2161 * Set up for verifying certificates *
2162 *************************************************/
2163
2164 #ifndef DISABLE_OCSP
2165 /* Load certs from file, return TRUE on success */
2166
2167 static BOOL
2168 chain_from_pem_file(const uschar * file, STACK_OF(X509) * verify_stack)
2169 {
2170 BIO * bp;
2171 X509 * x;
2172
2173 while (sk_X509_num(verify_stack) > 0)
2174 X509_free(sk_X509_pop(verify_stack));
2175
2176 if (!(bp = BIO_new_file(CS file, "r"))) return FALSE;
2177 while ((x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
2178 sk_X509_push(verify_stack, x);
2179 BIO_free(bp);
2180 return TRUE;
2181 }
2182 #endif
2183
2184
2185
2186 /* Called by both client and server startup; on the server possibly
2187 repeated after a Server Name Indication.
2188
2189 Arguments:
2190 sctx SSL_CTX* to initialise
2191 certs certs file or NULL
2192 crl CRL file or NULL
2193 host NULL in a server; the remote host in a client
2194 optional TRUE if called from a server for a host in tls_try_verify_hosts;
2195 otherwise passed as FALSE
2196 cert_vfy_cb Callback function for certificate verification
2197 errstr error string pointer
2198
2199 Returns: OK/DEFER/FAIL
2200 */
2201
2202 static int
2203 setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
2204 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr)
2205 {
2206 uschar *expcerts, *expcrl;
2207
2208 if (!expand_check(certs, US"tls_verify_certificates", &expcerts, errstr))
2209 return DEFER;
2210 DEBUG(D_tls) debug_printf("tls_verify_certificates: %s\n", expcerts);
2211
2212 if (expcerts && *expcerts)
2213 {
2214 /* Tell the library to use its compiled-in location for the system default
2215 CA bundle. Then add the ones specified in the config, if any. */
2216
2217 if (!SSL_CTX_set_default_verify_paths(sctx))
2218 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL, errstr);
2219
2220 if (Ustrcmp(expcerts, "system") != 0)
2221 {
2222 struct stat statbuf;
2223
2224 if (Ustat(expcerts, &statbuf) < 0)
2225 {
2226 log_write(0, LOG_MAIN|LOG_PANIC,
2227 "failed to stat %s for certificates", expcerts);
2228 return DEFER;
2229 }
2230 else
2231 {
2232 uschar *file, *dir;
2233 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
2234 { file = NULL; dir = expcerts; }
2235 else
2236 {
2237 file = expcerts; dir = NULL;
2238 #ifndef DISABLE_OCSP
2239 /* In the server if we will be offering an OCSP proof, load chain from
2240 file for verifying the OCSP proof at load time. */
2241
2242 if ( !host
2243 && statbuf.st_size > 0
2244 && server_static_cbinfo->u_ocsp.server.file
2245 && !chain_from_pem_file(file, server_static_cbinfo->verify_stack)
2246 )
2247 {
2248 log_write(0, LOG_MAIN|LOG_PANIC,
2249 "failed to load cert chain from %s", file);
2250 return DEFER;
2251 }
2252 #endif
2253 }
2254
2255 /* If a certificate file is empty, the next function fails with an
2256 unhelpful error message. If we skip it, we get the correct behaviour (no
2257 certificates are recognized, but the error message is still misleading (it
2258 says no certificate was supplied). But this is better. */
2259
2260 if ( (!file || statbuf.st_size > 0)
2261 && !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
2262 return tls_error(US"SSL_CTX_load_verify_locations", host, NULL, errstr);
2263
2264 /* Load the list of CAs for which we will accept certs, for sending
2265 to the client. This is only for the one-file tls_verify_certificates
2266 variant.
2267 If a list isn't loaded into the server, but some verify locations are set,
2268 the server end appears to make a wildcard request for client certs.
2269 Meanwhile, the client library as default behaviour *ignores* the list
2270 we send over the wire - see man SSL_CTX_set_client_cert_cb.
2271 Because of this, and that the dir variant is likely only used for
2272 the public-CA bundle (not for a private CA), not worth fixing. */
2273
2274 if (file)
2275 {
2276 STACK_OF(X509_NAME) * names = SSL_load_client_CA_file(CS file);
2277
2278 SSL_CTX_set_client_CA_list(sctx, names);
2279 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n",
2280 sk_X509_NAME_num(names));
2281 }
2282 }
2283 }
2284
2285 /* Handle a certificate revocation list. */
2286
2287 #if OPENSSL_VERSION_NUMBER > 0x00907000L
2288
2289 /* This bit of code is now the version supplied by Lars Mainka. (I have
2290 merely reformatted it into the Exim code style.)
2291
2292 "From here I changed the code to add support for multiple crl's
2293 in pem format in one file or to support hashed directory entries in
2294 pem format instead of a file. This method now uses the library function
2295 X509_STORE_load_locations to add the CRL location to the SSL context.
2296 OpenSSL will then handle the verify against CA certs and CRLs by
2297 itself in the verify callback." */
2298
2299 if (!expand_check(crl, US"tls_crl", &expcrl, errstr)) return DEFER;
2300 if (expcrl && *expcrl)
2301 {
2302 struct stat statbufcrl;
2303 if (Ustat(expcrl, &statbufcrl) < 0)
2304 {
2305 log_write(0, LOG_MAIN|LOG_PANIC,
2306 "failed to stat %s for certificates revocation lists", expcrl);
2307 return DEFER;
2308 }
2309 else
2310 {
2311 /* is it a file or directory? */
2312 uschar *file, *dir;
2313 X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
2314 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
2315 {
2316 file = NULL;
2317 dir = expcrl;
2318 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
2319 }
2320 else
2321 {
2322 file = expcrl;
2323 dir = NULL;
2324 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
2325 }
2326 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
2327 return tls_error(US"X509_STORE_load_locations", host, NULL, errstr);
2328
2329 /* setting the flags to check against the complete crl chain */
2330
2331 X509_STORE_set_flags(cvstore,
2332 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2333 }
2334 }
2335
2336 #endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
2337
2338 /* If verification is optional, don't fail if no certificate */
2339
2340 SSL_CTX_set_verify(sctx,
2341 SSL_VERIFY_PEER | (optional ? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
2342 cert_vfy_cb);
2343 }
2344
2345 return OK;
2346 }
2347
2348
2349
2350 /*************************************************
2351 * Start a TLS session in a server *
2352 *************************************************/
2353
2354 /* This is called when Exim is running as a server, after having received
2355 the STARTTLS command. It must respond to that command, and then negotiate
2356 a TLS session.
2357
2358 Arguments:
2359 require_ciphers allowed ciphers
2360 errstr pointer to error message
2361
2362 Returns: OK on success
2363 DEFER for errors before the start of the negotiation
2364 FAIL for errors during the negotiation; the server can't
2365 continue running.
2366 */
2367
2368 int
2369 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
2370 {
2371 int rc;
2372 uschar * expciphers;
2373 tls_ext_ctx_cb * cbinfo;
2374 static uschar peerdn[256];
2375
2376 /* Check for previous activation */
2377
2378 if (tls_in.active.sock >= 0)
2379 {
2380 tls_error(US"STARTTLS received after TLS started", NULL, US"", errstr);
2381 smtp_printf("554 Already in TLS\r\n", FALSE);
2382 return FAIL;
2383 }
2384
2385 /* Initialize the SSL library. If it fails, it will already have logged
2386 the error. */
2387
2388 rc = tls_init(&server_ctx, NULL, tls_dhparam, tls_certificate, tls_privatekey,
2389 #ifndef DISABLE_OCSP
2390 tls_ocsp_file, /*XXX stack*/
2391 #endif
2392 NULL, &server_static_cbinfo, &tls_in, errstr);
2393 if (rc != OK) return rc;
2394 cbinfo = server_static_cbinfo;
2395
2396 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers, errstr))
2397 return FAIL;
2398
2399 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2400 were historically separated by underscores. So that I can use either form in my
2401 tests, and also for general convenience, we turn underscores into hyphens here.
2402
2403 XXX SSL_CTX_set_cipher_list() is replaced by SSL_CTX_set_ciphersuites()
2404 for TLS 1.3 . Since we do not call it at present we get the default list:
2405 TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
2406 */
2407
2408 if (expciphers)
2409 {
2410 for (uschar * s = expciphers; *s; s++ ) if (*s == '_') *s = '-';
2411 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
2412 if (!SSL_CTX_set_cipher_list(server_ctx, CS expciphers))
2413 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL, errstr);
2414 cbinfo->server_cipher_list = expciphers;
2415 }
2416
2417 /* If this is a host for which certificate verification is mandatory or
2418 optional, set up appropriately. */
2419
2420 tls_in.certificate_verified = FALSE;
2421 #ifdef SUPPORT_DANE
2422 tls_in.dane_verified = FALSE;
2423 #endif
2424 server_verify_callback_called = FALSE;
2425
2426 if (verify_check_host(&tls_verify_hosts) == OK)
2427 {
2428 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
2429 FALSE, verify_callback_server, errstr);
2430 if (rc != OK) return rc;
2431 server_verify_optional = FALSE;
2432 }
2433 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2434 {
2435 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
2436 TRUE, verify_callback_server, errstr);
2437 if (rc != OK) return rc;
2438 server_verify_optional = TRUE;
2439 }
2440
2441 #ifdef EXPERIMENTAL_TLS_RESUME
2442 SSL_CTX_set_tlsext_ticket_key_cb(server_ctx, ticket_key_callback);
2443 /* despite working, appears to always return failure, so ignoring */
2444 #endif
2445 #ifdef OPENSSL_HAVE_NUM_TICKETS
2446 # ifdef EXPERIMENTAL_TLS_RESUME
2447 SSL_CTX_set_num_tickets(server_ctx, tls_in.host_resumable ? 1 : 0);
2448 # else
2449 SSL_CTX_set_num_tickets(server_ctx, 0); /* send no TLS1.3 stateful-tickets */
2450 # endif
2451 #endif
2452
2453
2454 /* Prepare for new connection */
2455
2456 if (!(server_ssl = SSL_new(server_ctx)))
2457 return tls_error(US"SSL_new", NULL, NULL, errstr);
2458
2459 /* Warning: we used to SSL_clear(ssl) here, it was removed.
2460 *
2461 * With the SSL_clear(), we get strange interoperability bugs with
2462 * OpenSSL 1.0.1b and TLS1.1/1.2. It looks as though this may be a bug in
2463 * OpenSSL itself, as a clear should not lead to inability to follow protocols.
2464 *
2465 * The SSL_clear() call is to let an existing SSL* be reused, typically after
2466 * session shutdown. In this case, we have a brand new object and there's no
2467 * obvious reason to immediately clear it. I'm guessing that this was
2468 * originally added because of incomplete initialisation which the clear fixed,
2469 * in some historic release.
2470 */
2471
2472 /* Set context and tell client to go ahead, except in the case of TLS startup
2473 on connection, where outputting anything now upsets the clients and tends to
2474 make them disconnect. We need to have an explicit fflush() here, to force out
2475 the response. Other smtp_printf() calls do not need it, because in non-TLS
2476 mode, the fflush() happens when smtp_getc() is called. */
2477
2478 SSL_set_session_id_context(server_ssl, sid_ctx, Ustrlen(sid_ctx));
2479 if (!tls_in.on_connect)
2480 {
2481 smtp_printf("220 TLS go ahead\r\n", FALSE);
2482 fflush(smtp_out);
2483 }
2484
2485 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2486 that the OpenSSL library doesn't. */
2487
2488 SSL_set_wfd(server_ssl, fileno(smtp_out));
2489 SSL_set_rfd(server_ssl, fileno(smtp_in));
2490 SSL_set_accept_state(server_ssl);
2491
2492 DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
2493
2494 sigalrm_seen = FALSE;
2495 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2496 rc = SSL_accept(server_ssl);
2497 ALARM_CLR(0);
2498
2499 if (rc <= 0)
2500 {
2501 (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
2502 return FAIL;
2503 }
2504
2505 DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
2506 ERR_clear_error(); /* Even success can leave errors in the stack. Seen with
2507 anon-authentication ciphersuite negotiated. */
2508
2509 #ifdef EXPERIMENTAL_TLS_RESUME
2510 if (SSL_session_reused(server_ssl))
2511 {
2512 tls_in.resumption |= RESUME_USED;
2513 DEBUG(D_tls) debug_printf("Session reused\n");
2514 }
2515 #endif
2516
2517 /* TLS has been set up. Adjust the input functions to read via TLS,
2518 and initialize things. */
2519
2520 peer_cert(server_ssl, &tls_in, peerdn, sizeof(peerdn));
2521
2522 tls_in.cipher = construct_cipher_name(server_ssl, &tls_in.bits);
2523 tls_in.cipher_stdname = cipher_stdname_ssl(server_ssl);
2524
2525 DEBUG(D_tls)
2526 {
2527 uschar buf[2048];
2528 if (SSL_get_shared_ciphers(server_ssl, CS buf, sizeof(buf)))
2529 debug_printf("Shared ciphers: %s\n", buf);
2530
2531 #ifdef EXIM_HAVE_OPENSSL_KEYLOG
2532 {
2533 BIO * bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
2534 SSL_SESSION_print_keylog(bp, SSL_get_session(server_ssl));
2535 BIO_free(bp);
2536 }
2537 #endif
2538
2539 #ifdef EXIM_HAVE_SESSION_TICKET
2540 {
2541 SSL_SESSION * ss = SSL_get_session(server_ssl);
2542 if (SSL_SESSION_has_ticket(ss))
2543 debug_printf("The session has a ticket, life %lu seconds\n",
2544 SSL_SESSION_get_ticket_lifetime_hint(ss));
2545 }
2546 #endif
2547 }
2548
2549 /* Record the certificate we presented */
2550 {
2551 X509 * crt = SSL_get_certificate(server_ssl);
2552 tls_in.ourcert = crt ? X509_dup(crt) : NULL;
2553 }
2554
2555 /* Only used by the server-side tls (tls_in), including tls_getc.
2556 Client-side (tls_out) reads (seem to?) go via
2557 smtp_read_response()/ip_recv().
2558 Hence no need to duplicate for _in and _out.
2559 */
2560 if (!ssl_xfer_buffer) ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2561 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
2562 ssl_xfer_eof = ssl_xfer_error = FALSE;
2563
2564 receive_getc = tls_getc;
2565 receive_getbuf = tls_getbuf;
2566 receive_get_cache = tls_get_cache;
2567 receive_ungetc = tls_ungetc;
2568 receive_feof = tls_feof;
2569 receive_ferror = tls_ferror;
2570 receive_smtp_buffered = tls_smtp_buffered;
2571
2572 tls_in.active.sock = fileno(smtp_out);
2573 tls_in.active.tls_ctx = NULL; /* not using explicit ctx for server-side */
2574 return OK;
2575 }
2576
2577
2578
2579
2580 static int
2581 tls_client_basic_ctx_init(SSL_CTX * ctx,
2582 host_item * host, smtp_transport_options_block * ob, tls_ext_ctx_cb * cbinfo,
2583 uschar ** errstr)
2584 {
2585 int rc;
2586 /* stick to the old behaviour for compatibility if tls_verify_certificates is
2587 set but both tls_verify_hosts and tls_try_verify_hosts is not set. Check only
2588 the specified host patterns if one of them is defined */
2589
2590 if ( ( !ob->tls_verify_hosts
2591 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2592 )
2593 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
2594 )
2595 client_verify_optional = FALSE;
2596 else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
2597 client_verify_optional = TRUE;
2598 else
2599 return OK;
2600
2601 if ((rc = setup_certs(ctx, ob->tls_verify_certificates,
2602 ob->tls_crl, host, client_verify_optional, verify_callback_client,
2603 errstr)) != OK)
2604 return rc;
2605
2606 if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
2607 {
2608 cbinfo->verify_cert_hostnames =
2609 #ifdef SUPPORT_I18N
2610 string_domain_utf8_to_alabel(host->name, NULL);
2611 #else
2612 host->name;
2613 #endif
2614 DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
2615 cbinfo->verify_cert_hostnames);
2616 }
2617 return OK;
2618 }
2619
2620
2621 #ifdef SUPPORT_DANE
2622 static int
2623 dane_tlsa_load(SSL * ssl, host_item * host, dns_answer * dnsa, uschar ** errstr)
2624 {
2625 dns_scan dnss;
2626 const char * hostnames[2] = { CS host->name, NULL };
2627 int found = 0;
2628
2629 if (DANESSL_init(ssl, NULL, hostnames) != 1)
2630 return tls_error(US"hostnames load", host, NULL, errstr);
2631
2632 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
2633 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2634 ) if (rr->type == T_TLSA && rr->size > 3)
2635 {
2636 const uschar * p = rr->data;
2637 uint8_t usage, selector, mtype;
2638 const char * mdname;
2639
2640 usage = *p++;
2641
2642 /* Only DANE-TA(2) and DANE-EE(3) are supported */
2643 if (usage != 2 && usage != 3) continue;
2644
2645 selector = *p++;
2646 mtype = *p++;
2647
2648 switch (mtype)
2649 {
2650 default: continue; /* Only match-types 0, 1, 2 are supported */
2651 case 0: mdname = NULL; break;
2652 case 1: mdname = "sha256"; break;
2653 case 2: mdname = "sha512"; break;
2654 }
2655
2656 found++;
2657 switch (DANESSL_add_tlsa(ssl, usage, selector, mdname, p, rr->size - 3))
2658 {
2659 default:
2660 return tls_error(US"tlsa load", host, NULL, errstr);
2661 case 0: /* action not taken */
2662 case 1: break;
2663 }
2664
2665 tls_out.tlsa_usage |= 1<<usage;
2666 }
2667
2668 if (found)
2669 return OK;
2670
2671 log_write(0, LOG_MAIN, "DANE error: No usable TLSA records");
2672 return DEFER;
2673 }
2674 #endif /*SUPPORT_DANE*/
2675
2676
2677
2678 #ifdef EXPERIMENTAL_TLS_RESUME
2679 /* On the client, get any stashed session for the given IP from hints db
2680 and apply it to the ssl-connection for attempted resumption. */
2681
2682 static void
2683 tls_retrieve_session(tls_support * tlsp, SSL * ssl, const uschar * key)
2684 {
2685 tlsp->resumption |= RESUME_SUPPORTED;
2686 if (tlsp->host_resumable)
2687 {
2688 dbdata_tls_session * dt;
2689 int len;
2690 open_db dbblock, * dbm_file;
2691
2692 tlsp->resumption |= RESUME_CLIENT_REQUESTED;
2693 DEBUG(D_tls) debug_printf("checking for resumable session for %s\n", key);
2694 if ((dbm_file = dbfn_open(US"tls", O_RDONLY, &dbblock, FALSE, FALSE)))
2695 {
2696 /* key for the db is the IP */
2697 if ((dt = dbfn_read_with_length(dbm_file, key, &len)))
2698 {
2699 SSL_SESSION * ss = NULL;
2700 const uschar * sess_asn1 = dt->session;
2701
2702 len -= sizeof(dbdata_tls_session);
2703 if (!(d2i_SSL_SESSION(&ss, &sess_asn1, (long)len)))
2704 {
2705 DEBUG(D_tls)
2706 {
2707 ERR_error_string_n(ERR_get_error(),
2708 ssl_errstring, sizeof(ssl_errstring));
2709 debug_printf("decoding session: %s\n", ssl_errstring);
2710 }
2711 }
2712 else if (!SSL_set_session(ssl, ss))
2713 {
2714 DEBUG(D_tls)
2715 {
2716 ERR_error_string_n(ERR_get_error(),
2717 ssl_errstring, sizeof(ssl_errstring));
2718 debug_printf("applying session to ssl: %s\n", ssl_errstring);
2719 }
2720 }
2721 else
2722 {
2723 DEBUG(D_tls) debug_printf("good session\n");
2724 tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
2725 }
2726 }
2727 else
2728 DEBUG(D_tls) debug_printf("no session record\n");
2729 dbfn_close(dbm_file);
2730 }
2731 }
2732 }
2733
2734
2735 /* On the client, save the session for later resumption */
2736
2737 static int
2738 tls_save_session_cb(SSL * ssl, SSL_SESSION * ss)
2739 {
2740 tls_ext_ctx_cb * cbinfo = SSL_get_ex_data(ssl, tls_exdata_idx);
2741 tls_support * tlsp;
2742
2743 DEBUG(D_tls) debug_printf("tls_save_session_cb\n");
2744
2745 if (!cbinfo || !(tlsp = cbinfo->tlsp)->host_resumable) return 0;
2746
2747 # ifdef EXIM_HAVE_SESSION_TICKET
2748
2749 if (SSL_SESSION_is_resumable(ss))
2750 {
2751 int len = i2d_SSL_SESSION(ss, NULL);
2752 int dlen = sizeof(dbdata_tls_session) + len;
2753 dbdata_tls_session * dt = store_get(dlen);
2754 uschar * s = dt->session;
2755 open_db dbblock, * dbm_file;
2756
2757 DEBUG(D_tls) debug_printf("session is resumable\n");
2758 tlsp->resumption |= RESUME_SERVER_TICKET; /* server gave us a ticket */
2759
2760 len = i2d_SSL_SESSION(ss, &s); /* s gets bumped to end */
2761
2762 if ((dbm_file = dbfn_open(US"tls", O_RDWR, &dbblock, FALSE, FALSE)))
2763 {
2764 const uschar * key = cbinfo->host->address;
2765 dbfn_delete(dbm_file, key);
2766 dbfn_write(dbm_file, key, dt, dlen);
2767 dbfn_close(dbm_file);
2768 DEBUG(D_tls) debug_printf("wrote session (len %u) to db\n",
2769 (unsigned)dlen);
2770 }
2771 }
2772 # endif
2773 return 1;
2774 }
2775
2776
2777 static void
2778 tls_client_ctx_resume_prehandshake(
2779 exim_openssl_client_tls_ctx * exim_client_ctx, tls_support * tlsp,
2780 smtp_transport_options_block * ob, host_item * host)
2781 {
2782 /* Should the client request a session resumption ticket? */
2783 if (verify_check_given_host(CUSS &ob->tls_resumption_hosts, host) == OK)
2784 {
2785 tlsp->host_resumable = TRUE;
2786
2787 SSL_CTX_set_session_cache_mode(exim_client_ctx->ctx,
2788 SSL_SESS_CACHE_CLIENT
2789 | SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2790 SSL_CTX_sess_set_new_cb(exim_client_ctx->ctx, tls_save_session_cb);
2791 }
2792 }
2793
2794 static BOOL
2795 tls_client_ssl_resume_prehandshake(SSL * ssl, tls_support * tlsp,
2796 host_item * host, uschar ** errstr)
2797 {
2798 if (tlsp->host_resumable)
2799 {
2800 DEBUG(D_tls)
2801 debug_printf("tls_resumption_hosts overrides openssl_options, enabling tickets\n");
2802 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
2803
2804 tls_exdata_idx = SSL_get_ex_new_index(0, 0, 0, 0, 0);
2805 if (!SSL_set_ex_data(ssl, tls_exdata_idx, client_static_cbinfo))
2806 {
2807 tls_error(US"set ex_data", host, NULL, errstr);
2808 return FALSE;
2809 }
2810 debug_printf("tls_exdata_idx %d cbinfo %p\n", tls_exdata_idx, client_static_cbinfo);
2811 }
2812
2813 tlsp->resumption = RESUME_SUPPORTED;
2814 /* Pick up a previous session, saved on an old ticket */
2815 tls_retrieve_session(tlsp, ssl, host->address);
2816 return TRUE;
2817 }
2818
2819 static void
2820 tls_client_resume_posthandshake(exim_openssl_client_tls_ctx * exim_client_ctx,
2821 tls_support * tlsp)
2822 {
2823 if (SSL_session_reused(exim_client_ctx->ssl))
2824 {
2825 DEBUG(D_tls) debug_printf("The session was reused\n");
2826 tlsp->resumption |= RESUME_USED;
2827 }
2828 }
2829 #endif /* EXPERIMENTAL_TLS_RESUME */
2830
2831
2832 /*************************************************
2833 * Start a TLS session in a client *
2834 *************************************************/
2835
2836 /* Called from the smtp transport after STARTTLS has been accepted.
2837
2838 Arguments:
2839 cctx connection context
2840 conn_args connection details
2841 cookie datum for randomness; can be NULL
2842 tlsp record details of TLS channel configuration here; must be non-NULL
2843 errstr error string pointer
2844
2845 Returns: TRUE for success with TLS session context set in connection context,
2846 FALSE on error
2847 */
2848
2849 BOOL
2850 tls_client_start(client_conn_ctx * cctx, smtp_connect_args * conn_args,
2851 void * cookie, tls_support * tlsp, uschar ** errstr)
2852 {
2853 host_item * host = conn_args->host; /* for msgs and option-tests */
2854 transport_instance * tb = conn_args->tblock; /* always smtp or NULL */
2855 smtp_transport_options_block * ob = tb
2856 ? (smtp_transport_options_block *)tb->options_block
2857 : &smtp_transport_option_defaults;
2858 exim_openssl_client_tls_ctx * exim_client_ctx;
2859 uschar * expciphers;
2860 int rc;
2861 static uschar peerdn[256];
2862
2863 #ifndef DISABLE_OCSP
2864 BOOL request_ocsp = FALSE;
2865 BOOL require_ocsp = FALSE;
2866 #endif
2867
2868 rc = store_pool;
2869 store_pool = POOL_PERM;
2870 exim_client_ctx = store_get(sizeof(exim_openssl_client_tls_ctx));
2871 exim_client_ctx->corked = NULL;
2872 store_pool = rc;
2873
2874 #ifdef SUPPORT_DANE
2875 tlsp->tlsa_usage = 0;
2876 #endif
2877
2878 #ifndef DISABLE_OCSP
2879 {
2880 # ifdef SUPPORT_DANE
2881 if ( conn_args->dane
2882 && ob->hosts_request_ocsp[0] == '*'
2883 && ob->hosts_request_ocsp[1] == '\0'
2884 )
2885 {
2886 /* Unchanged from default. Use a safer one under DANE */
2887 request_ocsp = TRUE;
2888 ob->hosts_request_ocsp = US"${if or { {= {0}{$tls_out_tlsa_usage}} "
2889 " {= {4}{$tls_out_tlsa_usage}} } "
2890 " {*}{}}";
2891 }
2892 # endif
2893
2894 if ((require_ocsp =
2895 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK))
2896 request_ocsp = TRUE;
2897 else
2898 # ifdef SUPPORT_DANE
2899 if (!request_ocsp)
2900 # endif
2901 request_ocsp =
2902 verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2903 }
2904 #endif
2905
2906 rc = tls_init(&exim_client_ctx->ctx, host, NULL,
2907 ob->tls_certificate, ob->tls_privatekey,
2908 #ifndef DISABLE_OCSP
2909 (void *)(long)request_ocsp,
2910 #endif
2911 cookie, &client_static_cbinfo, tlsp, errstr);
2912 if (rc != OK) return FALSE;
2913
2914 tlsp->certificate_verified = FALSE;
2915 client_verify_callback_called = FALSE;
2916
2917 expciphers = NULL;
2918 #ifdef SUPPORT_DANE
2919 if (conn_args->dane)
2920 {
2921 /* We fall back to tls_require_ciphers if unset, empty or forced failure, but
2922 other failures should be treated as problems. */
2923 if (ob->dane_require_tls_ciphers &&
2924 !expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2925 &expciphers, errstr))
2926 return FALSE;
2927 if (expciphers && *expciphers == '\0')
2928 expciphers = NULL;
2929 }
2930 #endif
2931 if (!expciphers &&
2932 !expand_check(ob->tls_require_ciphers, US"tls_require_ciphers",
2933 &expciphers, errstr))
2934 return FALSE;
2935
2936 /* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2937 are separated by underscores. So that I can use either form in my tests, and
2938 also for general convenience, we turn underscores into hyphens here. */
2939
2940 if (expciphers)
2941 {
2942 uschar *s = expciphers;
2943 while (*s) { if (*s == '_') *s = '-'; s++; }
2944 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
2945 if (!SSL_CTX_set_cipher_list(exim_client_ctx->ctx, CS expciphers))
2946 {
2947 tls_error(US"SSL_CTX_set_cipher_list", host, NULL, errstr);
2948 return FALSE;
2949 }
2950 }
2951
2952 #ifdef SUPPORT_DANE
2953 if (conn_args->dane)
2954 {
2955 SSL_CTX_set_verify(exim_client_ctx->ctx,
2956 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2957 verify_callback_client_dane);
2958
2959 if (!DANESSL_library_init())
2960 {
2961 tls_error(US"library init", host, NULL, errstr);
2962 return FALSE;
2963 }
2964 if (DANESSL_CTX_init(exim_client_ctx->ctx) <= 0)
2965 {
2966 tls_error(US"context init", host, NULL, errstr);
2967 return FALSE;
2968 }
2969 }
2970 else
2971
2972 #endif
2973
2974 if (tls_client_basic_ctx_init(exim_client_ctx->ctx, host, ob,
2975 client_static_cbinfo, errstr) != OK)
2976 return FALSE;
2977
2978 #ifdef EXPERIMENTAL_TLS_RESUME
2979 tls_client_ctx_resume_prehandshake(exim_client_ctx, tlsp, ob, host);
2980 #endif
2981
2982
2983 if (!(exim_client_ctx->ssl = SSL_new(exim_client_ctx->ctx)))
2984 {
2985 tls_error(US"SSL_new", host, NULL, errstr);
2986 return FALSE;
2987 }
2988 SSL_set_session_id_context(exim_client_ctx->ssl, sid_ctx, Ustrlen(sid_ctx));
2989
2990 #ifdef EXPERIMENTAL_TLS_RESUME
2991 if (!tls_client_ssl_resume_prehandshake(exim_client_ctx->ssl, tlsp, host,
2992 errstr))
2993 return FALSE;
2994 #endif
2995
2996 SSL_set_fd(exim_client_ctx->ssl, cctx->sock);
2997 SSL_set_connect_state(exim_client_ctx->ssl);
2998
2999 if (ob->tls_sni)
3000 {
3001 if (!expand_check(ob->tls_sni, US"tls_sni", &tlsp->sni, errstr))
3002 return FALSE;
3003 if (!tlsp->sni)
3004 {
3005 DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n");
3006 }
3007 else if (!Ustrlen(tlsp->sni))
3008 tlsp->sni = NULL;
3009 else
3010 {
3011 #ifdef EXIM_HAVE_OPENSSL_TLSEXT
3012 DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tlsp->sni);
3013 SSL_set_tlsext_host_name(exim_client_ctx->ssl, tlsp->sni);
3014 #else
3015 log_write(0, LOG_MAIN, "SNI unusable with this OpenSSL library version; ignoring \"%s\"\n",
3016 tlsp->sni);
3017 #endif
3018 }
3019 }
3020
3021 #ifdef SUPPORT_DANE
3022 if (conn_args->dane)
3023 if (dane_tlsa_load(exim_client_ctx->ssl, host, &conn_args->tlsa_dnsa, errstr) != OK)
3024 return FALSE;
3025 #endif
3026
3027 #ifndef DISABLE_OCSP
3028 /* Request certificate status at connection-time. If the server
3029 does OCSP stapling we will get the callback (set in tls_init()) */
3030 # ifdef SUPPORT_DANE
3031 if (request_ocsp)
3032 {
3033 const uschar * s;
3034 if ( ((s = ob->hosts_require_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
3035 || ((s = ob->hosts_request_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
3036 )
3037 { /* Re-eval now $tls_out_tlsa_usage is populated. If
3038 this means we avoid the OCSP request, we wasted the setup
3039 cost in tls_init(). */
3040 require_ocsp = verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
3041 request_ocsp = require_ocsp
3042 || verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
3043 }
3044 }
3045 # endif
3046
3047 if (request_ocsp)
3048 {
3049 SSL_set_tlsext_status_type(exim_client_ctx->ssl, TLSEXT_STATUSTYPE_ocsp);
3050 client_static_cbinfo->u_ocsp.client.verify_required = require_ocsp;
3051 tlsp->ocsp = OCSP_NOT_RESP;
3052 }
3053 #endif
3054
3055 #ifndef DISABLE_EVENT
3056 client_static_cbinfo->event_action = tb ? tb->event_action : NULL;
3057 #endif
3058
3059 /* There doesn't seem to be a built-in timeout on connection. */
3060
3061 DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
3062 sigalrm_seen = FALSE;
3063 ALARM(ob->command_timeout);
3064 rc = SSL_connect(exim_client_ctx->ssl);
3065 ALARM_CLR(0);
3066
3067 #ifdef SUPPORT_DANE
3068 if (conn_args->dane)
3069 DANESSL_cleanup(exim_client_ctx->ssl);
3070 #endif
3071
3072 if (rc <= 0)
3073 {
3074 tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL, errstr);
3075 return FALSE;
3076 }
3077
3078 DEBUG(D_tls)
3079 {
3080 debug_printf("SSL_connect succeeded\n");
3081 #ifdef EXIM_HAVE_OPENSSL_KEYLOG
3082 {
3083 BIO * bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
3084 SSL_SESSION_print_keylog(bp, SSL_get_session(exim_client_ctx->ssl));
3085 BIO_free(bp);
3086 }
3087 #endif
3088 }
3089
3090 #ifdef EXPERIMENTAL_TLS_RESUME
3091 tls_client_resume_posthandshake(exim_client_ctx, tlsp);
3092 #endif
3093
3094 peer_cert(exim_client_ctx->ssl, tlsp, peerdn, sizeof(peerdn));
3095
3096 tlsp->cipher = construct_cipher_name(exim_client_ctx->ssl, &tlsp->bits);
3097 tlsp->cipher_stdname = cipher_stdname_ssl(exim_client_ctx->ssl);
3098
3099 /* Record the certificate we presented */
3100 {
3101 X509 * crt = SSL_get_certificate(exim_client_ctx->ssl);
3102 tlsp->ourcert = crt ? X509_dup(crt) : NULL;
3103 }
3104
3105 tlsp->active.sock = cctx->sock;
3106 tlsp->active.tls_ctx = exim_client_ctx;
3107 cctx->tls_ctx = exim_client_ctx;
3108 return TRUE;
3109 }
3110
3111
3112
3113
3114
3115 static BOOL
3116 tls_refill(unsigned lim)
3117 {
3118 int error;
3119 int inbytes;
3120
3121 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", server_ssl,
3122 ssl_xfer_buffer, ssl_xfer_buffer_size);
3123
3124 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
3125 inbytes = SSL_read(server_ssl, CS ssl_xfer_buffer,
3126 MIN(ssl_xfer_buffer_size, lim));
3127 error = SSL_get_error(server_ssl, inbytes);
3128 if (smtp_receive_timeout > 0) ALARM_CLR(0);
3129
3130 if (had_command_timeout) /* set by signal handler */
3131 smtp_command_timeout_exit(); /* does not return */
3132 if (had_command_sigterm)
3133 smtp_command_sigterm_exit();
3134 if (had_data_timeout)
3135 smtp_data_timeout_exit();
3136 if (had_data_sigint)
3137 smtp_data_sigint_exit();
3138
3139 /* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
3140 closed down, not that the socket itself has been closed down. Revert to
3141 non-SSL handling. */
3142
3143 switch(error)
3144 {
3145 case SSL_ERROR_NONE:
3146 break;
3147
3148 case SSL_ERROR_ZERO_RETURN:
3149 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
3150
3151 receive_getc = smtp_getc;
3152 receive_getbuf = smtp_getbuf;
3153 receive_get_cache = smtp_get_cache;
3154 receive_ungetc = smtp_ungetc;
3155 receive_feof = smtp_feof;
3156 receive_ferror = smtp_ferror;
3157 receive_smtp_buffered = smtp_buffered;
3158
3159 if (SSL_get_shutdown(server_ssl) == SSL_RECEIVED_SHUTDOWN)
3160 SSL_shutdown(server_ssl);
3161
3162 #ifndef DISABLE_OCSP
3163 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
3164 server_static_cbinfo->verify_stack = NULL;
3165 #endif
3166 SSL_free(server_ssl);
3167 SSL_CTX_free(server_ctx);
3168 server_ctx = NULL;
3169 server_ssl = NULL;
3170 tls_in.active.sock = -1;
3171 tls_in.active.tls_ctx = NULL;
3172 tls_in.bits = 0;
3173 tls_in.cipher = NULL;
3174 tls_in.peerdn = NULL;
3175 tls_in.sni = NULL;
3176
3177 return FALSE;
3178
3179 /* Handle genuine errors */
3180 case SSL_ERROR_SSL:
3181 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3182 log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
3183 ssl_xfer_error = TRUE;
3184 return FALSE;
3185
3186 default:
3187 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
3188 DEBUG(D_tls) if (error == SSL_ERROR_SYSCALL)
3189 debug_printf(" - syscall %s\n", strerror(errno));
3190 ssl_xfer_error = TRUE;
3191 return FALSE;
3192 }
3193
3194 #ifndef DISABLE_DKIM
3195 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
3196 #endif
3197 ssl_xfer_buffer_hwm = inbytes;
3198 ssl_xfer_buffer_lwm = 0;
3199 return TRUE;
3200 }
3201
3202
3203 /*************************************************
3204 * TLS version of getc *
3205 *************************************************/
3206
3207 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
3208 it refills the buffer via the SSL reading function.
3209
3210 Arguments: lim Maximum amount to read/buffer
3211 Returns: the next character or EOF
3212
3213 Only used by the server-side TLS.
3214 */
3215
3216 int
3217 tls_getc(unsigned lim)
3218 {
3219 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
3220 if (!tls_refill(lim))
3221 return ssl_xfer_error ? EOF : smtp_getc(lim);
3222
3223 /* Something in the buffer; return next uschar */
3224
3225 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
3226 }
3227
3228 uschar *
3229 tls_getbuf(unsigned * len)
3230 {
3231 unsigned size;
3232 uschar * buf;
3233
3234 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
3235 if (!tls_refill(*len))
3236 {
3237 if (!ssl_xfer_error) return smtp_getbuf(len);
3238 *len = 0;
3239 return NULL;
3240 }
3241
3242 if ((size = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm) > *len)
3243 size = *len;
3244 buf = &ssl_xfer_buffer[ssl_xfer_buffer_lwm];
3245 ssl_xfer_buffer_lwm += size;
3246 *len = size;
3247 return buf;
3248 }
3249
3250
3251 void
3252 tls_get_cache()
3253 {
3254 #ifndef DISABLE_DKIM
3255 int n = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm;
3256 if (n > 0)
3257 dkim_exim_verify_feed(ssl_xfer_buffer+ssl_xfer_buffer_lwm, n);
3258 #endif
3259 }
3260
3261
3262 BOOL
3263 tls_could_read(void)
3264 {
3265 return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm || SSL_pending(server_ssl) > 0;
3266 }
3267
3268
3269 /*************************************************
3270 * Read bytes from TLS channel *
3271 *************************************************/
3272
3273 /*
3274 Arguments:
3275 ct_ctx client context pointer, or NULL for the one global server context
3276 buff buffer of data
3277 len size of buffer
3278
3279 Returns: the number of bytes read
3280 -1 after a failed read, including EOF
3281
3282 Only used by the client-side TLS.
3283 */
3284
3285 int
3286 tls_read(void * ct_ctx, uschar *buff, size_t len)
3287 {
3288 SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
3289 int inbytes;
3290 int error;
3291
3292 DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
3293 buff, (unsigned int)len);
3294
3295 inbytes = SSL_read(ssl, CS buff, len);
3296 error = SSL_get_error(ssl, inbytes);
3297
3298 if (error == SSL_ERROR_ZERO_RETURN)
3299 {
3300 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
3301 return -1;
3302 }
3303 else if (error != SSL_ERROR_NONE)
3304 return -1;
3305
3306 return inbytes;
3307 }
3308
3309
3310
3311
3312
3313 /*************************************************
3314 * Write bytes down TLS channel *
3315 *************************************************/
3316
3317 /*
3318 Arguments:
3319 ct_ctx client context pointer, or NULL for the one global server context
3320 buff buffer of data
3321 len number of bytes
3322 more further data expected soon
3323
3324 Returns: the number of bytes after a successful write,
3325 -1 after a failed write
3326
3327 Used by both server-side and client-side TLS.
3328 */
3329
3330 int
3331 tls_write(void * ct_ctx, const uschar *buff, size_t len, BOOL more)
3332 {
3333 size_t olen = len;
3334 int outbytes, error;
3335 SSL * ssl = ct_ctx
3336 ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
3337 static gstring * server_corked = NULL;
3338 gstring ** corkedp = ct_ctx
3339 ? &((exim_openssl_client_tls_ctx *)ct_ctx)->corked : &server_corked;
3340 gstring * corked = *corkedp;
3341
3342 DEBUG(D_tls) debug_printf("%s(%p, %lu%s)\n", __FUNCTION__,
3343 buff, (unsigned long)len, more ? ", more" : "");
3344
3345 /* Lacking a CORK or MSG_MORE facility (such as GnuTLS has) we copy data when
3346 "more" is notified. This hack is only ok if small amounts are involved AND only
3347 one stream does it, in one context (i.e. no store reset). Currently it is used
3348 for the responses to the received SMTP MAIL , RCPT, DATA sequence, only.
3349 We support callouts done by the server process by using a separate client
3350 context for the stashed information. */
3351 /* + if PIPE_COMMAND, banner & ehlo-resp for smmtp-on-connect. Suspect there's
3352 a store reset there, so use POOL_PERM. */
3353 /* + if CHUNKING, cmds EHLO,MAIL,RCPT(s),BDAT */
3354
3355 if ((more || corked))
3356 {
3357 #ifdef EXPERIMENTAL_PIPE_CONNECT
3358 int save_pool = store_pool;
3359 store_pool = POOL_PERM;
3360 #endif
3361
3362 corked = string_catn(corked, buff, len);
3363
3364 #ifdef EXPERIMENTAL_PIPE_CONNECT
3365 store_pool = save_pool;
3366 #endif
3367
3368 if (more)
3369 {
3370 *corkedp = corked;
3371 return len;
3372 }
3373 buff = CUS corked->s;
3374 len = corked->ptr;
3375 *corkedp = NULL;
3376 }
3377
3378 for (int left = len; left > 0;)
3379 {
3380 DEBUG(D_tls) debug_printf("SSL_write(%p, %p, %d)\n", ssl, buff, left);
3381 outbytes = SSL_write(ssl, CS buff, left);
3382 error = SSL_get_error(ssl, outbytes);
3383 DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
3384 switch (error)
3385 {
3386 case SSL_ERROR_SSL:
3387 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3388 log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
3389 return -1;
3390
3391 case SSL_ERROR_NONE:
3392 left -= outbytes;
3393 buff += outbytes;
3394 break;
3395
3396 case SSL_ERROR_ZERO_RETURN:
3397 log_write(0, LOG_MAIN, "SSL channel closed on write");
3398 return -1;
3399
3400 case SSL_ERROR_SYSCALL:
3401 log_write(0, LOG_MAIN, "SSL_write: (from %s) syscall: %s",
3402 sender_fullhost ? sender_fullhost : US"<unknown>",
3403 strerror(errno));
3404 return -1;
3405
3406 default:
3407 log_write(0, LOG_MAIN, "SSL_write error %d", error);
3408 return -1;
3409 }
3410 }
3411 return olen;
3412 }
3413
3414
3415
3416 /*************************************************
3417 * Close down a TLS session *
3418 *************************************************/
3419
3420 /* This is also called from within a delivery subprocess forked from the
3421 daemon, to shut down the TLS library, without actually doing a shutdown (which
3422 would tamper with the SSL session in the parent process).
3423
3424 Arguments:
3425 ct_ctx client TLS context pointer, or NULL for the one global server context
3426 shutdown 1 if TLS close-alert is to be sent,
3427 2 if also response to be waited for
3428
3429 Returns: nothing
3430
3431 Used by both server-side and client-side TLS.
3432 */
3433
3434 void
3435 tls_close(void * ct_ctx, int shutdown)
3436 {
3437 exim_openssl_client_tls_ctx * o_ctx = ct_ctx;
3438 SSL_CTX **ctxp = o_ctx ? &o_ctx->ctx : &server_ctx;
3439 SSL **sslp = o_ctx ? &o_ctx->ssl : &server_ssl;
3440 int *fdp = o_ctx ? &tls_out.active.sock : &tls_in.active.sock;
3441
3442 if (*fdp < 0) return; /* TLS was not active */
3443
3444 if (shutdown)
3445 {
3446 int rc;
3447 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
3448 shutdown > 1 ? " (with response-wait)" : "");
3449
3450 if ( (rc = SSL_shutdown(*sslp)) == 0 /* send "close notify" alert */
3451 && shutdown > 1)
3452 {
3453 ALARM(2);
3454 rc = SSL_shutdown(*sslp); /* wait for response */
3455 ALARM_CLR(0);
3456 }
3457
3458 if (rc < 0) DEBUG(D_tls)
3459 {
3460 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3461 debug_printf("SSL_shutdown: %s\n", ssl_errstring);
3462 }
3463 }
3464
3465 #ifndef DISABLE_OCSP
3466 if (!o_ctx) /* server side */
3467 {
3468 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
3469 server_static_cbinfo->verify_stack = NULL;
3470 }
3471 #endif
3472
3473 SSL_CTX_free(*ctxp);
3474 SSL_free(*sslp);
3475 *ctxp = NULL;
3476 *sslp = NULL;
3477 *fdp = -1;
3478 }
3479
3480
3481
3482
3483 /*************************************************
3484 * Let tls_require_ciphers be checked at startup *
3485 *************************************************/
3486
3487 /* The tls_require_ciphers option, if set, must be something which the
3488 library can parse.
3489
3490 Returns: NULL on success, or error message
3491 */
3492
3493 uschar *
3494 tls_validate_require_cipher(void)
3495 {
3496 SSL_CTX *ctx;
3497 uschar *s, *expciphers, *err;
3498
3499 /* this duplicates from tls_init(), we need a better "init just global
3500 state, for no specific purpose" singleton function of our own */
3501
3502 #ifdef EXIM_NEED_OPENSSL_INIT
3503 SSL_load_error_strings();
3504 OpenSSL_add_ssl_algorithms();
3505 #endif
3506 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
3507 /* SHA256 is becoming ever more popular. This makes sure it gets added to the
3508 list of available digests. */
3509 EVP_add_digest(EVP_sha256());
3510 #endif
3511
3512 if (!(tls_require_ciphers && *tls_require_ciphers))
3513 return NULL;
3514
3515 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3516 &err))
3517 return US"failed to expand tls_require_ciphers";
3518
3519 if (!(expciphers && *expciphers))
3520 return NULL;
3521
3522 /* normalisation ripped from above */
3523 s = expciphers;
3524 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
3525
3526 err = NULL;
3527
3528 #ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
3529 if (!(ctx = SSL_CTX_new(TLS_server_method())))
3530 #else
3531 if (!(ctx = SSL_CTX_new(SSLv23_server_method())))
3532 #endif
3533 {
3534 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3535 return string_sprintf("SSL_CTX_new() failed: %s", ssl_errstring);
3536 }
3537
3538 DEBUG(D_tls)
3539 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3540
3541 if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
3542 {
3543 ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
3544 err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed: %s",
3545 expciphers, ssl_errstring);
3546 }
3547
3548 SSL_CTX_free(ctx);
3549
3550 return err;
3551 }
3552
3553
3554
3555
3556 /*************************************************
3557 * Report the library versions. *
3558 *************************************************/
3559
3560 /* There have historically been some issues with binary compatibility in
3561 OpenSSL libraries; if Exim (like many other applications) is built against
3562 one version of OpenSSL but the run-time linker picks up another version,
3563 it can result in serious failures, including crashing with a SIGSEGV. So
3564 report the version found by the compiler and the run-time version.
3565
3566 Note: some OS vendors backport security fixes without changing the version
3567 number/string, and the version date remains unchanged. The _build_ date
3568 will change, so we can more usefully assist with version diagnosis by also
3569 reporting the build date.
3570
3571 Arguments: a FILE* to print the results to
3572 Returns: nothing
3573 */
3574
3575 void
3576 tls_version_report(FILE *f)
3577 {
3578 fprintf(f, "Library version: OpenSSL: Compile: %s\n"
3579 " Runtime: %s\n"
3580 " : %s\n",
3581 OPENSSL_VERSION_TEXT,
3582 SSLeay_version(SSLEAY_VERSION),
3583 SSLeay_version(SSLEAY_BUILT_ON));
3584 /* third line is 38 characters for the %s and the line is 73 chars long;
3585 the OpenSSL output includes a "built on: " prefix already. */
3586 }
3587
3588
3589
3590
3591 /*************************************************
3592 * Random number generation *
3593 *************************************************/
3594
3595 /* Pseudo-random number generation. The result is not expected to be
3596 cryptographically strong but not so weak that someone will shoot themselves
3597 in the foot using it as a nonce in input in some email header scheme or
3598 whatever weirdness they'll twist this into. The result should handle fork()
3599 and avoid repeating sequences. OpenSSL handles that for us.
3600
3601 Arguments:
3602 max range maximum
3603 Returns a random number in range [0, max-1]
3604 */
3605
3606 int
3607 vaguely_random_number(int max)
3608 {
3609 unsigned int r;
3610 int i, needed_len;
3611 static pid_t pidlast = 0;
3612 pid_t pidnow;
3613 uschar smallbuf[sizeof(r)];
3614
3615 if (max <= 1)
3616 return 0;
3617
3618 pidnow = getpid();
3619 if (pidnow != pidlast)
3620 {
3621 /* Although OpenSSL documents that "OpenSSL makes sure that the PRNG state
3622 is unique for each thread", this doesn't apparently apply across processes,
3623 so our own warning from vaguely_random_number_fallback() applies here too.
3624 Fix per PostgreSQL. */
3625 if (pidlast != 0)
3626 RAND_cleanup();
3627 pidlast = pidnow;
3628 }
3629
3630 /* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
3631 if (!RAND_status())
3632 {
3633 randstuff r;
3634 gettimeofday(&r.tv, NULL);
3635 r.p = getpid();
3636
3637 RAND_seed(US (&r), sizeof(r));
3638 }
3639 /* We're after pseudo-random, not random; if we still don't have enough data
3640 in the internal PRNG then our options are limited. We could sleep and hope
3641 for entropy to come along (prayer technique) but if the system is so depleted
3642 in the first place then something is likely to just keep taking it. Instead,
3643 we'll just take whatever little bit of pseudo-random we can still manage to
3644 get. */
3645
3646 needed_len = sizeof(r);
3647 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
3648 asked for a number less than 10. */
3649 for (r = max, i = 0; r; ++i)
3650 r >>= 1;
3651 i = (i + 7) / 8;
3652 if (i < needed_len)
3653 needed_len = i;
3654
3655 #ifdef EXIM_HAVE_RAND_PSEUDO
3656 /* We do not care if crypto-strong */
3657 i = RAND_pseudo_bytes(smallbuf, needed_len);
3658 #else
3659 i = RAND_bytes(smallbuf, needed_len);
3660 #endif
3661
3662 if (i < 0)
3663 {
3664 DEBUG(D_all)
3665 debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
3666 return vaguely_random_number_fallback(max);
3667 }
3668
3669 r = 0;
3670 for (uschar * p = smallbuf; needed_len; --needed_len, ++p)
3671 r = 256 * r + *p;
3672
3673 /* We don't particularly care about weighted results; if someone wants
3674 smooth distribution and cares enough then they should submit a patch then. */
3675 return r % max;
3676 }
3677
3678
3679
3680
3681 /*************************************************
3682 * OpenSSL option parse *
3683 *************************************************/
3684
3685 /* Parse one option for tls_openssl_options_parse below
3686
3687 Arguments:
3688 name one option name
3689 value place to store a value for it
3690 Returns success or failure in parsing
3691 */
3692
3693
3694
3695 static BOOL
3696 tls_openssl_one_option_parse(uschar *name, long *value)
3697 {
3698 int first = 0;
3699 int last = exim_openssl_options_size;
3700 while (last > first)
3701 {
3702 int middle = (first + last)/2;
3703 int c = Ustrcmp(name, exim_openssl_options[middle].name);
3704 if (c == 0)
3705 {
3706 *value = exim_openssl_options[middle].value;
3707 return TRUE;
3708 }
3709 else if (c > 0)
3710 first = middle + 1;
3711 else
3712 last = middle;
3713 }
3714 return FALSE;
3715 }
3716
3717
3718
3719
3720 /*************************************************
3721 * OpenSSL option parsing logic *
3722 *************************************************/
3723
3724 /* OpenSSL has a number of compatibility options which an administrator might
3725 reasonably wish to set. Interpret a list similarly to decode_bits(), so that
3726 we look like log_selector.
3727
3728 Arguments:
3729 option_spec the administrator-supplied string of options
3730 results ptr to long storage for the options bitmap
3731 Returns success or failure
3732 */
3733
3734 BOOL
3735 tls_openssl_options_parse(uschar *option_spec, long *results)
3736 {
3737 long result, item;
3738 uschar *end;
3739 uschar keep_c;
3740 BOOL adding, item_parsed;
3741
3742 /* Server: send no (<= TLS1.2) session tickets */
3743 result = SSL_OP_NO_TICKET;
3744
3745 /* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
3746 * from default because it increases BEAST susceptibility. */
3747 #ifdef SSL_OP_NO_SSLv2
3748 result |= SSL_OP_NO_SSLv2;
3749 #endif
3750 #ifdef SSL_OP_NO_SSLv3
3751 result |= SSL_OP_NO_SSLv3;
3752 #endif
3753 #ifdef SSL_OP_SINGLE_DH_USE
3754 result |= SSL_OP_SINGLE_DH_USE;
3755 #endif
3756
3757 if (!option_spec)
3758 {
3759 *results = result;
3760 return TRUE;
3761 }
3762
3763 for (uschar * s = option_spec; *s; /**/)
3764 {
3765 while (isspace(*s)) ++s;
3766 if (*s == '\0')
3767 break;
3768 if (*s != '+' && *s != '-')
3769 {
3770 DEBUG(D_tls) debug_printf("malformed openssl option setting: "
3771 "+ or - expected but found \"%s\"\n", s);
3772 return FALSE;
3773 }
3774 adding = *s++ == '+';
3775 for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
3776 keep_c = *end;
3777 *end = '\0';
3778 item_parsed = tls_openssl_one_option_parse(s, &item);
3779 *end = keep_c;
3780 if (!item_parsed)
3781 {
3782 DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
3783 return FALSE;
3784 }
3785 DEBUG(D_tls) debug_printf("openssl option, %s %8lx: %lx (%s)\n",
3786 adding ? "adding to " : "removing from", result, item, s);
3787 if (adding)
3788 result |= item;
3789 else
3790 result &= ~item;
3791 s = end;
3792 }
3793
3794 *results = result;
3795 return TRUE;
3796 }
3797
3798 #endif /*!MACRO_PREDEF*/
3799 /* vi: aw ai sw=2
3800 */
3801 /* End of tls-openssl.c */