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