Fix build on older OpenSSL
[exim.git] / src / src / tls-gnu.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
17c76198 8/* Copyright (c) Phil Pennock 2012 */
059ec3d9 9
17c76198
PP
10/* This file provides TLS/SSL support for Exim using the GnuTLS library,
11one of the available supported implementations. This file is #included into
12tls.c when USE_GNUTLS has been set.
059ec3d9 13
17c76198
PP
14The code herein is a revamp of GnuTLS integration using the current APIs; the
15original tls-gnu.c was based on a patch which was contributed by Nikos
6aa6fc9c 16Mavrogiannopoulos. The revamp is partially a rewrite, partially cut&paste as
17c76198 17appropriate.
059ec3d9 18
17c76198
PP
19APIs current as of GnuTLS 2.12.18; note that the GnuTLS manual is for GnuTLS 3,
20which is not widely deployed by OS vendors. Will note issues below, which may
21assist in updating the code in the future. Another sources of hints is
22mod_gnutls for Apache (SNI callback registration and handling).
059ec3d9 23
17c76198
PP
24Keeping client and server variables more split than before and is currently
25the norm, in anticipation of TLS in ACL callouts.
059ec3d9 26
17c76198
PP
27I wanted to switch to gnutls_certificate_set_verify_function() so that
28certificate rejection could happen during handshake where it belongs, rather
29than being dropped afterwards, but that was introduced in 2.10.0 and Debian
30(6.0.5) is still on 2.8.6. So for now we have to stick with sub-par behaviour.
059ec3d9 31
17c76198
PP
32(I wasn't looking for libraries quite that old, when updating to get rid of
33compiler warnings of deprecated APIs. If it turns out that a lot of the rest
34require current GnuTLS, then we'll drop support for the ancient libraries).
35*/
b5aea5e1 36
17c76198
PP
37#include <gnutls/gnutls.h>
38/* needed for cert checks in verification and DN extraction: */
39#include <gnutls/x509.h>
40/* man-page is incorrect, gnutls_rnd() is not in gnutls.h: */
41#include <gnutls/crypto.h>
184384c3 42
a5f239e4
PP
43/* needed to disable PKCS11 autoload unless requested */
44#if GNUTLS_VERSION_NUMBER >= 0x020c00
45# include <gnutls/pkcs11.h>
76075bb5 46# define SUPPORT_PARAM_TO_PK_BITS
a5f239e4 47#endif
7e07527a
JH
48#if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
49# warning "GnuTLS library version too old; define DISABLE_OCSP in Makefile"
50# define DISABLE_OCSP
51#endif
0cbf2b82 52#if GNUTLS_VERSION_NUMBER < 0x020a00 && !defined(DISABLE_EVENT)
774ef2d7 53# warning "GnuTLS library version too old; tls:cert event unsupported"
0cbf2b82 54# define DISABLE_EVENT
a7538db1 55#endif
a7fec7a7
JH
56#if GNUTLS_VERSION_NUMBER >= 0x030306
57# define SUPPORT_CA_DIR
58#else
59# undef SUPPORT_CA_DIR
60#endif
11a04b5a 61#if GNUTLS_VERSION_NUMBER >= 0x030014
cb1d7830
JH
62# define SUPPORT_SYSDEFAULT_CABUNDLE
63#endif
184384c3
JH
64#if GNUTLS_VERSION_NUMBER >= 0x030104
65# define GNUTLS_CERT_VFY_STATUS_PRINT
66#endif
925ac8e4
JH
67#if GNUTLS_VERSION_NUMBER >= 0x030109
68# define SUPPORT_CORK
69#endif
f20cfa4a
JH
70#if GNUTLS_VERSION_NUMBER >= 0x03010a
71# define SUPPORT_GNUTLS_SESS_DESC
72#endif
73#if GNUTLS_VERSION_NUMBER >= 0x030500
74# define SUPPORT_GNUTLS_KEYLOG
75#endif
47195144
JH
76#if GNUTLS_VERSION_NUMBER >= 0x030506 && !defined(DISABLE_OCSP)
77# define SUPPORT_SRV_OCSP_STACK
78#endif
c0635b6d
JH
79
80#ifdef SUPPORT_DANE
81# if GNUTLS_VERSION_NUMBER >= 0x030000
82# define DANESSL_USAGE_DANE_TA 2
83# define DANESSL_USAGE_DANE_EE 3
84# else
85# error GnuTLS version too early for DANE
86# endif
87# if GNUTLS_VERSION_NUMBER < 0x999999
88# define GNUTLS_BROKEN_DANE_VALIDATION
89# endif
899b8bbc 90#endif
7e07527a 91
f2de3a33 92#ifndef DISABLE_OCSP
2b4a568d
JH
93# include <gnutls/ocsp.h>
94#endif
899b8bbc
JH
95#ifdef SUPPORT_DANE
96# include <gnutls/dane.h>
97#endif
059ec3d9 98
f1be21cf
JH
99#include "tls-cipher-stdname.c"
100
101
b10c87b3
JH
102#ifdef MACRO_PREDEF
103void
104options_tls(void)
105{
106# ifdef EXPERIMENTAL_TLS_RESUME
107builtin_macro_create_var(US"_RESUME_DECODE", RESUME_DECODE_STRING );
108# endif
109}
110#else
111
112
17c76198 113/* GnuTLS 2 vs 3
059ec3d9 114
17c76198
PP
115GnuTLS 3 only:
116 gnutls_global_set_audit_log_function()
059ec3d9 117
17c76198
PP
118Changes:
119 gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
120*/
059ec3d9 121
17c76198 122/* Local static variables for GnuTLS */
059ec3d9 123
17c76198 124/* Values for verify_requirement */
059ec3d9 125
e51c7be2 126enum peer_verify_requirement
899b8bbc 127 { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED, VERIFY_DANE };
059ec3d9 128
17c76198
PP
129/* This holds most state for server or client; with this, we can set up an
130outbound TLS-enabled connection in an ACL callout, while not stomping all
131over the TLS variables available for expansion.
059ec3d9 132
17c76198
PP
133Some of these correspond to variables in globals.c; those variables will
134be set to point to content in one of these instances, as appropriate for
135the stage of the process lifetime.
059ec3d9 136
389ca47a 137Not handled here: global tls_channelbinding_b64.
17c76198 138*/
059ec3d9 139
17c76198 140typedef struct exim_gnutls_state {
9d1c15ef 141 gnutls_session_t session;
17c76198 142 gnutls_certificate_credentials_t x509_cred;
9d1c15ef 143 gnutls_priority_t priority_cache;
17c76198 144 enum peer_verify_requirement verify_requirement;
9d1c15ef
JH
145 int fd_in;
146 int fd_out;
147 BOOL peer_cert_verified;
899b8bbc 148 BOOL peer_dane_verified;
9d1c15ef
JH
149 BOOL trigger_sni_changes;
150 BOOL have_set_peerdn;
5fd28bb8 151 const struct host_item *host; /* NULL if server */
afdb5e9c 152 gnutls_x509_crt_t peercert;
9d1c15ef
JH
153 uschar *peerdn;
154 uschar *ciphersuite;
155 uschar *received_sni;
17c76198
PP
156
157 const uschar *tls_certificate;
158 const uschar *tls_privatekey;
159 const uschar *tls_sni; /* client send only, not received */
160 const uschar *tls_verify_certificates;
161 const uschar *tls_crl;
162 const uschar *tls_require_ciphers;
e51c7be2 163
17c76198
PP
164 uschar *exp_tls_certificate;
165 uschar *exp_tls_privatekey;
17c76198
PP
166 uschar *exp_tls_verify_certificates;
167 uschar *exp_tls_crl;
168 uschar *exp_tls_require_ciphers;
55414b25 169 const uschar *exp_tls_verify_cert_hostnames;
0cbf2b82 170#ifndef DISABLE_EVENT
a7538db1
JH
171 uschar *event_action;
172#endif
899b8bbc
JH
173#ifdef SUPPORT_DANE
174 char * const * dane_data;
175 const int * dane_data_len;
176#endif
17c76198 177
389ca47a 178 tls_support *tlsp; /* set in tls_init() */
817d9f57 179
17c76198
PP
180 uschar *xfer_buffer;
181 int xfer_buffer_lwm;
182 int xfer_buffer_hwm;
8b77d27a
JH
183 BOOL xfer_eof; /*XXX never gets set! */
184 BOOL xfer_error;
17c76198
PP
185} exim_gnutls_state_st;
186
187static const exim_gnutls_state_st exim_gnutls_state_init = {
b10c87b3 188 /* all elements not explicitly intialised here get 0/NULL/FALSE */
f2ed27cf
JH
189 .fd_in = -1,
190 .fd_out = -1,
17c76198 191};
83da1223 192
17c76198
PP
193/* Not only do we have our own APIs which don't pass around state, assuming
194it's held in globals, GnuTLS doesn't appear to let us register callback data
195for callbacks, or as part of the session, so we have to keep a "this is the
196context we're currently dealing with" pointer and rely upon being
197single-threaded to keep from processing data on an inbound TLS connection while
198talking to another TLS connection for an outbound check. This does mean that
199there's no way for heart-beats to be responded to, for the duration of the
a7538db1
JH
200second connection.
201XXX But see gnutls_session_get_ptr()
202*/
059ec3d9 203
74f1a423 204static exim_gnutls_state_st state_server;
059ec3d9 205
17c76198
PP
206/* dh_params are initialised once within the lifetime of a process using TLS;
207if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
208don't want to repeat this. */
83da1223 209
17c76198 210static gnutls_dh_params_t dh_server_params = NULL;
059ec3d9 211
b10c87b3 212static int ssl_session_timeout = 3600; /* One hour */
059ec3d9 213
fc243e94 214static const uschar * const exim_default_gnutls_priority = US"NORMAL";
83da1223 215
17c76198 216/* Guard library core initialisation */
83da1223 217
17c76198 218static BOOL exim_gnutls_base_init_done = FALSE;
059ec3d9 219
4fb7df6d 220#ifndef DISABLE_OCSP
9196d5bf 221static BOOL gnutls_buggy_ocsp = FALSE;
4fb7df6d 222#endif
9196d5bf 223
b10c87b3
JH
224#ifdef EXPERIMENTAL_TLS_RESUME
225static gnutls_datum_t server_sessticket_key;
226#endif
059ec3d9 227
17c76198
PP
228/* ------------------------------------------------------------------------ */
229/* macros */
83da1223 230
17c76198 231#define MAX_HOST_LEN 255
83da1223 232
17c76198
PP
233/* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
234the library logging; a value less than 0 disables the calls to set up logging
dc6d1769
JH
235callbacks. GNuTLS also looks for an environment variable - except not for
236setuid binaries, making it useless - "GNUTLS_DEBUG_LEVEL".
237Allegedly the testscript line "GNUTLS_DEBUG_LEVEL=9 sudo exim ..." would work,
238but the env var must be added to /etc/sudoers too. */
2c17bb02 239#ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
b1a4f234 240# define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
2c17bb02 241#endif
83da1223 242
2c17bb02 243#ifndef EXIM_CLIENT_DH_MIN_BITS
a7538db1 244# define EXIM_CLIENT_DH_MIN_BITS 1024
2c17bb02 245#endif
83da1223 246
af3498d6
PP
247/* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
248can ask for a bit-strength. Without that, we stick to the constant we had
249before, for now. */
2c17bb02 250#ifndef EXIM_SERVER_DH_BITS_PRE2_12
a7538db1 251# define EXIM_SERVER_DH_BITS_PRE2_12 1024
2c17bb02 252#endif
af3498d6 253
cf0c6164
JH
254#define expand_check_tlsvar(Varname, errstr) \
255 expand_check(state->Varname, US #Varname, &state->exp_##Varname, errstr)
83da1223 256
17c76198 257#if GNUTLS_VERSION_NUMBER >= 0x020c00
e51c7be2
JH
258# define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
259# define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
260# define HAVE_GNUTLS_RND
2519e60d
TL
261/* The security fix we provide with the gnutls_allow_auto_pkcs11 option
262 * (4.82 PP/09) introduces a compatibility regression. The symbol simply
263 * isn't available sometimes, so this needs to become a conditional
264 * compilation; the sanest way to deal with this being a problem on
265 * older OSes is to block it in the Local/Makefile with this compiler
266 * definition */
e51c7be2
JH
267# ifndef AVOID_GNUTLS_PKCS11
268# define HAVE_GNUTLS_PKCS11
269# endif /* AVOID_GNUTLS_PKCS11 */
17c76198 270#endif
83da1223 271
af3498d6
PP
272
273
274
275/* ------------------------------------------------------------------------ */
276/* Callback declarations */
277
278#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
279static void exim_gnutls_logger_cb(int level, const char *message);
280#endif
281
282static int exim_sni_handling_cb(gnutls_session_t session);
283
f2de3a33 284#ifndef DISABLE_OCSP
44662487
JH
285static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
286 gnutls_datum_t * ocsp_response);
287#endif
af3498d6
PP
288
289
290
b10c87b3
JH
291/* Daemon one-time initialisation */
292void
293tls_daemon_init(void)
294{
295#ifdef EXPERIMENTAL_TLS_RESUME
296/* We are dependent on the GnuTLS implementation of the Session Ticket
297encryption; both the strength and the key rotation period. We hope that
298the strength at least matches that of the ciphersuite (but GnuTLS does not
299document this). */
300
301static BOOL once = FALSE;
302if (once) return;
303once = TRUE;
304gnutls_session_ticket_key_generate(&server_sessticket_key); /* >= 2.10.0 */
305if (f.running_in_test_harness) ssl_session_timeout = 6;
306#endif
307}
308
17c76198
PP
309/* ------------------------------------------------------------------------ */
310/* Static functions */
059ec3d9
PH
311
312/*************************************************
313* Handle TLS error *
314*************************************************/
315
316/* Called from lots of places when errors occur before actually starting to do
317the TLS handshake, that is, while the session is still in clear. Always returns
318DEFER for a server and FAIL for a client so that most calls can use "return
319tls_error(...)" to do this processing and then give an appropriate return. A
320single function is used for both server and client, because it is called from
321some shared functions.
322
323Argument:
324 prefix text to include in the logged error
7199e1ee
TF
325 msg additional error string (may be NULL)
326 usually obtained from gnutls_strerror()
17c76198
PP
327 host NULL if setting up a server;
328 the connected host if setting up a client
cf0c6164 329 errstr pointer to returned error string
059ec3d9
PH
330
331Returns: OK/DEFER/FAIL
332*/
333
334static int
48224640 335tls_error(const uschar *prefix, const uschar *msg, const host_item *host,
cf0c6164 336 uschar ** errstr)
059ec3d9 337{
cf0c6164 338if (errstr)
48224640 339 *errstr = string_sprintf("(%s)%s%s", prefix, msg ? ": " : "", msg ? msg : US"");
cf0c6164 340return host ? FAIL : DEFER;
059ec3d9
PH
341}
342
343
452a164f
JH
344static int
345tls_error_gnu(const uschar *prefix, int err, const host_item *host,
346 uschar ** errstr)
347{
348return tls_error(prefix, US gnutls_strerror(err), host, errstr);
349}
350
351static int
352tls_error_sys(const uschar *prefix, int err, const host_item *host,
353 uschar ** errstr)
354{
355return tls_error(prefix, US strerror(err), host, errstr);
356}
059ec3d9 357
17c76198 358
059ec3d9 359/*************************************************
17c76198 360* Deal with logging errors during I/O *
059ec3d9
PH
361*************************************************/
362
17c76198 363/* We have to get the identity of the peer from saved data.
059ec3d9 364
17c76198
PP
365Argument:
366 state the current GnuTLS exim state container
367 rc the GnuTLS error code, or 0 if it's a local error
368 when text identifying read or write
95f52235 369 text local error text when rc is 0
059ec3d9 370
17c76198 371Returns: nothing
059ec3d9
PH
372*/
373
17c76198
PP
374static void
375record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
059ec3d9 376{
48224640 377const uschar * msg;
cf0c6164 378uschar * errstr;
059ec3d9 379
17c76198 380if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
95f52235 381 msg = string_sprintf("A TLS fatal alert has been received: %s",
17c76198
PP
382 US gnutls_alert_get_name(gnutls_alert_get(state->session)));
383else
48224640 384 msg = US gnutls_strerror(rc);
059ec3d9 385
cf0c6164
JH
386(void) tls_error(when, msg, state->host, &errstr);
387
388if (state->host)
389 log_write(0, LOG_MAIN, "H=%s [%s] TLS error on connection %s",
390 state->host->name, state->host->address, errstr);
391else
392 {
393 uschar * conn_info = smtp_get_connection_info();
394 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0) conn_info += 5;
395 /* I'd like to get separated H= here, but too hard for now */
396 log_write(0, LOG_MAIN, "TLS error on %s %s", conn_info, errstr);
397 }
17c76198 398}
059ec3d9 399
059ec3d9 400
059ec3d9 401
059ec3d9 402
17c76198
PP
403/*************************************************
404* Set various Exim expansion vars *
405*************************************************/
059ec3d9 406
e51c7be2
JH
407#define exim_gnutls_cert_err(Label) \
408 do \
409 { \
410 if (rc != GNUTLS_E_SUCCESS) \
411 { \
412 DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", \
413 (Label), gnutls_strerror(rc)); \
414 return rc; \
415 } \
416 } while (0)
9d1c15ef
JH
417
418static int
27f19eb4 419import_cert(const gnutls_datum_t * cert, gnutls_x509_crt_t * crtp)
9d1c15ef
JH
420{
421int rc;
422
423rc = gnutls_x509_crt_init(crtp);
424exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
425
426rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
427exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
428
429return rc;
430}
431
432#undef exim_gnutls_cert_err
433
434
17c76198
PP
435/* We set various Exim global variables from the state, once a session has
436been established. With TLS callouts, may need to change this to stack
437variables, or just re-call it with the server state after client callout
438has finished.
059ec3d9 439
9d1c15ef 440Make sure anything set here is unset in tls_getc().
17c76198
PP
441
442Sets:
443 tls_active fd
444 tls_bits strength indicator
445 tls_certificate_verified bool indicator
446 tls_channelbinding_b64 for some SASL mechanisms
447 tls_cipher a string
9d1c15ef 448 tls_peercert pointer to library internal
17c76198
PP
449 tls_peerdn a string
450 tls_sni a (UTF-8) string
9d1c15ef 451 tls_ourcert pointer to library internal
17c76198
PP
452
453Argument:
454 state the relevant exim_gnutls_state_st *
455*/
456
457static void
9d1c15ef 458extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
17c76198 459{
17c76198
PP
460#ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
461int old_pool;
462int rc;
463gnutls_datum_t channel;
464#endif
9d1c15ef 465tls_support * tlsp = state->tlsp;
17c76198 466
74f1a423
JH
467tlsp->active.sock = state->fd_out;
468tlsp->active.tls_ctx = state;
17c76198 469
817d9f57 470DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
17c76198 471
9d1c15ef 472tlsp->certificate_verified = state->peer_cert_verified;
899b8bbc
JH
473#ifdef SUPPORT_DANE
474tlsp->dane_verified = state->peer_dane_verified;
475#endif
059ec3d9 476
17c76198
PP
477/* note that tls_channelbinding_b64 is not saved to the spool file, since it's
478only available for use for authenticators while this TLS session is running. */
479
480tls_channelbinding_b64 = NULL;
481#ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
482channel.data = NULL;
483channel.size = 0;
1f20760b
JH
484if ((rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel)))
485 { DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc)); }
486else
487 {
17c76198
PP
488 old_pool = store_pool;
489 store_pool = POOL_PERM;
1f20760b 490 tls_channelbinding_b64 = b64encode(CUS channel.data, (int)channel.size);
17c76198
PP
491 store_pool = old_pool;
492 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
1f20760b 493 }
17c76198
PP
494#endif
495
9d1c15ef
JH
496/* peercert is set in peer_status() */
497tlsp->peerdn = state->peerdn;
498tlsp->sni = state->received_sni;
499
500/* record our certificate */
501 {
27f19eb4 502 const gnutls_datum_t * cert = gnutls_certificate_get_ours(state->session);
9d1c15ef
JH
503 gnutls_x509_crt_t crt;
504
505 tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
506 }
059ec3d9
PH
507}
508
509
510
17c76198 511
059ec3d9 512/*************************************************
575643cd 513* Setup up DH parameters *
059ec3d9
PH
514*************************************************/
515
575643cd 516/* Generating the D-H parameters may take a long time. They only need to
059ec3d9
PH
517be re-generated every so often, depending on security policy. What we do is to
518keep these parameters in a file in the spool directory. If the file does not
519exist, we generate them. This means that it is easy to cause a regeneration.
520
521The new file is written as a temporary file and renamed, so that an incomplete
522file is never present. If two processes both compute some new parameters, you
523waste a bit of effort, but it doesn't seem worth messing around with locking to
524prevent this.
525
059ec3d9
PH
526Returns: OK/DEFER/FAIL
527*/
528
529static int
cf0c6164 530init_server_dh(uschar ** errstr)
059ec3d9 531{
17c76198
PP
532int fd, rc;
533unsigned int dh_bits;
27f19eb4 534gnutls_datum_t m;
a799883d
PP
535uschar filename_buf[PATH_MAX];
536uschar *filename = NULL;
17c76198 537size_t sz;
a799883d
PP
538uschar *exp_tls_dhparam;
539BOOL use_file_in_spool = FALSE;
17c76198 540host_item *host = NULL; /* dummy for macros */
059ec3d9 541
17c76198 542DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
059ec3d9 543
452a164f
JH
544if ((rc = gnutls_dh_params_init(&dh_server_params)))
545 return tls_error_gnu(US"gnutls_dh_params_init", rc, host, errstr);
059ec3d9 546
a799883d
PP
547m.data = NULL;
548m.size = 0;
549
cf0c6164 550if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam, errstr))
a799883d
PP
551 return DEFER;
552
553if (!exp_tls_dhparam)
554 {
555 DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
556 m.data = US std_dh_prime_default();
557 m.size = Ustrlen(m.data);
558 }
559else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
560 use_file_in_spool = TRUE;
561else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
562 {
563 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
564 return OK;
565 }
566else if (exp_tls_dhparam[0] != '/')
567 {
f5d25c2b 568 if (!(m.data = US std_dh_prime_named(exp_tls_dhparam)))
48224640 569 return tls_error(US"No standard prime named", exp_tls_dhparam, NULL, errstr);
a799883d
PP
570 m.size = Ustrlen(m.data);
571 }
572else
a799883d 573 filename = exp_tls_dhparam;
a799883d
PP
574
575if (m.data)
576 {
452a164f
JH
577 if ((rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM)))
578 return tls_error_gnu(US"gnutls_dh_params_import_pkcs3", rc, host, errstr);
a799883d
PP
579 DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
580 return OK;
581 }
582
af3498d6
PP
583#ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
584/* If you change this constant, also change dh_param_fn_ext so that we can use a
17c76198 585different filename and ensure we have sufficient bits. */
452a164f
JH
586
587if (!(dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL)))
cf0c6164 588 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL, errstr);
af3498d6 589DEBUG(D_tls)
b34fc30c 590 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
af3498d6
PP
591 dh_bits);
592#else
593dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
594DEBUG(D_tls)
595 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
596 dh_bits);
597#endif
059ec3d9 598
3375e053
PP
599/* Some clients have hard-coded limits. */
600if (dh_bits > tls_dh_max_bits)
601 {
602 DEBUG(D_tls)
603 debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
604 tls_dh_max_bits);
605 dh_bits = tls_dh_max_bits;
606 }
607
a799883d
PP
608if (use_file_in_spool)
609 {
610 if (!string_format(filename_buf, sizeof(filename_buf),
611 "%s/gnutls-params-%d", spool_directory, dh_bits))
cf0c6164 612 return tls_error(US"overlong filename", NULL, NULL, errstr);
a799883d
PP
613 filename = filename_buf;
614 }
059ec3d9 615
b5aea5e1 616/* Open the cache file for reading and if successful, read it and set up the
575643cd 617parameters. */
059ec3d9 618
f5d25c2b 619if ((fd = Uopen(filename, O_RDONLY, 0)) >= 0)
059ec3d9 620 {
b5aea5e1 621 struct stat statbuf;
17c76198
PP
622 FILE *fp;
623 int saved_errno;
624
625 if (fstat(fd, &statbuf) < 0) /* EIO */
626 {
627 saved_errno = errno;
628 (void)close(fd);
452a164f 629 return tls_error_sys(US"TLS cache stat failed", saved_errno, NULL, errstr);
17c76198
PP
630 }
631 if (!S_ISREG(statbuf.st_mode))
b5aea5e1
PH
632 {
633 (void)close(fd);
cf0c6164 634 return tls_error(US"TLS cache not a file", NULL, NULL, errstr);
17c76198 635 }
40c90bca 636 if (!(fp = fdopen(fd, "rb")))
17c76198
PP
637 {
638 saved_errno = errno;
639 (void)close(fd);
452a164f
JH
640 return tls_error_sys(US"fdopen(TLS cache stat fd) failed",
641 saved_errno, NULL, errstr);
b5aea5e1 642 }
059ec3d9 643
b5aea5e1 644 m.size = statbuf.st_size;
40c90bca 645 if (!(m.data = malloc(m.size)))
17c76198
PP
646 {
647 fclose(fp);
452a164f 648 return tls_error_sys(US"malloc failed", errno, NULL, errstr);
17c76198 649 }
40c90bca 650 if (!(sz = fread(m.data, m.size, 1, fp)))
17c76198
PP
651 {
652 saved_errno = errno;
653 fclose(fp);
654 free(m.data);
452a164f 655 return tls_error_sys(US"fread failed", saved_errno, NULL, errstr);
17c76198
PP
656 }
657 fclose(fp);
b5aea5e1 658
17c76198 659 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
b5aea5e1 660 free(m.data);
452a164f
JH
661 if (rc)
662 return tls_error_gnu(US"gnutls_dh_params_import_pkcs3", rc, host, errstr);
17c76198 663 DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
b5aea5e1
PH
664 }
665
666/* If the file does not exist, fall through to compute new data and cache it.
667If there was any other opening error, it is serious. */
668
182ad5cf
PH
669else if (errno == ENOENT)
670 {
17c76198 671 rc = -1;
182ad5cf 672 DEBUG(D_tls)
17c76198 673 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
182ad5cf
PH
674 }
675else
17c76198 676 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
cf0c6164 677 NULL, NULL, errstr);
b5aea5e1
PH
678
679/* If ret < 0, either the cache file does not exist, or the data it contains
680is not useful. One particular case of this is when upgrading from an older
681release of Exim in which the data was stored in a different format. We don't
682try to be clever and support both formats; we just regenerate new data in this
683case. */
684
17c76198 685if (rc < 0)
b5aea5e1 686 {
17c76198 687 uschar *temp_fn;
201f5254 688 unsigned int dh_bits_gen = dh_bits;
059ec3d9 689
17c76198
PP
690 if ((PATH_MAX - Ustrlen(filename)) < 10)
691 return tls_error(US"Filename too long to generate replacement",
48224640 692 filename, NULL, errstr);
059ec3d9 693
48224640 694 temp_fn = string_copy(US"%s.XXXXXXX");
f5d25c2b 695 if ((fd = mkstemp(CS temp_fn)) < 0) /* modifies temp_fn */
452a164f 696 return tls_error_sys(US"Unable to open temp file", errno, NULL, errstr);
b66fecb4 697 (void)exim_chown(temp_fn, exim_uid, exim_gid); /* Probably not necessary */
059ec3d9 698
201f5254
PP
699 /* GnuTLS overshoots!
700 * If we ask for 2236, we might get 2237 or more.
701 * But there's no way to ask GnuTLS how many bits there really are.
702 * We can ask how many bits were used in a TLS session, but that's it!
703 * The prime itself is hidden behind too much abstraction.
704 * So we ask for less, and proceed on a wing and a prayer.
705 * First attempt, subtracted 3 for 2233 and got 2240.
706 */
cae6e576 707 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
201f5254
PP
708 {
709 dh_bits_gen = dh_bits - 10;
710 DEBUG(D_tls)
711 debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
712 dh_bits_gen);
713 }
714
715 DEBUG(D_tls)
716 debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
717 dh_bits_gen);
452a164f
JH
718 if ((rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen)))
719 return tls_error_gnu(US"gnutls_dh_params_generate2", rc, host, errstr);
17c76198
PP
720
721 /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
722 and I confirmed that a NULL call to get the size first is how the GnuTLS
723 sample apps handle this. */
724
725 sz = 0;
726 m.data = NULL;
452a164f
JH
727 if ( (rc = gnutls_dh_params_export_pkcs3(dh_server_params,
728 GNUTLS_X509_FMT_PEM, m.data, &sz))
729 && rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
730 return tls_error_gnu(US"gnutls_dh_params_export_pkcs3(NULL) sizing",
731 rc, host, errstr);
17c76198 732 m.size = sz;
40c90bca 733 if (!(m.data = malloc(m.size)))
452a164f 734 return tls_error_sys(US"memory allocation failed", errno, NULL, errstr);
40c90bca 735
1f00591e 736 /* this will return a size 1 less than the allocation size above */
452a164f
JH
737 if ((rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
738 m.data, &sz)))
17c76198
PP
739 {
740 free(m.data);
452a164f 741 return tls_error_gnu(US"gnutls_dh_params_export_pkcs3() real", rc, host, errstr);
17c76198 742 }
1f00591e 743 m.size = sz; /* shrink by 1, probably */
059ec3d9 744
f5d25c2b 745 if ((sz = write_to_fd_buf(fd, m.data, (size_t) m.size)) != m.size)
17c76198
PP
746 {
747 free(m.data);
452a164f
JH
748 return tls_error_sys(US"TLS cache write D-H params failed",
749 errno, NULL, errstr);
17c76198 750 }
b5aea5e1 751 free(m.data);
f5d25c2b 752 if ((sz = write_to_fd_buf(fd, US"\n", 1)) != 1)
452a164f
JH
753 return tls_error_sys(US"TLS cache write D-H params final newline failed",
754 errno, NULL, errstr);
17c76198 755
f5d25c2b 756 if ((rc = close(fd)))
452a164f 757 return tls_error_sys(US"TLS cache write close() failed", errno, NULL, errstr);
059ec3d9 758
17c76198 759 if (Urename(temp_fn, filename) < 0)
452a164f
JH
760 return tls_error_sys(string_sprintf("failed to rename \"%s\" as \"%s\"",
761 temp_fn, filename), errno, NULL, errstr);
059ec3d9 762
17c76198 763 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
059ec3d9
PH
764 }
765
17c76198 766DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
059ec3d9
PH
767return OK;
768}
769
770
771
772
23bb6982
JH
773/* Create and install a selfsigned certificate, for use in server mode */
774
775static int
cf0c6164 776tls_install_selfsign(exim_gnutls_state_st * state, uschar ** errstr)
23bb6982
JH
777{
778gnutls_x509_crt_t cert = NULL;
779time_t now;
780gnutls_x509_privkey_t pkey = NULL;
781const uschar * where;
782int rc;
783
784where = US"initialising pkey";
785if ((rc = gnutls_x509_privkey_init(&pkey))) goto err;
786
787where = US"initialising cert";
788if ((rc = gnutls_x509_crt_init(&cert))) goto err;
789
790where = US"generating pkey";
791if ((rc = gnutls_x509_privkey_generate(pkey, GNUTLS_PK_RSA,
76075bb5 792#ifdef SUPPORT_PARAM_TO_PK_BITS
4312da48
JH
793# ifndef GNUTLS_SEC_PARAM_MEDIUM
794# define GNUTLS_SEC_PARAM_MEDIUM GNUTLS_SEC_PARAM_HIGH
795# endif
6aac3239 796 gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_MEDIUM),
76075bb5 797#else
6aac3239 798 2048,
76075bb5
JH
799#endif
800 0)))
23bb6982
JH
801 goto err;
802
803where = US"configuring cert";
1613fd68 804now = 1;
23bb6982
JH
805if ( (rc = gnutls_x509_crt_set_version(cert, 3))
806 || (rc = gnutls_x509_crt_set_serial(cert, &now, sizeof(now)))
807 || (rc = gnutls_x509_crt_set_activation_time(cert, now = time(NULL)))
808 || (rc = gnutls_x509_crt_set_expiration_time(cert, now + 60 * 60)) /* 1 hr */
809 || (rc = gnutls_x509_crt_set_key(cert, pkey))
810
811 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
812 GNUTLS_OID_X520_COUNTRY_NAME, 0, "UK", 2))
813 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
814 GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "Exim Developers", 15))
815 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
816 GNUTLS_OID_X520_COMMON_NAME, 0,
817 smtp_active_hostname, Ustrlen(smtp_active_hostname)))
818 )
819 goto err;
820
821where = US"signing cert";
822if ((rc = gnutls_x509_crt_sign(cert, cert, pkey))) goto err;
823
824where = US"installing selfsign cert";
825 /* Since: 2.4.0 */
826if ((rc = gnutls_certificate_set_x509_key(state->x509_cred, &cert, 1, pkey)))
827 goto err;
828
829rc = OK;
830
831out:
832 if (cert) gnutls_x509_crt_deinit(cert);
833 if (pkey) gnutls_x509_privkey_deinit(pkey);
834 return rc;
835
836err:
452a164f 837 rc = tls_error_gnu(where, rc, NULL, errstr);
23bb6982
JH
838 goto out;
839}
840
841
842
843
47195144
JH
844/* Add certificate and key, from files.
845
846Return:
847 Zero or negative: good. Negate value for certificate index if < 0.
848 Greater than zero: FAIL or DEFER code.
849*/
850
ba86e143
JH
851static int
852tls_add_certfile(exim_gnutls_state_st * state, const host_item * host,
853 uschar * certfile, uschar * keyfile, uschar ** errstr)
854{
855int rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
856 CS certfile, CS keyfile, GNUTLS_X509_FMT_PEM);
47195144 857if (rc < 0)
452a164f 858 return tls_error_gnu(
47195144 859 string_sprintf("cert/key setup: cert=%s key=%s", certfile, keyfile),
452a164f 860 rc, host, errstr);
47195144 861return -rc;
ba86e143
JH
862}
863
864
059ec3d9 865/*************************************************
17c76198 866* Variables re-expanded post-SNI *
059ec3d9
PH
867*************************************************/
868
17c76198
PP
869/* Called from both server and client code, via tls_init(), and also from
870the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
871
872We can tell the two apart by state->received_sni being non-NULL in callback.
873
874The callback should not call us unless state->trigger_sni_changes is true,
875which we are responsible for setting on the first pass through.
059ec3d9
PH
876
877Arguments:
17c76198 878 state exim_gnutls_state_st *
cf0c6164 879 errstr error string pointer
059ec3d9
PH
880
881Returns: OK/DEFER/FAIL
882*/
883
884static int
ba86e143 885tls_expand_session_files(exim_gnutls_state_st * state, uschar ** errstr)
059ec3d9 886{
1365611d 887struct stat statbuf;
059ec3d9 888int rc;
17c76198
PP
889const host_item *host = state->host; /* macro should be reconsidered? */
890uschar *saved_tls_certificate = NULL;
891uschar *saved_tls_privatekey = NULL;
892uschar *saved_tls_verify_certificates = NULL;
893uschar *saved_tls_crl = NULL;
894int cert_count;
895
896/* We check for tls_sni *before* expansion. */
2b4a568d 897if (!host) /* server */
17c76198
PP
898 if (!state->received_sni)
899 {
ba86e143
JH
900 if ( state->tls_certificate
901 && ( Ustrstr(state->tls_certificate, US"tls_sni")
902 || Ustrstr(state->tls_certificate, US"tls_in_sni")
903 || Ustrstr(state->tls_certificate, US"tls_out_sni")
904 ) )
17c76198
PP
905 {
906 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
907 state->trigger_sni_changes = TRUE;
908 }
909 }
910 else
911 {
1365611d 912 /* useful for debugging */
17c76198
PP
913 saved_tls_certificate = state->exp_tls_certificate;
914 saved_tls_privatekey = state->exp_tls_privatekey;
915 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
916 saved_tls_crl = state->exp_tls_crl;
917 }
059ec3d9 918
452a164f
JH
919if ((rc = gnutls_certificate_allocate_credentials(&state->x509_cred)))
920 return tls_error_gnu(US"gnutls_certificate_allocate_credentials",
921 rc, host, errstr);
47195144
JH
922
923#ifdef SUPPORT_SRV_OCSP_STACK
924gnutls_certificate_set_flags(state->x509_cred, GNUTLS_CERTIFICATE_API_V2);
925#endif
1365611d 926
17c76198
PP
927/* remember: expand_check_tlsvar() is expand_check() but fiddling with
928state members, assuming consistent naming; and expand_check() returns
929false if expansion failed, unless expansion was forced to fail. */
059ec3d9 930
17c76198
PP
931/* check if we at least have a certificate, before doing expensive
932D-H generation. */
059ec3d9 933
cf0c6164 934if (!expand_check_tlsvar(tls_certificate, errstr))
17c76198 935 return DEFER;
059ec3d9 936
17c76198 937/* certificate is mandatory in server, optional in client */
059ec3d9 938
23bb6982
JH
939if ( !state->exp_tls_certificate
940 || !*state->exp_tls_certificate
941 )
2b4a568d 942 if (!host)
cf0c6164 943 return tls_install_selfsign(state, errstr);
17c76198
PP
944 else
945 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
059ec3d9 946
cf0c6164 947if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey, errstr))
059ec3d9
PH
948 return DEFER;
949
17c76198
PP
950/* tls_privatekey is optional, defaulting to same file as certificate */
951
952if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
059ec3d9 953 {
17c76198
PP
954 state->tls_privatekey = state->tls_certificate;
955 state->exp_tls_privatekey = state->exp_tls_certificate;
059ec3d9 956 }
c91535f3 957
059ec3d9 958
17c76198 959if (state->exp_tls_certificate && *state->exp_tls_certificate)
059ec3d9
PH
960 {
961 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
17c76198
PP
962 state->exp_tls_certificate, state->exp_tls_privatekey);
963
964 if (state->received_sni)
23bb6982
JH
965 if ( Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0
966 && Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0
967 )
17c76198 968 {
b34fc30c 969 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
17c76198
PP
970 }
971 else
972 {
b34fc30c 973 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
17c76198 974 }
059ec3d9 975
ba86e143
JH
976 if (!host) /* server */
977 {
978 const uschar * clist = state->exp_tls_certificate;
979 const uschar * klist = state->exp_tls_privatekey;
47195144
JH
980 const uschar * olist;
981 int csep = 0, ksep = 0, osep = 0, cnt = 0;
982 uschar * cfile, * kfile, * ofile;
983
984#ifndef DISABLE_OCSP
985 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file", &ofile, errstr))
986 return DEFER;
987 olist = ofile;
988#endif
ba86e143
JH
989
990 while (cfile = string_nextinlist(&clist, &csep, NULL, 0))
47195144 991
ba86e143
JH
992 if (!(kfile = string_nextinlist(&klist, &ksep, NULL, 0)))
993 return tls_error(US"cert/key setup: out of keys", NULL, host, errstr);
47195144 994 else if (0 < (rc = tls_add_certfile(state, host, cfile, kfile, errstr)))
ba86e143
JH
995 return rc;
996 else
47195144
JH
997 {
998 int gnutls_cert_index = -rc;
ba86e143 999 DEBUG(D_tls) debug_printf("TLS: cert/key %s registered\n", cfile);
47195144
JH
1000
1001 /* Set the OCSP stapling server info */
1002
1003#ifndef DISABLE_OCSP
1004 if (tls_ocsp_file)
1005 if (gnutls_buggy_ocsp)
1006 {
1007 DEBUG(D_tls)
1008 debug_printf("GnuTLS library is buggy for OCSP; avoiding\n");
1009 }
1010 else if ((ofile = string_nextinlist(&olist, &osep, NULL, 0)))
1011 {
1012 /* Use the full callback method for stapling just to get
1013 observability. More efficient would be to read the file once only,
1014 if it never changed (due to SNI). Would need restart on file update,
1015 or watch datestamp. */
1016
1017# ifdef SUPPORT_SRV_OCSP_STACK
452a164f
JH
1018 if ((rc = gnutls_certificate_set_ocsp_status_request_function2(
1019 state->x509_cred, gnutls_cert_index,
1020 server_ocsp_stapling_cb, ofile)))
1021 return tls_error_gnu(
1022 US"gnutls_certificate_set_ocsp_status_request_function2",
1023 rc, host, errstr);
47195144
JH
1024# else
1025 if (cnt++ > 0)
1026 {
1027 DEBUG(D_tls)
1028 debug_printf("oops; multiple OCSP files not supported\n");
1029 break;
1030 }
1031 gnutls_certificate_set_ocsp_status_request_function(
1032 state->x509_cred, server_ocsp_stapling_cb, ofile);
1033# endif
1034
1035 DEBUG(D_tls) debug_printf("OCSP response file = %s\n", ofile);
1036 }
1037 else
1038 DEBUG(D_tls) debug_printf("ran out of OCSP response files in list\n");
1039#endif
1040 }
ba86e143
JH
1041 }
1042 else
1043 {
47195144 1044 if (0 < (rc = tls_add_certfile(state, host,
ba86e143
JH
1045 state->exp_tls_certificate, state->exp_tls_privatekey, errstr)))
1046 return rc;
1047 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
1048 }
1049
b34fc30c 1050 } /* tls_certificate */
059ec3d9 1051
2b4a568d 1052
059ec3d9
PH
1053/* Set the trusted CAs file if one is provided, and then add the CRL if one is
1054provided. Experiment shows that, if the certificate file is empty, an unhelpful
1055error message is provided. However, if we just refrain from setting anything up
1056in that case, certificate verification fails, which seems to be the correct
1057behaviour. */
1058
610ff438 1059if (state->tls_verify_certificates && *state->tls_verify_certificates)
059ec3d9 1060 {
cf0c6164 1061 if (!expand_check_tlsvar(tls_verify_certificates, errstr))
059ec3d9 1062 return DEFER;
610ff438
JH
1063#ifndef SUPPORT_SYSDEFAULT_CABUNDLE
1064 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1065 state->exp_tls_verify_certificates = NULL;
1066#endif
17c76198 1067 if (state->tls_crl && *state->tls_crl)
cf0c6164 1068 if (!expand_check_tlsvar(tls_crl, errstr))
17c76198 1069 return DEFER;
059ec3d9 1070
1365611d
PP
1071 if (!(state->exp_tls_verify_certificates &&
1072 *state->exp_tls_verify_certificates))
b34fc30c
PP
1073 {
1074 DEBUG(D_tls)
1365611d
PP
1075 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
1076 /* With no tls_verify_certificates, we ignore tls_crl too */
17c76198 1077 return OK;
b34fc30c 1078 }
1365611d 1079 }
83e2f8a2
PP
1080else
1081 {
1082 DEBUG(D_tls)
1083 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
1084 return OK;
1085 }
17c76198 1086
cb1d7830
JH
1087#ifdef SUPPORT_SYSDEFAULT_CABUNDLE
1088if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1089 cert_count = gnutls_certificate_set_x509_system_trust(state->x509_cred);
1090else
1091#endif
1365611d 1092 {
cb1d7830
JH
1093 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
1094 {
1095 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
1096 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
1097 strerror(errno));
1098 return DEFER;
1099 }
17c76198 1100
a7fec7a7 1101#ifndef SUPPORT_CA_DIR
cb1d7830
JH
1102 /* The test suite passes in /dev/null; we could check for that path explicitly,
1103 but who knows if someone has some weird FIFO which always dumps some certs, or
1104 other weirdness. The thing we really want to check is that it's not a
1105 directory, since while OpenSSL supports that, GnuTLS does not.
60f914bc 1106 So s/!S_ISREG/S_ISDIR/ and change some messaging ... */
cb1d7830
JH
1107 if (S_ISDIR(statbuf.st_mode))
1108 {
1109 DEBUG(D_tls)
1110 debug_printf("verify certificates path is a dir: \"%s\"\n",
1111 state->exp_tls_verify_certificates);
1112 log_write(0, LOG_MAIN|LOG_PANIC,
1113 "tls_verify_certificates \"%s\" is a directory",
1114 state->exp_tls_verify_certificates);
1115 return DEFER;
1116 }
a7fec7a7 1117#endif
059ec3d9 1118
cb1d7830
JH
1119 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
1120 state->exp_tls_verify_certificates, statbuf.st_size);
059ec3d9 1121
cb1d7830
JH
1122 if (statbuf.st_size == 0)
1123 {
1124 DEBUG(D_tls)
1125 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
1126 return OK;
1127 }
059ec3d9 1128
cb1d7830 1129 cert_count =
a7fec7a7
JH
1130
1131#ifdef SUPPORT_CA_DIR
cb1d7830
JH
1132 (statbuf.st_mode & S_IFMT) == S_IFDIR
1133 ?
1134 gnutls_certificate_set_x509_trust_dir(state->x509_cred,
1135 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM)
1136 :
a7fec7a7 1137#endif
cb1d7830
JH
1138 gnutls_certificate_set_x509_trust_file(state->x509_cred,
1139 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
1140 }
a7fec7a7 1141
1365611d 1142if (cert_count < 0)
452a164f
JH
1143 return tls_error_gnu(US"setting certificate trust", cert_count, host, errstr);
1144DEBUG(D_tls)
1145 debug_printf("Added %d certificate authorities.\n", cert_count);
059ec3d9 1146
5c8cda3a
PP
1147if (state->tls_crl && *state->tls_crl &&
1148 state->exp_tls_crl && *state->exp_tls_crl)
1365611d 1149 {
5c8cda3a 1150 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
452a164f
JH
1151 if ((cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
1152 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM)) < 0)
1153 return tls_error_gnu(US"gnutls_certificate_set_x509_crl_file",
1154 cert_count, host, errstr);
1155
5c8cda3a 1156 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
1365611d 1157 }
059ec3d9 1158
059ec3d9
PH
1159return OK;
1160}
1161
1162
1163
1164
1365611d
PP
1165/*************************************************
1166* Set X.509 state variables *
1167*************************************************/
1168
1169/* In GnuTLS, the registered cert/key are not replaced by a later
1170set of a cert/key, so for SNI support we need a whole new x509_cred
1171structure. Which means various other non-re-expanded pieces of state
1172need to be re-set in the new struct, so the setting logic is pulled
1173out to this.
1174
1175Arguments:
1176 state exim_gnutls_state_st *
cf0c6164 1177 errstr error string pointer
1365611d
PP
1178
1179Returns: OK/DEFER/FAIL
1180*/
1181
1182static int
cf0c6164 1183tls_set_remaining_x509(exim_gnutls_state_st *state, uschar ** errstr)
1365611d
PP
1184{
1185int rc;
1186const host_item *host = state->host; /* macro should be reconsidered? */
1187
1188/* Create D-H parameters, or read them from the cache file. This function does
1189its own SMTP error messaging. This only happens for the server, TLS D-H ignores
1190client-side params. */
1191
1192if (!state->host)
1193 {
1194 if (!dh_server_params)
452a164f 1195 if ((rc = init_server_dh(errstr)) != OK) return rc;
1365611d
PP
1196 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
1197 }
1198
1199/* Link the credentials to the session. */
1200
452a164f
JH
1201if ((rc = gnutls_credentials_set(state->session,
1202 GNUTLS_CRD_CERTIFICATE, state->x509_cred)))
1203 return tls_error_gnu(US"gnutls_credentials_set", rc, host, errstr);
1365611d
PP
1204
1205return OK;
1206}
1207
059ec3d9 1208/*************************************************
17c76198 1209* Initialize for GnuTLS *
059ec3d9
PH
1210*************************************************/
1211
9196d5bf 1212
4fb7df6d
JH
1213#ifndef DISABLE_OCSP
1214
9196d5bf
JH
1215static BOOL
1216tls_is_buggy_ocsp(void)
1217{
1218const uschar * s;
1219uschar maj, mid, mic;
1220
1221s = CUS gnutls_check_version(NULL);
1222maj = atoi(CCS s);
1223if (maj == 3)
1224 {
1225 while (*s && *s != '.') s++;
1226 mid = atoi(CCS ++s);
1227 if (mid <= 2)
1228 return TRUE;
1229 else if (mid >= 5)
1230 return FALSE;
1231 else
1232 {
1233 while (*s && *s != '.') s++;
1234 mic = atoi(CCS ++s);
1235 return mic <= (mid == 3 ? 16 : 3);
1236 }
1237 }
1238return FALSE;
1239}
1240
4fb7df6d 1241#endif
9196d5bf
JH
1242
1243
17c76198
PP
1244/* Called from both server and client code. In the case of a server, errors
1245before actual TLS negotiation return DEFER.
059ec3d9
PH
1246
1247Arguments:
17c76198
PP
1248 host connected host, if client; NULL if server
1249 certificate certificate file
1250 privatekey private key file
1251 sni TLS SNI to send, sometimes when client; else NULL
1252 cas CA certs file
1253 crl CRL file
1254 require_ciphers tls_require_ciphers setting
817d9f57 1255 caller_state returned state-info structure
cf0c6164 1256 errstr error string pointer
059ec3d9 1257
17c76198 1258Returns: OK/DEFER/FAIL
059ec3d9
PH
1259*/
1260
17c76198
PP
1261static int
1262tls_init(
1263 const host_item *host,
1264 const uschar *certificate,
1265 const uschar *privatekey,
1266 const uschar *sni,
1267 const uschar *cas,
1268 const uschar *crl,
1269 const uschar *require_ciphers,
cf0c6164 1270 exim_gnutls_state_st **caller_state,
74f1a423 1271 tls_support * tlsp,
cf0c6164 1272 uschar ** errstr)
059ec3d9 1273{
00c0dd4e 1274exim_gnutls_state_st * state;
17c76198
PP
1275int rc;
1276size_t sz;
00c0dd4e
JH
1277const char * errpos;
1278const uschar * p;
17c76198
PP
1279
1280if (!exim_gnutls_base_init_done)
059ec3d9 1281 {
17c76198
PP
1282 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1283
a5f239e4
PP
1284#ifdef HAVE_GNUTLS_PKCS11
1285 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1286 which loads modules from a config file, which sounds good and may be wanted
1287 by some sysadmin, but also means in common configurations that GNOME keyring
1288 environment variables are used and so breaks for users calling mailq.
1289 To prevent this, we init PKCS11 first, which is the documented approach. */
2519e60d 1290 if (!gnutls_allow_auto_pkcs11)
452a164f
JH
1291 if ((rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL)))
1292 return tls_error_gnu(US"gnutls_pkcs11_init", rc, host, errstr);
a5f239e4
PP
1293#endif
1294
452a164f
JH
1295 if ((rc = gnutls_global_init()))
1296 return tls_error_gnu(US"gnutls_global_init", rc, host, errstr);
17c76198
PP
1297
1298#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1299 DEBUG(D_tls)
059ec3d9 1300 {
17c76198 1301 gnutls_global_set_log_function(exim_gnutls_logger_cb);
aded2255 1302 /* arbitrarily chosen level; bump up to 9 for more */
17c76198 1303 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
059ec3d9 1304 }
17c76198
PP
1305#endif
1306
4fb7df6d
JH
1307#ifndef DISABLE_OCSP
1308 if (tls_ocsp_file && (gnutls_buggy_ocsp = tls_is_buggy_ocsp()))
9196d5bf 1309 log_write(0, LOG_MAIN, "OCSP unusable with this GnuTLS library version");
4fb7df6d 1310#endif
9196d5bf 1311
17c76198 1312 exim_gnutls_base_init_done = TRUE;
059ec3d9 1313 }
059ec3d9 1314
17c76198
PP
1315if (host)
1316 {
74f1a423
JH
1317 /* For client-side sessions we allocate a context. This lets us run
1318 several in parallel. */
1319 int old_pool = store_pool;
1320 store_pool = POOL_PERM;
1321 state = store_get(sizeof(exim_gnutls_state_st));
1322 store_pool = old_pool;
1323
17c76198 1324 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
74f1a423 1325 state->tlsp = tlsp;
17c76198
PP
1326 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1327 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1328 }
1329else
1330 {
1331 state = &state_server;
1332 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
74f1a423 1333 state->tlsp = tlsp;
17c76198
PP
1334 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1335 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1336 }
452a164f
JH
1337if (rc)
1338 return tls_error_gnu(US"gnutls_init", rc, host, errstr);
059ec3d9 1339
17c76198 1340state->host = host;
059ec3d9 1341
17c76198
PP
1342state->tls_certificate = certificate;
1343state->tls_privatekey = privatekey;
5779e6aa 1344state->tls_require_ciphers = require_ciphers;
17c76198
PP
1345state->tls_sni = sni;
1346state->tls_verify_certificates = cas;
1347state->tls_crl = crl;
059ec3d9 1348
17c76198
PP
1349/* This handles the variables that might get re-expanded after TLS SNI;
1350that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
059ec3d9 1351
17c76198
PP
1352DEBUG(D_tls)
1353 debug_printf("Expanding various TLS configuration options for session credentials.\n");
cf0c6164 1354if ((rc = tls_expand_session_files(state, errstr)) != OK) return rc;
059ec3d9 1355
1365611d
PP
1356/* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1357requires a new structure afterwards. */
83da1223 1358
cf0c6164 1359if ((rc = tls_set_remaining_x509(state, errstr)) != OK) return rc;
83da1223 1360
17c76198
PP
1361/* set SNI in client, only */
1362if (host)
1363 {
cf0c6164 1364 if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni, errstr))
17c76198 1365 return DEFER;
0df4ab80 1366 if (state->tlsp->sni && *state->tlsp->sni)
17c76198
PP
1367 {
1368 DEBUG(D_tls)
0df4ab80
JH
1369 debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1370 sz = Ustrlen(state->tlsp->sni);
452a164f
JH
1371 if ((rc = gnutls_server_name_set(state->session,
1372 GNUTLS_NAME_DNS, state->tlsp->sni, sz)))
1373 return tls_error_gnu(US"gnutls_server_name_set", rc, host, errstr);
17c76198
PP
1374 }
1375 }
1376else if (state->tls_sni)
1377 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
ba86e143 1378 "have an SNI set for a server [%s]\n", state->tls_sni);
83da1223 1379
17c76198 1380/* This is the priority string support,
42bfef1e 1381http://www.gnutls.org/manual/html_node/Priority-Strings.html
17c76198
PP
1382and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1383This was backwards incompatible, but means Exim no longer needs to track
1384all algorithms and provide string forms for them. */
83da1223 1385
fc243e94 1386p = NULL;
17c76198 1387if (state->tls_require_ciphers && *state->tls_require_ciphers)
83da1223 1388 {
cf0c6164 1389 if (!expand_check_tlsvar(tls_require_ciphers, errstr))
17c76198
PP
1390 return DEFER;
1391 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
83da1223 1392 {
17c76198 1393 p = state->exp_tls_require_ciphers;
fc243e94 1394 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n", p);
83da1223
PH
1395 }
1396 }
fc243e94 1397if (!p)
17c76198 1398 {
fc243e94 1399 p = exim_default_gnutls_priority;
83e2f8a2 1400 DEBUG(D_tls)
fc243e94 1401 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n", p);
17c76198 1402 }
83da1223 1403
452a164f
JH
1404if ((rc = gnutls_priority_init(&state->priority_cache, CCS p, &errpos)))
1405 return tls_error_gnu(string_sprintf(
1406 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1407 p, errpos - CS p, errpos),
1408 rc, host, errstr);
17c76198 1409
452a164f
JH
1410if ((rc = gnutls_priority_set(state->session, state->priority_cache)))
1411 return tls_error_gnu(US"gnutls_priority_set", rc, host, errstr);
17c76198 1412
b10c87b3
JH
1413/* This also sets the server ticket expiration time to the same, and
1414the STEK rotation time to 3x. */
1415
17c76198
PP
1416gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1417
1418/* Reduce security in favour of increased compatibility, if the admin
1419decides to make that trade-off. */
1420if (gnutls_compat_mode)
83da1223 1421 {
17c76198
PP
1422#if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1423 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1424 gnutls_session_enable_compatibility_mode(state->session);
1425#else
1426 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1427#endif
83da1223
PH
1428 }
1429
17c76198 1430*caller_state = state;
17c76198 1431return OK;
83da1223
PH
1432}
1433
1434
1435
059ec3d9 1436/*************************************************
17c76198 1437* Extract peer information *
059ec3d9
PH
1438*************************************************/
1439
f1be21cf
JH
1440static const uschar *
1441cipher_stdname_kcm(gnutls_kx_algorithm_t kx, gnutls_cipher_algorithm_t cipher,
1442 gnutls_mac_algorithm_t mac)
1443{
1444uschar cs_id[2];
1445gnutls_kx_algorithm_t kx_i;
1446gnutls_cipher_algorithm_t cipher_i;
1447gnutls_mac_algorithm_t mac_i;
1448
1449for (size_t i = 0;
1450 gnutls_cipher_suite_info(i, cs_id, &kx_i, &cipher_i, &mac_i, NULL);
1451 i++)
1452 if (kx_i == kx && cipher_i == cipher && mac_i == mac)
1453 return cipher_stdname(cs_id[0], cs_id[1]);
1454return NULL;
1455}
1456
1457
1458
17c76198 1459/* Called from both server and client code.
4fe99a6c
PP
1460Only this is allowed to set state->peerdn and state->have_set_peerdn
1461and we use that to detect double-calls.
059ec3d9 1462
75fe387d
PP
1463NOTE: the state blocks last while the TLS connection is up, which is fine
1464for logging in the server side, but for the client side, we log after teardown
1465in src/deliver.c. While the session is up, we can twist about states and
1466repoint tls_* globals, but those variables used for logging or other variable
1467expansion that happens _after_ delivery need to have a longer life-time.
1468
1469So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1470doing this more than once per generation of a state context. We set them in
1471the state context, and repoint tls_* to them. After the state goes away, the
1472tls_* copies of the pointers remain valid and client delivery logging is happy.
1473
1474tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1475don't apply.
1476
059ec3d9 1477Arguments:
17c76198 1478 state exim_gnutls_state_st *
cf0c6164 1479 errstr pointer to error string
059ec3d9 1480
17c76198 1481Returns: OK/DEFER/FAIL
059ec3d9
PH
1482*/
1483
17c76198 1484static int
b10c87b3 1485peer_status(exim_gnutls_state_st * state, uschar ** errstr)
059ec3d9 1486{
b10c87b3
JH
1487gnutls_session_t session = state->session;
1488const gnutls_datum_t * cert_list;
75fe387d 1489int old_pool, rc;
17c76198 1490unsigned int cert_list_size = 0;
4fe99a6c
PP
1491gnutls_protocol_t protocol;
1492gnutls_cipher_algorithm_t cipher;
1493gnutls_kx_algorithm_t kx;
1494gnutls_mac_algorithm_t mac;
17c76198
PP
1495gnutls_certificate_type_t ct;
1496gnutls_x509_crt_t crt;
b10c87b3 1497uschar * dn_buf;
17c76198 1498size_t sz;
059ec3d9 1499
4fe99a6c 1500if (state->have_set_peerdn)
17c76198 1501 return OK;
4fe99a6c 1502state->have_set_peerdn = TRUE;
059ec3d9 1503
4fe99a6c 1504state->peerdn = NULL;
059ec3d9 1505
4fe99a6c 1506/* tls_cipher */
b10c87b3
JH
1507cipher = gnutls_cipher_get(session);
1508protocol = gnutls_protocol_get_version(session);
1509mac = gnutls_mac_get(session);
b9c6f63c
JH
1510kx =
1511#ifdef GNUTLS_TLS1_3
1512 protocol >= GNUTLS_TLS1_3 ? 0 :
1513#endif
b10c87b3 1514 gnutls_kx_get(session);
4fe99a6c 1515
75fe387d 1516old_pool = store_pool;
f1be21cf 1517 {
b10c87b3 1518 tls_support * tlsp = state->tlsp;
f1be21cf 1519 store_pool = POOL_PERM;
d9acfc1c
JH
1520
1521#ifdef SUPPORT_GNUTLS_SESS_DESC
1522 {
1523 gstring * g = NULL;
b10c87b3 1524 uschar * s = US gnutls_session_get_desc(session), c;
d9acfc1c
JH
1525
1526 /* Nikos M suggests we use this by preference. It returns like:
1527 (TLS1.3)-(ECDHE-SECP256R1)-(RSA-PSS-RSAE-SHA256)-(AES-256-GCM)
1528
1529 For partial back-compat, put a colon after the TLS version, replace the
1530 )-( grouping with __, replace in-group - with _ and append the :keysize. */
1531
1532 /* debug_printf("peer_status: gnutls_session_get_desc %s\n", s); */
1533
1534 for (s++; (c = *s) && c != ')'; s++) g = string_catn(g, s, 1);
1535 g = string_catn(g, US":", 1);
1536 if (*s) s++; /* now on _ between groups */
1537 while ((c = *s))
1538 {
1539 for (*++s && ++s; (c = *s) && c != ')'; s++) g = string_catn(g, c == '-' ? US"_" : s, 1);
1540 /* now on ) closing group */
1541 if ((c = *s) && *++s == '-') g = string_catn(g, US"__", 2);
1542 /* now on _ between groups */
1543 }
1544 g = string_catn(g, US":", 1);
1545 g = string_cat(g, string_sprintf("%d", (int) gnutls_cipher_get_key_size(cipher) * 8));
1546 state->ciphersuite = string_from_gstring(g);
1547 }
1548#else
f1be21cf
JH
1549 state->ciphersuite = string_sprintf("%s:%s:%d",
1550 gnutls_protocol_get_name(protocol),
1551 gnutls_cipher_suite_get_name(kx, cipher, mac),
1552 (int) gnutls_cipher_get_key_size(cipher) * 8);
1553
1554 /* I don't see a way that spaces could occur, in the current GnuTLS
1555 code base, but it was a concern in the old code and perhaps older GnuTLS
1556 releases did return "TLS 1.0"; play it safe, just in case. */
1557
1558 for (uschar * p = state->ciphersuite; *p; p++) if (isspace(*p)) *p = '-';
d9acfc1c
JH
1559#endif
1560
1561/* debug_printf("peer_status: ciphersuite %s\n", state->ciphersuite); */
1562
b10c87b3
JH
1563 tlsp->cipher = state->ciphersuite;
1564 tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
f1be21cf 1565
b10c87b3 1566 tlsp->cipher_stdname = cipher_stdname_kcm(kx, cipher, mac);
f1be21cf 1567 }
75fe387d 1568store_pool = old_pool;
4fe99a6c
PP
1569
1570/* tls_peerdn */
b10c87b3 1571cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
83da1223 1572
f1be21cf 1573if (!cert_list || cert_list_size == 0)
17c76198 1574 {
17c76198
PP
1575 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1576 cert_list, cert_list_size);
e51c7be2 1577 if (state->verify_requirement >= VERIFY_REQUIRED)
17c76198 1578 return tls_error(US"certificate verification failed",
48224640 1579 US"no certificate received from peer", state->host, errstr);
17c76198
PP
1580 return OK;
1581 }
059ec3d9 1582
b10c87b3 1583if ((ct = gnutls_certificate_type_get(session)) != GNUTLS_CRT_X509)
059ec3d9 1584 {
95f52235 1585 const uschar * ctn = US gnutls_certificate_type_get_name(ct);
17c76198
PP
1586 DEBUG(D_tls)
1587 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
e51c7be2 1588 if (state->verify_requirement >= VERIFY_REQUIRED)
17c76198 1589 return tls_error(US"certificate verification not possible, unhandled type",
cf0c6164 1590 ctn, state->host, errstr);
17c76198 1591 return OK;
83da1223 1592 }
059ec3d9 1593
e51c7be2
JH
1594#define exim_gnutls_peer_err(Label) \
1595 do { \
1596 if (rc != GNUTLS_E_SUCCESS) \
1597 { \
1598 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1599 (Label), gnutls_strerror(rc)); \
1600 if (state->verify_requirement >= VERIFY_REQUIRED) \
452a164f 1601 return tls_error_gnu((Label), rc, state->host, errstr); \
e51c7be2
JH
1602 return OK; \
1603 } \
1604 } while (0)
17c76198 1605
9d1c15ef
JH
1606rc = import_cert(&cert_list[0], &crt);
1607exim_gnutls_peer_err(US"cert 0");
1608
1609state->tlsp->peercert = state->peercert = crt;
17c76198 1610
17c76198
PP
1611sz = 0;
1612rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1613if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
83da1223 1614 {
17c76198
PP
1615 exim_gnutls_peer_err(US"getting size for cert DN failed");
1616 return FAIL; /* should not happen */
059ec3d9 1617 }
17c76198
PP
1618dn_buf = store_get_perm(sz);
1619rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1620exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
9d1c15ef 1621
17c76198
PP
1622state->peerdn = dn_buf;
1623
1624return OK;
1625#undef exim_gnutls_peer_err
1626}
059ec3d9 1627
059ec3d9 1628
059ec3d9 1629
059ec3d9 1630
17c76198
PP
1631/*************************************************
1632* Verify peer certificate *
1633*************************************************/
059ec3d9 1634
17c76198
PP
1635/* Called from both server and client code.
1636*Should* be using a callback registered with
1637gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1638the peer information, but that's too new for some OSes.
059ec3d9 1639
17c76198 1640Arguments:
899b8bbc
JH
1641 state exim_gnutls_state_st *
1642 errstr where to put an error message
059ec3d9 1643
17c76198
PP
1644Returns:
1645 FALSE if the session should be rejected
1646 TRUE if the cert is okay or we just don't care
1647*/
059ec3d9 1648
17c76198 1649static BOOL
28646fa9 1650verify_certificate(exim_gnutls_state_st * state, uschar ** errstr)
17c76198
PP
1651{
1652int rc;
899b8bbc
JH
1653uint verify;
1654
8008accd 1655DEBUG(D_tls) debug_printf("TLS: checking peer certificate\n");
cf0c6164 1656*errstr = NULL;
b10c87b3 1657rc = peer_status(state, errstr);
17c76198 1658
b10c87b3
JH
1659if (state->verify_requirement == VERIFY_NONE)
1660 return TRUE;
1661
1662if (rc != OK || !state->peerdn)
e6060e2c 1663 {
17c76198 1664 verify = GNUTLS_CERT_INVALID;
cf0c6164 1665 *errstr = US"certificate not supplied";
17c76198
PP
1666 }
1667else
899b8bbc
JH
1668
1669 {
1670#ifdef SUPPORT_DANE
1671 if (state->verify_requirement == VERIFY_DANE && state->host)
1672 {
1673 /* Using dane_verify_session_crt() would be easy, as it does it all for us
1674 including talking to a DNS resolver. But we want to do that bit ourselves
1675 as the testsuite intercepts and fakes its own DNS environment. */
1676
1677 dane_state_t s;
1678 dane_query_t r;
899b8bbc 1679 uint lsize;
94c13285
JH
1680 const gnutls_datum_t * certlist =
1681 gnutls_certificate_get_peers(state->session, &lsize);
1682 int usage = tls_out.tlsa_usage;
1683
1684# ifdef GNUTLS_BROKEN_DANE_VALIDATION
1685 /* Split the TLSA records into two sets, TA and EE selectors. Run the
1686 dane-verification separately so that we know which selector verified;
570cb1bd 1687 then we know whether to do name-verification (needed for TA but not EE). */
94c13285
JH
1688
1689 if (usage == ((1<<DANESSL_USAGE_DANE_TA) | (1<<DANESSL_USAGE_DANE_EE)))
bd5b3f3c 1690 { /* a mixed-usage bundle */
94c13285
JH
1691 int i, j, nrec;
1692 const char ** dd;
1693 int * ddl;
1694
1695 for(nrec = 0; state->dane_data_len[nrec]; ) nrec++;
1696 nrec++;
1697
1698 dd = store_get(nrec * sizeof(uschar *));
1699 ddl = store_get(nrec * sizeof(int));
1700 nrec--;
1701
1702 if ((rc = dane_state_init(&s, 0)))
1703 goto tlsa_prob;
1704
1705 for (usage = DANESSL_USAGE_DANE_EE;
1706 usage >= DANESSL_USAGE_DANE_TA; usage--)
1707 { /* take records with this usage */
1708 for (j = i = 0; i < nrec; i++)
1709 if (state->dane_data[i][0] == usage)
1710 {
1711 dd[j] = state->dane_data[i];
1712 ddl[j++] = state->dane_data_len[i];
1713 }
1714 if (j)
1715 {
1716 dd[j] = NULL;
1717 ddl[j] = 0;
1718
1719 if ((rc = dane_raw_tlsa(s, &r, (char * const *)dd, ddl, 1, 0)))
1720 goto tlsa_prob;
1721
1722 if ((rc = dane_verify_crt_raw(s, certlist, lsize,
1723 gnutls_certificate_type_get(state->session),
1724 r, 0,
1725 usage == DANESSL_USAGE_DANE_EE
1726 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1727 &verify)))
1728 {
1729 DEBUG(D_tls)
1730 debug_printf("TLSA record problem: %s\n", dane_strerror(rc));
1731 }
1732 else if (verify == 0) /* verification passed */
1733 {
1734 usage = 1 << usage;
1735 break;
1736 }
1737 }
1738 }
899b8bbc 1739
94c13285
JH
1740 if (rc) goto tlsa_prob;
1741 }
1742 else
1743# endif
899b8bbc 1744 {
94c13285
JH
1745 if ( (rc = dane_state_init(&s, 0))
1746 || (rc = dane_raw_tlsa(s, &r, state->dane_data, state->dane_data_len,
1747 1, 0))
1748 || (rc = dane_verify_crt_raw(s, certlist, lsize,
1749 gnutls_certificate_type_get(state->session),
5ec37a55 1750 r, 0,
94c13285
JH
1751# ifdef GNUTLS_BROKEN_DANE_VALIDATION
1752 usage == (1 << DANESSL_USAGE_DANE_EE)
1753 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1754# else
1755 0,
1756# endif
1757 &verify))
1758 )
1759 goto tlsa_prob;
899b8bbc 1760 }
94c13285
JH
1761
1762 if (verify != 0) /* verification failed */
899b8bbc
JH
1763 {
1764 gnutls_datum_t str;
1765 (void) dane_verification_status_print(verify, &str, 0);
1766 *errstr = US str.data; /* don't bother to free */
1767 goto badcert;
1768 }
28646fa9 1769
94c13285
JH
1770# ifdef GNUTLS_BROKEN_DANE_VALIDATION
1771 /* If a TA-mode TLSA record was used for verification we must additionally
570cb1bd 1772 verify the cert name (but not the CA chain). For EE-mode, skip it. */
28646fa9 1773
94c13285
JH
1774 if (usage & (1 << DANESSL_USAGE_DANE_EE))
1775# endif
28646fa9 1776 {
570cb1bd 1777 state->peer_dane_verified = state->peer_cert_verified = TRUE;
28646fa9
JH
1778 goto goodcert;
1779 }
570cb1bd
JH
1780# ifdef GNUTLS_BROKEN_DANE_VALIDATION
1781 /* Assume that the name on the A-record is the one that should be matching
1782 the cert. An alternate view is that the domain part of the email address
1783 is also permissible. */
1784
1785 if (gnutls_x509_crt_check_hostname(state->tlsp->peercert,
1786 CS state->host->name))
1787 {
1788 state->peer_dane_verified = state->peer_cert_verified = TRUE;
1789 goto goodcert;
1790 }
1791# endif
899b8bbc 1792 }
570cb1bd 1793#endif /*SUPPORT_DANE*/
899b8bbc 1794
17c76198 1795 rc = gnutls_certificate_verify_peers2(state->session, &verify);
899b8bbc 1796 }
e6060e2c 1797
899b8bbc 1798/* Handle the result of verification. INVALID is set if any others are. */
059ec3d9 1799
28646fa9 1800if (rc < 0 || verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED))
17c76198
PP
1801 {
1802 state->peer_cert_verified = FALSE;
cf0c6164 1803 if (!*errstr)
184384c3
JH
1804 {
1805#ifdef GNUTLS_CERT_VFY_STATUS_PRINT
1806 DEBUG(D_tls)
1807 {
1808 gnutls_datum_t txt;
1809
1810 if (gnutls_certificate_verification_status_print(verify,
1811 gnutls_certificate_type_get(state->session), &txt, 0)
1812 == GNUTLS_E_SUCCESS)
1813 {
1814 debug_printf("%s\n", txt.data);
1815 gnutls_free(txt.data);
1816 }
1817 }
1818#endif
cf0c6164
JH
1819 *errstr = verify & GNUTLS_CERT_REVOKED
1820 ? US"certificate revoked" : US"certificate invalid";
184384c3 1821 }
059ec3d9 1822
17c76198 1823 DEBUG(D_tls)
e51c7be2 1824 debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
cf0c6164 1825 *errstr, state->peerdn ? state->peerdn : US"<unset>");
059ec3d9 1826
e51c7be2 1827 if (state->verify_requirement >= VERIFY_REQUIRED)
899b8bbc 1828 goto badcert;
17c76198 1829 DEBUG(D_tls)
4789da3a 1830 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
17c76198 1831 }
e51c7be2 1832
17c76198
PP
1833else
1834 {
5fd28bb8
JH
1835 /* Client side, check the server's certificate name versus the name on the
1836 A-record for the connection we made. What to do for server side - what name
1837 to use for client? We document that there is no such checking for server
1838 side. */
1839
1840 if ( state->exp_tls_verify_cert_hostnames
1841 && !gnutls_x509_crt_check_hostname(state->tlsp->peercert,
1842 CS state->exp_tls_verify_cert_hostnames)
1843 )
e51c7be2 1844 {
5fd28bb8
JH
1845 DEBUG(D_tls)
1846 debug_printf("TLS certificate verification failed: cert name mismatch\n");
1847 if (state->verify_requirement >= VERIFY_REQUIRED)
1848 goto badcert;
1849 return TRUE;
e51c7be2 1850 }
5fd28bb8 1851
17c76198 1852 state->peer_cert_verified = TRUE;
e51c7be2 1853 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
4fe99a6c 1854 state->peerdn ? state->peerdn : US"<unset>");
17c76198 1855 }
059ec3d9 1856
28646fa9
JH
1857goodcert:
1858 state->tlsp->peerdn = state->peerdn;
1859 return TRUE;
899b8bbc 1860
b83314e3 1861#ifdef SUPPORT_DANE
94c13285 1862tlsa_prob:
624f33df
JH
1863 *errstr = string_sprintf("TLSA record problem: %s",
1864 rc == DANE_E_REQUESTED_DATA_NOT_AVAILABLE ? "none usable" : dane_strerror(rc));
b83314e3
JH
1865#endif
1866
899b8bbc
JH
1867badcert:
1868 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1869 return FALSE;
17c76198 1870}
059ec3d9 1871
17c76198
PP
1872
1873
1874
1875/* ------------------------------------------------------------------------ */
1876/* Callbacks */
1877
1878/* Logging function which can be registered with
1879 * gnutls_global_set_log_function()
1880 * gnutls_global_set_log_level() 0..9
1881 */
af3498d6 1882#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
059ec3d9 1883static void
17c76198 1884exim_gnutls_logger_cb(int level, const char *message)
059ec3d9 1885{
8c79eebf
PP
1886 size_t len = strlen(message);
1887 if (len < 1)
1888 {
1889 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1890 return;
1891 }
1892 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1893 message[len-1] == '\n' ? "" : "\n");
17c76198 1894}
af3498d6 1895#endif
059ec3d9 1896
059ec3d9 1897
17c76198
PP
1898/* Called after client hello, should handle SNI work.
1899This will always set tls_sni (state->received_sni) if available,
1900and may trigger presenting different certificates,
1901if state->trigger_sni_changes is TRUE.
059ec3d9 1902
17c76198
PP
1903Should be registered with
1904 gnutls_handshake_set_post_client_hello_function()
059ec3d9 1905
17c76198
PP
1906"This callback must return 0 on success or a gnutls error code to terminate the
1907handshake.".
059ec3d9 1908
17c76198
PP
1909For inability to get SNI information, we return 0.
1910We only return non-zero if re-setup failed.
817d9f57 1911Only used for server-side TLS.
17c76198 1912*/
44bbabb5 1913
17c76198
PP
1914static int
1915exim_sni_handling_cb(gnutls_session_t session)
1916{
1917char sni_name[MAX_HOST_LEN];
1918size_t data_len = MAX_HOST_LEN;
817d9f57 1919exim_gnutls_state_st *state = &state_server;
17c76198
PP
1920unsigned int sni_type;
1921int rc, old_pool;
cf0c6164 1922uschar * dummy_errstr;
17c76198
PP
1923
1924rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
b34fc30c
PP
1925if (rc != GNUTLS_E_SUCCESS)
1926 {
1927 DEBUG(D_tls) {
1928 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1929 debug_printf("TLS: no SNI presented in handshake.\n");
1930 else
1931 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1932 gnutls_strerror(rc), rc);
cf0c6164 1933 }
b34fc30c
PP
1934 return 0;
1935 }
1936
17c76198
PP
1937if (sni_type != GNUTLS_NAME_DNS)
1938 {
1939 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1940 return 0;
1941 }
44bbabb5 1942
17c76198
PP
1943/* We now have a UTF-8 string in sni_name */
1944old_pool = store_pool;
1945store_pool = POOL_PERM;
1946state->received_sni = string_copyn(US sni_name, data_len);
1947store_pool = old_pool;
1948
1949/* We set this one now so that variable expansions below will work */
817d9f57 1950state->tlsp->sni = state->received_sni;
17c76198
PP
1951
1952DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1953 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1954
1955if (!state->trigger_sni_changes)
1956 return 0;
1957
cf0c6164 1958if ((rc = tls_expand_session_files(state, &dummy_errstr)) != OK)
17c76198
PP
1959 {
1960 /* If the setup of certs/etc failed before handshake, TLS would not have
1961 been offered. The best we can do now is abort. */
1962 return GNUTLS_E_APPLICATION_ERROR_MIN;
1963 }
1964
cf0c6164 1965rc = tls_set_remaining_x509(state, &dummy_errstr);
1365611d
PP
1966if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1967
1968return 0;
059ec3d9
PH
1969}
1970
1971
1972
f2de3a33 1973#ifndef DISABLE_OCSP
44662487
JH
1974
1975static int
1976server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1977 gnutls_datum_t * ocsp_response)
1978{
1979int ret;
47195144 1980DEBUG(D_tls) debug_printf("OCSP stapling callback: %s\n", US ptr);
44662487 1981
44662487
JH
1982if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1983 {
1984 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
5903c6ff 1985 CS ptr);
018058b2 1986 tls_in.ocsp = OCSP_NOT_RESP;
44662487
JH
1987 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1988 }
1989
018058b2 1990tls_in.ocsp = OCSP_VFY_NOT_TRIED;
44662487
JH
1991return 0;
1992}
1993
1994#endif
1995
1996
0cbf2b82 1997#ifndef DISABLE_EVENT
a7538db1
JH
1998/*
1999We use this callback to get observability and detail-level control
723fe533
JH
2000for an exim TLS connection (either direction), raising a tls:cert event
2001for each cert in the chain presented by the peer. Any event
a7538db1
JH
2002can deny verification.
2003
2004Return 0 for the handshake to continue or non-zero to terminate.
2005*/
2006
2007static int
723fe533 2008verify_cb(gnutls_session_t session)
a7538db1 2009{
27f19eb4 2010const gnutls_datum_t * cert_list;
a7538db1
JH
2011unsigned int cert_list_size = 0;
2012gnutls_x509_crt_t crt;
2013int rc;
b30275b8 2014uschar * yield;
a7538db1
JH
2015exim_gnutls_state_st * state = gnutls_session_get_ptr(session);
2016
bd5b3f3c 2017if ((cert_list = gnutls_certificate_get_peers(session, &cert_list_size)))
a7538db1
JH
2018 while (cert_list_size--)
2019 {
bd5b3f3c 2020 if ((rc = import_cert(&cert_list[cert_list_size], &crt)) != GNUTLS_E_SUCCESS)
a7538db1
JH
2021 {
2022 DEBUG(D_tls) debug_printf("TLS: peer cert problem: depth %d: %s\n",
2023 cert_list_size, gnutls_strerror(rc));
2024 break;
2025 }
2026
2027 state->tlsp->peercert = crt;
b30275b8
JH
2028 if ((yield = event_raise(state->event_action,
2029 US"tls:cert", string_sprintf("%d", cert_list_size))))
a7538db1
JH
2030 {
2031 log_write(0, LOG_MAIN,
b30275b8
JH
2032 "SSL verify denied by event-action: depth=%d: %s",
2033 cert_list_size, yield);
a7538db1
JH
2034 return 1; /* reject */
2035 }
2036 state->tlsp->peercert = NULL;
2037 }
2038
2039return 0;
2040}
2041
2042#endif
44662487
JH
2043
2044
f20cfa4a
JH
2045static gstring *
2046ddump(gnutls_datum_t * d)
2047{
2048gstring * g = string_get((d->size+1) * 2);
2049uschar * s = d->data;
2050for (unsigned i = d->size; i > 0; i--, s++)
2051 {
2052 g = string_catn(g, US "0123456789abcdef" + (*s >> 4), 1);
2053 g = string_catn(g, US "0123456789abcdef" + (*s & 0xf), 1);
2054 }
2055return g;
2056}
17c76198 2057
dc6d1769
JH
2058static void
2059post_handshake_debug(exim_gnutls_state_st * state)
2060{
dc6d1769
JH
2061#ifdef SUPPORT_GNUTLS_SESS_DESC
2062debug_printf("%s\n", gnutls_session_get_desc(state->session));
2063#endif
2064#ifdef SUPPORT_GNUTLS_KEYLOG
a8af957d 2065# ifdef GNUTLS_TLS1_3
dc6d1769 2066if (gnutls_protocol_get_version(state->session) < GNUTLS_TLS1_3)
a8af957d
JH
2067#else
2068if (TRUE)
2069#endif
dc6d1769
JH
2070 {
2071 gnutls_datum_t c, s;
2072 gstring * gc, * gs;
2073 /* we only want the client random and the master secret */
2074 gnutls_session_get_random(state->session, &c, &s);
2075 gnutls_session_get_master_secret(state->session, &s);
2076 gc = ddump(&c);
2077 gs = ddump(&s);
2078 debug_printf("CLIENT_RANDOM %.*s %.*s\n", (int)gc->ptr, gc->s, (int)gs->ptr, gs->s);
2079 }
2080else
2081 debug_printf("To get keying info for TLS1.3 is hard:\n"
2082 " set environment variable SSLKEYLOGFILE to a filename writable by uid exim\n"
2083 " add SSLKEYLOGFILE to keep_environment in the exim config\n"
2084 " run exim as root\n"
2085 " if using sudo, add SSLKEYLOGFILE to env_keep in /etc/sudoers\n");
2086#endif
2087}
2088
b10c87b3
JH
2089
2090#ifdef EXPERIMENTAL_TLS_RESUME
2091static int
2092tls_server_ticket_cb(gnutls_session_t sess, u_int htype, unsigned when,
2093 unsigned incoming, const gnutls_datum_t * msg)
2094{
2095DEBUG(D_tls) debug_printf("newticket cb\n");
2096tls_in.resumption |= RESUME_CLIENT_REQUESTED;
2097return 0;
2098}
2099
2100static void
2101tls_server_resume_prehandshake(exim_gnutls_state_st * state)
2102{
2103/* Should the server offer session resumption? */
2104tls_in.resumption = RESUME_SUPPORTED;
2105if (verify_check_host(&tls_resumption_hosts) == OK)
2106 {
2107 int rc;
2108 /* GnuTLS appears to not do ticket overlap, but does emit a fresh ticket when
2109 an offered resumption is unacceptable. We lose one resumption per ticket
2110 lifetime, and sessions cannot be indefinitely re-used. There seems to be no
2111 way (3.6.7) of changing the default number of 2 TLS1.3 tickets issued, but at
2112 least they go out in a single packet. */
2113
2114 if (!(rc = gnutls_session_ticket_enable_server(state->session,
2115 &server_sessticket_key)))
2116 tls_in.resumption |= RESUME_SERVER_TICKET;
2117 else
2118 DEBUG(D_tls)
2119 debug_printf("enabling session tickets: %s\n", US gnutls_strerror(rc));
2120
2121 /* Try to tell if we see a ticket request */
2122 gnutls_handshake_set_hook_function(state->session,
2123 GNUTLS_HANDSHAKE_NEW_SESSION_TICKET, GNUTLS_HOOK_POST, tls_server_ticket_cb);
2124 }
2125}
2126
2127static void
2128tls_server_resume_posthandshake(exim_gnutls_state_st * state)
2129{
2130if (gnutls_session_resumption_requested(state->session))
2131 {
2132 /* This tells us the client sent a full ticket. We use a
2133 callback on session-ticket request, elsewhere, to tell
2134 if a client asked for a ticket. */
2135
2136 tls_in.resumption |= RESUME_CLIENT_SUGGESTED;
2137 DEBUG(D_tls) debug_printf("client requested resumption\n");
2138 }
2139if (gnutls_session_is_resumed(state->session))
2140 {
2141 tls_in.resumption |= RESUME_USED;
2142 DEBUG(D_tls) debug_printf("Session resumed\n");
2143 }
2144}
2145#endif
17c76198
PP
2146/* ------------------------------------------------------------------------ */
2147/* Exported functions */
2148
2149
2150
2151
059ec3d9
PH
2152/*************************************************
2153* Start a TLS session in a server *
2154*************************************************/
2155
2156/* This is called when Exim is running as a server, after having received
2157the STARTTLS command. It must respond to that command, and then negotiate
2158a TLS session.
2159
2160Arguments:
83da1223 2161 require_ciphers list of allowed ciphers or NULL
cf0c6164 2162 errstr pointer to error string
059ec3d9
PH
2163
2164Returns: OK on success
2165 DEFER for errors before the start of the negotiation
4c04137d 2166 FAIL for errors during the negotiation; the server can't
059ec3d9
PH
2167 continue running.
2168*/
2169
2170int
cf0c6164 2171tls_server_start(const uschar * require_ciphers, uschar ** errstr)
059ec3d9
PH
2172{
2173int rc;
cf0c6164 2174exim_gnutls_state_st * state = NULL;
059ec3d9
PH
2175
2176/* Check for previous activation */
74f1a423 2177if (tls_in.active.sock >= 0)
059ec3d9 2178 {
48224640 2179 tls_error(US"STARTTLS received after TLS started", US "", NULL, errstr);
925ac8e4 2180 smtp_printf("554 Already in TLS\r\n", FALSE);
059ec3d9
PH
2181 return FAIL;
2182 }
2183
2184/* Initialize the library. If it fails, it will already have logged the error
2185and sent an SMTP response. */
2186
17c76198 2187DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
059ec3d9 2188
cf0c6164 2189if ((rc = tls_init(NULL, tls_certificate, tls_privatekey,
17c76198 2190 NULL, tls_verify_certificates, tls_crl,
74f1a423 2191 require_ciphers, &state, &tls_in, errstr)) != OK) return rc;
059ec3d9 2192
b10c87b3
JH
2193#ifdef EXPERIMENTAL_TLS_RESUME
2194tls_server_resume_prehandshake(state);
2195#endif
2196
059ec3d9
PH
2197/* If this is a host for which certificate verification is mandatory or
2198optional, set up appropriately. */
2199
059ec3d9 2200if (verify_check_host(&tls_verify_hosts) == OK)
17c76198 2201 {
e51c7be2
JH
2202 DEBUG(D_tls)
2203 debug_printf("TLS: a client certificate will be required.\n");
17c76198
PP
2204 state->verify_requirement = VERIFY_REQUIRED;
2205 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2206 }
059ec3d9 2207else if (verify_check_host(&tls_try_verify_hosts) == OK)
17c76198 2208 {
e51c7be2
JH
2209 DEBUG(D_tls)
2210 debug_printf("TLS: a client certificate will be requested but not required.\n");
17c76198
PP
2211 state->verify_requirement = VERIFY_OPTIONAL;
2212 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2213 }
2214else
2215 {
e51c7be2
JH
2216 DEBUG(D_tls)
2217 debug_printf("TLS: a client certificate will not be requested.\n");
17c76198
PP
2218 state->verify_requirement = VERIFY_NONE;
2219 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2220 }
059ec3d9 2221
0cbf2b82 2222#ifndef DISABLE_EVENT
723fe533
JH
2223if (event_action)
2224 {
2225 state->event_action = event_action;
2226 gnutls_session_set_ptr(state->session, state);
2227 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2228 }
2229#endif
2230
17c76198
PP
2231/* Register SNI handling; always, even if not in tls_certificate, so that the
2232expansion variable $tls_sni is always available. */
059ec3d9 2233
17c76198
PP
2234gnutls_handshake_set_post_client_hello_function(state->session,
2235 exim_sni_handling_cb);
059ec3d9
PH
2236
2237/* Set context and tell client to go ahead, except in the case of TLS startup
2238on connection, where outputting anything now upsets the clients and tends to
2239make them disconnect. We need to have an explicit fflush() here, to force out
2240the response. Other smtp_printf() calls do not need it, because in non-TLS
2241mode, the fflush() happens when smtp_getc() is called. */
2242
817d9f57 2243if (!state->tlsp->on_connect)
059ec3d9 2244 {
925ac8e4 2245 smtp_printf("220 TLS go ahead\r\n", FALSE);
9d1c15ef 2246 fflush(smtp_out);
059ec3d9
PH
2247 }
2248
2249/* Now negotiate the TLS session. We put our own timer on it, since it seems
8008accd
JH
2250that the GnuTLS library doesn't.
2251From 3.1.0 there is gnutls_handshake_set_timeout() - but it requires you
2252to set (and clear down afterwards) up a pull-timeout callback function that does
2253a select, so we're no better off unless avoiding signals becomes an issue. */
059ec3d9 2254
17c76198 2255gnutls_transport_set_ptr2(state->session,
27f19eb4
JH
2256 (gnutls_transport_ptr_t)(long) fileno(smtp_in),
2257 (gnutls_transport_ptr_t)(long) fileno(smtp_out));
17c76198
PP
2258state->fd_in = fileno(smtp_in);
2259state->fd_out = fileno(smtp_out);
059ec3d9
PH
2260
2261sigalrm_seen = FALSE;
c2a1bba0 2262if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
17c76198 2263do
17c76198 2264 rc = gnutls_handshake(state->session);
157a7880 2265while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
c2a1bba0 2266ALARM_CLR(0);
059ec3d9 2267
17c76198 2268if (rc != GNUTLS_E_SUCCESS)
059ec3d9 2269 {
059ec3d9
PH
2270 /* It seems that, except in the case of a timeout, we have to close the
2271 connection right here; otherwise if the other end is running OpenSSL it hangs
2272 until the server times out. */
2273
60d10ce7 2274 if (sigalrm_seen)
ad7fc6eb 2275 {
48224640 2276 tls_error(US"gnutls_handshake", US"timed out", NULL, errstr);
ad7fc6eb
JH
2277 gnutls_db_remove_session(state->session);
2278 }
60d10ce7 2279 else
059ec3d9 2280 {
452a164f 2281 tls_error_gnu(US"gnutls_handshake", rc, NULL, errstr);
f5d25c2b 2282 (void) gnutls_alert_send_appropriate(state->session, rc);
ad7fc6eb 2283 gnutls_deinit(state->session);
ed62aae3 2284 gnutls_certificate_free_credentials(state->x509_cred);
60d10ce7 2285 millisleep(500);
ad7fc6eb 2286 shutdown(state->fd_out, SHUT_WR);
d7978c0f 2287 for (int i = 1024; fgetc(smtp_in) != EOF && i > 0; ) i--; /* drain skt */
f1e894f3
PH
2288 (void)fclose(smtp_out);
2289 (void)fclose(smtp_in);
60d10ce7 2290 smtp_out = smtp_in = NULL;
059ec3d9
PH
2291 }
2292
2293 return FAIL;
2294 }
2295
b10c87b3
JH
2296#ifdef EXPERIMENTAL_TLS_RESUME
2297tls_server_resume_posthandshake(state);
2298#endif
2299
dc6d1769 2300DEBUG(D_tls) post_handshake_debug(state);
059ec3d9 2301
17c76198
PP
2302/* Verify after the fact */
2303
899b8bbc 2304if (!verify_certificate(state, errstr))
059ec3d9 2305 {
9d1c15ef 2306 if (state->verify_requirement != VERIFY_OPTIONAL)
17c76198 2307 {
cf0c6164 2308 (void) tls_error(US"certificate verification failed", *errstr, NULL, errstr);
9d1c15ef 2309 return FAIL;
17c76198 2310 }
9d1c15ef
JH
2311 DEBUG(D_tls)
2312 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
cf0c6164 2313 *errstr);
059ec3d9
PH
2314 }
2315
17c76198
PP
2316/* Sets various Exim expansion variables; always safe within server */
2317
9d1c15ef 2318extract_exim_vars_from_tls_state(state);
059ec3d9
PH
2319
2320/* TLS has been set up. Adjust the input functions to read via TLS,
2321and initialize appropriately. */
2322
17c76198 2323state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
059ec3d9
PH
2324
2325receive_getc = tls_getc;
0d81dabc 2326receive_getbuf = tls_getbuf;
584e96c6 2327receive_get_cache = tls_get_cache;
059ec3d9
PH
2328receive_ungetc = tls_ungetc;
2329receive_feof = tls_feof;
2330receive_ferror = tls_ferror;
58eb016e 2331receive_smtp_buffered = tls_smtp_buffered;
059ec3d9 2332
059ec3d9
PH
2333return OK;
2334}
2335
2336
2337
2338
aa2a70ba
JH
2339static void
2340tls_client_setup_hostname_checks(host_item * host, exim_gnutls_state_st * state,
2341 smtp_transport_options_block * ob)
2342{
3fb3231c 2343if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
aa2a70ba 2344 {
4af0d74a 2345 state->exp_tls_verify_cert_hostnames =
8c5d388a 2346#ifdef SUPPORT_I18N
4af0d74a
JH
2347 string_domain_utf8_to_alabel(host->name, NULL);
2348#else
2349 host->name;
2350#endif
aa2a70ba
JH
2351 DEBUG(D_tls)
2352 debug_printf("TLS: server cert verification includes hostname: \"%s\".\n",
2353 state->exp_tls_verify_cert_hostnames);
2354 }
2355}
aa2a70ba
JH
2356
2357
899b8bbc
JH
2358
2359
2360#ifdef SUPPORT_DANE
2361/* Given our list of RRs from the TLSA lookup, build a lookup block in
2362GnuTLS-DANE's preferred format. Hang it on the state str for later
2363use in DANE verification.
2364
2365We point at the dnsa data not copy it, so it must remain valid until
2366after verification is done.*/
2367
3674140c 2368static BOOL
899b8bbc
JH
2369dane_tlsa_load(exim_gnutls_state_st * state, dns_answer * dnsa)
2370{
899b8bbc
JH
2371dns_scan dnss;
2372int i;
2373const char ** dane_data;
2374int * dane_data_len;
2375
d7978c0f
JH
2376i = 1;
2377for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
899b8bbc
JH
2378 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2379 ) if (rr->type == T_TLSA) i++;
2380
2381dane_data = store_get(i * sizeof(uschar *));
2382dane_data_len = store_get(i * sizeof(int));
2383
d7978c0f
JH
2384i = 0;
2385for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
899b8bbc 2386 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
1b76ad22 2387 ) if (rr->type == T_TLSA && rr->size > 3)
899b8bbc
JH
2388 {
2389 const uschar * p = rr->data;
3674140c
JH
2390 uint8_t usage = p[0], sel = p[1], type = p[2];
2391
2392 DEBUG(D_tls)
2393 debug_printf("TLSA: %d %d %d size %d\n", usage, sel, type, rr->size);
2394
94c13285
JH
2395 if ( (usage != DANESSL_USAGE_DANE_TA && usage != DANESSL_USAGE_DANE_EE)
2396 || (sel != 0 && sel != 1)
2397 )
2398 continue;
3674140c
JH
2399 switch(type)
2400 {
2401 case 0: /* Full: cannot check at present */
2402 break;
2403 case 1: if (rr->size != 3 + 256/8) continue; /* sha2-256 */
2404 break;
2405 case 2: if (rr->size != 3 + 512/8) continue; /* sha2-512 */
2406 break;
2407 default: continue;
2408 }
899b8bbc
JH
2409
2410 tls_out.tlsa_usage |= 1<<usage;
48224640 2411 dane_data[i] = CS p;
899b8bbc
JH
2412 dane_data_len[i++] = rr->size;
2413 }
3674140c
JH
2414
2415if (!i) return FALSE;
2416
899b8bbc
JH
2417dane_data[i] = NULL;
2418dane_data_len[i] = 0;
2419
2420state->dane_data = (char * const *)dane_data;
2421state->dane_data_len = dane_data_len;
3674140c 2422return TRUE;
899b8bbc
JH
2423}
2424#endif
2425
2426
2427
b10c87b3
JH
2428#ifdef EXPERIMENTAL_TLS_RESUME
2429/* On the client, get any stashed session for the given IP from hints db
2430and apply it to the ssl-connection for attempted resumption. Although
2431there is a gnutls_session_ticket_enable_client() interface it is
2432documented as unnecessary (as of 3.6.7) as "session tickets are emabled
2433by deafult". There seems to be no way to disable them, so even hosts not
2434enabled by the transport option will be sent a ticket request. We will
2435however avoid storing and retrieving session information. */
2436
2437static void
2438tls_retrieve_session(tls_support * tlsp, gnutls_session_t session,
2439 host_item * host, smtp_transport_options_block * ob)
2440{
2441tlsp->resumption = RESUME_SUPPORTED;
2442if (verify_check_given_host(CUSS &ob->tls_resumption_hosts, host) == OK)
2443 {
2444 dbdata_tls_session * dt;
2445 int len, rc;
2446 open_db dbblock, * dbm_file;
2447
2448 DEBUG(D_tls)
2449 debug_printf("check for resumable session for %s\n", host->address);
2450 tlsp->host_resumable = TRUE;
2451 tlsp->resumption |= RESUME_CLIENT_REQUESTED;
2452 if ((dbm_file = dbfn_open(US"tls", O_RDONLY, &dbblock, FALSE, FALSE)))
2453 {
2454 /* key for the db is the IP */
2455 if ((dt = dbfn_read_with_length(dbm_file, host->address, &len)))
2456 if (!(rc = gnutls_session_set_data(session,
2457 CUS dt->session, (size_t)len - sizeof(dbdata_tls_session))))
2458 {
2459 DEBUG(D_tls) debug_printf("good session\n");
2460 tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
2461 }
2462 else DEBUG(D_tls) debug_printf("setting session resumption data: %s\n",
2463 US gnutls_strerror(rc));
2464 dbfn_close(dbm_file);
2465 }
2466 }
2467}
2468
2469
2470static void
2471tls_save_session(tls_support * tlsp, gnutls_session_t session, const host_item * host)
2472{
2473/* TLS 1.2 - we get both the callback and the direct posthandshake call,
2474but this flag is not set until the second. TLS 1.3 it's the other way about.
2475Keep both calls as the session data cannot be extracted before handshake
2476completes. */
2477
fb34a7cb 2478#ifdef GNUTLS_SFLAGS_SESSION_TICKET
b10c87b3
JH
2479if (gnutls_session_get_flags(session) & GNUTLS_SFLAGS_SESSION_TICKET)
2480 {
2481 gnutls_datum_t tkt;
2482 int rc;
2483
2484 DEBUG(D_tls) debug_printf("server offered session ticket\n");
2485 tlsp->ticket_received = TRUE;
2486 tlsp->resumption |= RESUME_SERVER_TICKET;
2487
2488 if (tlsp->host_resumable)
2489 if (!(rc = gnutls_session_get_data2(session, &tkt)))
2490 {
2491 open_db dbblock, * dbm_file;
2492 int dlen = sizeof(dbdata_tls_session) + tkt.size;
2493 dbdata_tls_session * dt = store_get(dlen);
2494
2495 DEBUG(D_tls) debug_printf("session data size %u\n", (unsigned)tkt.size);
2496 memcpy(dt->session, tkt.data, tkt.size);
2497 gnutls_free(tkt.data);
2498
2499 if ((dbm_file = dbfn_open(US"tls", O_RDWR, &dbblock, FALSE, FALSE)))
2500 {
2501 /* key for the db is the IP */
2502 dbfn_delete(dbm_file, host->address);
2503 dbfn_write(dbm_file, host->address, dt, dlen);
2504 dbfn_close(dbm_file);
2505
2506 DEBUG(D_tls)
2507 debug_printf("wrote session db (len %u)\n", (unsigned)dlen);
2508 }
2509 }
2510 else DEBUG(D_tls)
2511 debug_printf("extract session data: %s\n", US gnutls_strerror(rc));
2512 }
fb34a7cb 2513#endif
b10c87b3
JH
2514}
2515
2516
2517/* With a TLS1.3 session, the ticket(s) are not seen until
2518the first data read is attempted. And there's often two of them.
2519Pick them up with this callback. We are also called for 1.2
2520but we do nothing.
2521*/
2522static int
2523tls_client_ticket_cb(gnutls_session_t sess, u_int htype, unsigned when,
2524 unsigned incoming, const gnutls_datum_t * msg)
2525{
2526exim_gnutls_state_st * state = gnutls_session_get_ptr(sess);
2527tls_support * tlsp = state->tlsp;
2528
2529DEBUG(D_tls) debug_printf("newticket cb\n");
2530
2531if (!tlsp->ticket_received)
2532 tls_save_session(tlsp, sess, state->host);
2533return 0;
2534}
2535
2536
2537static void
2538tls_client_resume_prehandshake(exim_gnutls_state_st * state,
2539 tls_support * tlsp, host_item * host,
2540 smtp_transport_options_block * ob)
2541{
2542gnutls_session_set_ptr(state->session, state);
2543gnutls_handshake_set_hook_function(state->session,
2544 GNUTLS_HANDSHAKE_NEW_SESSION_TICKET, GNUTLS_HOOK_POST, tls_client_ticket_cb);
2545
2546tls_retrieve_session(tlsp, state->session, host, ob);
2547}
2548
2549static void
2550tls_client_resume_posthandshake(exim_gnutls_state_st * state,
2551 tls_support * tlsp, host_item * host)
2552{
2553if (gnutls_session_is_resumed(state->session))
2554 {
2555 DEBUG(D_tls) debug_printf("Session resumed\n");
2556 tlsp->resumption |= RESUME_USED;
2557 }
2558
2559tls_save_session(tlsp, state->session, host);
2560}
2561#endif /* EXPERIMENTAL_TLS_RESUME */
2562
2563
059ec3d9
PH
2564/*************************************************
2565* Start a TLS session in a client *
2566*************************************************/
2567
2568/* Called from the smtp transport after STARTTLS has been accepted.
2569
2570Arguments:
c05bdbd6
JH
2571 cctx connection context
2572 conn_args connection details
2573 cookie datum for randomness (not used)
2574 tlsp record details of channel configuration here; must be non-NULL
2575 errstr error string pointer
2576
2577Returns: TRUE for success with TLS session context set in smtp context,
2578 FALSE on error
059ec3d9
PH
2579*/
2580
c05bdbd6
JH
2581BOOL
2582tls_client_start(client_conn_ctx * cctx, smtp_connect_args * conn_args,
2583 void * cookie ARG_UNUSED,
2584 tls_support * tlsp, uschar ** errstr)
059ec3d9 2585{
c05bdbd6
JH
2586host_item * host = conn_args->host; /* for msgs and option-tests */
2587transport_instance * tb = conn_args->tblock; /* always smtp or NULL */
2588smtp_transport_options_block * ob = tb
afdb5e9c
JH
2589 ? (smtp_transport_options_block *)tb->options_block
2590 : &smtp_transport_option_defaults;
059ec3d9 2591int rc;
899b8bbc 2592exim_gnutls_state_st * state = NULL;
c05bdbd6 2593uschar * cipher_list = NULL;
74f1a423 2594
f2de3a33 2595#ifndef DISABLE_OCSP
5130845b 2596BOOL require_ocsp =
3fb3231c 2597 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
44662487 2598BOOL request_ocsp = require_ocsp ? TRUE
3fb3231c 2599 : verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2b4a568d 2600#endif
059ec3d9 2601
c05bdbd6 2602DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", cctx->sock);
059ec3d9 2603
5ec37a55 2604#ifdef SUPPORT_DANE
c05bdbd6
JH
2605/* If dane is flagged, have either request or require dane for this host, and
2606a TLSA record found. Therefore, dane verify required. Which implies cert must
2607be requested and supplied, dane verify must pass, and cert verify irrelevant
2608(incl. hostnames), and (caller handled) require_tls */
2609
2610if (conn_args->dane && ob->dane_require_tls_ciphers)
5ec37a55
PP
2611 {
2612 /* not using expand_check_tlsvar because not yet in state */
2613 if (!expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2614 &cipher_list, errstr))
c05bdbd6 2615 return FALSE;
cf260049
JH
2616 cipher_list = cipher_list && *cipher_list
2617 ? ob->dane_require_tls_ciphers : ob->tls_require_ciphers;
5ec37a55
PP
2618 }
2619#endif
2620
2621if (!cipher_list)
2622 cipher_list = ob->tls_require_ciphers;
2623
74f1a423 2624if (tls_init(host, ob->tls_certificate, ob->tls_privatekey,
65867078 2625 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
74f1a423 2626 cipher_list, &state, tlsp, errstr) != OK)
c05bdbd6 2627 return FALSE;
059ec3d9 2628
54c90be1 2629 {
65867078
JH
2630 int dh_min_bits = ob->tls_dh_min_bits;
2631 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
2632 {
2633 DEBUG(D_tls)
2634 debug_printf("WARNING: tls_dh_min_bits far too low,"
2635 " clamping %d up to %d\n",
2636 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
2637 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
2638 }
54c90be1 2639
65867078
JH
2640 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
2641 " acceptable bits to %d\n",
2642 dh_min_bits);
2643 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
2644 }
83da1223 2645
94431adb 2646/* Stick to the old behaviour for compatibility if tls_verify_certificates is
2b4a568d
JH
2647set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
2648the specified host patterns if one of them is defined */
2649
899b8bbc 2650#ifdef SUPPORT_DANE
c05bdbd6 2651if (conn_args->dane && dane_tlsa_load(state, &conn_args->tlsa_dnsa))
899b8bbc
JH
2652 {
2653 DEBUG(D_tls)
2654 debug_printf("TLS: server certificate DANE required.\n");
2655 state->verify_requirement = VERIFY_DANE;
2656 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
899b8bbc
JH
2657 }
2658else
2659#endif
2660 if ( ( state->exp_tls_verify_certificates
2661 && !ob->tls_verify_hosts
2662 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2663 )
3fb3231c 2664 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
899b8bbc 2665 )
17c76198 2666 {
aa2a70ba 2667 tls_client_setup_hostname_checks(host, state, ob);
aa2a70ba
JH
2668 DEBUG(D_tls)
2669 debug_printf("TLS: server certificate verification required.\n");
2670 state->verify_requirement = VERIFY_REQUIRED;
52f93eed
WB
2671 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2672 }
3fb3231c 2673else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
52f93eed 2674 {
aa2a70ba 2675 tls_client_setup_hostname_checks(host, state, ob);
e51c7be2
JH
2676 DEBUG(D_tls)
2677 debug_printf("TLS: server certificate verification optional.\n");
52f93eed 2678 state->verify_requirement = VERIFY_OPTIONAL;
17c76198
PP
2679 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2680 }
2681else
2682 {
e51c7be2
JH
2683 DEBUG(D_tls)
2684 debug_printf("TLS: server certificate verification not required.\n");
52f93eed
WB
2685 state->verify_requirement = VERIFY_NONE;
2686 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
17c76198 2687 }
059ec3d9 2688
f2de3a33
JH
2689#ifndef DISABLE_OCSP
2690 /* supported since GnuTLS 3.1.3 */
44662487 2691if (request_ocsp)
9d1c15ef
JH
2692 {
2693 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
65867078
JH
2694 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
2695 NULL, 0, NULL)) != OK)
74f1a423 2696 {
452a164f 2697 tls_error_gnu(US"cert-status-req", rc, state->host, errstr);
c05bdbd6 2698 return FALSE;
74f1a423
JH
2699 }
2700 tlsp->ocsp = OCSP_NOT_RESP;
9d1c15ef 2701 }
2b4a568d
JH
2702#endif
2703
b10c87b3
JH
2704#ifdef EXPERIMENTAL_TLS_RESUME
2705tls_client_resume_prehandshake(state, tlsp, host, ob);
2706#endif
2707
0cbf2b82 2708#ifndef DISABLE_EVENT
afdb5e9c 2709if (tb && tb->event_action)
a7538db1 2710 {
774ef2d7 2711 state->event_action = tb->event_action;
a7538db1 2712 gnutls_session_set_ptr(state->session, state);
723fe533 2713 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
a7538db1
JH
2714 }
2715#endif
2716
c05bdbd6
JH
2717gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr_t)(long) cctx->sock);
2718state->fd_in = cctx->sock;
2719state->fd_out = cctx->sock;
059ec3d9 2720
9d1c15ef 2721DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
059ec3d9
PH
2722/* There doesn't seem to be a built-in timeout on connection. */
2723
2724sigalrm_seen = FALSE;
c2a1bba0 2725ALARM(ob->command_timeout);
17c76198 2726do
17c76198 2727 rc = gnutls_handshake(state->session);
f1fed05b 2728while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
c2a1bba0 2729ALARM_CLR(0);
059ec3d9 2730
4fe99a6c 2731if (rc != GNUTLS_E_SUCCESS)
74f1a423 2732 {
60d10ce7
JH
2733 if (sigalrm_seen)
2734 {
2735 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_USER_CANCELED);
48224640 2736 tls_error(US"gnutls_handshake", US"timed out", state->host, errstr);
60d10ce7
JH
2737 }
2738 else
452a164f 2739 tls_error_gnu(US"gnutls_handshake", rc, state->host, errstr);
c05bdbd6 2740 return FALSE;
74f1a423 2741 }
4fe99a6c 2742
dc6d1769 2743DEBUG(D_tls) post_handshake_debug(state);
059ec3d9 2744
17c76198 2745/* Verify late */
059ec3d9 2746
899b8bbc 2747if (!verify_certificate(state, errstr))
74f1a423
JH
2748 {
2749 tls_error(US"certificate verification failed", *errstr, state->host, errstr);
c05bdbd6 2750 return FALSE;
74f1a423 2751 }
059ec3d9 2752
f2de3a33 2753#ifndef DISABLE_OCSP
2b4a568d
JH
2754if (require_ocsp)
2755 {
2756 DEBUG(D_tls)
2757 {
2758 gnutls_datum_t stapling;
2759 gnutls_ocsp_resp_t resp;
2760 gnutls_datum_t printed;
2761 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
2762 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
2763 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
2764 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
2765 )
2766 {
65867078 2767 debug_printf("%.4096s", printed.data);
2b4a568d
JH
2768 gnutls_free(printed.data);
2769 }
2770 else
452a164f 2771 (void) tls_error_gnu(US"ocsp decode", rc, state->host, errstr);
2b4a568d
JH
2772 }
2773
2b4a568d 2774 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
018058b2 2775 {
74f1a423
JH
2776 tlsp->ocsp = OCSP_FAILED;
2777 tls_error(US"certificate status check failed", NULL, state->host, errstr);
c05bdbd6 2778 return FALSE;
018058b2 2779 }
2b4a568d 2780 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
74f1a423 2781 tlsp->ocsp = OCSP_VFIED;
2b4a568d
JH
2782 }
2783#endif
2784
b10c87b3
JH
2785#ifdef EXPERIMENTAL_TLS_RESUME
2786tls_client_resume_posthandshake(state, tlsp, host);
2787#endif
059ec3d9 2788
4fe99a6c 2789/* Sets various Exim expansion variables; may need to adjust for ACL callouts */
059ec3d9 2790
9d1c15ef 2791extract_exim_vars_from_tls_state(state);
059ec3d9 2792
c05bdbd6
JH
2793cctx->tls_ctx = state;
2794return TRUE;
059ec3d9
PH
2795}
2796
2797
2798
17c76198 2799
059ec3d9 2800/*************************************************
17c76198 2801* Close down a TLS session *
059ec3d9
PH
2802*************************************************/
2803
17c76198
PP
2804/* This is also called from within a delivery subprocess forked from the
2805daemon, to shut down the TLS library, without actually doing a shutdown (which
2806would tamper with the TLS session in the parent process).
059ec3d9 2807
dec766a1 2808Arguments:
74f1a423 2809 ct_ctx client context pointer, or NULL for the one global server context
dec766a1 2810 shutdown 1 if TLS close-alert is to be sent,
afdb5e9c 2811 2 if also response to be waited for
dec766a1 2812
17c76198 2813Returns: nothing
059ec3d9
PH
2814*/
2815
17c76198 2816void
74f1a423 2817tls_close(void * ct_ctx, int shutdown)
059ec3d9 2818{
74f1a423 2819exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
059ec3d9 2820
74f1a423 2821if (!state->tlsp || state->tlsp->active.sock < 0) return; /* TLS was not active */
17c76198
PP
2822
2823if (shutdown)
2824 {
dec766a1
WB
2825 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
2826 shutdown > 1 ? " (with response-wait)" : "");
2827
c2a1bba0 2828 ALARM(2);
dec766a1 2829 gnutls_bye(state->session, shutdown > 1 ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
c2a1bba0 2830 ALARM_CLR(0);
17c76198
PP
2831 }
2832
2833gnutls_deinit(state->session);
ed62aae3
HSHR
2834gnutls_certificate_free_credentials(state->x509_cred);
2835
17c76198 2836
74f1a423
JH
2837state->tlsp->active.sock = -1;
2838state->tlsp->active.tls_ctx = NULL;
b808677c 2839if (state->xfer_buffer) store_free(state->xfer_buffer);
17c76198 2840memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
059ec3d9
PH
2841}
2842
2843
2844
17c76198 2845
0d81dabc
JH
2846static BOOL
2847tls_refill(unsigned lim)
2848{
2849exim_gnutls_state_st * state = &state_server;
2850ssize_t inbytes;
2851
2852DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
2853 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
2854
f1fed05b 2855sigalrm_seen = FALSE;
c2a1bba0 2856if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
4896a319
AM
2857
2858do
2859 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
2860 MIN(ssl_xfer_buffer_size, lim));
2861while (inbytes == GNUTLS_E_AGAIN);
2862
c2a1bba0 2863if (smtp_receive_timeout > 0) ALARM_CLR(0);
9723f966
JH
2864
2865if (had_command_timeout) /* set by signal handler */
2866 smtp_command_timeout_exit(); /* does not return */
2867if (had_command_sigterm)
2868 smtp_command_sigterm_exit();
2869if (had_data_timeout)
2870 smtp_data_timeout_exit();
2871if (had_data_sigint)
2872 smtp_data_sigint_exit();
2873
2874/* Timeouts do not get this far. A zero-byte return appears to mean that the
2875TLS session has been closed down, not that the socket itself has been closed
2876down. Revert to non-TLS handling. */
0d81dabc
JH
2877
2878if (sigalrm_seen)
2879 {
2880 DEBUG(D_tls) debug_printf("Got tls read timeout\n");
8b77d27a 2881 state->xfer_error = TRUE;
0d81dabc
JH
2882 return FALSE;
2883 }
2884
2885else if (inbytes == 0)
2886 {
2887 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2888
2889 receive_getc = smtp_getc;
2890 receive_getbuf = smtp_getbuf;
2891 receive_get_cache = smtp_get_cache;
2892 receive_ungetc = smtp_ungetc;
2893 receive_feof = smtp_feof;
2894 receive_ferror = smtp_ferror;
2895 receive_smtp_buffered = smtp_buffered;
2896
2897 gnutls_deinit(state->session);
2898 gnutls_certificate_free_credentials(state->x509_cred);
2899
2900 state->session = NULL;
74f1a423
JH
2901 state->tlsp->active.sock = -1;
2902 state->tlsp->active.tls_ctx = NULL;
0d81dabc
JH
2903 state->tlsp->bits = 0;
2904 state->tlsp->certificate_verified = FALSE;
2905 tls_channelbinding_b64 = NULL;
2906 state->tlsp->cipher = NULL;
2907 state->tlsp->peercert = NULL;
2908 state->tlsp->peerdn = NULL;
2909
2910 return FALSE;
2911 }
2912
2913/* Handle genuine errors */
2914
2915else if (inbytes < 0)
2916 {
95f52235 2917 DEBUG(D_tls) debug_printf("%s: err from gnutls_record_recv\n", __FUNCTION__);
0d81dabc 2918 record_io_error(state, (int) inbytes, US"recv", NULL);
8b77d27a 2919 state->xfer_error = TRUE;
0d81dabc
JH
2920 return FALSE;
2921 }
2922#ifndef DISABLE_DKIM
2923dkim_exim_verify_feed(state->xfer_buffer, inbytes);
2924#endif
2925state->xfer_buffer_hwm = (int) inbytes;
2926state->xfer_buffer_lwm = 0;
2927return TRUE;
2928}
2929
059ec3d9
PH
2930/*************************************************
2931* TLS version of getc *
2932*************************************************/
2933
2934/* This gets the next byte from the TLS input buffer. If the buffer is empty,
2935it refills the buffer via the GnuTLS reading function.
817d9f57 2936Only used by the server-side TLS.
059ec3d9 2937
17c76198
PP
2938This feeds DKIM and should be used for all message-body reads.
2939
aded2255 2940Arguments: lim Maximum amount to read/buffer
059ec3d9
PH
2941Returns: the next character or EOF
2942*/
2943
2944int
bd8fbe36 2945tls_getc(unsigned lim)
059ec3d9 2946{
0d81dabc 2947exim_gnutls_state_st * state = &state_server;
059ec3d9 2948
0d81dabc
JH
2949if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2950 if (!tls_refill(lim))
2951 return state->xfer_error ? EOF : smtp_getc(lim);
ed62aae3 2952
0d81dabc 2953/* Something in the buffer; return next uschar */
059ec3d9 2954
0d81dabc
JH
2955return state->xfer_buffer[state->xfer_buffer_lwm++];
2956}
059ec3d9 2957
0d81dabc
JH
2958uschar *
2959tls_getbuf(unsigned * len)
2960{
2961exim_gnutls_state_st * state = &state_server;
2962unsigned size;
2963uschar * buf;
059ec3d9 2964
0d81dabc
JH
2965if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2966 if (!tls_refill(*len))
059ec3d9 2967 {
0d81dabc
JH
2968 if (!state->xfer_error) return smtp_getbuf(len);
2969 *len = 0;
2970 return NULL;
059ec3d9 2971 }
059ec3d9 2972
0d81dabc
JH
2973if ((size = state->xfer_buffer_hwm - state->xfer_buffer_lwm) > *len)
2974 size = *len;
2975buf = &state->xfer_buffer[state->xfer_buffer_lwm];
2976state->xfer_buffer_lwm += size;
2977*len = size;
2978return buf;
059ec3d9
PH
2979}
2980
0d81dabc 2981
584e96c6
JH
2982void
2983tls_get_cache()
2984{
9960d1e5 2985#ifndef DISABLE_DKIM
584e96c6
JH
2986exim_gnutls_state_st * state = &state_server;
2987int n = state->xfer_buffer_hwm - state->xfer_buffer_lwm;
2988if (n > 0)
2989 dkim_exim_verify_feed(state->xfer_buffer+state->xfer_buffer_lwm, n);
584e96c6 2990#endif
9960d1e5 2991}
584e96c6 2992
059ec3d9 2993
925ac8e4
JH
2994BOOL
2995tls_could_read(void)
2996{
2997return state_server.xfer_buffer_lwm < state_server.xfer_buffer_hwm
2998 || gnutls_record_check_pending(state_server.session) > 0;
2999}
3000
3001
059ec3d9 3002
17c76198 3003
059ec3d9
PH
3004/*************************************************
3005* Read bytes from TLS channel *
3006*************************************************/
3007
17c76198
PP
3008/* This does not feed DKIM, so if the caller uses this for reading message body,
3009then the caller must feed DKIM.
817d9f57 3010
059ec3d9 3011Arguments:
74f1a423 3012 ct_ctx client context pointer, or NULL for the one global server context
059ec3d9
PH
3013 buff buffer of data
3014 len size of buffer
3015
3016Returns: the number of bytes read
afdb5e9c 3017 -1 after a failed read, including EOF
059ec3d9
PH
3018*/
3019
3020int
74f1a423 3021tls_read(void * ct_ctx, uschar *buff, size_t len)
059ec3d9 3022{
74f1a423 3023exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
17c76198 3024ssize_t inbytes;
059ec3d9 3025
17c76198
PP
3026if (len > INT_MAX)
3027 len = INT_MAX;
059ec3d9 3028
17c76198
PP
3029if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
3030 DEBUG(D_tls)
3031 debug_printf("*** PROBABLY A BUG *** " \
3032 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
3033 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
3034
3035DEBUG(D_tls)
3036 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
3037 state->session, buff, len);
3038
4896a319
AM
3039do
3040 inbytes = gnutls_record_recv(state->session, buff, len);
3041while (inbytes == GNUTLS_E_AGAIN);
3042
059ec3d9
PH
3043if (inbytes > 0) return inbytes;
3044if (inbytes == 0)
3045 {
3046 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
3047 }
5fd28bb8 3048else
4896a319 3049 {
95f52235 3050 DEBUG(D_tls) debug_printf("%s: err from gnutls_record_recv\n", __FUNCTION__);
4896a319
AM
3051 record_io_error(state, (int)inbytes, US"recv", NULL);
3052 }
059ec3d9
PH
3053
3054return -1;
3055}
3056
3057
3058
17c76198 3059
059ec3d9
PH
3060/*************************************************
3061* Write bytes down TLS channel *
3062*************************************************/
3063
3064/*
3065Arguments:
74f1a423 3066 ct_ctx client context pointer, or NULL for the one global server context
059ec3d9
PH
3067 buff buffer of data
3068 len number of bytes
925ac8e4 3069 more more data expected soon
059ec3d9
PH
3070
3071Returns: the number of bytes after a successful write,
3072 -1 after a failed write
3073*/
3074
3075int
74f1a423 3076tls_write(void * ct_ctx, const uschar * buff, size_t len, BOOL more)
059ec3d9 3077{
17c76198
PP
3078ssize_t outbytes;
3079size_t left = len;
74f1a423 3080exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
925ac8e4
JH
3081#ifdef SUPPORT_CORK
3082static BOOL corked = FALSE;
3083
3084if (more && !corked) gnutls_record_cork(state->session);
3085#endif
3086
3087DEBUG(D_tls) debug_printf("%s(%p, " SIZE_T_FMT "%s)\n", __FUNCTION__,
3088 buff, left, more ? ", more" : "");
059ec3d9 3089
059ec3d9
PH
3090while (left > 0)
3091 {
17c76198
PP
3092 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
3093 buff, left);
4896a319
AM
3094
3095 do
3096 outbytes = gnutls_record_send(state->session, buff, left);
3097 while (outbytes == GNUTLS_E_AGAIN);
059ec3d9 3098
17c76198 3099 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
059ec3d9
PH
3100 if (outbytes < 0)
3101 {
1b76ad22 3102 DEBUG(D_tls) debug_printf("%s: gnutls_record_send err\n", __FUNCTION__);
17c76198 3103 record_io_error(state, outbytes, US"send", NULL);
059ec3d9
PH
3104 return -1;
3105 }
3106 if (outbytes == 0)
3107 {
17c76198 3108 record_io_error(state, 0, US"send", US"TLS channel closed on write");
059ec3d9
PH
3109 return -1;
3110 }
3111
3112 left -= outbytes;
3113 buff += outbytes;
3114 }
3115
17c76198
PP
3116if (len > INT_MAX)
3117 {
3118 DEBUG(D_tls)
3119 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
3120 len);
3121 len = INT_MAX;
3122 }
3123
925ac8e4
JH
3124#ifdef SUPPORT_CORK
3125if (more != corked)
3126 {
3127 if (!more) (void) gnutls_record_uncork(state->session, 0);
3128 corked = more;
3129 }
3130#endif
3131
17c76198 3132return (int) len;
059ec3d9
PH
3133}
3134
3135
3136
17c76198 3137
059ec3d9 3138/*************************************************
17c76198 3139* Random number generation *
059ec3d9
PH
3140*************************************************/
3141
17c76198
PP
3142/* Pseudo-random number generation. The result is not expected to be
3143cryptographically strong but not so weak that someone will shoot themselves
3144in the foot using it as a nonce in input in some email header scheme or
3145whatever weirdness they'll twist this into. The result should handle fork()
3146and avoid repeating sequences. OpenSSL handles that for us.
059ec3d9 3147
17c76198
PP
3148Arguments:
3149 max range maximum
3150Returns a random number in range [0, max-1]
059ec3d9
PH
3151*/
3152
af3498d6 3153#ifdef HAVE_GNUTLS_RND
17c76198
PP
3154int
3155vaguely_random_number(int max)
059ec3d9 3156{
17c76198
PP
3157unsigned int r;
3158int i, needed_len;
17c76198
PP
3159uschar smallbuf[sizeof(r)];
3160
3161if (max <= 1)
3162 return 0;
3163
3164needed_len = sizeof(r);
3165/* Don't take 8 times more entropy than needed if int is 8 octets and we were
d7978c0f
JH
3166asked for a number less than 10. */
3167
17c76198
PP
3168for (r = max, i = 0; r; ++i)
3169 r >>= 1;
3170i = (i + 7) / 8;
3171if (i < needed_len)
3172 needed_len = i;
3173
3174i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
3175if (i < 0)
059ec3d9 3176 {
17c76198
PP
3177 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
3178 return vaguely_random_number_fallback(max);
3179 }
3180r = 0;
d7978c0f
JH
3181for (uschar * p = smallbuf; needed_len; --needed_len, ++p)
3182 r = r * 256 + *p;
059ec3d9 3183
17c76198
PP
3184/* We don't particularly care about weighted results; if someone wants
3185 * smooth distribution and cares enough then they should submit a patch then. */
3186return r % max;
059ec3d9 3187}
af3498d6
PP
3188#else /* HAVE_GNUTLS_RND */
3189int
3190vaguely_random_number(int max)
3191{
3192 return vaguely_random_number_fallback(max);
3193}
3194#endif /* HAVE_GNUTLS_RND */
059ec3d9 3195
36f12725
NM
3196
3197
3198
3375e053
PP
3199/*************************************************
3200* Let tls_require_ciphers be checked at startup *
3201*************************************************/
3202
3203/* The tls_require_ciphers option, if set, must be something which the
3204library can parse.
3205
3206Returns: NULL on success, or error message
3207*/
3208
3209uschar *
3210tls_validate_require_cipher(void)
3211{
3212int rc;
3213uschar *expciphers = NULL;
3214gnutls_priority_t priority_cache;
3215const char *errpos;
cf0c6164 3216uschar * dummy_errstr;
3375e053
PP
3217
3218#define validate_check_rc(Label) do { \
3219 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
3220 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
3221#define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
3222
3223if (exim_gnutls_base_init_done)
3224 log_write(0, LOG_MAIN|LOG_PANIC,
3225 "already initialised GnuTLS, Exim developer bug");
3226
a5f239e4 3227#ifdef HAVE_GNUTLS_PKCS11
2519e60d 3228if (!gnutls_allow_auto_pkcs11)
a5f239e4
PP
3229 {
3230 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
3231 validate_check_rc(US"gnutls_pkcs11_init");
3232 }
3233#endif
3375e053
PP
3234rc = gnutls_global_init();
3235validate_check_rc(US"gnutls_global_init()");
3236exim_gnutls_base_init_done = TRUE;
3237
3238if (!(tls_require_ciphers && *tls_require_ciphers))
3239 return_deinit(NULL);
3240
cf0c6164
JH
3241if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3242 &dummy_errstr))
3375e053
PP
3243 return_deinit(US"failed to expand tls_require_ciphers");
3244
3245if (!(expciphers && *expciphers))
3246 return_deinit(NULL);
3247
3248DEBUG(D_tls)
3249 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3250
3251rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
3252validate_check_rc(string_sprintf(
3253 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
3254 expciphers, errpos - CS expciphers, errpos));
3255
3256#undef return_deinit
3257#undef validate_check_rc
3258gnutls_global_deinit();
3259
3260return NULL;
3261}
3262
3263
3264
3265
36f12725
NM
3266/*************************************************
3267* Report the library versions. *
3268*************************************************/
3269
3270/* See a description in tls-openssl.c for an explanation of why this exists.
3271
3272Arguments: a FILE* to print the results to
3273Returns: nothing
3274*/
3275
3276void
3277tls_version_report(FILE *f)
3278{
754a0503
PP
3279fprintf(f, "Library version: GnuTLS: Compile: %s\n"
3280 " Runtime: %s\n",
3281 LIBGNUTLS_VERSION,
3282 gnutls_check_version(NULL));
36f12725
NM
3283}
3284
b10c87b3 3285#endif /*!MACRO_PREDEF*/
2b4a568d
JH
3286/* vi: aw ai sw=2
3287*/
059ec3d9 3288/* End of tls-gnu.c */