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