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