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