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