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