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