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