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