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