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