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