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