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