ARC: Fix verification to do AS checks in reverse order
[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)))
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:
018058b2
JH
963 if (running_in_test_harness)
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
JH
1096 return OK;
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
7be682ca 1251if (cbinfo->server_cipher_list)
817d9f57 1252 SSL_CTX_set_cipher_list(server_sni, CS cbinfo->server_cipher_list);
f2de3a33 1253#ifndef DISABLE_OCSP
f5d78688 1254if (cbinfo->u_ocsp.server.file)
3f7eeb86 1255 {
f5d78688 1256 SSL_CTX_set_tlsext_status_cb(server_sni, tls_server_stapling_cb);
14c7b357 1257 SSL_CTX_set_tlsext_status_arg(server_sni, cbinfo);
3f7eeb86
PP
1258 }
1259#endif
7be682ca 1260
c3033f13 1261if ((rc = setup_certs(server_sni, tls_verify_certificates, tls_crl, NULL, FALSE,
cf0c6164 1262 verify_callback_server, &dummy_errstr)) != OK)
c3033f13 1263 return SSL_TLSEXT_ERR_NOACK;
7be682ca 1264
3f7eeb86
PP
1265/* do this after setup_certs, because this can require the certs for verifying
1266OCSP information. */
cf0c6164 1267if ((rc = tls_expand_session_files(server_sni, cbinfo, &dummy_errstr)) != OK)
0df4ab80 1268 return SSL_TLSEXT_ERR_NOACK;
a799883d 1269
7be682ca 1270DEBUG(D_tls) debug_printf("Switching SSL context.\n");
817d9f57 1271SSL_set_SSL_CTX(s, server_sni);
7be682ca
PP
1272
1273return SSL_TLSEXT_ERR_OK;
1274}
3bcbbbe2 1275#endif /* EXIM_HAVE_OPENSSL_TLSEXT */
7be682ca
PP
1276
1277
1278
1279
f2de3a33 1280#ifndef DISABLE_OCSP
f5d78688 1281
3f7eeb86
PP
1282/*************************************************
1283* Callback to handle OCSP Stapling *
1284*************************************************/
1285
1286/* Called when acting as server during the TLS session setup if the client
1287requests OCSP information with a Certificate Status Request.
1288
1289Documentation via openssl s_server.c and the Apache patch from the OpenSSL
1290project.
1291
1292*/
1293
1294static int
f5d78688 1295tls_server_stapling_cb(SSL *s, void *arg)
3f7eeb86
PP
1296{
1297const tls_ext_ctx_cb *cbinfo = (tls_ext_ctx_cb *) arg;
47195144 1298uschar *response_der; /*XXX blob */
3f7eeb86
PP
1299int response_der_len;
1300
47195144
JH
1301/*XXX stack: use SSL_get_certificate() to see which cert; from that work
1302out which ocsp blob to send. Unfortunately, SSL_get_certificate is known
1303buggy in current OpenSSL; it returns the last cert loaded always rather than
1304the one actually presented. So we can't support a stack of OCSP proofs at
1305this time. */
1306
af4a1bca 1307DEBUG(D_tls)
b3ef41c9 1308 debug_printf("Received TLS status request (OCSP stapling); %s response\n",
f5d78688
JH
1309 cbinfo->u_ocsp.server.response ? "have" : "lack");
1310
44662487 1311tls_in.ocsp = OCSP_NOT_RESP;
f5d78688 1312if (!cbinfo->u_ocsp.server.response)
3f7eeb86
PP
1313 return SSL_TLSEXT_ERR_NOACK;
1314
1315response_der = NULL;
47195144 1316response_der_len = i2d_OCSP_RESPONSE(cbinfo->u_ocsp.server.response, /*XXX stack*/
44662487 1317 &response_der);
3f7eeb86
PP
1318if (response_der_len <= 0)
1319 return SSL_TLSEXT_ERR_NOACK;
1320
5e55c7a9 1321SSL_set_tlsext_status_ocsp_resp(server_ssl, response_der, response_der_len);
44662487 1322tls_in.ocsp = OCSP_VFIED;
3f7eeb86
PP
1323return SSL_TLSEXT_ERR_OK;
1324}
1325
3f7eeb86 1326
f5d78688
JH
1327static void
1328time_print(BIO * bp, const char * str, ASN1_GENERALIZEDTIME * time)
1329{
1330BIO_printf(bp, "\t%s: ", str);
1331ASN1_GENERALIZEDTIME_print(bp, time);
1332BIO_puts(bp, "\n");
1333}
1334
1335static int
1336tls_client_stapling_cb(SSL *s, void *arg)
1337{
1338tls_ext_ctx_cb * cbinfo = arg;
1339const unsigned char * p;
1340int len;
1341OCSP_RESPONSE * rsp;
1342OCSP_BASICRESP * bs;
1343int i;
1344
1345DEBUG(D_tls) debug_printf("Received TLS status response (OCSP stapling):");
1346len = SSL_get_tlsext_status_ocsp_resp(s, &p);
1347if(!p)
1348 {
44662487 1349 /* Expect this when we requested ocsp but got none */
6c6d6e48 1350 if (cbinfo->u_ocsp.client.verify_required && LOGGING(tls_cipher))
44662487 1351 log_write(0, LOG_MAIN, "Received TLS status callback, null content");
f5d78688
JH
1352 else
1353 DEBUG(D_tls) debug_printf(" null\n");
44662487 1354 return cbinfo->u_ocsp.client.verify_required ? 0 : 1;
f5d78688 1355 }
018058b2 1356
f5d78688
JH
1357if(!(rsp = d2i_OCSP_RESPONSE(NULL, &p, len)))
1358 {
018058b2 1359 tls_out.ocsp = OCSP_FAILED;
6c6d6e48 1360 if (LOGGING(tls_cipher))
1eca31ca 1361 log_write(0, LOG_MAIN, "Received TLS cert status response, parse error");
f5d78688
JH
1362 else
1363 DEBUG(D_tls) debug_printf(" parse error\n");
1364 return 0;
1365 }
1366
1367if(!(bs = OCSP_response_get1_basic(rsp)))
1368 {
018058b2 1369 tls_out.ocsp = OCSP_FAILED;
6c6d6e48 1370 if (LOGGING(tls_cipher))
1eca31ca 1371 log_write(0, LOG_MAIN, "Received TLS cert status response, error parsing response");
f5d78688
JH
1372 else
1373 DEBUG(D_tls) debug_printf(" error parsing response\n");
1374 OCSP_RESPONSE_free(rsp);
1375 return 0;
1376 }
1377
1378/* We'd check the nonce here if we'd put one in the request. */
1379/* However that would defeat cacheability on the server so we don't. */
1380
f5d78688
JH
1381/* This section of code reworked from OpenSSL apps source;
1382 The OpenSSL Project retains copyright:
1383 Copyright (c) 1999 The OpenSSL Project. All rights reserved.
1384*/
1385 {
1386 BIO * bp = NULL;
f5d78688
JH
1387 int status, reason;
1388 ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1389
57887ecc 1390 DEBUG(D_tls) bp = BIO_new_fp(debug_file, BIO_NOCLOSE);
f5d78688
JH
1391
1392 /*OCSP_RESPONSE_print(bp, rsp, 0); extreme debug: stapling content */
1393
1394 /* Use the chain that verified the server cert to verify the stapled info */
1395 /* DEBUG(D_tls) x509_store_dump_cert_s_names(cbinfo->u_ocsp.client.verify_store); */
1396
c3033f13 1397 if ((i = OCSP_basic_verify(bs, cbinfo->verify_stack,
44662487 1398 cbinfo->u_ocsp.client.verify_store, 0)) <= 0)
f5d78688 1399 {
018058b2 1400 tls_out.ocsp = OCSP_FAILED;
57887ecc
JH
1401 if (LOGGING(tls_cipher)) log_write(0, LOG_MAIN,
1402 "Received TLS cert status response, itself unverifiable: %s",
1403 ERR_reason_error_string(ERR_peek_error()));
f5d78688
JH
1404 BIO_printf(bp, "OCSP response verify failure\n");
1405 ERR_print_errors(bp);
57887ecc 1406 OCSP_RESPONSE_print(bp, rsp, 0);
c8dfb21d 1407 goto failed;
f5d78688
JH
1408 }
1409
1410 BIO_printf(bp, "OCSP response well-formed and signed OK\n");
1411
c8dfb21d
JH
1412 /*XXX So we have a good stapled OCSP status. How do we know
1413 it is for the cert of interest? OpenSSL 1.1.0 has a routine
1414 OCSP_resp_find_status() which matches on a cert id, which presumably
1415 we should use. Making an id needs OCSP_cert_id_new(), which takes
1416 issuerName, issuerKey, serialNumber. Are they all in the cert?
1417
1418 For now, carry on blindly accepting the resp. */
1419
f5d78688 1420 {
f5d78688
JH
1421 OCSP_SINGLERESP * single;
1422
c8dfb21d
JH
1423#ifdef EXIM_HAVE_OCSP_RESP_COUNT
1424 if (OCSP_resp_count(bs) != 1)
1425#else
1426 STACK_OF(OCSP_SINGLERESP) * sresp = bs->tbsResponseData->responses;
f5d78688 1427 if (sk_OCSP_SINGLERESP_num(sresp) != 1)
c8dfb21d 1428#endif
f5d78688 1429 {
018058b2 1430 tls_out.ocsp = OCSP_FAILED;
44662487
JH
1431 log_write(0, LOG_MAIN, "OCSP stapling "
1432 "with multiple responses not handled");
c8dfb21d 1433 goto failed;
f5d78688
JH
1434 }
1435 single = OCSP_resp_get0(bs, 0);
44662487
JH
1436 status = OCSP_single_get0_status(single, &reason, &rev,
1437 &thisupd, &nextupd);
f5d78688
JH
1438 }
1439
f5d78688
JH
1440 DEBUG(D_tls) time_print(bp, "This OCSP Update", thisupd);
1441 DEBUG(D_tls) if(nextupd) time_print(bp, "Next OCSP Update", nextupd);
44662487
JH
1442 if (!OCSP_check_validity(thisupd, nextupd,
1443 EXIM_OCSP_SKEW_SECONDS, EXIM_OCSP_MAX_AGE))
f5d78688 1444 {
018058b2 1445 tls_out.ocsp = OCSP_FAILED;
f5d78688
JH
1446 DEBUG(D_tls) ERR_print_errors(bp);
1447 log_write(0, LOG_MAIN, "Server OSCP dates invalid");
f5d78688 1448 }
44662487 1449 else
f5d78688 1450 {
44662487
JH
1451 DEBUG(D_tls) BIO_printf(bp, "Certificate status: %s\n",
1452 OCSP_cert_status_str(status));
1453 switch(status)
1454 {
1455 case V_OCSP_CERTSTATUS_GOOD:
44662487 1456 tls_out.ocsp = OCSP_VFIED;
018058b2 1457 i = 1;
c8dfb21d 1458 goto good;
44662487 1459 case V_OCSP_CERTSTATUS_REVOKED:
018058b2 1460 tls_out.ocsp = OCSP_FAILED;
44662487
JH
1461 log_write(0, LOG_MAIN, "Server certificate revoked%s%s",
1462 reason != -1 ? "; reason: " : "",
1463 reason != -1 ? OCSP_crl_reason_str(reason) : "");
1464 DEBUG(D_tls) time_print(bp, "Revocation Time", rev);
44662487
JH
1465 break;
1466 default:
018058b2 1467 tls_out.ocsp = OCSP_FAILED;
44662487
JH
1468 log_write(0, LOG_MAIN,
1469 "Server certificate status unknown, in OCSP stapling");
44662487
JH
1470 break;
1471 }
f5d78688 1472 }
c8dfb21d
JH
1473 failed:
1474 i = cbinfo->u_ocsp.client.verify_required ? 0 : 1;
1475 good:
f5d78688
JH
1476 BIO_free(bp);
1477 }
1478
1479OCSP_RESPONSE_free(rsp);
1480return i;
1481}
f2de3a33 1482#endif /*!DISABLE_OCSP*/
3f7eeb86
PP
1483
1484
059ec3d9
PH
1485/*************************************************
1486* Initialize for TLS *
1487*************************************************/
1488
e51c7be2
JH
1489/* Called from both server and client code, to do preliminary initialization
1490of the library. We allocate and return a context structure.
059ec3d9
PH
1491
1492Arguments:
946ecbe0 1493 ctxp returned SSL context
059ec3d9
PH
1494 host connected host, if client; NULL if server
1495 dhparam DH parameter file
1496 certificate certificate file
1497 privatekey private key
f5d78688 1498 ocsp_file file of stapling info (server); flag for require ocsp (client)
059ec3d9 1499 addr address if client; NULL if server (for some randomness)
946ecbe0 1500 cbp place to put allocated callback context
cf0c6164 1501 errstr error string pointer
059ec3d9
PH
1502
1503Returns: OK/DEFER/FAIL
1504*/
1505
1506static int
817d9f57 1507tls_init(SSL_CTX **ctxp, host_item *host, uschar *dhparam, uschar *certificate,
3f7eeb86 1508 uschar *privatekey,
f2de3a33 1509#ifndef DISABLE_OCSP
47195144 1510 uschar *ocsp_file, /*XXX stack, in server*/
3f7eeb86 1511#endif
cf0c6164 1512 address_item *addr, tls_ext_ctx_cb ** cbp, uschar ** errstr)
059ec3d9 1513{
7006ee24 1514SSL_CTX * ctx;
77bb000f 1515long init_options;
7be682ca 1516int rc;
a7538db1 1517tls_ext_ctx_cb * cbinfo;
7be682ca
PP
1518
1519cbinfo = store_malloc(sizeof(tls_ext_ctx_cb));
1520cbinfo->certificate = certificate;
1521cbinfo->privatekey = privatekey;
a6510420 1522cbinfo->is_server = host==NULL;
f2de3a33 1523#ifndef DISABLE_OCSP
c3033f13 1524cbinfo->verify_stack = NULL;
a6510420 1525if (!host)
f5d78688
JH
1526 {
1527 cbinfo->u_ocsp.server.file = ocsp_file;
1528 cbinfo->u_ocsp.server.file_expanded = NULL;
1529 cbinfo->u_ocsp.server.response = NULL;
1530 }
1531else
1532 cbinfo->u_ocsp.client.verify_store = NULL;
3f7eeb86 1533#endif
7be682ca 1534cbinfo->dhparam = dhparam;
0df4ab80 1535cbinfo->server_cipher_list = NULL;
7be682ca 1536cbinfo->host = host;
0cbf2b82 1537#ifndef DISABLE_EVENT
a7538db1
JH
1538cbinfo->event_action = NULL;
1539#endif
77bb000f 1540
059ec3d9
PH
1541SSL_load_error_strings(); /* basic set up */
1542OpenSSL_add_ssl_algorithms();
1543
c8dfb21d 1544#ifdef EXIM_HAVE_SHA256
77bb000f 1545/* SHA256 is becoming ever more popular. This makes sure it gets added to the
a0475b69
TK
1546list of available digests. */
1547EVP_add_digest(EVP_sha256());
cf1ef1a9 1548#endif
a0475b69 1549
f0f5a555
PP
1550/* Create a context.
1551The OpenSSL docs in 1.0.1b have not been updated to clarify TLS variant
1552negotiation in the different methods; as far as I can tell, the only
1553*_{server,client}_method which allows negotiation is SSLv23, which exists even
1554when OpenSSL is built without SSLv2 support.
1555By disabling with openssl_options, we can let admins re-enable with the
1556existing knob. */
059ec3d9 1557
7a8b9519
JH
1558#ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
1559if (!(ctx = SSL_CTX_new(host ? TLS_client_method() : TLS_server_method())))
1560#else
7006ee24 1561if (!(ctx = SSL_CTX_new(host ? SSLv23_client_method() : SSLv23_server_method())))
7a8b9519 1562#endif
7006ee24 1563 return tls_error(US"SSL_CTX_new", host, NULL, errstr);
059ec3d9
PH
1564
1565/* It turns out that we need to seed the random number generator this early in
1566order to get the full complement of ciphers to work. It took me roughly a day
1567of work to discover this by experiment.
1568
1569On systems that have /dev/urandom, SSL may automatically seed itself from
1570there. Otherwise, we have to make something up as best we can. Double check
1571afterwards. */
1572
1573if (!RAND_status())
1574 {
1575 randstuff r;
9e3331ea 1576 gettimeofday(&r.tv, NULL);
059ec3d9
PH
1577 r.p = getpid();
1578
5903c6ff
JH
1579 RAND_seed(US (&r), sizeof(r));
1580 RAND_seed(US big_buffer, big_buffer_size);
1581 if (addr != NULL) RAND_seed(US addr, sizeof(addr));
059ec3d9
PH
1582
1583 if (!RAND_status())
7199e1ee 1584 return tls_error(US"RAND_status", host,
cf0c6164 1585 US"unable to seed random number generator", errstr);
059ec3d9
PH
1586 }
1587
1588/* Set up the information callback, which outputs if debugging is at a suitable
1589level. */
1590
7006ee24 1591DEBUG(D_tls) SSL_CTX_set_info_callback(ctx, (void (*)())info_callback);
059ec3d9 1592
c80c5570 1593/* Automatically re-try reads/writes after renegotiation. */
7006ee24 1594(void) SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
c80c5570 1595
77bb000f
PP
1596/* Apply administrator-supplied work-arounds.
1597Historically we applied just one requested option,
1598SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS, but when bug 994 requested a second, we
1599moved to an administrator-controlled list of options to specify and
1600grandfathered in the first one as the default value for "openssl_options".
059ec3d9 1601
77bb000f
PP
1602No OpenSSL version number checks: the options we accept depend upon the
1603availability of the option value macros from OpenSSL. */
059ec3d9 1604
7006ee24 1605if (!tls_openssl_options_parse(openssl_options, &init_options))
cf0c6164 1606 return tls_error(US"openssl_options parsing failed", host, NULL, errstr);
77bb000f
PP
1607
1608if (init_options)
1609 {
1610 DEBUG(D_tls) debug_printf("setting SSL CTX options: %#lx\n", init_options);
7006ee24 1611 if (!(SSL_CTX_set_options(ctx, init_options)))
77bb000f 1612 return tls_error(string_sprintf(
cf0c6164 1613 "SSL_CTX_set_option(%#lx)", init_options), host, NULL, errstr);
77bb000f
PP
1614 }
1615else
1616 DEBUG(D_tls) debug_printf("no SSL CTX options to set\n");
059ec3d9 1617
a28050f8
JH
1618/* We'd like to disable session cache unconditionally, but foolish Outlook
1619Express clients then give up the first TLS connection and make a second one
1620(which works). Only when there is an IMAP service on the same machine.
1621Presumably OE is trying to use the cache for A on B. Leave it enabled for
1622now, until we work out a decent way of presenting control to the config. It
1623will never be used because we use a new context every time. */
1624#ifdef notdef
7006ee24 1625(void) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
a28050f8 1626#endif
7006ee24 1627
059ec3d9 1628/* Initialize with DH parameters if supplied */
10ca4f1c 1629/* Initialize ECDH temp key parameter selection */
059ec3d9 1630
7006ee24
JH
1631if ( !init_dh(ctx, dhparam, host, errstr)
1632 || !init_ecdh(ctx, host, errstr)
038597d2
PP
1633 )
1634 return DEFER;
059ec3d9 1635
3f7eeb86 1636/* Set up certificate and key (and perhaps OCSP info) */
059ec3d9 1637
7006ee24 1638if ((rc = tls_expand_session_files(ctx, cbinfo, errstr)) != OK)
23bb6982 1639 return rc;
c91535f3 1640
c3033f13
JH
1641/* If we need to handle SNI or OCSP, do so */
1642
3bcbbbe2 1643#ifdef EXIM_HAVE_OPENSSL_TLSEXT
c3033f13
JH
1644# ifndef DISABLE_OCSP
1645 if (!(cbinfo->verify_stack = sk_X509_new_null()))
1646 {
1647 DEBUG(D_tls) debug_printf("failed to create stack for stapling verify\n");
1648 return FAIL;
1649 }
1650# endif
1651
7a8b9519 1652if (!host) /* server */
3f0945ff 1653 {
f2de3a33 1654# ifndef DISABLE_OCSP
f5d78688 1655 /* We check u_ocsp.server.file, not server.response, because we care about if
3f7eeb86
PP
1656 the option exists, not what the current expansion might be, as SNI might
1657 change the certificate and OCSP file in use between now and the time the
1658 callback is invoked. */
f5d78688 1659 if (cbinfo->u_ocsp.server.file)
3f7eeb86 1660 {
7006ee24
JH
1661 SSL_CTX_set_tlsext_status_cb(ctx, tls_server_stapling_cb);
1662 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
3f7eeb86 1663 }
f5d78688 1664# endif
3f0945ff
PP
1665 /* We always do this, so that $tls_sni is available even if not used in
1666 tls_certificate */
7006ee24
JH
1667 SSL_CTX_set_tlsext_servername_callback(ctx, tls_servername_cb);
1668 SSL_CTX_set_tlsext_servername_arg(ctx, cbinfo);
3f0945ff 1669 }
f2de3a33 1670# ifndef DISABLE_OCSP
f5d78688
JH
1671else /* client */
1672 if(ocsp_file) /* wanting stapling */
1673 {
1674 if (!(cbinfo->u_ocsp.client.verify_store = X509_STORE_new()))
1675 {
1676 DEBUG(D_tls) debug_printf("failed to create store for stapling verify\n");
1677 return FAIL;
1678 }
7006ee24
JH
1679 SSL_CTX_set_tlsext_status_cb(ctx, tls_client_stapling_cb);
1680 SSL_CTX_set_tlsext_status_arg(ctx, cbinfo);
f5d78688
JH
1681 }
1682# endif
7be682ca 1683#endif
059ec3d9 1684
e51c7be2 1685cbinfo->verify_cert_hostnames = NULL;
e51c7be2 1686
c8dfb21d 1687#ifdef EXIM_HAVE_EPHEM_RSA_KEX
059ec3d9 1688/* Set up the RSA callback */
7006ee24 1689SSL_CTX_set_tmp_rsa_callback(ctx, rsa_callback);
c8dfb21d 1690#endif
059ec3d9
PH
1691
1692/* Finally, set the timeout, and we are done */
1693
7006ee24 1694SSL_CTX_set_timeout(ctx, ssl_session_timeout);
059ec3d9 1695DEBUG(D_tls) debug_printf("Initialized TLS\n");
7be682ca 1696
817d9f57 1697*cbp = cbinfo;
7006ee24 1698*ctxp = ctx;
7be682ca 1699
059ec3d9
PH
1700return OK;
1701}
1702
1703
1704
1705
1706/*************************************************
1707* Get name of cipher in use *
1708*************************************************/
1709
817d9f57 1710/*
059ec3d9 1711Argument: pointer to an SSL structure for the connection
817d9f57
JH
1712 buffer to use for answer
1713 size of buffer
1714 pointer to number of bits for cipher
059ec3d9
PH
1715Returns: nothing
1716*/
1717
1718static void
817d9f57 1719construct_cipher_name(SSL *ssl, uschar *cipherbuf, int bsize, int *bits)
059ec3d9 1720{
7a8b9519 1721/* With OpenSSL 1.0.0a, 'c' needs to be const but the documentation doesn't
57b3a7f5
PP
1722yet reflect that. It should be a safe change anyway, even 0.9.8 versions have
1723the accessor functions use const in the prototype. */
059ec3d9 1724
7a8b9519
JH
1725const uschar * ver = CUS SSL_get_version(ssl);
1726const SSL_CIPHER * c = (const SSL_CIPHER *) SSL_get_current_cipher(ssl);
059ec3d9 1727
817d9f57 1728SSL_CIPHER_get_bits(c, bits);
059ec3d9 1729
817d9f57
JH
1730string_format(cipherbuf, bsize, "%s:%s:%u", ver,
1731 SSL_CIPHER_get_name(c), *bits);
059ec3d9
PH
1732
1733DEBUG(D_tls) debug_printf("Cipher: %s\n", cipherbuf);
1734}
1735
1736
f69979cf
JH
1737static void
1738peer_cert(SSL * ssl, tls_support * tlsp, uschar * peerdn, unsigned bsize)
1739{
1740/*XXX we might consider a list-of-certs variable for the cert chain.
1741SSL_get_peer_cert_chain(SSL*). We'd need a new variable type and support
1742in list-handling functions, also consider the difference between the entire
1743chain and the elements sent by the peer. */
1744
1745/* Will have already noted peercert on a verify fail; possibly not the leaf */
1746if (!tlsp->peercert)
1747 tlsp->peercert = SSL_get_peer_certificate(ssl);
1748/* Beware anonymous ciphers which lead to server_cert being NULL */
1749if (tlsp->peercert)
1750 {
1751 X509_NAME_oneline(X509_get_subject_name(tlsp->peercert), CS peerdn, bsize);
1752 peerdn[bsize-1] = '\0';
1753 tlsp->peerdn = peerdn; /*XXX a static buffer... */
1754 }
1755else
1756 tlsp->peerdn = NULL;
1757}
1758
1759
059ec3d9
PH
1760
1761
1762
1763/*************************************************
1764* Set up for verifying certificates *
1765*************************************************/
1766
0e8aed8a 1767#ifndef DISABLE_OCSP
c3033f13
JH
1768/* Load certs from file, return TRUE on success */
1769
1770static BOOL
1771chain_from_pem_file(const uschar * file, STACK_OF(X509) * verify_stack)
1772{
1773BIO * bp;
1774X509 * x;
1775
dec766a1
WB
1776while (sk_X509_num(verify_stack) > 0)
1777 X509_free(sk_X509_pop(verify_stack));
1778
c3033f13
JH
1779if (!(bp = BIO_new_file(CS file, "r"))) return FALSE;
1780while ((x = PEM_read_bio_X509(bp, NULL, 0, NULL)))
1781 sk_X509_push(verify_stack, x);
1782BIO_free(bp);
1783return TRUE;
1784}
0e8aed8a 1785#endif
c3033f13
JH
1786
1787
1788
dec766a1
WB
1789/* Called by both client and server startup; on the server possibly
1790repeated after a Server Name Indication.
059ec3d9
PH
1791
1792Arguments:
7be682ca 1793 sctx SSL_CTX* to initialise
059ec3d9
PH
1794 certs certs file or NULL
1795 crl CRL file or NULL
1796 host NULL in a server; the remote host in a client
1797 optional TRUE if called from a server for a host in tls_try_verify_hosts;
1798 otherwise passed as FALSE
983207c1 1799 cert_vfy_cb Callback function for certificate verification
cf0c6164 1800 errstr error string pointer
059ec3d9
PH
1801
1802Returns: OK/DEFER/FAIL
1803*/
1804
1805static int
983207c1 1806setup_certs(SSL_CTX *sctx, uschar *certs, uschar *crl, host_item *host, BOOL optional,
cf0c6164 1807 int (*cert_vfy_cb)(int, X509_STORE_CTX *), uschar ** errstr)
059ec3d9
PH
1808{
1809uschar *expcerts, *expcrl;
1810
cf0c6164 1811if (!expand_check(certs, US"tls_verify_certificates", &expcerts, errstr))
059ec3d9 1812 return DEFER;
57cc2785 1813DEBUG(D_tls) debug_printf("tls_verify_certificates: %s\n", expcerts);
059ec3d9 1814
10a831a3 1815if (expcerts && *expcerts)
059ec3d9 1816 {
10a831a3
JH
1817 /* Tell the library to use its compiled-in location for the system default
1818 CA bundle. Then add the ones specified in the config, if any. */
cb1d7830 1819
10a831a3 1820 if (!SSL_CTX_set_default_verify_paths(sctx))
cf0c6164 1821 return tls_error(US"SSL_CTX_set_default_verify_paths", host, NULL, errstr);
10a831a3
JH
1822
1823 if (Ustrcmp(expcerts, "system") != 0)
059ec3d9 1824 {
cb1d7830
JH
1825 struct stat statbuf;
1826
cb1d7830
JH
1827 if (Ustat(expcerts, &statbuf) < 0)
1828 {
1829 log_write(0, LOG_MAIN|LOG_PANIC,
1830 "failed to stat %s for certificates", expcerts);
1831 return DEFER;
1832 }
059ec3d9 1833 else
059ec3d9 1834 {
cb1d7830
JH
1835 uschar *file, *dir;
1836 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
1837 { file = NULL; dir = expcerts; }
1838 else
c3033f13
JH
1839 {
1840 file = expcerts; dir = NULL;
1841#ifndef DISABLE_OCSP
1842 /* In the server if we will be offering an OCSP proof, load chain from
1843 file for verifying the OCSP proof at load time. */
1844
1845 if ( !host
1846 && statbuf.st_size > 0
1847 && server_static_cbinfo->u_ocsp.server.file
1848 && !chain_from_pem_file(file, server_static_cbinfo->verify_stack)
1849 )
1850 {
1851 log_write(0, LOG_MAIN|LOG_PANIC,
57887ecc 1852 "failed to load cert chain from %s", file);
c3033f13
JH
1853 return DEFER;
1854 }
1855#endif
1856 }
cb1d7830
JH
1857
1858 /* If a certificate file is empty, the next function fails with an
1859 unhelpful error message. If we skip it, we get the correct behaviour (no
1860 certificates are recognized, but the error message is still misleading (it
c3033f13 1861 says no certificate was supplied). But this is better. */
cb1d7830 1862
f2f2c91b
JH
1863 if ( (!file || statbuf.st_size > 0)
1864 && !SSL_CTX_load_verify_locations(sctx, CS file, CS dir))
cf0c6164 1865 return tls_error(US"SSL_CTX_load_verify_locations", host, NULL, errstr);
cb1d7830
JH
1866
1867 /* Load the list of CAs for which we will accept certs, for sending
1868 to the client. This is only for the one-file tls_verify_certificates
1869 variant.
1870 If a list isn't loaded into the server, but
1871 some verify locations are set, the server end appears to make
4c04137d 1872 a wildcard request for client certs.
10a831a3 1873 Meanwhile, the client library as default behaviour *ignores* the list
cb1d7830
JH
1874 we send over the wire - see man SSL_CTX_set_client_cert_cb.
1875 Because of this, and that the dir variant is likely only used for
1876 the public-CA bundle (not for a private CA), not worth fixing.
1877 */
f2f2c91b 1878 if (file)
cb1d7830 1879 {
2009ecca 1880 STACK_OF(X509_NAME) * names = SSL_load_client_CA_file(CS file);
dec766a1
WB
1881
1882 SSL_CTX_set_client_CA_list(sctx, names);
f2f2c91b 1883 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n",
cb1d7830 1884 sk_X509_NAME_num(names));
cb1d7830 1885 }
059ec3d9
PH
1886 }
1887 }
1888
1889 /* Handle a certificate revocation list. */
1890
10a831a3 1891#if OPENSSL_VERSION_NUMBER > 0x00907000L
059ec3d9 1892
8b417f2c 1893 /* This bit of code is now the version supplied by Lars Mainka. (I have
10a831a3 1894 merely reformatted it into the Exim code style.)
8b417f2c 1895
10a831a3
JH
1896 "From here I changed the code to add support for multiple crl's
1897 in pem format in one file or to support hashed directory entries in
1898 pem format instead of a file. This method now uses the library function
1899 X509_STORE_load_locations to add the CRL location to the SSL context.
1900 OpenSSL will then handle the verify against CA certs and CRLs by
1901 itself in the verify callback." */
8b417f2c 1902
cf0c6164 1903 if (!expand_check(crl, US"tls_crl", &expcrl, errstr)) return DEFER;
10a831a3 1904 if (expcrl && *expcrl)
059ec3d9 1905 {
8b417f2c
PH
1906 struct stat statbufcrl;
1907 if (Ustat(expcrl, &statbufcrl) < 0)
1908 {
1909 log_write(0, LOG_MAIN|LOG_PANIC,
1910 "failed to stat %s for certificates revocation lists", expcrl);
1911 return DEFER;
1912 }
1913 else
059ec3d9 1914 {
8b417f2c
PH
1915 /* is it a file or directory? */
1916 uschar *file, *dir;
7be682ca 1917 X509_STORE *cvstore = SSL_CTX_get_cert_store(sctx);
8b417f2c 1918 if ((statbufcrl.st_mode & S_IFMT) == S_IFDIR)
059ec3d9 1919 {
8b417f2c
PH
1920 file = NULL;
1921 dir = expcrl;
1922 DEBUG(D_tls) debug_printf("SSL CRL value is a directory %s\n", dir);
059ec3d9
PH
1923 }
1924 else
1925 {
8b417f2c
PH
1926 file = expcrl;
1927 dir = NULL;
1928 DEBUG(D_tls) debug_printf("SSL CRL value is a file %s\n", file);
059ec3d9 1929 }
8b417f2c 1930 if (X509_STORE_load_locations(cvstore, CS file, CS dir) == 0)
cf0c6164 1931 return tls_error(US"X509_STORE_load_locations", host, NULL, errstr);
8b417f2c
PH
1932
1933 /* setting the flags to check against the complete crl chain */
1934
1935 X509_STORE_set_flags(cvstore,
1936 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
059ec3d9 1937 }
059ec3d9
PH
1938 }
1939
10a831a3 1940#endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
059ec3d9
PH
1941
1942 /* If verification is optional, don't fail if no certificate */
1943
7be682ca 1944 SSL_CTX_set_verify(sctx,
059ec3d9 1945 SSL_VERIFY_PEER | (optional? 0 : SSL_VERIFY_FAIL_IF_NO_PEER_CERT),
983207c1 1946 cert_vfy_cb);
059ec3d9
PH
1947 }
1948
1949return OK;
1950}
1951
1952
1953
1954/*************************************************
1955* Start a TLS session in a server *
1956*************************************************/
1957
1958/* This is called when Exim is running as a server, after having received
1959the STARTTLS command. It must respond to that command, and then negotiate
1960a TLS session.
1961
1962Arguments:
1963 require_ciphers allowed ciphers
cf0c6164 1964 errstr pointer to error message
059ec3d9
PH
1965
1966Returns: OK on success
1967 DEFER for errors before the start of the negotiation
4c04137d 1968 FAIL for errors during the negotiation; the server can't
059ec3d9
PH
1969 continue running.
1970*/
1971
1972int
cf0c6164 1973tls_server_start(const uschar * require_ciphers, uschar ** errstr)
059ec3d9
PH
1974{
1975int rc;
cf0c6164
JH
1976uschar * expciphers;
1977tls_ext_ctx_cb * cbinfo;
f69979cf 1978static uschar peerdn[256];
817d9f57 1979static uschar cipherbuf[256];
059ec3d9
PH
1980
1981/* Check for previous activation */
1982
74f1a423 1983if (tls_in.active.sock >= 0)
059ec3d9 1984 {
cf0c6164 1985 tls_error(US"STARTTLS received after TLS started", NULL, US"", errstr);
925ac8e4 1986 smtp_printf("554 Already in TLS\r\n", FALSE);
059ec3d9
PH
1987 return FAIL;
1988 }
1989
1990/* Initialize the SSL library. If it fails, it will already have logged
1991the error. */
1992
817d9f57 1993rc = tls_init(&server_ctx, NULL, tls_dhparam, tls_certificate, tls_privatekey,
f2de3a33 1994#ifndef DISABLE_OCSP
47195144 1995 tls_ocsp_file, /*XXX stack*/
3f7eeb86 1996#endif
cf0c6164 1997 NULL, &server_static_cbinfo, errstr);
059ec3d9 1998if (rc != OK) return rc;
817d9f57 1999cbinfo = server_static_cbinfo;
059ec3d9 2000
cf0c6164 2001if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers, errstr))
059ec3d9
PH
2002 return FAIL;
2003
2004/* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
17c76198
PP
2005were historically separated by underscores. So that I can use either form in my
2006tests, and also for general convenience, we turn underscores into hyphens here.
0c3807a8
JH
2007
2008XXX SSL_CTX_set_cipher_list() is replaced by SSL_CTX_set_ciphersuites()
2009for TLS 1.3 . Since we do not call it at present we get the default list:
2010TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
17c76198 2011*/
059ec3d9 2012
c3033f13 2013if (expciphers)
059ec3d9 2014 {
c3033f13 2015 uschar * s = expciphers;
059ec3d9
PH
2016 while (*s != 0) { if (*s == '_') *s = '-'; s++; }
2017 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
817d9f57 2018 if (!SSL_CTX_set_cipher_list(server_ctx, CS expciphers))
cf0c6164 2019 return tls_error(US"SSL_CTX_set_cipher_list", NULL, NULL, errstr);
7be682ca 2020 cbinfo->server_cipher_list = expciphers;
059ec3d9
PH
2021 }
2022
2023/* If this is a host for which certificate verification is mandatory or
2024optional, set up appropriately. */
2025
817d9f57 2026tls_in.certificate_verified = FALSE;
c0635b6d 2027#ifdef SUPPORT_DANE
53a7196b
JH
2028tls_in.dane_verified = FALSE;
2029#endif
a2ff477a 2030server_verify_callback_called = FALSE;
059ec3d9
PH
2031
2032if (verify_check_host(&tls_verify_hosts) == OK)
2033 {
983207c1 2034 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
cf0c6164 2035 FALSE, verify_callback_server, errstr);
059ec3d9 2036 if (rc != OK) return rc;
a2ff477a 2037 server_verify_optional = FALSE;
059ec3d9
PH
2038 }
2039else if (verify_check_host(&tls_try_verify_hosts) == OK)
2040 {
983207c1 2041 rc = setup_certs(server_ctx, tls_verify_certificates, tls_crl, NULL,
cf0c6164 2042 TRUE, verify_callback_server, errstr);
059ec3d9 2043 if (rc != OK) return rc;
a2ff477a 2044 server_verify_optional = TRUE;
059ec3d9
PH
2045 }
2046
2047/* Prepare for new connection */
2048
cf0c6164
JH
2049if (!(server_ssl = SSL_new(server_ctx)))
2050 return tls_error(US"SSL_new", NULL, NULL, errstr);
da3ad30d
PP
2051
2052/* Warning: we used to SSL_clear(ssl) here, it was removed.
2053 *
2054 * With the SSL_clear(), we get strange interoperability bugs with
2055 * OpenSSL 1.0.1b and TLS1.1/1.2. It looks as though this may be a bug in
2056 * OpenSSL itself, as a clear should not lead to inability to follow protocols.
2057 *
2058 * The SSL_clear() call is to let an existing SSL* be reused, typically after
2059 * session shutdown. In this case, we have a brand new object and there's no
2060 * obvious reason to immediately clear it. I'm guessing that this was
2061 * originally added because of incomplete initialisation which the clear fixed,
2062 * in some historic release.
2063 */
059ec3d9
PH
2064
2065/* Set context and tell client to go ahead, except in the case of TLS startup
2066on connection, where outputting anything now upsets the clients and tends to
2067make them disconnect. We need to have an explicit fflush() here, to force out
2068the response. Other smtp_printf() calls do not need it, because in non-TLS
2069mode, the fflush() happens when smtp_getc() is called. */
2070
817d9f57
JH
2071SSL_set_session_id_context(server_ssl, sid_ctx, Ustrlen(sid_ctx));
2072if (!tls_in.on_connect)
059ec3d9 2073 {
925ac8e4 2074 smtp_printf("220 TLS go ahead\r\n", FALSE);
059ec3d9
PH
2075 fflush(smtp_out);
2076 }
2077
2078/* Now negotiate the TLS session. We put our own timer on it, since it seems
2079that the OpenSSL library doesn't. */
2080
817d9f57
JH
2081SSL_set_wfd(server_ssl, fileno(smtp_out));
2082SSL_set_rfd(server_ssl, fileno(smtp_in));
2083SSL_set_accept_state(server_ssl);
059ec3d9
PH
2084
2085DEBUG(D_tls) debug_printf("Calling SSL_accept\n");
2086
2087sigalrm_seen = FALSE;
2088if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
817d9f57 2089rc = SSL_accept(server_ssl);
059ec3d9
PH
2090alarm(0);
2091
2092if (rc <= 0)
2093 {
cf0c6164 2094 (void) tls_error(US"SSL_accept", NULL, sigalrm_seen ? US"timed out" : NULL, errstr);
059ec3d9
PH
2095 return FAIL;
2096 }
2097
2098DEBUG(D_tls) debug_printf("SSL_accept was successful\n");
2099
2100/* TLS has been set up. Adjust the input functions to read via TLS,
2101and initialize things. */
2102
f69979cf
JH
2103peer_cert(server_ssl, &tls_in, peerdn, sizeof(peerdn));
2104
817d9f57
JH
2105construct_cipher_name(server_ssl, cipherbuf, sizeof(cipherbuf), &tls_in.bits);
2106tls_in.cipher = cipherbuf;
059ec3d9
PH
2107
2108DEBUG(D_tls)
2109 {
2110 uschar buf[2048];
817d9f57 2111 if (SSL_get_shared_ciphers(server_ssl, CS buf, sizeof(buf)) != NULL)
059ec3d9
PH
2112 debug_printf("Shared ciphers: %s\n", buf);
2113 }
2114
9d1c15ef
JH
2115/* Record the certificate we presented */
2116 {
2117 X509 * crt = SSL_get_certificate(server_ssl);
2118 tls_in.ourcert = crt ? X509_dup(crt) : NULL;
2119 }
059ec3d9 2120
817d9f57
JH
2121/* Only used by the server-side tls (tls_in), including tls_getc.
2122 Client-side (tls_out) reads (seem to?) go via
2123 smtp_read_response()/ip_recv().
2124 Hence no need to duplicate for _in and _out.
2125 */
b808677c 2126if (!ssl_xfer_buffer) ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
059ec3d9 2127ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
8b77d27a 2128ssl_xfer_eof = ssl_xfer_error = FALSE;
059ec3d9
PH
2129
2130receive_getc = tls_getc;
0d81dabc 2131receive_getbuf = tls_getbuf;
584e96c6 2132receive_get_cache = tls_get_cache;
059ec3d9
PH
2133receive_ungetc = tls_ungetc;
2134receive_feof = tls_feof;
2135receive_ferror = tls_ferror;
58eb016e 2136receive_smtp_buffered = tls_smtp_buffered;
059ec3d9 2137
74f1a423
JH
2138tls_in.active.sock = fileno(smtp_out);
2139tls_in.active.tls_ctx = NULL; /* not using explicit ctx for server-side */
059ec3d9
PH
2140return OK;
2141}
2142
2143
2144
2145
043b1248
JH
2146static int
2147tls_client_basic_ctx_init(SSL_CTX * ctx,
cf0c6164
JH
2148 host_item * host, smtp_transport_options_block * ob, tls_ext_ctx_cb * cbinfo,
2149 uschar ** errstr)
043b1248
JH
2150{
2151int rc;
94431adb 2152/* stick to the old behaviour for compatibility if tls_verify_certificates is
043b1248
JH
2153 set but both tls_verify_hosts and tls_try_verify_hosts is not set. Check only
2154 the specified host patterns if one of them is defined */
2155
610ff438
JH
2156if ( ( !ob->tls_verify_hosts
2157 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2158 )
5130845b 2159 || (verify_check_given_host(&ob->tls_verify_hosts, host) == OK)
aa2a70ba 2160 )
043b1248 2161 client_verify_optional = FALSE;
5130845b 2162else if (verify_check_given_host(&ob->tls_try_verify_hosts, host) == OK)
aa2a70ba
JH
2163 client_verify_optional = TRUE;
2164else
2165 return OK;
2166
2167if ((rc = setup_certs(ctx, ob->tls_verify_certificates,
cf0c6164
JH
2168 ob->tls_crl, host, client_verify_optional, verify_callback_client,
2169 errstr)) != OK)
aa2a70ba 2170 return rc;
043b1248 2171
5130845b 2172if (verify_check_given_host(&ob->tls_verify_cert_hostnames, host) == OK)
043b1248 2173 {
4af0d74a 2174 cbinfo->verify_cert_hostnames =
8c5d388a 2175#ifdef SUPPORT_I18N
4af0d74a
JH
2176 string_domain_utf8_to_alabel(host->name, NULL);
2177#else
2178 host->name;
2179#endif
aa2a70ba
JH
2180 DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
2181 cbinfo->verify_cert_hostnames);
043b1248 2182 }
043b1248
JH
2183return OK;
2184}
059ec3d9 2185
fde080a4 2186
c0635b6d 2187#ifdef SUPPORT_DANE
fde080a4 2188static int
cf0c6164 2189dane_tlsa_load(SSL * ssl, host_item * host, dns_answer * dnsa, uschar ** errstr)
fde080a4
JH
2190{
2191dns_record * rr;
2192dns_scan dnss;
2193const char * hostnames[2] = { CS host->name, NULL };
2194int found = 0;
2195
2196if (DANESSL_init(ssl, NULL, hostnames) != 1)
cf0c6164 2197 return tls_error(US"hostnames load", host, NULL, errstr);
fde080a4
JH
2198
2199for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
2200 rr;
2201 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2202 ) if (rr->type == T_TLSA)
2203 {
c3033f13 2204 const uschar * p = rr->data;
fde080a4
JH
2205 uint8_t usage, selector, mtype;
2206 const char * mdname;
2207
fde080a4 2208 usage = *p++;
133d2546
JH
2209
2210 /* Only DANE-TA(2) and DANE-EE(3) are supported */
2211 if (usage != 2 && usage != 3) continue;
2212
fde080a4
JH
2213 selector = *p++;
2214 mtype = *p++;
2215
2216 switch (mtype)
2217 {
133d2546
JH
2218 default: continue; /* Only match-types 0, 1, 2 are supported */
2219 case 0: mdname = NULL; break;
2220 case 1: mdname = "sha256"; break;
2221 case 2: mdname = "sha512"; break;
fde080a4
JH
2222 }
2223
133d2546 2224 found++;
fde080a4
JH
2225 switch (DANESSL_add_tlsa(ssl, usage, selector, mdname, p, rr->size - 3))
2226 {
2227 default:
cf0c6164 2228 return tls_error(US"tlsa load", host, NULL, errstr);
c035b645 2229 case 0: /* action not taken */
fde080a4
JH
2230 case 1: break;
2231 }
594706ea
JH
2232
2233 tls_out.tlsa_usage |= 1<<usage;
fde080a4
JH
2234 }
2235
2236if (found)
2237 return OK;
2238
133d2546 2239log_write(0, LOG_MAIN, "DANE error: No usable TLSA records");
6ebd79ec 2240return DEFER;
fde080a4 2241}
c0635b6d 2242#endif /*SUPPORT_DANE*/
fde080a4
JH
2243
2244
2245
059ec3d9
PH
2246/*************************************************
2247* Start a TLS session in a client *
2248*************************************************/
2249
2250/* Called from the smtp transport after STARTTLS has been accepted.
2251
2252Argument:
2253 fd the fd of the connection
2254 host connected host (for messages)
83da1223 2255 addr the first address
a7538db1 2256 tb transport (always smtp)
0e66b3b6 2257 tlsa_dnsa tlsa lookup, if DANE, else null
74f1a423 2258 tlsp record details of channel configuration
cf0c6164 2259 errstr error string pointer
059ec3d9 2260
74f1a423 2261Returns: Pointer to TLS session context, or NULL on error
059ec3d9
PH
2262*/
2263
74f1a423 2264void *
f5d78688 2265tls_client_start(int fd, host_item *host, address_item *addr,
cf0c6164 2266 transport_instance * tb,
c0635b6d 2267#ifdef SUPPORT_DANE
cf0c6164 2268 dns_answer * tlsa_dnsa,
0e66b3b6 2269#endif
74f1a423 2270 tls_support * tlsp, uschar ** errstr)
059ec3d9 2271{
a7538db1
JH
2272smtp_transport_options_block * ob =
2273 (smtp_transport_options_block *)tb->options_block;
74f1a423 2274exim_openssl_client_tls_ctx * exim_client_ctx;
f69979cf 2275static uschar peerdn[256];
868f5672 2276uschar * expciphers;
059ec3d9 2277int rc;
817d9f57 2278static uschar cipherbuf[256];
043b1248
JH
2279
2280#ifndef DISABLE_OCSP
043b1248 2281BOOL request_ocsp = FALSE;
6634ac8d 2282BOOL require_ocsp = FALSE;
043b1248 2283#endif
043b1248 2284
74f1a423
JH
2285rc = store_pool;
2286store_pool = POOL_PERM;
2287exim_client_ctx = store_get(sizeof(exim_openssl_client_tls_ctx));
2288store_pool = rc;
2289
c0635b6d 2290#ifdef SUPPORT_DANE
74f1a423 2291tlsp->tlsa_usage = 0;
043b1248
JH
2292#endif
2293
f2de3a33 2294#ifndef DISABLE_OCSP
043b1248 2295 {
c0635b6d 2296# ifdef SUPPORT_DANE
4f59c424
JH
2297 if ( tlsa_dnsa
2298 && ob->hosts_request_ocsp[0] == '*'
2299 && ob->hosts_request_ocsp[1] == '\0'
2300 )
2301 {
2302 /* Unchanged from default. Use a safer one under DANE */
2303 request_ocsp = TRUE;
2304 ob->hosts_request_ocsp = US"${if or { {= {0}{$tls_out_tlsa_usage}} "
2305 " {= {4}{$tls_out_tlsa_usage}} } "
2306 " {*}{}}";
2307 }
2308# endif
2309
5130845b
JH
2310 if ((require_ocsp =
2311 verify_check_given_host(&ob->hosts_require_ocsp, host) == OK))
fca41d5a
JH
2312 request_ocsp = TRUE;
2313 else
c0635b6d 2314# ifdef SUPPORT_DANE
4f59c424 2315 if (!request_ocsp)
fca41d5a 2316# endif
5130845b
JH
2317 request_ocsp =
2318 verify_check_given_host(&ob->hosts_request_ocsp, host) == OK;
043b1248 2319 }
f5d78688 2320#endif
059ec3d9 2321
74f1a423 2322rc = tls_init(&exim_client_ctx->ctx, host, NULL,
65867078 2323 ob->tls_certificate, ob->tls_privatekey,
f2de3a33 2324#ifndef DISABLE_OCSP
44662487 2325 (void *)(long)request_ocsp,
3f7eeb86 2326#endif
cf0c6164 2327 addr, &client_static_cbinfo, errstr);
74f1a423 2328if (rc != OK) return NULL;
059ec3d9 2329
74f1a423 2330tlsp->certificate_verified = FALSE;
a2ff477a 2331client_verify_callback_called = FALSE;
059ec3d9 2332
5ec37a55
PP
2333expciphers = NULL;
2334#ifdef SUPPORT_DANE
2335if (tlsa_dnsa)
2336 {
2337 /* We fall back to tls_require_ciphers if unset, empty or forced failure, but
2338 other failures should be treated as problems. */
2339 if (ob->dane_require_tls_ciphers &&
2340 !expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2341 &expciphers, errstr))
74f1a423 2342 return NULL;
5ec37a55
PP
2343 if (expciphers && *expciphers == '\0')
2344 expciphers = NULL;
2345 }
2346#endif
2347if (!expciphers &&
2348 !expand_check(ob->tls_require_ciphers, US"tls_require_ciphers",
2349 &expciphers, errstr))
74f1a423 2350 return NULL;
059ec3d9
PH
2351
2352/* In OpenSSL, cipher components are separated by hyphens. In GnuTLS, they
2353are separated by underscores. So that I can use either form in my tests, and
2354also for general convenience, we turn underscores into hyphens here. */
2355
cf0c6164 2356if (expciphers)
059ec3d9
PH
2357 {
2358 uschar *s = expciphers;
cf0c6164 2359 while (*s) { if (*s == '_') *s = '-'; s++; }
059ec3d9 2360 DEBUG(D_tls) debug_printf("required ciphers: %s\n", expciphers);
74f1a423
JH
2361 if (!SSL_CTX_set_cipher_list(exim_client_ctx->ctx, CS expciphers))
2362 {
2363 tls_error(US"SSL_CTX_set_cipher_list", host, NULL, errstr);
2364 return NULL;
2365 }
059ec3d9
PH
2366 }
2367
c0635b6d 2368#ifdef SUPPORT_DANE
0e66b3b6 2369if (tlsa_dnsa)
a63be306 2370 {
74f1a423 2371 SSL_CTX_set_verify(exim_client_ctx->ctx,
02af313d
JH
2372 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
2373 verify_callback_client_dane);
e5cccda9 2374
043b1248 2375 if (!DANESSL_library_init())
74f1a423
JH
2376 {
2377 tls_error(US"library init", host, NULL, errstr);
2378 return NULL;
2379 }
2380 if (DANESSL_CTX_init(exim_client_ctx->ctx) <= 0)
2381 {
2382 tls_error(US"context init", host, NULL, errstr);
2383 return NULL;
2384 }
043b1248
JH
2385 }
2386else
e51c7be2 2387
043b1248
JH
2388#endif
2389
74f1a423
JH
2390 if (tls_client_basic_ctx_init(exim_client_ctx->ctx, host, ob,
2391 client_static_cbinfo, errstr) != OK)
2392 return NULL;
059ec3d9 2393
74f1a423
JH
2394if (!(exim_client_ctx->ssl = SSL_new(exim_client_ctx->ctx)))
2395 {
2396 tls_error(US"SSL_new", host, NULL, errstr);
2397 return NULL;
2398 }
2399SSL_set_session_id_context(exim_client_ctx->ssl, sid_ctx, Ustrlen(sid_ctx));
2400SSL_set_fd(exim_client_ctx->ssl, fd);
2401SSL_set_connect_state(exim_client_ctx->ssl);
059ec3d9 2402
65867078 2403if (ob->tls_sni)
3f0945ff 2404 {
74f1a423
JH
2405 if (!expand_check(ob->tls_sni, US"tls_sni", &tlsp->sni, errstr))
2406 return NULL;
2407 if (!tlsp->sni)
2c9a0e86
PP
2408 {
2409 DEBUG(D_tls) debug_printf("Setting TLS SNI forced to fail, not sending\n");
2410 }
74f1a423
JH
2411 else if (!Ustrlen(tlsp->sni))
2412 tlsp->sni = NULL;
3f0945ff
PP
2413 else
2414 {
35731706 2415#ifdef EXIM_HAVE_OPENSSL_TLSEXT
74f1a423
JH
2416 DEBUG(D_tls) debug_printf("Setting TLS SNI \"%s\"\n", tlsp->sni);
2417 SSL_set_tlsext_host_name(exim_client_ctx->ssl, tlsp->sni);
35731706 2418#else
66802652 2419 log_write(0, LOG_MAIN, "SNI unusable with this OpenSSL library version; ignoring \"%s\"\n",
74f1a423 2420 tlsp->sni);
35731706 2421#endif
3f0945ff
PP
2422 }
2423 }
2424
c0635b6d 2425#ifdef SUPPORT_DANE
0e66b3b6 2426if (tlsa_dnsa)
74f1a423
JH
2427 if (dane_tlsa_load(exim_client_ctx->ssl, host, tlsa_dnsa, errstr) != OK)
2428 return NULL;
594706ea
JH
2429#endif
2430
f2de3a33 2431#ifndef DISABLE_OCSP
f5d78688
JH
2432/* Request certificate status at connection-time. If the server
2433does OCSP stapling we will get the callback (set in tls_init()) */
c0635b6d 2434# ifdef SUPPORT_DANE
594706ea
JH
2435if (request_ocsp)
2436 {
2437 const uschar * s;
41afb5cb
JH
2438 if ( ((s = ob->hosts_require_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
2439 || ((s = ob->hosts_request_ocsp) && Ustrstr(s, US"tls_out_tlsa_usage"))
594706ea
JH
2440 )
2441 { /* Re-eval now $tls_out_tlsa_usage is populated. If
2442 this means we avoid the OCSP request, we wasted the setup
2443 cost in tls_init(). */
5130845b
JH
2444 require_ocsp = verify_check_given_host(&ob->hosts_require_ocsp, host) == OK;
2445 request_ocsp = require_ocsp
2446 || verify_check_given_host(&ob->hosts_request_ocsp, host) == OK;
594706ea
JH
2447 }
2448 }
b50c8b84
JH
2449# endif
2450
44662487
JH
2451if (request_ocsp)
2452 {
74f1a423 2453 SSL_set_tlsext_status_type(exim_client_ctx->ssl, TLSEXT_STATUSTYPE_ocsp);
44662487 2454 client_static_cbinfo->u_ocsp.client.verify_required = require_ocsp;
74f1a423 2455 tlsp->ocsp = OCSP_NOT_RESP;
44662487 2456 }
f5d78688
JH
2457#endif
2458
0cbf2b82 2459#ifndef DISABLE_EVENT
774ef2d7 2460client_static_cbinfo->event_action = tb->event_action;
a7538db1 2461#endif
043b1248 2462
059ec3d9
PH
2463/* There doesn't seem to be a built-in timeout on connection. */
2464
2465DEBUG(D_tls) debug_printf("Calling SSL_connect\n");
2466sigalrm_seen = FALSE;
65867078 2467alarm(ob->command_timeout);
74f1a423 2468rc = SSL_connect(exim_client_ctx->ssl);
059ec3d9
PH
2469alarm(0);
2470
c0635b6d 2471#ifdef SUPPORT_DANE
0e66b3b6 2472if (tlsa_dnsa)
74f1a423 2473 DANESSL_cleanup(exim_client_ctx->ssl);
043b1248
JH
2474#endif
2475
059ec3d9 2476if (rc <= 0)
74f1a423
JH
2477 {
2478 tls_error(US"SSL_connect", host, sigalrm_seen ? US"timed out" : NULL, errstr);
2479 return NULL;
2480 }
059ec3d9
PH
2481
2482DEBUG(D_tls) debug_printf("SSL_connect succeeded\n");
2483
74f1a423 2484peer_cert(exim_client_ctx->ssl, tlsp, peerdn, sizeof(peerdn));
059ec3d9 2485
74f1a423
JH
2486construct_cipher_name(exim_client_ctx->ssl, cipherbuf, sizeof(cipherbuf), &tlsp->bits);
2487tlsp->cipher = cipherbuf;
059ec3d9 2488
9d1c15ef
JH
2489/* Record the certificate we presented */
2490 {
74f1a423
JH
2491 X509 * crt = SSL_get_certificate(exim_client_ctx->ssl);
2492 tlsp->ourcert = crt ? X509_dup(crt) : NULL;
9d1c15ef
JH
2493 }
2494
74f1a423
JH
2495tlsp->active.sock = fd;
2496tlsp->active.tls_ctx = exim_client_ctx;
2497return exim_client_ctx;
059ec3d9
PH
2498}
2499
2500
2501
2502
2503
0d81dabc
JH
2504static BOOL
2505tls_refill(unsigned lim)
2506{
2507int error;
2508int inbytes;
2509
2510DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", server_ssl,
2511 ssl_xfer_buffer, ssl_xfer_buffer_size);
2512
2513if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2514inbytes = SSL_read(server_ssl, CS ssl_xfer_buffer,
2515 MIN(ssl_xfer_buffer_size, lim));
2516error = SSL_get_error(server_ssl, inbytes);
9723f966
JH
2517if (smtp_receive_timeout > 0) alarm(0);
2518
2519if (had_command_timeout) /* set by signal handler */
2520 smtp_command_timeout_exit(); /* does not return */
2521if (had_command_sigterm)
2522 smtp_command_sigterm_exit();
2523if (had_data_timeout)
2524 smtp_data_timeout_exit();
2525if (had_data_sigint)
2526 smtp_data_sigint_exit();
0d81dabc
JH
2527
2528/* SSL_ERROR_ZERO_RETURN appears to mean that the SSL session has been
2529closed down, not that the socket itself has been closed down. Revert to
2530non-SSL handling. */
2531
74f1a423 2532switch(error)
0d81dabc 2533 {
74f1a423
JH
2534 case SSL_ERROR_NONE:
2535 break;
2536
2537 case SSL_ERROR_ZERO_RETURN:
2538 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
0d81dabc 2539
74f1a423
JH
2540 receive_getc = smtp_getc;
2541 receive_getbuf = smtp_getbuf;
2542 receive_get_cache = smtp_get_cache;
2543 receive_ungetc = smtp_ungetc;
2544 receive_feof = smtp_feof;
2545 receive_ferror = smtp_ferror;
2546 receive_smtp_buffered = smtp_buffered;
0d81dabc 2547
74f1a423
JH
2548 if (SSL_get_shutdown(server_ssl) == SSL_RECEIVED_SHUTDOWN)
2549 SSL_shutdown(server_ssl);
dec766a1 2550
37f0ce65 2551#ifndef DISABLE_OCSP
74f1a423
JH
2552 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
2553 server_static_cbinfo->verify_stack = NULL;
37f0ce65 2554#endif
74f1a423
JH
2555 SSL_free(server_ssl);
2556 SSL_CTX_free(server_ctx);
2557 server_ctx = NULL;
2558 server_ssl = NULL;
2559 tls_in.active.sock = -1;
2560 tls_in.active.tls_ctx = NULL;
2561 tls_in.bits = 0;
2562 tls_in.cipher = NULL;
2563 tls_in.peerdn = NULL;
2564 tls_in.sni = NULL;
0d81dabc 2565
74f1a423 2566 return FALSE;
0d81dabc 2567
74f1a423
JH
2568 /* Handle genuine errors */
2569 case SSL_ERROR_SSL:
2570 ERR_error_string(ERR_get_error(), ssl_errstring);
2571 log_write(0, LOG_MAIN, "TLS error (SSL_read): %s", ssl_errstring);
2572 ssl_xfer_error = TRUE;
2573 return FALSE;
0d81dabc 2574
74f1a423
JH
2575 default:
2576 DEBUG(D_tls) debug_printf("Got SSL error %d\n", error);
2577 DEBUG(D_tls) if (error == SSL_ERROR_SYSCALL)
2578 debug_printf(" - syscall %s\n", strerror(errno));
2579 ssl_xfer_error = TRUE;
2580 return FALSE;
0d81dabc
JH
2581 }
2582
2583#ifndef DISABLE_DKIM
2584dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
2585#endif
2586ssl_xfer_buffer_hwm = inbytes;
2587ssl_xfer_buffer_lwm = 0;
2588return TRUE;
2589}
2590
2591
059ec3d9
PH
2592/*************************************************
2593* TLS version of getc *
2594*************************************************/
2595
2596/* This gets the next byte from the TLS input buffer. If the buffer is empty,
2597it refills the buffer via the SSL reading function.
2598
bd8fbe36 2599Arguments: lim Maximum amount to read/buffer
059ec3d9 2600Returns: the next character or EOF
817d9f57
JH
2601
2602Only used by the server-side TLS.
059ec3d9
PH
2603*/
2604
2605int
bd8fbe36 2606tls_getc(unsigned lim)
059ec3d9
PH
2607{
2608if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
0d81dabc
JH
2609 if (!tls_refill(lim))
2610 return ssl_xfer_error ? EOF : smtp_getc(lim);
059ec3d9 2611
0d81dabc 2612/* Something in the buffer; return next uschar */
059ec3d9 2613
0d81dabc
JH
2614return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
2615}
059ec3d9 2616
0d81dabc
JH
2617uschar *
2618tls_getbuf(unsigned * len)
2619{
2620unsigned size;
2621uschar * buf;
ba084640 2622
0d81dabc
JH
2623if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
2624 if (!tls_refill(*len))
059ec3d9 2625 {
0d81dabc
JH
2626 if (!ssl_xfer_error) return smtp_getbuf(len);
2627 *len = 0;
2628 return NULL;
059ec3d9 2629 }
c80c5570 2630
0d81dabc
JH
2631if ((size = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm) > *len)
2632 size = *len;
2633buf = &ssl_xfer_buffer[ssl_xfer_buffer_lwm];
2634ssl_xfer_buffer_lwm += size;
2635*len = size;
2636return buf;
059ec3d9
PH
2637}
2638
0d81dabc 2639
584e96c6
JH
2640void
2641tls_get_cache()
2642{
9960d1e5 2643#ifndef DISABLE_DKIM
584e96c6
JH
2644int n = ssl_xfer_buffer_hwm - ssl_xfer_buffer_lwm;
2645if (n > 0)
2646 dkim_exim_verify_feed(ssl_xfer_buffer+ssl_xfer_buffer_lwm, n);
584e96c6 2647#endif
9960d1e5 2648}
584e96c6 2649
059ec3d9 2650
925ac8e4
JH
2651BOOL
2652tls_could_read(void)
2653{
a5ffa9b4 2654return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm || SSL_pending(server_ssl) > 0;
925ac8e4
JH
2655}
2656
059ec3d9
PH
2657
2658/*************************************************
2659* Read bytes from TLS channel *
2660*************************************************/
2661
2662/*
2663Arguments:
74f1a423 2664 ct_ctx client context pointer, or NULL for the one global server context
059ec3d9
PH
2665 buff buffer of data
2666 len size of buffer
2667
2668Returns: the number of bytes read
2669 -1 after a failed read
817d9f57
JH
2670
2671Only used by the client-side TLS.
059ec3d9
PH
2672*/
2673
2674int
74f1a423 2675tls_read(void * ct_ctx, uschar *buff, size_t len)
059ec3d9 2676{
74f1a423 2677SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
059ec3d9
PH
2678int inbytes;
2679int error;
2680
389ca47a 2681DEBUG(D_tls) debug_printf("Calling SSL_read(%p, %p, %u)\n", ssl,
c80c5570 2682 buff, (unsigned int)len);
059ec3d9 2683
389ca47a
JH
2684inbytes = SSL_read(ssl, CS buff, len);
2685error = SSL_get_error(ssl, inbytes);
059ec3d9
PH
2686
2687if (error == SSL_ERROR_ZERO_RETURN)
2688 {
2689 DEBUG(D_tls) debug_printf("Got SSL_ERROR_ZERO_RETURN\n");
2690 return -1;
2691 }
2692else if (error != SSL_ERROR_NONE)
059ec3d9 2693 return -1;
059ec3d9
PH
2694
2695return inbytes;
2696}
2697
2698
2699
2700
2701
2702/*************************************************
2703* Write bytes down TLS channel *
2704*************************************************/
2705
2706/*
2707Arguments:
74f1a423 2708 ct_ctx client context pointer, or NULL for the one global server context
059ec3d9
PH
2709 buff buffer of data
2710 len number of bytes
925ac8e4 2711 more further data expected soon
059ec3d9
PH
2712
2713Returns: the number of bytes after a successful write,
2714 -1 after a failed write
817d9f57
JH
2715
2716Used by both server-side and client-side TLS.
059ec3d9
PH
2717*/
2718
2719int
74f1a423 2720tls_write(void * ct_ctx, const uschar *buff, size_t len, BOOL more)
059ec3d9 2721{
a5ffa9b4 2722int outbytes, error, left;
74f1a423 2723SSL * ssl = ct_ctx ? ((exim_openssl_client_tls_ctx *)ct_ctx)->ssl : server_ssl;
acec9514 2724static gstring * corked = NULL;
a5ffa9b4 2725
ef698bf6 2726DEBUG(D_tls) debug_printf("%s(%p, %lu%s)\n", __FUNCTION__,
b93be52e 2727 buff, (unsigned long)len, more ? ", more" : "");
a5ffa9b4
JH
2728
2729/* Lacking a CORK or MSG_MORE facility (such as GnuTLS has) we copy data when
2730"more" is notified. This hack is only ok if small amounts are involved AND only
2731one stream does it, in one context (i.e. no store reset). Currently it is used
2732for the responses to the received SMTP MAIL , RCPT, DATA sequence, only. */
2733
74f1a423 2734if (!ct_ctx && (more || corked))
a5ffa9b4 2735 {
acec9514 2736 corked = string_catn(corked, buff, len);
a5ffa9b4
JH
2737 if (more)
2738 return len;
acec9514
JH
2739 buff = CUS corked->s;
2740 len = corked->ptr;
2741 corked = NULL;
a5ffa9b4 2742 }
059ec3d9 2743
a5ffa9b4 2744for (left = len; left > 0;)
059ec3d9 2745 {
74f1a423 2746 DEBUG(D_tls) debug_printf("SSL_write(%p, %p, %d)\n", ssl, buff, left);
059ec3d9
PH
2747 outbytes = SSL_write(ssl, CS buff, left);
2748 error = SSL_get_error(ssl, outbytes);
2749 DEBUG(D_tls) debug_printf("outbytes=%d error=%d\n", outbytes, error);
2750 switch (error)
2751 {
2752 case SSL_ERROR_SSL:
96f5fe4c
JH
2753 ERR_error_string(ERR_get_error(), ssl_errstring);
2754 log_write(0, LOG_MAIN, "TLS error (SSL_write): %s", ssl_errstring);
2755 return -1;
059ec3d9
PH
2756
2757 case SSL_ERROR_NONE:
96f5fe4c
JH
2758 left -= outbytes;
2759 buff += outbytes;
2760 break;
059ec3d9
PH
2761
2762 case SSL_ERROR_ZERO_RETURN:
96f5fe4c
JH
2763 log_write(0, LOG_MAIN, "SSL channel closed on write");
2764 return -1;
059ec3d9 2765
817d9f57 2766 case SSL_ERROR_SYSCALL:
96f5fe4c
JH
2767 log_write(0, LOG_MAIN, "SSL_write: (from %s) syscall: %s",
2768 sender_fullhost ? sender_fullhost : US"<unknown>",
2769 strerror(errno));
2770 return -1;
817d9f57 2771
059ec3d9 2772 default:
96f5fe4c
JH
2773 log_write(0, LOG_MAIN, "SSL_write error %d", error);
2774 return -1;
059ec3d9
PH
2775 }
2776 }
2777return len;
2778}
2779
2780
2781
2782/*************************************************
2783* Close down a TLS session *
2784*************************************************/
2785
2786/* This is also called from within a delivery subprocess forked from the
2787daemon, to shut down the TLS library, without actually doing a shutdown (which
2788would tamper with the SSL session in the parent process).
2789
dec766a1 2790Arguments:
74f1a423 2791 ct_ctx client TLS context pointer, or NULL for the one global server context
dec766a1
WB
2792 shutdown 1 if TLS close-alert is to be sent,
2793 2 if also response to be waited for
2794
059ec3d9 2795Returns: nothing
817d9f57
JH
2796
2797Used by both server-side and client-side TLS.
059ec3d9
PH
2798*/
2799
2800void
74f1a423 2801tls_close(void * ct_ctx, int shutdown)
059ec3d9 2802{
74f1a423
JH
2803exim_openssl_client_tls_ctx * o_ctx = ct_ctx;
2804SSL_CTX **ctxp = o_ctx ? &o_ctx->ctx : &server_ctx;
2805SSL **sslp = o_ctx ? &o_ctx->ssl : &server_ssl;
2806int *fdp = o_ctx ? &tls_out.active.sock : &tls_in.active.sock;
817d9f57
JH
2807
2808if (*fdp < 0) return; /* TLS was not active */
059ec3d9
PH
2809
2810if (shutdown)
2811 {
dec766a1
WB
2812 int rc;
2813 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
2814 shutdown > 1 ? " (with response-wait)" : "");
2815
2816 if ( (rc = SSL_shutdown(*sslp)) == 0 /* send "close notify" alert */
2817 && shutdown > 1)
2818 {
2819 alarm(2);
2820 rc = SSL_shutdown(*sslp); /* wait for response */
2821 alarm(0);
2822 }
2823
2824 if (rc < 0) DEBUG(D_tls)
2825 {
2826 ERR_error_string(ERR_get_error(), ssl_errstring);
2827 debug_printf("SSL_shutdown: %s\n", ssl_errstring);
2828 }
2829 }
2830
37f0ce65 2831#ifndef DISABLE_OCSP
74f1a423 2832if (!o_ctx) /* server side */
dec766a1
WB
2833 {
2834 sk_X509_pop_free(server_static_cbinfo->verify_stack, X509_free);
dec766a1 2835 server_static_cbinfo->verify_stack = NULL;
059ec3d9 2836 }
37f0ce65 2837#endif
059ec3d9 2838
dec766a1 2839SSL_CTX_free(*ctxp);
817d9f57 2840SSL_free(*sslp);
dec766a1 2841*ctxp = NULL;
817d9f57 2842*sslp = NULL;
817d9f57 2843*fdp = -1;
059ec3d9
PH
2844}
2845
36f12725
NM
2846
2847
2848
3375e053
PP
2849/*************************************************
2850* Let tls_require_ciphers be checked at startup *
2851*************************************************/
2852
2853/* The tls_require_ciphers option, if set, must be something which the
2854library can parse.
2855
2856Returns: NULL on success, or error message
2857*/
2858
2859uschar *
2860tls_validate_require_cipher(void)
2861{
2862SSL_CTX *ctx;
2863uschar *s, *expciphers, *err;
2864
2865/* this duplicates from tls_init(), we need a better "init just global
2866state, for no specific purpose" singleton function of our own */
2867
2868SSL_load_error_strings();
2869OpenSSL_add_ssl_algorithms();
2870#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
2871/* SHA256 is becoming ever more popular. This makes sure it gets added to the
2872list of available digests. */
2873EVP_add_digest(EVP_sha256());
2874#endif
2875
2876if (!(tls_require_ciphers && *tls_require_ciphers))
2877 return NULL;
2878
cf0c6164
JH
2879if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
2880 &err))
3375e053
PP
2881 return US"failed to expand tls_require_ciphers";
2882
2883if (!(expciphers && *expciphers))
2884 return NULL;
2885
2886/* normalisation ripped from above */
2887s = expciphers;
2888while (*s != 0) { if (*s == '_') *s = '-'; s++; }
2889
2890err = NULL;
2891
7a8b9519
JH
2892#ifdef EXIM_HAVE_OPENSSL_TLS_METHOD
2893if (!(ctx = SSL_CTX_new(TLS_server_method())))
2894#else
2895if (!(ctx = SSL_CTX_new(SSLv23_server_method())))
2896#endif
3375e053
PP
2897 {
2898 ERR_error_string(ERR_get_error(), ssl_errstring);
2899 return string_sprintf("SSL_CTX_new() failed: %s", ssl_errstring);
2900 }
2901
2902DEBUG(D_tls)
2903 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2904
2905if (!SSL_CTX_set_cipher_list(ctx, CS expciphers))
2906 {
2907 ERR_error_string(ERR_get_error(), ssl_errstring);
cf0c6164
JH
2908 err = string_sprintf("SSL_CTX_set_cipher_list(%s) failed: %s",
2909 expciphers, ssl_errstring);
3375e053
PP
2910 }
2911
2912SSL_CTX_free(ctx);
2913
2914return err;
2915}
2916
2917
2918
2919
36f12725
NM
2920/*************************************************
2921* Report the library versions. *
2922*************************************************/
2923
2924/* There have historically been some issues with binary compatibility in
2925OpenSSL libraries; if Exim (like many other applications) is built against
2926one version of OpenSSL but the run-time linker picks up another version,
2927it can result in serious failures, including crashing with a SIGSEGV. So
2928report the version found by the compiler and the run-time version.
2929
f64a1e23
PP
2930Note: some OS vendors backport security fixes without changing the version
2931number/string, and the version date remains unchanged. The _build_ date
2932will change, so we can more usefully assist with version diagnosis by also
2933reporting the build date.
2934
36f12725
NM
2935Arguments: a FILE* to print the results to
2936Returns: nothing
2937*/
2938
2939void
2940tls_version_report(FILE *f)
2941{
754a0503 2942fprintf(f, "Library version: OpenSSL: Compile: %s\n"
f64a1e23
PP
2943 " Runtime: %s\n"
2944 " : %s\n",
754a0503 2945 OPENSSL_VERSION_TEXT,
f64a1e23
PP
2946 SSLeay_version(SSLEAY_VERSION),
2947 SSLeay_version(SSLEAY_BUILT_ON));
2948/* third line is 38 characters for the %s and the line is 73 chars long;
2949the OpenSSL output includes a "built on: " prefix already. */
36f12725
NM
2950}
2951
9e3331ea
TK
2952
2953
2954
2955/*************************************************
17c76198 2956* Random number generation *
9e3331ea
TK
2957*************************************************/
2958
2959/* Pseudo-random number generation. The result is not expected to be
2960cryptographically strong but not so weak that someone will shoot themselves
2961in the foot using it as a nonce in input in some email header scheme or
2962whatever weirdness they'll twist this into. The result should handle fork()
2963and avoid repeating sequences. OpenSSL handles that for us.
2964
2965Arguments:
2966 max range maximum
2967Returns a random number in range [0, max-1]
2968*/
2969
2970int
17c76198 2971vaguely_random_number(int max)
9e3331ea
TK
2972{
2973unsigned int r;
2974int i, needed_len;
de6135a0
PP
2975static pid_t pidlast = 0;
2976pid_t pidnow;
9e3331ea
TK
2977uschar *p;
2978uschar smallbuf[sizeof(r)];
2979
2980if (max <= 1)
2981 return 0;
2982
de6135a0
PP
2983pidnow = getpid();
2984if (pidnow != pidlast)
2985 {
2986 /* Although OpenSSL documents that "OpenSSL makes sure that the PRNG state
2987 is unique for each thread", this doesn't apparently apply across processes,
2988 so our own warning from vaguely_random_number_fallback() applies here too.
2989 Fix per PostgreSQL. */
2990 if (pidlast != 0)
2991 RAND_cleanup();
2992 pidlast = pidnow;
2993 }
2994
9e3331ea
TK
2995/* OpenSSL auto-seeds from /dev/random, etc, but this a double-check. */
2996if (!RAND_status())
2997 {
2998 randstuff r;
2999 gettimeofday(&r.tv, NULL);
3000 r.p = getpid();
3001
5903c6ff 3002 RAND_seed(US (&r), sizeof(r));
9e3331ea
TK
3003 }
3004/* We're after pseudo-random, not random; if we still don't have enough data
3005in the internal PRNG then our options are limited. We could sleep and hope
3006for entropy to come along (prayer technique) but if the system is so depleted
3007in the first place then something is likely to just keep taking it. Instead,
3008we'll just take whatever little bit of pseudo-random we can still manage to
3009get. */
3010
3011needed_len = sizeof(r);
3012/* Don't take 8 times more entropy than needed if int is 8 octets and we were
3013asked for a number less than 10. */
3014for (r = max, i = 0; r; ++i)
3015 r >>= 1;
3016i = (i + 7) / 8;
3017if (i < needed_len)
3018 needed_len = i;
3019
c8dfb21d 3020#ifdef EXIM_HAVE_RAND_PSEUDO
9e3331ea 3021/* We do not care if crypto-strong */
17c76198 3022i = RAND_pseudo_bytes(smallbuf, needed_len);
c8dfb21d
JH
3023#else
3024i = RAND_bytes(smallbuf, needed_len);
3025#endif
3026
17c76198
PP
3027if (i < 0)
3028 {
3029 DEBUG(D_all)
3030 debug_printf("OpenSSL RAND_pseudo_bytes() not supported by RAND method, using fallback.\n");
3031 return vaguely_random_number_fallback(max);
3032 }
3033
9e3331ea
TK
3034r = 0;
3035for (p = smallbuf; needed_len; --needed_len, ++p)
3036 {
3037 r *= 256;
3038 r += *p;
3039 }
3040
3041/* We don't particularly care about weighted results; if someone wants
3042smooth distribution and cares enough then they should submit a patch then. */
3043return r % max;
3044}
3045
77bb000f
PP
3046
3047
3048
3049/*************************************************
3050* OpenSSL option parse *
3051*************************************************/
3052
3053/* Parse one option for tls_openssl_options_parse below
3054
3055Arguments:
3056 name one option name
3057 value place to store a value for it
3058Returns success or failure in parsing
3059*/
3060
3061struct exim_openssl_option {
3062 uschar *name;
3063 long value;
3064};
3065/* We could use a macro to expand, but we need the ifdef and not all the
3066options document which version they were introduced in. Policylet: include
3067all options unless explicitly for DTLS, let the administrator choose which
3068to apply.
3069
3070This list is current as of:
e2fbf4a2
PP
3071 ==> 1.0.1b <==
3072Plus SSL_OP_SAFARI_ECDHE_ECDSA_BUG from 2013-June patch/discussion on openssl-dev
3073*/
77bb000f
PP
3074static struct exim_openssl_option exim_openssl_options[] = {
3075/* KEEP SORTED ALPHABETICALLY! */
3076#ifdef SSL_OP_ALL
73a46702 3077 { US"all", SSL_OP_ALL },
77bb000f
PP
3078#endif
3079#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
73a46702 3080 { US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
77bb000f
PP
3081#endif
3082#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
73a46702 3083 { US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
77bb000f
PP
3084#endif
3085#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
73a46702 3086 { US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
77bb000f
PP
3087#endif
3088#ifdef SSL_OP_EPHEMERAL_RSA
73a46702 3089 { US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
77bb000f
PP
3090#endif
3091#ifdef SSL_OP_LEGACY_SERVER_CONNECT
73a46702 3092 { US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
77bb000f
PP
3093#endif
3094#ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
73a46702 3095 { US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
77bb000f
PP
3096#endif
3097#ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
73a46702 3098 { US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
77bb000f
PP
3099#endif
3100#ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
73a46702 3101 { US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
77bb000f
PP
3102#endif
3103#ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
73a46702 3104 { US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
77bb000f
PP
3105#endif
3106#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
73a46702 3107 { US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
77bb000f 3108#endif
c80c5570
PP
3109#ifdef SSL_OP_NO_COMPRESSION
3110 { US"no_compression", SSL_OP_NO_COMPRESSION },
3111#endif
77bb000f 3112#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
73a46702 3113 { US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
77bb000f 3114#endif
c0c7b2da
PP
3115#ifdef SSL_OP_NO_SSLv2
3116 { US"no_sslv2", SSL_OP_NO_SSLv2 },
3117#endif
3118#ifdef SSL_OP_NO_SSLv3
3119 { US"no_sslv3", SSL_OP_NO_SSLv3 },
3120#endif
3121#ifdef SSL_OP_NO_TICKET
3122 { US"no_ticket", SSL_OP_NO_TICKET },
3123#endif
3124#ifdef SSL_OP_NO_TLSv1
3125 { US"no_tlsv1", SSL_OP_NO_TLSv1 },
3126#endif
c80c5570
PP
3127#ifdef SSL_OP_NO_TLSv1_1
3128#if SSL_OP_NO_TLSv1_1 == 0x00000400L
3129 /* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
3130#warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
3131#else
3132 { US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
3133#endif
3134#endif
3135#ifdef SSL_OP_NO_TLSv1_2
3136 { US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
3137#endif
e2fbf4a2
PP
3138#ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
3139 { US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
3140#endif
77bb000f 3141#ifdef SSL_OP_SINGLE_DH_USE
73a46702 3142 { US"single_dh_use", SSL_OP_SINGLE_DH_USE },
77bb000f
PP
3143#endif
3144#ifdef SSL_OP_SINGLE_ECDH_USE
73a46702 3145 { US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
77bb000f
PP
3146#endif
3147#ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
73a46702 3148 { US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
77bb000f
PP
3149#endif
3150#ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
73a46702 3151 { US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
77bb000f
PP
3152#endif
3153#ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
73a46702 3154 { US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
77bb000f
PP
3155#endif
3156#ifdef SSL_OP_TLS_D5_BUG
73a46702 3157 { US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
77bb000f
PP
3158#endif
3159#ifdef SSL_OP_TLS_ROLLBACK_BUG
73a46702 3160 { US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
77bb000f
PP
3161#endif
3162};
3163static int exim_openssl_options_size =
3164 sizeof(exim_openssl_options)/sizeof(struct exim_openssl_option);
3165
c80c5570 3166
77bb000f
PP
3167static BOOL
3168tls_openssl_one_option_parse(uschar *name, long *value)
3169{
3170int first = 0;
3171int last = exim_openssl_options_size;
3172while (last > first)
3173 {
3174 int middle = (first + last)/2;
3175 int c = Ustrcmp(name, exim_openssl_options[middle].name);
3176 if (c == 0)
3177 {
3178 *value = exim_openssl_options[middle].value;
3179 return TRUE;
3180 }
3181 else if (c > 0)
3182 first = middle + 1;
3183 else
3184 last = middle;
3185 }
3186return FALSE;
3187}
3188
3189
3190
3191
3192/*************************************************
3193* OpenSSL option parsing logic *
3194*************************************************/
3195
3196/* OpenSSL has a number of compatibility options which an administrator might
3197reasonably wish to set. Interpret a list similarly to decode_bits(), so that
3198we look like log_selector.
3199
3200Arguments:
3201 option_spec the administrator-supplied string of options
3202 results ptr to long storage for the options bitmap
3203Returns success or failure
3204*/
3205
3206BOOL
3207tls_openssl_options_parse(uschar *option_spec, long *results)
3208{
3209long result, item;
3210uschar *s, *end;
3211uschar keep_c;
3212BOOL adding, item_parsed;
3213
7006ee24 3214result = SSL_OP_NO_TICKET;
b1770b6e 3215/* Prior to 4.80 we or'd in SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; removed
da3ad30d 3216 * from default because it increases BEAST susceptibility. */
f0f5a555
PP
3217#ifdef SSL_OP_NO_SSLv2
3218result |= SSL_OP_NO_SSLv2;
3219#endif
a57b6200
JH
3220#ifdef SSL_OP_SINGLE_DH_USE
3221result |= SSL_OP_SINGLE_DH_USE;
3222#endif
77bb000f 3223
7006ee24 3224if (!option_spec)
77bb000f
PP
3225 {
3226 *results = result;
3227 return TRUE;
3228 }
3229
3230for (s=option_spec; *s != '\0'; /**/)
3231 {
3232 while (isspace(*s)) ++s;
3233 if (*s == '\0')
3234 break;
3235 if (*s != '+' && *s != '-')
3236 {
3237 DEBUG(D_tls) debug_printf("malformed openssl option setting: "
0e944a0d 3238 "+ or - expected but found \"%s\"\n", s);
77bb000f
PP
3239 return FALSE;
3240 }
3241 adding = *s++ == '+';
3242 for (end = s; (*end != '\0') && !isspace(*end); ++end) /**/ ;
3243 keep_c = *end;
3244 *end = '\0';
3245 item_parsed = tls_openssl_one_option_parse(s, &item);
96f5fe4c 3246 *end = keep_c;
77bb000f
PP
3247 if (!item_parsed)
3248 {
0e944a0d 3249 DEBUG(D_tls) debug_printf("openssl option setting unrecognised: \"%s\"\n", s);
77bb000f
PP
3250 return FALSE;
3251 }
3252 DEBUG(D_tls) debug_printf("openssl option, %s from %lx: %lx (%s)\n",
3253 adding ? "adding" : "removing", result, item, s);
3254 if (adding)
3255 result |= item;
3256 else
3257 result &= ~item;
77bb000f
PP
3258 s = end;
3259 }
3260
3261*results = result;
3262return TRUE;
3263}
3264
9d1c15ef
JH
3265/* vi: aw ai sw=2
3266*/
059ec3d9 3267/* End of tls-openssl.c */