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