TLS: support multiple certificate files in server. Bug 2092
[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,
e51c7be2 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
PP
217/* ------------------------------------------------------------------------ */
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
ba86e143
JH
807static int
808tls_add_certfile(exim_gnutls_state_st * state, const host_item * host,
809 uschar * certfile, uschar * keyfile, uschar ** errstr)
810{
811int rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
812 CS certfile, CS keyfile, GNUTLS_X509_FMT_PEM);
813exim_gnutls_err_check(
814 string_sprintf("cert/key setup: cert=%s key=%s", certfile, keyfile));
815return OK;
816}
817
818
059ec3d9 819/*************************************************
17c76198 820* Variables re-expanded post-SNI *
059ec3d9
PH
821*************************************************/
822
17c76198
PP
823/* Called from both server and client code, via tls_init(), and also from
824the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
825
826We can tell the two apart by state->received_sni being non-NULL in callback.
827
828The callback should not call us unless state->trigger_sni_changes is true,
829which we are responsible for setting on the first pass through.
059ec3d9
PH
830
831Arguments:
17c76198 832 state exim_gnutls_state_st *
cf0c6164 833 errstr error string pointer
059ec3d9
PH
834
835Returns: OK/DEFER/FAIL
836*/
837
838static int
ba86e143 839tls_expand_session_files(exim_gnutls_state_st * state, uschar ** errstr)
059ec3d9 840{
1365611d 841struct stat statbuf;
059ec3d9 842int rc;
17c76198
PP
843const host_item *host = state->host; /* macro should be reconsidered? */
844uschar *saved_tls_certificate = NULL;
845uschar *saved_tls_privatekey = NULL;
846uschar *saved_tls_verify_certificates = NULL;
847uschar *saved_tls_crl = NULL;
848int cert_count;
849
850/* We check for tls_sni *before* expansion. */
2b4a568d 851if (!host) /* server */
17c76198
PP
852 if (!state->received_sni)
853 {
ba86e143
JH
854 if ( state->tls_certificate
855 && ( Ustrstr(state->tls_certificate, US"tls_sni")
856 || Ustrstr(state->tls_certificate, US"tls_in_sni")
857 || Ustrstr(state->tls_certificate, US"tls_out_sni")
858 ) )
17c76198
PP
859 {
860 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
861 state->trigger_sni_changes = TRUE;
862 }
863 }
864 else
865 {
1365611d 866 /* useful for debugging */
17c76198
PP
867 saved_tls_certificate = state->exp_tls_certificate;
868 saved_tls_privatekey = state->exp_tls_privatekey;
869 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
870 saved_tls_crl = state->exp_tls_crl;
871 }
059ec3d9 872
1365611d
PP
873rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
874exim_gnutls_err_check(US"gnutls_certificate_allocate_credentials");
875
17c76198
PP
876/* remember: expand_check_tlsvar() is expand_check() but fiddling with
877state members, assuming consistent naming; and expand_check() returns
878false if expansion failed, unless expansion was forced to fail. */
059ec3d9 879
17c76198
PP
880/* check if we at least have a certificate, before doing expensive
881D-H generation. */
059ec3d9 882
cf0c6164 883if (!expand_check_tlsvar(tls_certificate, errstr))
17c76198 884 return DEFER;
059ec3d9 885
17c76198 886/* certificate is mandatory in server, optional in client */
059ec3d9 887
23bb6982
JH
888if ( !state->exp_tls_certificate
889 || !*state->exp_tls_certificate
890 )
2b4a568d 891 if (!host)
cf0c6164 892 return tls_install_selfsign(state, errstr);
17c76198
PP
893 else
894 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
059ec3d9 895
cf0c6164 896if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey, errstr))
059ec3d9
PH
897 return DEFER;
898
17c76198
PP
899/* tls_privatekey is optional, defaulting to same file as certificate */
900
901if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
059ec3d9 902 {
17c76198
PP
903 state->tls_privatekey = state->tls_certificate;
904 state->exp_tls_privatekey = state->exp_tls_certificate;
059ec3d9 905 }
c91535f3 906
059ec3d9 907
17c76198 908if (state->exp_tls_certificate && *state->exp_tls_certificate)
059ec3d9
PH
909 {
910 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
17c76198
PP
911 state->exp_tls_certificate, state->exp_tls_privatekey);
912
913 if (state->received_sni)
23bb6982
JH
914 if ( Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0
915 && Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0
916 )
17c76198 917 {
b34fc30c 918 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
17c76198
PP
919 }
920 else
921 {
b34fc30c 922 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
17c76198 923 }
059ec3d9 924
ba86e143
JH
925 if (!host) /* server */
926 {
927 const uschar * clist = state->exp_tls_certificate;
928 const uschar * klist = state->exp_tls_privatekey;
929 int csep = 0, ksep = 0;
930 uschar * cfile, * kfile;
931
932 while (cfile = string_nextinlist(&clist, &csep, NULL, 0))
933 if (!(kfile = string_nextinlist(&klist, &ksep, NULL, 0)))
934 return tls_error(US"cert/key setup: out of keys", NULL, host, errstr);
935 else if ((rc = tls_add_certfile(state, host, cfile, kfile, errstr)))
936 return rc;
937 else
938 DEBUG(D_tls) debug_printf("TLS: cert/key %s registered\n", cfile);
939 }
940 else
941 {
942 if ((rc = tls_add_certfile(state, host,
943 state->exp_tls_certificate, state->exp_tls_privatekey, errstr)))
944 return rc;
945 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
946 }
947
b34fc30c 948 } /* tls_certificate */
059ec3d9 949
2b4a568d
JH
950
951/* Set the OCSP stapling server info */
952
f2de3a33 953#ifndef DISABLE_OCSP
2b4a568d
JH
954if ( !host /* server */
955 && tls_ocsp_file
956 )
957 {
9196d5bf
JH
958 if (gnutls_buggy_ocsp)
959 {
960 DEBUG(D_tls) debug_printf("GnuTLS library is buggy for OCSP; avoiding\n");
961 }
962 else
963 {
964 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file",
cf0c6164 965 &state->exp_tls_ocsp_file, errstr))
9196d5bf 966 return DEFER;
2b4a568d 967
9196d5bf
JH
968 /* Use the full callback method for stapling just to get observability.
969 More efficient would be to read the file once only, if it never changed
970 (due to SNI). Would need restart on file update, or watch datestamp. */
44662487 971
9196d5bf
JH
972 gnutls_certificate_set_ocsp_status_request_function(state->x509_cred,
973 server_ocsp_stapling_cb, state->exp_tls_ocsp_file);
2b4a568d 974
9196d5bf
JH
975 DEBUG(D_tls) debug_printf("OCSP response file = %s\n", state->exp_tls_ocsp_file);
976 }
2b4a568d
JH
977 }
978#endif
979
980
059ec3d9
PH
981/* Set the trusted CAs file if one is provided, and then add the CRL if one is
982provided. Experiment shows that, if the certificate file is empty, an unhelpful
983error message is provided. However, if we just refrain from setting anything up
984in that case, certificate verification fails, which seems to be the correct
985behaviour. */
986
610ff438 987if (state->tls_verify_certificates && *state->tls_verify_certificates)
059ec3d9 988 {
cf0c6164 989 if (!expand_check_tlsvar(tls_verify_certificates, errstr))
059ec3d9 990 return DEFER;
610ff438
JH
991#ifndef SUPPORT_SYSDEFAULT_CABUNDLE
992 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
993 state->exp_tls_verify_certificates = NULL;
994#endif
17c76198 995 if (state->tls_crl && *state->tls_crl)
cf0c6164 996 if (!expand_check_tlsvar(tls_crl, errstr))
17c76198 997 return DEFER;
059ec3d9 998
1365611d
PP
999 if (!(state->exp_tls_verify_certificates &&
1000 *state->exp_tls_verify_certificates))
b34fc30c
PP
1001 {
1002 DEBUG(D_tls)
1365611d
PP
1003 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
1004 /* With no tls_verify_certificates, we ignore tls_crl too */
17c76198 1005 return OK;
b34fc30c 1006 }
1365611d 1007 }
83e2f8a2
PP
1008else
1009 {
1010 DEBUG(D_tls)
1011 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
1012 return OK;
1013 }
17c76198 1014
cb1d7830
JH
1015#ifdef SUPPORT_SYSDEFAULT_CABUNDLE
1016if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1017 cert_count = gnutls_certificate_set_x509_system_trust(state->x509_cred);
1018else
1019#endif
1365611d 1020 {
cb1d7830
JH
1021 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
1022 {
1023 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
1024 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
1025 strerror(errno));
1026 return DEFER;
1027 }
17c76198 1028
a7fec7a7 1029#ifndef SUPPORT_CA_DIR
cb1d7830
JH
1030 /* The test suite passes in /dev/null; we could check for that path explicitly,
1031 but who knows if someone has some weird FIFO which always dumps some certs, or
1032 other weirdness. The thing we really want to check is that it's not a
1033 directory, since while OpenSSL supports that, GnuTLS does not.
60f914bc 1034 So s/!S_ISREG/S_ISDIR/ and change some messaging ... */
cb1d7830
JH
1035 if (S_ISDIR(statbuf.st_mode))
1036 {
1037 DEBUG(D_tls)
1038 debug_printf("verify certificates path is a dir: \"%s\"\n",
1039 state->exp_tls_verify_certificates);
1040 log_write(0, LOG_MAIN|LOG_PANIC,
1041 "tls_verify_certificates \"%s\" is a directory",
1042 state->exp_tls_verify_certificates);
1043 return DEFER;
1044 }
a7fec7a7 1045#endif
059ec3d9 1046
cb1d7830
JH
1047 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
1048 state->exp_tls_verify_certificates, statbuf.st_size);
059ec3d9 1049
cb1d7830
JH
1050 if (statbuf.st_size == 0)
1051 {
1052 DEBUG(D_tls)
1053 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
1054 return OK;
1055 }
059ec3d9 1056
cb1d7830 1057 cert_count =
a7fec7a7
JH
1058
1059#ifdef SUPPORT_CA_DIR
cb1d7830
JH
1060 (statbuf.st_mode & S_IFMT) == S_IFDIR
1061 ?
1062 gnutls_certificate_set_x509_trust_dir(state->x509_cred,
1063 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM)
1064 :
a7fec7a7 1065#endif
cb1d7830
JH
1066 gnutls_certificate_set_x509_trust_file(state->x509_cred,
1067 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
1068 }
a7fec7a7 1069
1365611d
PP
1070if (cert_count < 0)
1071 {
1072 rc = cert_count;
cb1d7830 1073 exim_gnutls_err_check(US"setting certificate trust");
1365611d
PP
1074 }
1075DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
059ec3d9 1076
5c8cda3a
PP
1077if (state->tls_crl && *state->tls_crl &&
1078 state->exp_tls_crl && *state->exp_tls_crl)
1365611d 1079 {
5c8cda3a
PP
1080 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
1081 cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
1082 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM);
1083 if (cert_count < 0)
1365611d 1084 {
5c8cda3a 1085 rc = cert_count;
1365611d
PP
1086 exim_gnutls_err_check(US"gnutls_certificate_set_x509_crl_file");
1087 }
5c8cda3a 1088 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
1365611d 1089 }
059ec3d9 1090
059ec3d9
PH
1091return OK;
1092}
1093
1094
1095
1096
1365611d
PP
1097/*************************************************
1098* Set X.509 state variables *
1099*************************************************/
1100
1101/* In GnuTLS, the registered cert/key are not replaced by a later
1102set of a cert/key, so for SNI support we need a whole new x509_cred
1103structure. Which means various other non-re-expanded pieces of state
1104need to be re-set in the new struct, so the setting logic is pulled
1105out to this.
1106
1107Arguments:
1108 state exim_gnutls_state_st *
cf0c6164 1109 errstr error string pointer
1365611d
PP
1110
1111Returns: OK/DEFER/FAIL
1112*/
1113
1114static int
cf0c6164 1115tls_set_remaining_x509(exim_gnutls_state_st *state, uschar ** errstr)
1365611d
PP
1116{
1117int rc;
1118const host_item *host = state->host; /* macro should be reconsidered? */
1119
1120/* Create D-H parameters, or read them from the cache file. This function does
1121its own SMTP error messaging. This only happens for the server, TLS D-H ignores
1122client-side params. */
1123
1124if (!state->host)
1125 {
1126 if (!dh_server_params)
1127 {
cf0c6164 1128 rc = init_server_dh(errstr);
1365611d
PP
1129 if (rc != OK) return rc;
1130 }
1131 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
1132 }
1133
1134/* Link the credentials to the session. */
1135
1136rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
1137exim_gnutls_err_check(US"gnutls_credentials_set");
1138
1139return OK;
1140}
1141
059ec3d9 1142/*************************************************
17c76198 1143* Initialize for GnuTLS *
059ec3d9
PH
1144*************************************************/
1145
9196d5bf 1146
4fb7df6d
JH
1147#ifndef DISABLE_OCSP
1148
9196d5bf
JH
1149static BOOL
1150tls_is_buggy_ocsp(void)
1151{
1152const uschar * s;
1153uschar maj, mid, mic;
1154
1155s = CUS gnutls_check_version(NULL);
1156maj = atoi(CCS s);
1157if (maj == 3)
1158 {
1159 while (*s && *s != '.') s++;
1160 mid = atoi(CCS ++s);
1161 if (mid <= 2)
1162 return TRUE;
1163 else if (mid >= 5)
1164 return FALSE;
1165 else
1166 {
1167 while (*s && *s != '.') s++;
1168 mic = atoi(CCS ++s);
1169 return mic <= (mid == 3 ? 16 : 3);
1170 }
1171 }
1172return FALSE;
1173}
1174
4fb7df6d 1175#endif
9196d5bf
JH
1176
1177
17c76198
PP
1178/* Called from both server and client code. In the case of a server, errors
1179before actual TLS negotiation return DEFER.
059ec3d9
PH
1180
1181Arguments:
17c76198
PP
1182 host connected host, if client; NULL if server
1183 certificate certificate file
1184 privatekey private key file
1185 sni TLS SNI to send, sometimes when client; else NULL
1186 cas CA certs file
1187 crl CRL file
1188 require_ciphers tls_require_ciphers setting
817d9f57 1189 caller_state returned state-info structure
cf0c6164 1190 errstr error string pointer
059ec3d9 1191
17c76198 1192Returns: OK/DEFER/FAIL
059ec3d9
PH
1193*/
1194
17c76198
PP
1195static int
1196tls_init(
1197 const host_item *host,
1198 const uschar *certificate,
1199 const uschar *privatekey,
1200 const uschar *sni,
1201 const uschar *cas,
1202 const uschar *crl,
1203 const uschar *require_ciphers,
cf0c6164
JH
1204 exim_gnutls_state_st **caller_state,
1205 uschar ** errstr)
059ec3d9 1206{
17c76198
PP
1207exim_gnutls_state_st *state;
1208int rc;
1209size_t sz;
1210const char *errpos;
1211uschar *p;
1212BOOL want_default_priorities;
1213
1214if (!exim_gnutls_base_init_done)
059ec3d9 1215 {
17c76198
PP
1216 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1217
a5f239e4
PP
1218#ifdef HAVE_GNUTLS_PKCS11
1219 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1220 which loads modules from a config file, which sounds good and may be wanted
1221 by some sysadmin, but also means in common configurations that GNOME keyring
1222 environment variables are used and so breaks for users calling mailq.
1223 To prevent this, we init PKCS11 first, which is the documented approach. */
2519e60d 1224 if (!gnutls_allow_auto_pkcs11)
a5f239e4
PP
1225 {
1226 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
1227 exim_gnutls_err_check(US"gnutls_pkcs11_init");
1228 }
1229#endif
1230
17c76198
PP
1231 rc = gnutls_global_init();
1232 exim_gnutls_err_check(US"gnutls_global_init");
1233
1234#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1235 DEBUG(D_tls)
059ec3d9 1236 {
17c76198
PP
1237 gnutls_global_set_log_function(exim_gnutls_logger_cb);
1238 /* arbitrarily chosen level; bump upto 9 for more */
1239 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
059ec3d9 1240 }
17c76198
PP
1241#endif
1242
4fb7df6d
JH
1243#ifndef DISABLE_OCSP
1244 if (tls_ocsp_file && (gnutls_buggy_ocsp = tls_is_buggy_ocsp()))
9196d5bf 1245 log_write(0, LOG_MAIN, "OCSP unusable with this GnuTLS library version");
4fb7df6d 1246#endif
9196d5bf 1247
17c76198 1248 exim_gnutls_base_init_done = TRUE;
059ec3d9 1249 }
059ec3d9 1250
17c76198
PP
1251if (host)
1252 {
1253 state = &state_client;
1254 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
817d9f57 1255 state->tlsp = &tls_out;
17c76198
PP
1256 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1257 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1258 }
1259else
1260 {
1261 state = &state_server;
1262 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
817d9f57 1263 state->tlsp = &tls_in;
17c76198
PP
1264 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1265 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1266 }
1267exim_gnutls_err_check(US"gnutls_init");
059ec3d9 1268
17c76198 1269state->host = host;
059ec3d9 1270
17c76198
PP
1271state->tls_certificate = certificate;
1272state->tls_privatekey = privatekey;
5779e6aa 1273state->tls_require_ciphers = require_ciphers;
17c76198
PP
1274state->tls_sni = sni;
1275state->tls_verify_certificates = cas;
1276state->tls_crl = crl;
059ec3d9 1277
17c76198
PP
1278/* This handles the variables that might get re-expanded after TLS SNI;
1279that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
059ec3d9 1280
17c76198
PP
1281DEBUG(D_tls)
1282 debug_printf("Expanding various TLS configuration options for session credentials.\n");
cf0c6164 1283if ((rc = tls_expand_session_files(state, errstr)) != OK) return rc;
059ec3d9 1284
1365611d
PP
1285/* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1286requires a new structure afterwards. */
83da1223 1287
cf0c6164 1288if ((rc = tls_set_remaining_x509(state, errstr)) != OK) return rc;
83da1223 1289
17c76198
PP
1290/* set SNI in client, only */
1291if (host)
1292 {
cf0c6164 1293 if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni, errstr))
17c76198 1294 return DEFER;
0df4ab80 1295 if (state->tlsp->sni && *state->tlsp->sni)
17c76198
PP
1296 {
1297 DEBUG(D_tls)
0df4ab80
JH
1298 debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1299 sz = Ustrlen(state->tlsp->sni);
17c76198 1300 rc = gnutls_server_name_set(state->session,
0df4ab80 1301 GNUTLS_NAME_DNS, state->tlsp->sni, sz);
17c76198
PP
1302 exim_gnutls_err_check(US"gnutls_server_name_set");
1303 }
1304 }
1305else if (state->tls_sni)
1306 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
ba86e143 1307 "have an SNI set for a server [%s]\n", state->tls_sni);
83da1223 1308
17c76198 1309/* This is the priority string support,
42bfef1e 1310http://www.gnutls.org/manual/html_node/Priority-Strings.html
17c76198
PP
1311and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1312This was backwards incompatible, but means Exim no longer needs to track
1313all algorithms and provide string forms for them. */
83da1223 1314
17c76198 1315want_default_priorities = TRUE;
83da1223 1316
17c76198 1317if (state->tls_require_ciphers && *state->tls_require_ciphers)
83da1223 1318 {
cf0c6164 1319 if (!expand_check_tlsvar(tls_require_ciphers, errstr))
17c76198
PP
1320 return DEFER;
1321 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
83da1223 1322 {
17c76198
PP
1323 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n",
1324 state->exp_tls_require_ciphers);
1325
1326 rc = gnutls_priority_init(&state->priority_cache,
1327 CS state->exp_tls_require_ciphers, &errpos);
1328 want_default_priorities = FALSE;
1329 p = state->exp_tls_require_ciphers;
83da1223
PH
1330 }
1331 }
17c76198
PP
1332if (want_default_priorities)
1333 {
83e2f8a2
PP
1334 DEBUG(D_tls)
1335 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n",
1336 exim_default_gnutls_priority);
17c76198
PP
1337 rc = gnutls_priority_init(&state->priority_cache,
1338 exim_default_gnutls_priority, &errpos);
1339 p = US exim_default_gnutls_priority;
1340 }
83da1223 1341
17c76198
PP
1342exim_gnutls_err_check(string_sprintf(
1343 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1344 p, errpos - CS p, errpos));
1345
1346rc = gnutls_priority_set(state->session, state->priority_cache);
1347exim_gnutls_err_check(US"gnutls_priority_set");
1348
1349gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1350
1351/* Reduce security in favour of increased compatibility, if the admin
1352decides to make that trade-off. */
1353if (gnutls_compat_mode)
83da1223 1354 {
17c76198
PP
1355#if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1356 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1357 gnutls_session_enable_compatibility_mode(state->session);
1358#else
1359 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1360#endif
83da1223
PH
1361 }
1362
17c76198 1363*caller_state = state;
17c76198 1364return OK;
83da1223
PH
1365}
1366
1367
1368
059ec3d9 1369/*************************************************
17c76198 1370* Extract peer information *
059ec3d9
PH
1371*************************************************/
1372
17c76198 1373/* Called from both server and client code.
4fe99a6c
PP
1374Only this is allowed to set state->peerdn and state->have_set_peerdn
1375and we use that to detect double-calls.
059ec3d9 1376
75fe387d
PP
1377NOTE: the state blocks last while the TLS connection is up, which is fine
1378for logging in the server side, but for the client side, we log after teardown
1379in src/deliver.c. While the session is up, we can twist about states and
1380repoint tls_* globals, but those variables used for logging or other variable
1381expansion that happens _after_ delivery need to have a longer life-time.
1382
1383So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1384doing this more than once per generation of a state context. We set them in
1385the state context, and repoint tls_* to them. After the state goes away, the
1386tls_* copies of the pointers remain valid and client delivery logging is happy.
1387
1388tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1389don't apply.
1390
059ec3d9 1391Arguments:
17c76198 1392 state exim_gnutls_state_st *
cf0c6164 1393 errstr pointer to error string
059ec3d9 1394
17c76198 1395Returns: OK/DEFER/FAIL
059ec3d9
PH
1396*/
1397
17c76198 1398static int
cf0c6164 1399peer_status(exim_gnutls_state_st *state, uschar ** errstr)
059ec3d9 1400{
75fe387d 1401uschar cipherbuf[256];
27f19eb4 1402const gnutls_datum_t *cert_list;
75fe387d 1403int old_pool, rc;
17c76198 1404unsigned int cert_list_size = 0;
4fe99a6c
PP
1405gnutls_protocol_t protocol;
1406gnutls_cipher_algorithm_t cipher;
1407gnutls_kx_algorithm_t kx;
1408gnutls_mac_algorithm_t mac;
17c76198
PP
1409gnutls_certificate_type_t ct;
1410gnutls_x509_crt_t crt;
4fe99a6c 1411uschar *p, *dn_buf;
17c76198 1412size_t sz;
059ec3d9 1413
4fe99a6c 1414if (state->have_set_peerdn)
17c76198 1415 return OK;
4fe99a6c 1416state->have_set_peerdn = TRUE;
059ec3d9 1417
4fe99a6c 1418state->peerdn = NULL;
059ec3d9 1419
4fe99a6c
PP
1420/* tls_cipher */
1421cipher = gnutls_cipher_get(state->session);
1422protocol = gnutls_protocol_get_version(state->session);
1423mac = gnutls_mac_get(state->session);
1424kx = gnutls_kx_get(state->session);
1425
75fe387d 1426string_format(cipherbuf, sizeof(cipherbuf),
4fe99a6c
PP
1427 "%s:%s:%d",
1428 gnutls_protocol_get_name(protocol),
1429 gnutls_cipher_suite_get_name(kx, cipher, mac),
1430 (int) gnutls_cipher_get_key_size(cipher) * 8);
1431
1432/* I don't see a way that spaces could occur, in the current GnuTLS
1433code base, but it was a concern in the old code and perhaps older GnuTLS
1434releases did return "TLS 1.0"; play it safe, just in case. */
75fe387d 1435for (p = cipherbuf; *p != '\0'; ++p)
4fe99a6c
PP
1436 if (isspace(*p))
1437 *p = '-';
75fe387d
PP
1438old_pool = store_pool;
1439store_pool = POOL_PERM;
1440state->ciphersuite = string_copy(cipherbuf);
1441store_pool = old_pool;
817d9f57 1442state->tlsp->cipher = state->ciphersuite;
4fe99a6c
PP
1443
1444/* tls_peerdn */
17c76198 1445cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
83da1223 1446
17c76198
PP
1447if (cert_list == NULL || cert_list_size == 0)
1448 {
17c76198
PP
1449 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1450 cert_list, cert_list_size);
e51c7be2 1451 if (state->verify_requirement >= VERIFY_REQUIRED)
17c76198 1452 return tls_error(US"certificate verification failed",
cf0c6164 1453 "no certificate received from peer", state->host, errstr);
17c76198
PP
1454 return OK;
1455 }
059ec3d9 1456
17c76198
PP
1457ct = gnutls_certificate_type_get(state->session);
1458if (ct != GNUTLS_CRT_X509)
059ec3d9 1459 {
17c76198 1460 const char *ctn = gnutls_certificate_type_get_name(ct);
17c76198
PP
1461 DEBUG(D_tls)
1462 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
e51c7be2 1463 if (state->verify_requirement >= VERIFY_REQUIRED)
17c76198 1464 return tls_error(US"certificate verification not possible, unhandled type",
cf0c6164 1465 ctn, state->host, errstr);
17c76198 1466 return OK;
83da1223 1467 }
059ec3d9 1468
e51c7be2
JH
1469#define exim_gnutls_peer_err(Label) \
1470 do { \
1471 if (rc != GNUTLS_E_SUCCESS) \
1472 { \
1473 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1474 (Label), gnutls_strerror(rc)); \
1475 if (state->verify_requirement >= VERIFY_REQUIRED) \
cf0c6164 1476 return tls_error((Label), gnutls_strerror(rc), state->host, errstr); \
e51c7be2
JH
1477 return OK; \
1478 } \
1479 } while (0)
17c76198 1480
9d1c15ef
JH
1481rc = import_cert(&cert_list[0], &crt);
1482exim_gnutls_peer_err(US"cert 0");
1483
1484state->tlsp->peercert = state->peercert = crt;
17c76198 1485
17c76198
PP
1486sz = 0;
1487rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1488if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
83da1223 1489 {
17c76198
PP
1490 exim_gnutls_peer_err(US"getting size for cert DN failed");
1491 return FAIL; /* should not happen */
059ec3d9 1492 }
17c76198
PP
1493dn_buf = store_get_perm(sz);
1494rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1495exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
9d1c15ef 1496
17c76198
PP
1497state->peerdn = dn_buf;
1498
1499return OK;
1500#undef exim_gnutls_peer_err
1501}
059ec3d9 1502
059ec3d9 1503
059ec3d9 1504
059ec3d9 1505
17c76198
PP
1506/*************************************************
1507* Verify peer certificate *
1508*************************************************/
059ec3d9 1509
17c76198
PP
1510/* Called from both server and client code.
1511*Should* be using a callback registered with
1512gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1513the peer information, but that's too new for some OSes.
059ec3d9 1514
17c76198
PP
1515Arguments:
1516 state exim_gnutls_state_st *
cf0c6164 1517 errstr where to put an error message
059ec3d9 1518
17c76198
PP
1519Returns:
1520 FALSE if the session should be rejected
1521 TRUE if the cert is okay or we just don't care
1522*/
059ec3d9 1523
17c76198 1524static BOOL
cf0c6164 1525verify_certificate(exim_gnutls_state_st *state, uschar ** errstr)
17c76198
PP
1526{
1527int rc;
1528unsigned int verify;
1529
cf0c6164 1530*errstr = NULL;
17c76198 1531
cf0c6164 1532if ((rc = peer_status(state, errstr)) != OK)
e6060e2c 1533 {
17c76198 1534 verify = GNUTLS_CERT_INVALID;
cf0c6164 1535 *errstr = US"certificate not supplied";
17c76198
PP
1536 }
1537else
17c76198 1538 rc = gnutls_certificate_verify_peers2(state->session, &verify);
e6060e2c 1539
17c76198
PP
1540/* Handle the result of verification. INVALID seems to be set as well
1541as REVOKED, but leave the test for both. */
059ec3d9 1542
e51c7be2
JH
1543if (rc < 0 ||
1544 verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED)
1545 )
17c76198
PP
1546 {
1547 state->peer_cert_verified = FALSE;
cf0c6164
JH
1548 if (!*errstr)
1549 *errstr = verify & GNUTLS_CERT_REVOKED
1550 ? US"certificate revoked" : US"certificate invalid";
059ec3d9 1551
17c76198 1552 DEBUG(D_tls)
e51c7be2 1553 debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
cf0c6164 1554 *errstr, state->peerdn ? state->peerdn : US"<unset>");
059ec3d9 1555
e51c7be2 1556 if (state->verify_requirement >= VERIFY_REQUIRED)
17c76198 1557 {
e51c7be2
JH
1558 gnutls_alert_send(state->session,
1559 GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
17c76198
PP
1560 return FALSE;
1561 }
1562 DEBUG(D_tls)
4789da3a 1563 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
17c76198 1564 }
e51c7be2 1565
17c76198
PP
1566else
1567 {
aa2a70ba 1568 if (state->exp_tls_verify_cert_hostnames)
e51c7be2
JH
1569 {
1570 int sep = 0;
55414b25 1571 const uschar * list = state->exp_tls_verify_cert_hostnames;
e51c7be2 1572 uschar * name;
76075bb5 1573 while ((name = string_nextinlist(&list, &sep, NULL, 0)))
e51c7be2
JH
1574 if (gnutls_x509_crt_check_hostname(state->tlsp->peercert, CS name))
1575 break;
1576 if (!name)
1577 {
1578 DEBUG(D_tls)
1579 debug_printf("TLS certificate verification failed: cert name mismatch\n");
aa2a70ba
JH
1580 if (state->verify_requirement >= VERIFY_REQUIRED)
1581 {
1582 gnutls_alert_send(state->session,
1583 GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1584 return FALSE;
1585 }
1586 return TRUE;
e51c7be2
JH
1587 }
1588 }
17c76198 1589 state->peer_cert_verified = TRUE;
e51c7be2 1590 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
4fe99a6c 1591 state->peerdn ? state->peerdn : US"<unset>");
17c76198 1592 }
059ec3d9 1593
817d9f57 1594state->tlsp->peerdn = state->peerdn;
059ec3d9 1595
17c76198
PP
1596return TRUE;
1597}
059ec3d9 1598
17c76198
PP
1599
1600
1601
1602/* ------------------------------------------------------------------------ */
1603/* Callbacks */
1604
1605/* Logging function which can be registered with
1606 * gnutls_global_set_log_function()
1607 * gnutls_global_set_log_level() 0..9
1608 */
af3498d6 1609#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
059ec3d9 1610static void
17c76198 1611exim_gnutls_logger_cb(int level, const char *message)
059ec3d9 1612{
8c79eebf
PP
1613 size_t len = strlen(message);
1614 if (len < 1)
1615 {
1616 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1617 return;
1618 }
1619 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1620 message[len-1] == '\n' ? "" : "\n");
17c76198 1621}
af3498d6 1622#endif
059ec3d9 1623
059ec3d9 1624
17c76198
PP
1625/* Called after client hello, should handle SNI work.
1626This will always set tls_sni (state->received_sni) if available,
1627and may trigger presenting different certificates,
1628if state->trigger_sni_changes is TRUE.
059ec3d9 1629
17c76198
PP
1630Should be registered with
1631 gnutls_handshake_set_post_client_hello_function()
059ec3d9 1632
17c76198
PP
1633"This callback must return 0 on success or a gnutls error code to terminate the
1634handshake.".
059ec3d9 1635
17c76198
PP
1636For inability to get SNI information, we return 0.
1637We only return non-zero if re-setup failed.
817d9f57 1638Only used for server-side TLS.
17c76198 1639*/
44bbabb5 1640
17c76198
PP
1641static int
1642exim_sni_handling_cb(gnutls_session_t session)
1643{
1644char sni_name[MAX_HOST_LEN];
1645size_t data_len = MAX_HOST_LEN;
817d9f57 1646exim_gnutls_state_st *state = &state_server;
17c76198
PP
1647unsigned int sni_type;
1648int rc, old_pool;
cf0c6164 1649uschar * dummy_errstr;
17c76198
PP
1650
1651rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
b34fc30c
PP
1652if (rc != GNUTLS_E_SUCCESS)
1653 {
1654 DEBUG(D_tls) {
1655 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1656 debug_printf("TLS: no SNI presented in handshake.\n");
1657 else
1658 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1659 gnutls_strerror(rc), rc);
cf0c6164 1660 }
b34fc30c
PP
1661 return 0;
1662 }
1663
17c76198
PP
1664if (sni_type != GNUTLS_NAME_DNS)
1665 {
1666 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1667 return 0;
1668 }
44bbabb5 1669
17c76198
PP
1670/* We now have a UTF-8 string in sni_name */
1671old_pool = store_pool;
1672store_pool = POOL_PERM;
1673state->received_sni = string_copyn(US sni_name, data_len);
1674store_pool = old_pool;
1675
1676/* We set this one now so that variable expansions below will work */
817d9f57 1677state->tlsp->sni = state->received_sni;
17c76198
PP
1678
1679DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1680 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1681
1682if (!state->trigger_sni_changes)
1683 return 0;
1684
cf0c6164 1685if ((rc = tls_expand_session_files(state, &dummy_errstr)) != OK)
17c76198
PP
1686 {
1687 /* If the setup of certs/etc failed before handshake, TLS would not have
1688 been offered. The best we can do now is abort. */
1689 return GNUTLS_E_APPLICATION_ERROR_MIN;
1690 }
1691
cf0c6164 1692rc = tls_set_remaining_x509(state, &dummy_errstr);
1365611d
PP
1693if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1694
1695return 0;
059ec3d9
PH
1696}
1697
1698
1699
f2de3a33 1700#ifndef DISABLE_OCSP
44662487
JH
1701
1702static int
1703server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1704 gnutls_datum_t * ocsp_response)
1705{
1706int ret;
1707
44662487
JH
1708if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1709 {
1710 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
5903c6ff 1711 CS ptr);
018058b2 1712 tls_in.ocsp = OCSP_NOT_RESP;
44662487
JH
1713 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1714 }
1715
018058b2 1716tls_in.ocsp = OCSP_VFY_NOT_TRIED;
44662487
JH
1717return 0;
1718}
1719
1720#endif
1721
1722
0cbf2b82 1723#ifndef DISABLE_EVENT
a7538db1
JH
1724/*
1725We use this callback to get observability and detail-level control
723fe533
JH
1726for an exim TLS connection (either direction), raising a tls:cert event
1727for each cert in the chain presented by the peer. Any event
a7538db1
JH
1728can deny verification.
1729
1730Return 0 for the handshake to continue or non-zero to terminate.
1731*/
1732
1733static int
723fe533 1734verify_cb(gnutls_session_t session)
a7538db1 1735{
27f19eb4 1736const gnutls_datum_t * cert_list;
a7538db1
JH
1737unsigned int cert_list_size = 0;
1738gnutls_x509_crt_t crt;
1739int rc;
b30275b8 1740uschar * yield;
a7538db1
JH
1741exim_gnutls_state_st * state = gnutls_session_get_ptr(session);
1742
1743cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
1744if (cert_list)
1745 while (cert_list_size--)
1746 {
1747 rc = import_cert(&cert_list[cert_list_size], &crt);
1748 if (rc != GNUTLS_E_SUCCESS)
1749 {
1750 DEBUG(D_tls) debug_printf("TLS: peer cert problem: depth %d: %s\n",
1751 cert_list_size, gnutls_strerror(rc));
1752 break;
1753 }
1754
1755 state->tlsp->peercert = crt;
b30275b8
JH
1756 if ((yield = event_raise(state->event_action,
1757 US"tls:cert", string_sprintf("%d", cert_list_size))))
a7538db1
JH
1758 {
1759 log_write(0, LOG_MAIN,
b30275b8
JH
1760 "SSL verify denied by event-action: depth=%d: %s",
1761 cert_list_size, yield);
a7538db1
JH
1762 return 1; /* reject */
1763 }
1764 state->tlsp->peercert = NULL;
1765 }
1766
1767return 0;
1768}
1769
1770#endif
44662487
JH
1771
1772
17c76198
PP
1773
1774/* ------------------------------------------------------------------------ */
1775/* Exported functions */
1776
1777
1778
1779
059ec3d9
PH
1780/*************************************************
1781* Start a TLS session in a server *
1782*************************************************/
1783
1784/* This is called when Exim is running as a server, after having received
1785the STARTTLS command. It must respond to that command, and then negotiate
1786a TLS session.
1787
1788Arguments:
83da1223 1789 require_ciphers list of allowed ciphers or NULL
cf0c6164 1790 errstr pointer to error string
059ec3d9
PH
1791
1792Returns: OK on success
1793 DEFER for errors before the start of the negotiation
4c04137d 1794 FAIL for errors during the negotiation; the server can't
059ec3d9
PH
1795 continue running.
1796*/
1797
1798int
cf0c6164 1799tls_server_start(const uschar * require_ciphers, uschar ** errstr)
059ec3d9
PH
1800{
1801int rc;
cf0c6164 1802exim_gnutls_state_st * state = NULL;
059ec3d9
PH
1803
1804/* Check for previous activation */
817d9f57 1805if (tls_in.active >= 0)
059ec3d9 1806 {
cf0c6164 1807 tls_error(US"STARTTLS received after TLS started", "", NULL, errstr);
925ac8e4 1808 smtp_printf("554 Already in TLS\r\n", FALSE);
059ec3d9
PH
1809 return FAIL;
1810 }
1811
1812/* Initialize the library. If it fails, it will already have logged the error
1813and sent an SMTP response. */
1814
17c76198 1815DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
059ec3d9 1816
cf0c6164 1817if ((rc = tls_init(NULL, tls_certificate, tls_privatekey,
17c76198 1818 NULL, tls_verify_certificates, tls_crl,
cf0c6164 1819 require_ciphers, &state, errstr)) != OK) return rc;
059ec3d9 1820
059ec3d9
PH
1821/* If this is a host for which certificate verification is mandatory or
1822optional, set up appropriately. */
1823
059ec3d9 1824if (verify_check_host(&tls_verify_hosts) == OK)
17c76198 1825 {
e51c7be2
JH
1826 DEBUG(D_tls)
1827 debug_printf("TLS: a client certificate will be required.\n");
17c76198
PP
1828 state->verify_requirement = VERIFY_REQUIRED;
1829 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1830 }
059ec3d9 1831else if (verify_check_host(&tls_try_verify_hosts) == OK)
17c76198 1832 {
e51c7be2
JH
1833 DEBUG(D_tls)
1834 debug_printf("TLS: a client certificate will be requested but not required.\n");
17c76198
PP
1835 state->verify_requirement = VERIFY_OPTIONAL;
1836 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1837 }
1838else
1839 {
e51c7be2
JH
1840 DEBUG(D_tls)
1841 debug_printf("TLS: a client certificate will not be requested.\n");
17c76198
PP
1842 state->verify_requirement = VERIFY_NONE;
1843 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1844 }
059ec3d9 1845
0cbf2b82 1846#ifndef DISABLE_EVENT
723fe533
JH
1847if (event_action)
1848 {
1849 state->event_action = event_action;
1850 gnutls_session_set_ptr(state->session, state);
1851 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
1852 }
1853#endif
1854
17c76198
PP
1855/* Register SNI handling; always, even if not in tls_certificate, so that the
1856expansion variable $tls_sni is always available. */
059ec3d9 1857
17c76198
PP
1858gnutls_handshake_set_post_client_hello_function(state->session,
1859 exim_sni_handling_cb);
059ec3d9
PH
1860
1861/* Set context and tell client to go ahead, except in the case of TLS startup
1862on connection, where outputting anything now upsets the clients and tends to
1863make them disconnect. We need to have an explicit fflush() here, to force out
1864the response. Other smtp_printf() calls do not need it, because in non-TLS
1865mode, the fflush() happens when smtp_getc() is called. */
1866
817d9f57 1867if (!state->tlsp->on_connect)
059ec3d9 1868 {
925ac8e4 1869 smtp_printf("220 TLS go ahead\r\n", FALSE);
9d1c15ef 1870 fflush(smtp_out);
059ec3d9
PH
1871 }
1872
1873/* Now negotiate the TLS session. We put our own timer on it, since it seems
1874that the GnuTLS library doesn't. */
1875
17c76198 1876gnutls_transport_set_ptr2(state->session,
27f19eb4
JH
1877 (gnutls_transport_ptr_t)(long) fileno(smtp_in),
1878 (gnutls_transport_ptr_t)(long) fileno(smtp_out));
17c76198
PP
1879state->fd_in = fileno(smtp_in);
1880state->fd_out = fileno(smtp_out);
059ec3d9
PH
1881
1882sigalrm_seen = FALSE;
1883if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
17c76198 1884do
17c76198 1885 rc = gnutls_handshake(state->session);
157a7880 1886while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
059ec3d9
PH
1887alarm(0);
1888
17c76198 1889if (rc != GNUTLS_E_SUCCESS)
059ec3d9 1890 {
059ec3d9
PH
1891 /* It seems that, except in the case of a timeout, we have to close the
1892 connection right here; otherwise if the other end is running OpenSSL it hangs
1893 until the server times out. */
1894
60d10ce7 1895 if (sigalrm_seen)
ad7fc6eb 1896 {
cf0c6164 1897 tls_error(US"gnutls_handshake", "timed out", NULL, errstr);
ad7fc6eb
JH
1898 gnutls_db_remove_session(state->session);
1899 }
60d10ce7 1900 else
059ec3d9 1901 {
cf0c6164 1902 tls_error(US"gnutls_handshake", gnutls_strerror(rc), NULL, errstr);
f5d25c2b 1903 (void) gnutls_alert_send_appropriate(state->session, rc);
ad7fc6eb 1904 gnutls_deinit(state->session);
ed62aae3 1905 gnutls_certificate_free_credentials(state->x509_cred);
60d10ce7 1906 millisleep(500);
ad7fc6eb 1907 shutdown(state->fd_out, SHUT_WR);
60d10ce7 1908 for (rc = 1024; fgetc(smtp_in) != EOF && rc > 0; ) rc--; /* drain skt */
f1e894f3
PH
1909 (void)fclose(smtp_out);
1910 (void)fclose(smtp_in);
60d10ce7 1911 smtp_out = smtp_in = NULL;
059ec3d9
PH
1912 }
1913
1914 return FAIL;
1915 }
1916
1917DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1918
17c76198
PP
1919/* Verify after the fact */
1920
9d1c15ef 1921if ( state->verify_requirement != VERIFY_NONE
cf0c6164 1922 && !verify_certificate(state, errstr))
059ec3d9 1923 {
9d1c15ef 1924 if (state->verify_requirement != VERIFY_OPTIONAL)
17c76198 1925 {
cf0c6164 1926 (void) tls_error(US"certificate verification failed", *errstr, NULL, errstr);
9d1c15ef 1927 return FAIL;
17c76198 1928 }
9d1c15ef
JH
1929 DEBUG(D_tls)
1930 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
cf0c6164 1931 *errstr);
059ec3d9
PH
1932 }
1933
17c76198
PP
1934/* Figure out peer DN, and if authenticated, etc. */
1935
cf0c6164 1936if ((rc = peer_status(state, NULL)) != OK) return rc;
17c76198
PP
1937
1938/* Sets various Exim expansion variables; always safe within server */
1939
9d1c15ef 1940extract_exim_vars_from_tls_state(state);
059ec3d9
PH
1941
1942/* TLS has been set up. Adjust the input functions to read via TLS,
1943and initialize appropriately. */
1944
17c76198 1945state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
059ec3d9
PH
1946
1947receive_getc = tls_getc;
0d81dabc 1948receive_getbuf = tls_getbuf;
584e96c6 1949receive_get_cache = tls_get_cache;
059ec3d9
PH
1950receive_ungetc = tls_ungetc;
1951receive_feof = tls_feof;
1952receive_ferror = tls_ferror;
58eb016e 1953receive_smtp_buffered = tls_smtp_buffered;
059ec3d9 1954
059ec3d9
PH
1955return OK;
1956}
1957
1958
1959
1960
aa2a70ba
JH
1961static void
1962tls_client_setup_hostname_checks(host_item * host, exim_gnutls_state_st * state,
1963 smtp_transport_options_block * ob)
1964{
5130845b 1965if (verify_check_given_host(&ob->tls_verify_cert_hostnames, host) == OK)
aa2a70ba 1966 {
4af0d74a 1967 state->exp_tls_verify_cert_hostnames =
8c5d388a 1968#ifdef SUPPORT_I18N
4af0d74a
JH
1969 string_domain_utf8_to_alabel(host->name, NULL);
1970#else
1971 host->name;
1972#endif
aa2a70ba
JH
1973 DEBUG(D_tls)
1974 debug_printf("TLS: server cert verification includes hostname: \"%s\".\n",
1975 state->exp_tls_verify_cert_hostnames);
1976 }
1977}
aa2a70ba
JH
1978
1979
059ec3d9
PH
1980/*************************************************
1981* Start a TLS session in a client *
1982*************************************************/
1983
1984/* Called from the smtp transport after STARTTLS has been accepted.
1985
1986Arguments:
1987 fd the fd of the connection
1988 host connected host (for messages)
83da1223 1989 addr the first address (not used)
a7538db1 1990 tb transport (always smtp)
059ec3d9 1991
cf0c6164
JH
1992 errstr error string pointer
1993
059ec3d9
PH
1994Returns: OK/DEFER/FAIL (because using common functions),
1995 but for a client, DEFER and FAIL have the same meaning
1996*/
1997
1998int
17c76198 1999tls_client_start(int fd, host_item *host,
f5d78688 2000 address_item *addr ARG_UNUSED,
cf0c6164 2001 transport_instance * tb,
0e66b3b6 2002#ifdef EXPERIMENTAL_DANE
cf0c6164 2003 dns_answer * tlsa_dnsa ARG_UNUSED,
0e66b3b6 2004#endif
cf0c6164 2005 uschar ** errstr)
059ec3d9 2006{
a7538db1
JH
2007smtp_transport_options_block *ob =
2008 (smtp_transport_options_block *)tb->options_block;
059ec3d9 2009int rc;
17c76198 2010exim_gnutls_state_st *state = NULL;
f2de3a33 2011#ifndef DISABLE_OCSP
5130845b
JH
2012BOOL require_ocsp =
2013 verify_check_given_host(&ob->hosts_require_ocsp, host) == OK;
44662487 2014BOOL request_ocsp = require_ocsp ? TRUE
5130845b 2015 : verify_check_given_host(&ob->hosts_request_ocsp, host) == OK;
2b4a568d 2016#endif
059ec3d9 2017
17c76198 2018DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
059ec3d9 2019
65867078
JH
2020if ((rc = tls_init(host, ob->tls_certificate, ob->tls_privatekey,
2021 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
cf0c6164 2022 ob->tls_require_ciphers, &state, errstr)) != OK)
2b4a568d 2023 return rc;
059ec3d9 2024
54c90be1 2025 {
65867078
JH
2026 int dh_min_bits = ob->tls_dh_min_bits;
2027 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
2028 {
2029 DEBUG(D_tls)
2030 debug_printf("WARNING: tls_dh_min_bits far too low,"
2031 " clamping %d up to %d\n",
2032 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
2033 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
2034 }
54c90be1 2035
65867078
JH
2036 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
2037 " acceptable bits to %d\n",
2038 dh_min_bits);
2039 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
2040 }
83da1223 2041
94431adb 2042/* Stick to the old behaviour for compatibility if tls_verify_certificates is
2b4a568d
JH
2043set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
2044the specified host patterns if one of them is defined */
2045
aa2a70ba
JH
2046if ( ( state->exp_tls_verify_certificates
2047 && !ob->tls_verify_hosts
610ff438 2048 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
aa2a70ba 2049 )
5130845b 2050 || verify_check_given_host(&ob->tls_verify_hosts, host) == OK
2b4a568d 2051 )
17c76198 2052 {
aa2a70ba 2053 tls_client_setup_hostname_checks(host, state, ob);
aa2a70ba
JH
2054 DEBUG(D_tls)
2055 debug_printf("TLS: server certificate verification required.\n");
2056 state->verify_requirement = VERIFY_REQUIRED;
52f93eed
WB
2057 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2058 }
5130845b 2059else if (verify_check_given_host(&ob->tls_try_verify_hosts, host) == OK)
52f93eed 2060 {
aa2a70ba 2061 tls_client_setup_hostname_checks(host, state, ob);
e51c7be2
JH
2062 DEBUG(D_tls)
2063 debug_printf("TLS: server certificate verification optional.\n");
52f93eed 2064 state->verify_requirement = VERIFY_OPTIONAL;
17c76198
PP
2065 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2066 }
2067else
2068 {
e51c7be2
JH
2069 DEBUG(D_tls)
2070 debug_printf("TLS: server certificate verification not required.\n");
52f93eed
WB
2071 state->verify_requirement = VERIFY_NONE;
2072 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
17c76198 2073 }
059ec3d9 2074
f2de3a33
JH
2075#ifndef DISABLE_OCSP
2076 /* supported since GnuTLS 3.1.3 */
44662487 2077if (request_ocsp)
9d1c15ef
JH
2078 {
2079 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
65867078
JH
2080 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
2081 NULL, 0, NULL)) != OK)
9d1c15ef 2082 return tls_error(US"cert-status-req",
cf0c6164 2083 gnutls_strerror(rc), state->host, errstr);
44662487 2084 tls_out.ocsp = OCSP_NOT_RESP;
9d1c15ef 2085 }
2b4a568d
JH
2086#endif
2087
0cbf2b82 2088#ifndef DISABLE_EVENT
774ef2d7 2089if (tb->event_action)
a7538db1 2090 {
774ef2d7 2091 state->event_action = tb->event_action;
a7538db1 2092 gnutls_session_set_ptr(state->session, state);
723fe533 2093 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
a7538db1
JH
2094 }
2095#endif
2096
27f19eb4 2097gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr_t)(long) fd);
17c76198
PP
2098state->fd_in = fd;
2099state->fd_out = fd;
059ec3d9 2100
9d1c15ef 2101DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
059ec3d9
PH
2102/* There doesn't seem to be a built-in timeout on connection. */
2103
2104sigalrm_seen = FALSE;
65867078 2105alarm(ob->command_timeout);
17c76198
PP
2106do
2107 {
2108 rc = gnutls_handshake(state->session);
619b2b25
PP
2109 } while ((rc == GNUTLS_E_AGAIN) ||
2110 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
059ec3d9
PH
2111alarm(0);
2112
4fe99a6c 2113if (rc != GNUTLS_E_SUCCESS)
60d10ce7
JH
2114 if (sigalrm_seen)
2115 {
2116 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_USER_CANCELED);
cf0c6164 2117 return tls_error(US"gnutls_handshake", "timed out", state->host, errstr);
60d10ce7
JH
2118 }
2119 else
cf0c6164 2120 return tls_error(US"gnutls_handshake", gnutls_strerror(rc), state->host, errstr);
4fe99a6c 2121
17c76198 2122DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
059ec3d9 2123
17c76198 2124/* Verify late */
059ec3d9 2125
17c76198 2126if (state->verify_requirement != VERIFY_NONE &&
cf0c6164
JH
2127 !verify_certificate(state, errstr))
2128 return tls_error(US"certificate verification failed", *errstr, state->host, errstr);
059ec3d9 2129
f2de3a33 2130#ifndef DISABLE_OCSP
2b4a568d
JH
2131if (require_ocsp)
2132 {
2133 DEBUG(D_tls)
2134 {
2135 gnutls_datum_t stapling;
2136 gnutls_ocsp_resp_t resp;
2137 gnutls_datum_t printed;
2138 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
2139 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
2140 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
2141 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
2142 )
2143 {
65867078 2144 debug_printf("%.4096s", printed.data);
2b4a568d
JH
2145 gnutls_free(printed.data);
2146 }
2147 else
cf0c6164 2148 (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host, errstr);
2b4a568d
JH
2149 }
2150
2b4a568d 2151 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
018058b2
JH
2152 {
2153 tls_out.ocsp = OCSP_FAILED;
cf0c6164 2154 return tls_error(US"certificate status check failed", NULL, state->host, errstr);
018058b2 2155 }
2b4a568d 2156 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
44662487 2157 tls_out.ocsp = OCSP_VFIED;
2b4a568d
JH
2158 }
2159#endif
2160
17c76198 2161/* Figure out peer DN, and if authenticated, etc. */
059ec3d9 2162
cf0c6164 2163if ((rc = peer_status(state, errstr)) != OK)
2b4a568d 2164 return rc;
059ec3d9 2165
4fe99a6c 2166/* Sets various Exim expansion variables; may need to adjust for ACL callouts */
059ec3d9 2167
9d1c15ef 2168extract_exim_vars_from_tls_state(state);
059ec3d9 2169
059ec3d9
PH
2170return OK;
2171}
2172
2173
2174
17c76198 2175
059ec3d9 2176/*************************************************
17c76198 2177* Close down a TLS session *
059ec3d9
PH
2178*************************************************/
2179
17c76198
PP
2180/* This is also called from within a delivery subprocess forked from the
2181daemon, to shut down the TLS library, without actually doing a shutdown (which
2182would tamper with the TLS session in the parent process).
059ec3d9 2183
17c76198
PP
2184Arguments: TRUE if gnutls_bye is to be called
2185Returns: nothing
059ec3d9
PH
2186*/
2187
17c76198 2188void
817d9f57 2189tls_close(BOOL is_server, BOOL shutdown)
059ec3d9 2190{
817d9f57 2191exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
059ec3d9 2192
389ca47a 2193if (!state->tlsp || state->tlsp->active < 0) return; /* TLS was not active */
17c76198
PP
2194
2195if (shutdown)
2196 {
f5723109 2197 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
17c76198
PP
2198 gnutls_bye(state->session, GNUTLS_SHUT_WR);
2199 }
2200
2201gnutls_deinit(state->session);
ed62aae3
HSHR
2202gnutls_certificate_free_credentials(state->x509_cred);
2203
17c76198 2204
389ca47a 2205state->tlsp->active = -1;
17c76198
PP
2206memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
2207
2208if ((state_server.session == NULL) && (state_client.session == NULL))
2209 {
2210 gnutls_global_deinit();
2211 exim_gnutls_base_init_done = FALSE;
2212 }
059ec3d9
PH
2213}
2214
2215
2216
17c76198 2217
0d81dabc
JH
2218static BOOL
2219tls_refill(unsigned lim)
2220{
2221exim_gnutls_state_st * state = &state_server;
2222ssize_t inbytes;
2223
2224DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
2225 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
2226
2227if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2228inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
2229 MIN(ssl_xfer_buffer_size, lim));
2230alarm(0);
2231
2232/* Timeouts do not get this far; see command_timeout_handler().
2233 A zero-byte return appears to mean that the TLS session has been
2234 closed down, not that the socket itself has been closed down. Revert to
2235 non-TLS handling. */
2236
2237if (sigalrm_seen)
2238 {
2239 DEBUG(D_tls) debug_printf("Got tls read timeout\n");
2240 state->xfer_error = 1;
2241 return FALSE;
2242 }
2243
2244else if (inbytes == 0)
2245 {
2246 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2247
2248 receive_getc = smtp_getc;
2249 receive_getbuf = smtp_getbuf;
2250 receive_get_cache = smtp_get_cache;
2251 receive_ungetc = smtp_ungetc;
2252 receive_feof = smtp_feof;
2253 receive_ferror = smtp_ferror;
2254 receive_smtp_buffered = smtp_buffered;
2255
2256 gnutls_deinit(state->session);
2257 gnutls_certificate_free_credentials(state->x509_cred);
2258
2259 state->session = NULL;
2260 state->tlsp->active = -1;
2261 state->tlsp->bits = 0;
2262 state->tlsp->certificate_verified = FALSE;
2263 tls_channelbinding_b64 = NULL;
2264 state->tlsp->cipher = NULL;
2265 state->tlsp->peercert = NULL;
2266 state->tlsp->peerdn = NULL;
2267
2268 return FALSE;
2269 }
2270
2271/* Handle genuine errors */
2272
2273else if (inbytes < 0)
2274 {
2275 record_io_error(state, (int) inbytes, US"recv", NULL);
2276 state->xfer_error = 1;
2277 return FALSE;
2278 }
2279#ifndef DISABLE_DKIM
2280dkim_exim_verify_feed(state->xfer_buffer, inbytes);
2281#endif
2282state->xfer_buffer_hwm = (int) inbytes;
2283state->xfer_buffer_lwm = 0;
2284return TRUE;
2285}
2286
059ec3d9
PH
2287/*************************************************
2288* TLS version of getc *
2289*************************************************/
2290
2291/* This gets the next byte from the TLS input buffer. If the buffer is empty,
2292it refills the buffer via the GnuTLS reading function.
817d9f57 2293Only used by the server-side TLS.
059ec3d9 2294
17c76198
PP
2295This feeds DKIM and should be used for all message-body reads.
2296
bd8fbe36 2297Arguments: lim Maximum amount to read/bufffer
059ec3d9
PH
2298Returns: the next character or EOF
2299*/
2300
2301int
bd8fbe36 2302tls_getc(unsigned lim)
059ec3d9 2303{
0d81dabc 2304exim_gnutls_state_st * state = &state_server;
059ec3d9 2305
0d81dabc
JH
2306if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2307 if (!tls_refill(lim))
2308 return state->xfer_error ? EOF : smtp_getc(lim);
ed62aae3 2309
0d81dabc 2310/* Something in the buffer; return next uschar */
059ec3d9 2311
0d81dabc
JH
2312return state->xfer_buffer[state->xfer_buffer_lwm++];
2313}
059ec3d9 2314
0d81dabc
JH
2315uschar *
2316tls_getbuf(unsigned * len)
2317{
2318exim_gnutls_state_st * state = &state_server;
2319unsigned size;
2320uschar * buf;
059ec3d9 2321
0d81dabc
JH
2322if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2323 if (!tls_refill(*len))
059ec3d9 2324 {
0d81dabc
JH
2325 if (!state->xfer_error) return smtp_getbuf(len);
2326 *len = 0;
2327 return NULL;
059ec3d9 2328 }
059ec3d9 2329
0d81dabc
JH
2330if ((size = state->xfer_buffer_hwm - state->xfer_buffer_lwm) > *len)
2331 size = *len;
2332buf = &state->xfer_buffer[state->xfer_buffer_lwm];
2333state->xfer_buffer_lwm += size;
2334*len = size;
2335return buf;
059ec3d9
PH
2336}
2337
0d81dabc 2338
584e96c6
JH
2339void
2340tls_get_cache()
2341{
9960d1e5 2342#ifndef DISABLE_DKIM
584e96c6
JH
2343exim_gnutls_state_st * state = &state_server;
2344int n = state->xfer_buffer_hwm - state->xfer_buffer_lwm;
2345if (n > 0)
2346 dkim_exim_verify_feed(state->xfer_buffer+state->xfer_buffer_lwm, n);
584e96c6 2347#endif
9960d1e5 2348}
584e96c6 2349
059ec3d9 2350
925ac8e4
JH
2351BOOL
2352tls_could_read(void)
2353{
2354return state_server.xfer_buffer_lwm < state_server.xfer_buffer_hwm
2355 || gnutls_record_check_pending(state_server.session) > 0;
2356}
2357
2358
059ec3d9 2359
17c76198 2360
059ec3d9
PH
2361/*************************************************
2362* Read bytes from TLS channel *
2363*************************************************/
2364
17c76198
PP
2365/* This does not feed DKIM, so if the caller uses this for reading message body,
2366then the caller must feed DKIM.
817d9f57 2367
059ec3d9
PH
2368Arguments:
2369 buff buffer of data
2370 len size of buffer
2371
2372Returns: the number of bytes read
2373 -1 after a failed read
2374*/
2375
2376int
817d9f57 2377tls_read(BOOL is_server, uschar *buff, size_t len)
059ec3d9 2378{
817d9f57 2379exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
17c76198 2380ssize_t inbytes;
059ec3d9 2381
17c76198
PP
2382if (len > INT_MAX)
2383 len = INT_MAX;
059ec3d9 2384
17c76198
PP
2385if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
2386 DEBUG(D_tls)
2387 debug_printf("*** PROBABLY A BUG *** " \
2388 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
2389 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
2390
2391DEBUG(D_tls)
2392 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
2393 state->session, buff, len);
2394
2395inbytes = gnutls_record_recv(state->session, buff, len);
059ec3d9
PH
2396if (inbytes > 0) return inbytes;
2397if (inbytes == 0)
2398 {
2399 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2400 }
17c76198 2401else record_io_error(state, (int)inbytes, US"recv", NULL);
059ec3d9
PH
2402
2403return -1;
2404}
2405
2406
2407
17c76198 2408
059ec3d9
PH
2409/*************************************************
2410* Write bytes down TLS channel *
2411*************************************************/
2412
2413/*
2414Arguments:
817d9f57 2415 is_server channel specifier
059ec3d9
PH
2416 buff buffer of data
2417 len number of bytes
925ac8e4 2418 more more data expected soon
059ec3d9
PH
2419
2420Returns: the number of bytes after a successful write,
2421 -1 after a failed write
2422*/
2423
2424int
925ac8e4 2425tls_write(BOOL is_server, const uschar *buff, size_t len, BOOL more)
059ec3d9 2426{
17c76198
PP
2427ssize_t outbytes;
2428size_t left = len;
817d9f57 2429exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
925ac8e4
JH
2430#ifdef SUPPORT_CORK
2431static BOOL corked = FALSE;
2432
2433if (more && !corked) gnutls_record_cork(state->session);
2434#endif
2435
2436DEBUG(D_tls) debug_printf("%s(%p, " SIZE_T_FMT "%s)\n", __FUNCTION__,
2437 buff, left, more ? ", more" : "");
059ec3d9 2438
059ec3d9
PH
2439while (left > 0)
2440 {
17c76198
PP
2441 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
2442 buff, left);
2443 outbytes = gnutls_record_send(state->session, buff, left);
059ec3d9 2444
17c76198 2445 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
059ec3d9
PH
2446 if (outbytes < 0)
2447 {
17c76198 2448 record_io_error(state, outbytes, US"send", NULL);
059ec3d9
PH
2449 return -1;
2450 }
2451 if (outbytes == 0)
2452 {
17c76198 2453 record_io_error(state, 0, US"send", US"TLS channel closed on write");
059ec3d9
PH
2454 return -1;
2455 }
2456
2457 left -= outbytes;
2458 buff += outbytes;
2459 }
2460
17c76198
PP
2461if (len > INT_MAX)
2462 {
2463 DEBUG(D_tls)
2464 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
2465 len);
2466 len = INT_MAX;
2467 }
2468
925ac8e4
JH
2469#ifdef SUPPORT_CORK
2470if (more != corked)
2471 {
2472 if (!more) (void) gnutls_record_uncork(state->session, 0);
2473 corked = more;
2474 }
2475#endif
2476
17c76198 2477return (int) len;
059ec3d9
PH
2478}
2479
2480
2481
17c76198 2482
059ec3d9 2483/*************************************************
17c76198 2484* Random number generation *
059ec3d9
PH
2485*************************************************/
2486
17c76198
PP
2487/* Pseudo-random number generation. The result is not expected to be
2488cryptographically strong but not so weak that someone will shoot themselves
2489in the foot using it as a nonce in input in some email header scheme or
2490whatever weirdness they'll twist this into. The result should handle fork()
2491and avoid repeating sequences. OpenSSL handles that for us.
059ec3d9 2492
17c76198
PP
2493Arguments:
2494 max range maximum
2495Returns a random number in range [0, max-1]
059ec3d9
PH
2496*/
2497
af3498d6 2498#ifdef HAVE_GNUTLS_RND
17c76198
PP
2499int
2500vaguely_random_number(int max)
059ec3d9 2501{
17c76198
PP
2502unsigned int r;
2503int i, needed_len;
2504uschar *p;
2505uschar smallbuf[sizeof(r)];
2506
2507if (max <= 1)
2508 return 0;
2509
2510needed_len = sizeof(r);
2511/* Don't take 8 times more entropy than needed if int is 8 octets and we were
2512 * asked for a number less than 10. */
2513for (r = max, i = 0; r; ++i)
2514 r >>= 1;
2515i = (i + 7) / 8;
2516if (i < needed_len)
2517 needed_len = i;
2518
2519i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2520if (i < 0)
059ec3d9 2521 {
17c76198
PP
2522 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2523 return vaguely_random_number_fallback(max);
2524 }
2525r = 0;
2526for (p = smallbuf; needed_len; --needed_len, ++p)
2527 {
2528 r *= 256;
2529 r += *p;
059ec3d9
PH
2530 }
2531
17c76198
PP
2532/* We don't particularly care about weighted results; if someone wants
2533 * smooth distribution and cares enough then they should submit a patch then. */
2534return r % max;
059ec3d9 2535}
af3498d6
PP
2536#else /* HAVE_GNUTLS_RND */
2537int
2538vaguely_random_number(int max)
2539{
2540 return vaguely_random_number_fallback(max);
2541}
2542#endif /* HAVE_GNUTLS_RND */
059ec3d9 2543
36f12725
NM
2544
2545
2546
3375e053
PP
2547/*************************************************
2548* Let tls_require_ciphers be checked at startup *
2549*************************************************/
2550
2551/* The tls_require_ciphers option, if set, must be something which the
2552library can parse.
2553
2554Returns: NULL on success, or error message
2555*/
2556
2557uschar *
2558tls_validate_require_cipher(void)
2559{
2560int rc;
2561uschar *expciphers = NULL;
2562gnutls_priority_t priority_cache;
2563const char *errpos;
cf0c6164 2564uschar * dummy_errstr;
3375e053
PP
2565
2566#define validate_check_rc(Label) do { \
2567 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
2568 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
2569#define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
2570
2571if (exim_gnutls_base_init_done)
2572 log_write(0, LOG_MAIN|LOG_PANIC,
2573 "already initialised GnuTLS, Exim developer bug");
2574
a5f239e4 2575#ifdef HAVE_GNUTLS_PKCS11
2519e60d 2576if (!gnutls_allow_auto_pkcs11)
a5f239e4
PP
2577 {
2578 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2579 validate_check_rc(US"gnutls_pkcs11_init");
2580 }
2581#endif
3375e053
PP
2582rc = gnutls_global_init();
2583validate_check_rc(US"gnutls_global_init()");
2584exim_gnutls_base_init_done = TRUE;
2585
2586if (!(tls_require_ciphers && *tls_require_ciphers))
2587 return_deinit(NULL);
2588
cf0c6164
JH
2589if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
2590 &dummy_errstr))
3375e053
PP
2591 return_deinit(US"failed to expand tls_require_ciphers");
2592
2593if (!(expciphers && *expciphers))
2594 return_deinit(NULL);
2595
2596DEBUG(D_tls)
2597 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2598
2599rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2600validate_check_rc(string_sprintf(
2601 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
2602 expciphers, errpos - CS expciphers, errpos));
2603
2604#undef return_deinit
2605#undef validate_check_rc
2606gnutls_global_deinit();
2607
2608return NULL;
2609}
2610
2611
2612
2613
36f12725
NM
2614/*************************************************
2615* Report the library versions. *
2616*************************************************/
2617
2618/* See a description in tls-openssl.c for an explanation of why this exists.
2619
2620Arguments: a FILE* to print the results to
2621Returns: nothing
2622*/
2623
2624void
2625tls_version_report(FILE *f)
2626{
754a0503
PP
2627fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2628 " Runtime: %s\n",
2629 LIBGNUTLS_VERSION,
2630 gnutls_check_version(NULL));
36f12725
NM
2631}
2632
2b4a568d
JH
2633/* vi: aw ai sw=2
2634*/
059ec3d9 2635/* End of tls-gnu.c */