1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
8 /* Copyright (c) Phil Pennock 2012 */
10 /* This file provides TLS/SSL support for Exim using the GnuTLS library,
11 one of the available supported implementations. This file is #included into
12 tls.c when USE_GNUTLS has been set.
14 The code herein is a revamp of GnuTLS integration using the current APIs; the
15 original tls-gnu.c was based on a patch which was contributed by Nikos
16 Mavrogiannopoulos. The revamp is partially a rewrite, partially cut&paste as
19 APIs current as of GnuTLS 2.12.18; note that the GnuTLS manual is for GnuTLS 3,
20 which is not widely deployed by OS vendors. Will note issues below, which may
21 assist in updating the code in the future. Another sources of hints is
22 mod_gnutls for Apache (SNI callback registration and handling).
24 Keeping client and server variables more split than before and is currently
25 the norm, in anticipation of TLS in ACL callouts.
27 I wanted to switch to gnutls_certificate_set_verify_function() so that
28 certificate rejection could happen during handshake where it belongs, rather
29 than 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.
32 (I wasn't looking for libraries quite that old, when updating to get rid of
33 compiler warnings of deprecated APIs. If it turns out that a lot of the rest
34 require current GnuTLS, then we'll drop support for the ancient libraries).
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>
43 /* needed to disable PKCS11 autoload unless requested */
44 #if GNUTLS_VERSION_NUMBER >= 0x020c00
45 # include <gnutls/pkcs11.h>
46 # define SUPPORT_PARAM_TO_PK_BITS
48 #if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
49 # warning "GnuTLS library version too old; define DISABLE_OCSP in Makefile"
52 #if GNUTLS_VERSION_NUMBER < 0x020a00 && !defined(DISABLE_EVENT)
53 # warning "GnuTLS library version too old; tls:cert event unsupported"
54 # define DISABLE_EVENT
56 #if GNUTLS_VERSION_NUMBER >= 0x030306
57 # define SUPPORT_CA_DIR
59 # undef SUPPORT_CA_DIR
61 #if GNUTLS_VERSION_NUMBER >= 0x030014
62 # define SUPPORT_SYSDEFAULT_CABUNDLE
64 #if GNUTLS_VERSION_NUMBER >= 0x030104
65 # define GNUTLS_CERT_VFY_STATUS_PRINT
67 #if GNUTLS_VERSION_NUMBER >= 0x030109
70 #if GNUTLS_VERSION_NUMBER >= 0x03010a
71 # define SUPPORT_GNUTLS_SESS_DESC
73 #if GNUTLS_VERSION_NUMBER >= 0x030506 && !defined(DISABLE_OCSP)
74 # define SUPPORT_SRV_OCSP_STACK
78 # if GNUTLS_VERSION_NUMBER >= 0x030000
79 # define DANESSL_USAGE_DANE_TA 2
80 # define DANESSL_USAGE_DANE_EE 3
82 # error GnuTLS version too early for DANE
84 # if GNUTLS_VERSION_NUMBER < 0x999999
85 # define GNUTLS_BROKEN_DANE_VALIDATION
90 # include <gnutls/ocsp.h>
93 # include <gnutls/dane.h>
99 gnutls_global_set_audit_log_function()
102 gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
105 /* Local static variables for GnuTLS */
107 /* Values for verify_requirement */
109 enum peer_verify_requirement
110 { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED, VERIFY_DANE };
112 /* This holds most state for server or client; with this, we can set up an
113 outbound TLS-enabled connection in an ACL callout, while not stomping all
114 over the TLS variables available for expansion.
116 Some of these correspond to variables in globals.c; those variables will
117 be set to point to content in one of these instances, as appropriate for
118 the stage of the process lifetime.
120 Not handled here: global tls_channelbinding_b64.
123 typedef struct exim_gnutls_state {
124 gnutls_session_t session;
125 gnutls_certificate_credentials_t x509_cred;
126 gnutls_priority_t priority_cache;
127 enum peer_verify_requirement verify_requirement;
131 BOOL peer_cert_verified:1;
132 BOOL peer_dane_verified:1;
133 BOOL trigger_sni_changes:1;
134 BOOL have_set_peerdn:1;
135 BOOL xfer_eof:1; /*XXX never gets set! */
141 const struct host_item *host; /* NULL if server */
142 gnutls_x509_crt_t peercert;
145 uschar *received_sni;
147 const uschar *tls_certificate;
148 const uschar *tls_privatekey;
149 const uschar *tls_sni; /* client send only, not received */
150 const uschar *tls_verify_certificates;
151 const uschar *tls_crl;
152 const uschar *tls_require_ciphers;
154 uschar *exp_tls_certificate;
155 uschar *exp_tls_privatekey;
156 uschar *exp_tls_verify_certificates;
158 uschar *exp_tls_require_ciphers;
159 const uschar *exp_tls_verify_cert_hostnames;
160 #ifndef DISABLE_EVENT
161 uschar *event_action;
164 char * const * dane_data;
165 const int * dane_data_len;
168 tls_support *tlsp; /* set in tls_init() */
173 } exim_gnutls_state_st;
175 static const exim_gnutls_state_st exim_gnutls_state_init = {
178 .priority_cache = NULL,
179 .verify_requirement = VERIFY_NONE,
182 .peer_cert_verified = FALSE,
183 .peer_dane_verified = FALSE,
184 .trigger_sni_changes =FALSE,
185 .have_set_peerdn = FALSE,
190 .received_sni = NULL,
192 .tls_certificate = NULL,
193 .tls_privatekey = NULL,
195 .tls_verify_certificates = NULL,
197 .tls_require_ciphers =NULL,
199 .exp_tls_certificate = NULL,
200 .exp_tls_privatekey = NULL,
201 .exp_tls_verify_certificates = NULL,
203 .exp_tls_require_ciphers = NULL,
204 .exp_tls_verify_cert_hostnames = NULL,
205 #ifndef DISABLE_EVENT
206 .event_action = NULL,
211 .xfer_buffer_lwm = 0,
212 .xfer_buffer_hwm = 0,
217 /* Not only do we have our own APIs which don't pass around state, assuming
218 it's held in globals, GnuTLS doesn't appear to let us register callback data
219 for callbacks, or as part of the session, so we have to keep a "this is the
220 context we're currently dealing with" pointer and rely upon being
221 single-threaded to keep from processing data on an inbound TLS connection while
222 talking to another TLS connection for an outbound check. This does mean that
223 there's no way for heart-beats to be responded to, for the duration of the
225 XXX But see gnutls_session_get_ptr()
228 static exim_gnutls_state_st state_server;
230 /* dh_params are initialised once within the lifetime of a process using TLS;
231 if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
232 don't want to repeat this. */
234 static gnutls_dh_params_t dh_server_params = NULL;
236 /* No idea how this value was chosen; preserving it. Default is 3600. */
238 static const int ssl_session_timeout = 200;
240 static const uschar * const exim_default_gnutls_priority = US"NORMAL";
242 /* Guard library core initialisation */
244 static BOOL exim_gnutls_base_init_done = FALSE;
247 static BOOL gnutls_buggy_ocsp = FALSE;
251 /* ------------------------------------------------------------------------ */
254 #define MAX_HOST_LEN 255
256 /* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
257 the library logging; a value less than 0 disables the calls to set up logging
258 callbacks. Possibly GNuTLS also looks for an environment variable
259 "GNUTLS_DEBUG_LEVEL". */
260 #ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
261 # define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
264 #ifndef EXIM_CLIENT_DH_MIN_BITS
265 # define EXIM_CLIENT_DH_MIN_BITS 1024
268 /* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
269 can ask for a bit-strength. Without that, we stick to the constant we had
271 #ifndef EXIM_SERVER_DH_BITS_PRE2_12
272 # define EXIM_SERVER_DH_BITS_PRE2_12 1024
275 #define exim_gnutls_err_check(rc, Label) do { \
276 if ((rc) != GNUTLS_E_SUCCESS) \
277 return tls_error((Label), US gnutls_strerror(rc), host, errstr); \
280 #define expand_check_tlsvar(Varname, errstr) \
281 expand_check(state->Varname, US #Varname, &state->exp_##Varname, errstr)
283 #if GNUTLS_VERSION_NUMBER >= 0x020c00
284 # define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
285 # define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
286 # define HAVE_GNUTLS_RND
287 /* The security fix we provide with the gnutls_allow_auto_pkcs11 option
288 * (4.82 PP/09) introduces a compatibility regression. The symbol simply
289 * isn't available sometimes, so this needs to become a conditional
290 * compilation; the sanest way to deal with this being a problem on
291 * older OSes is to block it in the Local/Makefile with this compiler
293 # ifndef AVOID_GNUTLS_PKCS11
294 # define HAVE_GNUTLS_PKCS11
295 # endif /* AVOID_GNUTLS_PKCS11 */
301 /* ------------------------------------------------------------------------ */
302 /* Callback declarations */
304 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
305 static void exim_gnutls_logger_cb(int level, const char *message);
308 static int exim_sni_handling_cb(gnutls_session_t session);
311 static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
312 gnutls_datum_t * ocsp_response);
317 /* ------------------------------------------------------------------------ */
318 /* Static functions */
320 /*************************************************
322 *************************************************/
324 /* Called from lots of places when errors occur before actually starting to do
325 the TLS handshake, that is, while the session is still in clear. Always returns
326 DEFER for a server and FAIL for a client so that most calls can use "return
327 tls_error(...)" to do this processing and then give an appropriate return. A
328 single function is used for both server and client, because it is called from
329 some shared functions.
332 prefix text to include in the logged error
333 msg additional error string (may be NULL)
334 usually obtained from gnutls_strerror()
335 host NULL if setting up a server;
336 the connected host if setting up a client
337 errstr pointer to returned error string
339 Returns: OK/DEFER/FAIL
343 tls_error(const uschar *prefix, const uschar *msg, const host_item *host,
347 *errstr = string_sprintf("(%s)%s%s", prefix, msg ? ": " : "", msg ? msg : US"");
348 return host ? FAIL : DEFER;
354 /*************************************************
355 * Deal with logging errors during I/O *
356 *************************************************/
358 /* We have to get the identity of the peer from saved data.
361 state the current GnuTLS exim state container
362 rc the GnuTLS error code, or 0 if it's a local error
363 when text identifying read or write
364 text local error text when ec is 0
370 record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
375 if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
376 msg = string_sprintf("%s: %s", US gnutls_strerror(rc),
377 US gnutls_alert_get_name(gnutls_alert_get(state->session)));
379 msg = US gnutls_strerror(rc);
381 (void) tls_error(when, msg, state->host, &errstr);
384 log_write(0, LOG_MAIN, "H=%s [%s] TLS error on connection %s",
385 state->host->name, state->host->address, errstr);
388 uschar * conn_info = smtp_get_connection_info();
389 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0) conn_info += 5;
390 /* I'd like to get separated H= here, but too hard for now */
391 log_write(0, LOG_MAIN, "TLS error on %s %s", conn_info, errstr);
398 /*************************************************
399 * Set various Exim expansion vars *
400 *************************************************/
402 #define exim_gnutls_cert_err(Label) \
405 if (rc != GNUTLS_E_SUCCESS) \
407 DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", \
408 (Label), gnutls_strerror(rc)); \
414 import_cert(const gnutls_datum_t * cert, gnutls_x509_crt_t * crtp)
418 rc = gnutls_x509_crt_init(crtp);
419 exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
421 rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
422 exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
427 #undef exim_gnutls_cert_err
430 /* We set various Exim global variables from the state, once a session has
431 been established. With TLS callouts, may need to change this to stack
432 variables, or just re-call it with the server state after client callout
435 Make sure anything set here is unset in tls_getc().
439 tls_bits strength indicator
440 tls_certificate_verified bool indicator
441 tls_channelbinding_b64 for some SASL mechanisms
443 tls_peercert pointer to library internal
445 tls_sni a (UTF-8) string
446 tls_ourcert pointer to library internal
449 state the relevant exim_gnutls_state_st *
453 extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
455 gnutls_cipher_algorithm_t cipher;
456 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
459 gnutls_datum_t channel;
461 tls_support * tlsp = state->tlsp;
463 tlsp->active.sock = state->fd_out;
464 tlsp->active.tls_ctx = state;
466 cipher = gnutls_cipher_get(state->session);
467 /* returns size in "bytes" */
468 tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
470 tlsp->cipher = state->ciphersuite;
472 DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
474 tlsp->certificate_verified = state->peer_cert_verified;
476 tlsp->dane_verified = state->peer_dane_verified;
479 /* note that tls_channelbinding_b64 is not saved to the spool file, since it's
480 only available for use for authenticators while this TLS session is running. */
482 tls_channelbinding_b64 = NULL;
483 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
486 rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel);
488 DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc));
490 old_pool = store_pool;
491 store_pool = POOL_PERM;
492 tls_channelbinding_b64 = b64encode(channel.data, (int)channel.size);
493 store_pool = old_pool;
494 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
498 /* peercert is set in peer_status() */
499 tlsp->peerdn = state->peerdn;
500 tlsp->sni = state->received_sni;
502 /* record our certificate */
504 const gnutls_datum_t * cert = gnutls_certificate_get_ours(state->session);
505 gnutls_x509_crt_t crt;
507 tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
514 /*************************************************
515 * Setup up DH parameters *
516 *************************************************/
518 /* Generating the D-H parameters may take a long time. They only need to
519 be re-generated every so often, depending on security policy. What we do is to
520 keep these parameters in a file in the spool directory. If the file does not
521 exist, we generate them. This means that it is easy to cause a regeneration.
523 The new file is written as a temporary file and renamed, so that an incomplete
524 file is never present. If two processes both compute some new parameters, you
525 waste a bit of effort, but it doesn't seem worth messing around with locking to
528 Returns: OK/DEFER/FAIL
532 init_server_dh(uschar ** errstr)
535 unsigned int dh_bits;
537 uschar filename_buf[PATH_MAX];
538 uschar *filename = NULL;
540 uschar *exp_tls_dhparam;
541 BOOL use_file_in_spool = FALSE;
542 BOOL use_fixed_file = FALSE;
543 host_item *host = NULL; /* dummy for macros */
545 DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
547 rc = gnutls_dh_params_init(&dh_server_params);
548 exim_gnutls_err_check(rc, US"gnutls_dh_params_init");
553 if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam, errstr))
556 if (!exp_tls_dhparam)
558 DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
559 m.data = US std_dh_prime_default();
560 m.size = Ustrlen(m.data);
562 else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
563 use_file_in_spool = TRUE;
564 else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
566 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
569 else if (exp_tls_dhparam[0] != '/')
571 if (!(m.data = US std_dh_prime_named(exp_tls_dhparam)))
572 return tls_error(US"No standard prime named", exp_tls_dhparam, NULL, errstr);
573 m.size = Ustrlen(m.data);
577 use_fixed_file = TRUE;
578 filename = exp_tls_dhparam;
583 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
584 exim_gnutls_err_check(rc, US"gnutls_dh_params_import_pkcs3");
585 DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
589 #ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
590 /* If you change this constant, also change dh_param_fn_ext so that we can use a
591 different filename and ensure we have sufficient bits. */
592 dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
594 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL, errstr);
596 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
599 dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
601 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
605 /* Some clients have hard-coded limits. */
606 if (dh_bits > tls_dh_max_bits)
609 debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
611 dh_bits = tls_dh_max_bits;
614 if (use_file_in_spool)
616 if (!string_format(filename_buf, sizeof(filename_buf),
617 "%s/gnutls-params-%d", spool_directory, dh_bits))
618 return tls_error(US"overlong filename", NULL, NULL, errstr);
619 filename = filename_buf;
622 /* Open the cache file for reading and if successful, read it and set up the
625 if ((fd = Uopen(filename, O_RDONLY, 0)) >= 0)
631 if (fstat(fd, &statbuf) < 0) /* EIO */
635 return tls_error(US"TLS cache stat failed", US strerror(saved_errno), NULL, errstr);
637 if (!S_ISREG(statbuf.st_mode))
640 return tls_error(US"TLS cache not a file", NULL, NULL, errstr);
642 if (!(fp = fdopen(fd, "rb")))
646 return tls_error(US"fdopen(TLS cache stat fd) failed",
647 US strerror(saved_errno), NULL, errstr);
650 m.size = statbuf.st_size;
651 if (!(m.data = malloc(m.size)))
654 return tls_error(US"malloc failed", US strerror(errno), NULL, errstr);
656 if (!(sz = fread(m.data, m.size, 1, fp)))
661 return tls_error(US"fread failed", US strerror(saved_errno), NULL, errstr);
665 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
667 exim_gnutls_err_check(rc, US"gnutls_dh_params_import_pkcs3");
668 DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
671 /* If the file does not exist, fall through to compute new data and cache it.
672 If there was any other opening error, it is serious. */
674 else if (errno == ENOENT)
678 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
681 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
684 /* If ret < 0, either the cache file does not exist, or the data it contains
685 is not useful. One particular case of this is when upgrading from an older
686 release of Exim in which the data was stored in a different format. We don't
687 try to be clever and support both formats; we just regenerate new data in this
693 unsigned int dh_bits_gen = dh_bits;
695 if ((PATH_MAX - Ustrlen(filename)) < 10)
696 return tls_error(US"Filename too long to generate replacement",
697 filename, NULL, errstr);
699 temp_fn = string_copy(US"%s.XXXXXXX");
700 if ((fd = mkstemp(CS temp_fn)) < 0) /* modifies temp_fn */
701 return tls_error(US"Unable to open temp file", US strerror(errno), NULL, errstr);
702 (void)fchown(fd, exim_uid, exim_gid); /* Probably not necessary */
704 /* GnuTLS overshoots!
705 * If we ask for 2236, we might get 2237 or more.
706 * But there's no way to ask GnuTLS how many bits there really are.
707 * We can ask how many bits were used in a TLS session, but that's it!
708 * The prime itself is hidden behind too much abstraction.
709 * So we ask for less, and proceed on a wing and a prayer.
710 * First attempt, subtracted 3 for 2233 and got 2240.
712 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
714 dh_bits_gen = dh_bits - 10;
716 debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
721 debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
723 rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen);
724 exim_gnutls_err_check(rc, US"gnutls_dh_params_generate2");
726 /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
727 and I confirmed that a NULL call to get the size first is how the GnuTLS
728 sample apps handle this. */
732 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
734 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
735 exim_gnutls_err_check(rc, US"gnutls_dh_params_export_pkcs3(NULL) sizing");
737 if (!(m.data = malloc(m.size)))
738 return tls_error(US"memory allocation failed", US strerror(errno), NULL, errstr);
740 /* this will return a size 1 less than the allocation size above */
741 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
743 if (rc != GNUTLS_E_SUCCESS)
746 exim_gnutls_err_check(rc, US"gnutls_dh_params_export_pkcs3() real");
748 m.size = sz; /* shrink by 1, probably */
750 if ((sz = write_to_fd_buf(fd, m.data, (size_t) m.size)) != m.size)
753 return tls_error(US"TLS cache write D-H params failed",
754 US strerror(errno), NULL, errstr);
757 if ((sz = write_to_fd_buf(fd, US"\n", 1)) != 1)
758 return tls_error(US"TLS cache write D-H params final newline failed",
759 US strerror(errno), NULL, errstr);
761 if ((rc = close(fd)))
762 return tls_error(US"TLS cache write close() failed", US strerror(errno), NULL, errstr);
764 if (Urename(temp_fn, filename) < 0)
765 return tls_error(string_sprintf("failed to rename \"%s\" as \"%s\"",
766 temp_fn, filename), US strerror(errno), NULL, errstr);
768 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
771 DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
778 /* Create and install a selfsigned certificate, for use in server mode */
781 tls_install_selfsign(exim_gnutls_state_st * state, uschar ** errstr)
783 gnutls_x509_crt_t cert = NULL;
785 gnutls_x509_privkey_t pkey = NULL;
786 const uschar * where;
789 where = US"initialising pkey";
790 if ((rc = gnutls_x509_privkey_init(&pkey))) goto err;
792 where = US"initialising cert";
793 if ((rc = gnutls_x509_crt_init(&cert))) goto err;
795 where = US"generating pkey";
796 if ((rc = gnutls_x509_privkey_generate(pkey, GNUTLS_PK_RSA,
797 #ifdef SUPPORT_PARAM_TO_PK_BITS
798 # ifndef GNUTLS_SEC_PARAM_MEDIUM
799 # define GNUTLS_SEC_PARAM_MEDIUM GNUTLS_SEC_PARAM_HIGH
801 gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_MEDIUM),
808 where = US"configuring cert";
810 if ( (rc = gnutls_x509_crt_set_version(cert, 3))
811 || (rc = gnutls_x509_crt_set_serial(cert, &now, sizeof(now)))
812 || (rc = gnutls_x509_crt_set_activation_time(cert, now = time(NULL)))
813 || (rc = gnutls_x509_crt_set_expiration_time(cert, now + 60 * 60)) /* 1 hr */
814 || (rc = gnutls_x509_crt_set_key(cert, pkey))
816 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
817 GNUTLS_OID_X520_COUNTRY_NAME, 0, "UK", 2))
818 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
819 GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "Exim Developers", 15))
820 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
821 GNUTLS_OID_X520_COMMON_NAME, 0,
822 smtp_active_hostname, Ustrlen(smtp_active_hostname)))
826 where = US"signing cert";
827 if ((rc = gnutls_x509_crt_sign(cert, cert, pkey))) goto err;
829 where = US"installing selfsign cert";
831 if ((rc = gnutls_certificate_set_x509_key(state->x509_cred, &cert, 1, pkey)))
837 if (cert) gnutls_x509_crt_deinit(cert);
838 if (pkey) gnutls_x509_privkey_deinit(pkey);
842 rc = tls_error(where, US gnutls_strerror(rc), NULL, errstr);
849 /* Add certificate and key, from files.
852 Zero or negative: good. Negate value for certificate index if < 0.
853 Greater than zero: FAIL or DEFER code.
857 tls_add_certfile(exim_gnutls_state_st * state, const host_item * host,
858 uschar * certfile, uschar * keyfile, uschar ** errstr)
860 int rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
861 CS certfile, CS keyfile, GNUTLS_X509_FMT_PEM);
864 string_sprintf("cert/key setup: cert=%s key=%s", certfile, keyfile),
865 US gnutls_strerror(rc), host, errstr);
870 /*************************************************
871 * Variables re-expanded post-SNI *
872 *************************************************/
874 /* Called from both server and client code, via tls_init(), and also from
875 the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
877 We can tell the two apart by state->received_sni being non-NULL in callback.
879 The callback should not call us unless state->trigger_sni_changes is true,
880 which we are responsible for setting on the first pass through.
883 state exim_gnutls_state_st *
884 errstr error string pointer
886 Returns: OK/DEFER/FAIL
890 tls_expand_session_files(exim_gnutls_state_st * state, uschar ** errstr)
894 const host_item *host = state->host; /* macro should be reconsidered? */
895 uschar *saved_tls_certificate = NULL;
896 uschar *saved_tls_privatekey = NULL;
897 uschar *saved_tls_verify_certificates = NULL;
898 uschar *saved_tls_crl = NULL;
901 /* We check for tls_sni *before* expansion. */
902 if (!host) /* server */
903 if (!state->received_sni)
905 if ( state->tls_certificate
906 && ( Ustrstr(state->tls_certificate, US"tls_sni")
907 || Ustrstr(state->tls_certificate, US"tls_in_sni")
908 || Ustrstr(state->tls_certificate, US"tls_out_sni")
911 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
912 state->trigger_sni_changes = TRUE;
917 /* useful for debugging */
918 saved_tls_certificate = state->exp_tls_certificate;
919 saved_tls_privatekey = state->exp_tls_privatekey;
920 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
921 saved_tls_crl = state->exp_tls_crl;
924 rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
925 exim_gnutls_err_check(rc, US"gnutls_certificate_allocate_credentials");
927 #ifdef SUPPORT_SRV_OCSP_STACK
928 gnutls_certificate_set_flags(state->x509_cred, GNUTLS_CERTIFICATE_API_V2);
931 /* remember: expand_check_tlsvar() is expand_check() but fiddling with
932 state members, assuming consistent naming; and expand_check() returns
933 false if expansion failed, unless expansion was forced to fail. */
935 /* check if we at least have a certificate, before doing expensive
938 if (!expand_check_tlsvar(tls_certificate, errstr))
941 /* certificate is mandatory in server, optional in client */
943 if ( !state->exp_tls_certificate
944 || !*state->exp_tls_certificate
947 return tls_install_selfsign(state, errstr);
949 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
951 if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey, errstr))
954 /* tls_privatekey is optional, defaulting to same file as certificate */
956 if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
958 state->tls_privatekey = state->tls_certificate;
959 state->exp_tls_privatekey = state->exp_tls_certificate;
963 if (state->exp_tls_certificate && *state->exp_tls_certificate)
965 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
966 state->exp_tls_certificate, state->exp_tls_privatekey);
968 if (state->received_sni)
969 if ( Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0
970 && Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0
973 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
977 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
980 if (!host) /* server */
982 const uschar * clist = state->exp_tls_certificate;
983 const uschar * klist = state->exp_tls_privatekey;
984 const uschar * olist;
985 int csep = 0, ksep = 0, osep = 0, cnt = 0;
986 uschar * cfile, * kfile, * ofile;
989 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file", &ofile, errstr))
994 while (cfile = string_nextinlist(&clist, &csep, NULL, 0))
996 if (!(kfile = string_nextinlist(&klist, &ksep, NULL, 0)))
997 return tls_error(US"cert/key setup: out of keys", NULL, host, errstr);
998 else if (0 < (rc = tls_add_certfile(state, host, cfile, kfile, errstr)))
1002 int gnutls_cert_index = -rc;
1003 DEBUG(D_tls) debug_printf("TLS: cert/key %s registered\n", cfile);
1005 /* Set the OCSP stapling server info */
1007 #ifndef DISABLE_OCSP
1009 if (gnutls_buggy_ocsp)
1012 debug_printf("GnuTLS library is buggy for OCSP; avoiding\n");
1014 else if ((ofile = string_nextinlist(&olist, &osep, NULL, 0)))
1016 /* Use the full callback method for stapling just to get
1017 observability. More efficient would be to read the file once only,
1018 if it never changed (due to SNI). Would need restart on file update,
1019 or watch datestamp. */
1021 # ifdef SUPPORT_SRV_OCSP_STACK
1022 rc = gnutls_certificate_set_ocsp_status_request_function2(
1023 state->x509_cred, gnutls_cert_index,
1024 server_ocsp_stapling_cb, ofile);
1026 exim_gnutls_err_check(rc,
1027 US"gnutls_certificate_set_ocsp_status_request_function2");
1032 debug_printf("oops; multiple OCSP files not supported\n");
1035 gnutls_certificate_set_ocsp_status_request_function(
1036 state->x509_cred, server_ocsp_stapling_cb, ofile);
1039 DEBUG(D_tls) debug_printf("OCSP response file = %s\n", ofile);
1042 DEBUG(D_tls) debug_printf("ran out of OCSP response files in list\n");
1048 if (0 < (rc = tls_add_certfile(state, host,
1049 state->exp_tls_certificate, state->exp_tls_privatekey, errstr)))
1051 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
1054 } /* tls_certificate */
1057 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
1058 provided. Experiment shows that, if the certificate file is empty, an unhelpful
1059 error message is provided. However, if we just refrain from setting anything up
1060 in that case, certificate verification fails, which seems to be the correct
1063 if (state->tls_verify_certificates && *state->tls_verify_certificates)
1065 if (!expand_check_tlsvar(tls_verify_certificates, errstr))
1067 #ifndef SUPPORT_SYSDEFAULT_CABUNDLE
1068 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1069 state->exp_tls_verify_certificates = NULL;
1071 if (state->tls_crl && *state->tls_crl)
1072 if (!expand_check_tlsvar(tls_crl, errstr))
1075 if (!(state->exp_tls_verify_certificates &&
1076 *state->exp_tls_verify_certificates))
1079 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
1080 /* With no tls_verify_certificates, we ignore tls_crl too */
1087 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
1091 #ifdef SUPPORT_SYSDEFAULT_CABUNDLE
1092 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1093 cert_count = gnutls_certificate_set_x509_system_trust(state->x509_cred);
1097 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
1099 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
1100 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
1105 #ifndef SUPPORT_CA_DIR
1106 /* The test suite passes in /dev/null; we could check for that path explicitly,
1107 but who knows if someone has some weird FIFO which always dumps some certs, or
1108 other weirdness. The thing we really want to check is that it's not a
1109 directory, since while OpenSSL supports that, GnuTLS does not.
1110 So s/!S_ISREG/S_ISDIR/ and change some messaging ... */
1111 if (S_ISDIR(statbuf.st_mode))
1114 debug_printf("verify certificates path is a dir: \"%s\"\n",
1115 state->exp_tls_verify_certificates);
1116 log_write(0, LOG_MAIN|LOG_PANIC,
1117 "tls_verify_certificates \"%s\" is a directory",
1118 state->exp_tls_verify_certificates);
1123 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
1124 state->exp_tls_verify_certificates, statbuf.st_size);
1126 if (statbuf.st_size == 0)
1129 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
1135 #ifdef SUPPORT_CA_DIR
1136 (statbuf.st_mode & S_IFMT) == S_IFDIR
1138 gnutls_certificate_set_x509_trust_dir(state->x509_cred,
1139 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM)
1142 gnutls_certificate_set_x509_trust_file(state->x509_cred,
1143 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
1145 #ifdef SUPPORT_CA_DIR
1146 /* Mimic the behaviour with OpenSSL of not advertising a usable-cert list
1147 when using the directory-of-certs config model. */
1149 if ((statbuf.st_mode & S_IFMT) == S_IFDIR)
1150 gnutls_certificate_send_x509_rdn_sequence(state->session, 1);
1157 exim_gnutls_err_check(rc, US"setting certificate trust");
1159 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
1161 if (state->tls_crl && *state->tls_crl &&
1162 state->exp_tls_crl && *state->exp_tls_crl)
1164 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
1165 cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
1166 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM);
1170 exim_gnutls_err_check(rc, US"gnutls_certificate_set_x509_crl_file");
1172 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
1181 /*************************************************
1182 * Set X.509 state variables *
1183 *************************************************/
1185 /* In GnuTLS, the registered cert/key are not replaced by a later
1186 set of a cert/key, so for SNI support we need a whole new x509_cred
1187 structure. Which means various other non-re-expanded pieces of state
1188 need to be re-set in the new struct, so the setting logic is pulled
1192 state exim_gnutls_state_st *
1193 errstr error string pointer
1195 Returns: OK/DEFER/FAIL
1199 tls_set_remaining_x509(exim_gnutls_state_st *state, uschar ** errstr)
1202 const host_item *host = state->host; /* macro should be reconsidered? */
1204 /* Create D-H parameters, or read them from the cache file. This function does
1205 its own SMTP error messaging. This only happens for the server, TLS D-H ignores
1206 client-side params. */
1210 if (!dh_server_params)
1212 rc = init_server_dh(errstr);
1213 if (rc != OK) return rc;
1215 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
1218 /* Link the credentials to the session. */
1220 rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
1221 exim_gnutls_err_check(rc, US"gnutls_credentials_set");
1226 /*************************************************
1227 * Initialize for GnuTLS *
1228 *************************************************/
1231 #ifndef DISABLE_OCSP
1234 tls_is_buggy_ocsp(void)
1237 uschar maj, mid, mic;
1239 s = CUS gnutls_check_version(NULL);
1243 while (*s && *s != '.') s++;
1244 mid = atoi(CCS ++s);
1251 while (*s && *s != '.') s++;
1252 mic = atoi(CCS ++s);
1253 return mic <= (mid == 3 ? 16 : 3);
1262 /* Called from both server and client code. In the case of a server, errors
1263 before actual TLS negotiation return DEFER.
1266 host connected host, if client; NULL if server
1267 certificate certificate file
1268 privatekey private key file
1269 sni TLS SNI to send, sometimes when client; else NULL
1272 require_ciphers tls_require_ciphers setting
1273 caller_state returned state-info structure
1274 errstr error string pointer
1276 Returns: OK/DEFER/FAIL
1281 const host_item *host,
1282 const uschar *certificate,
1283 const uschar *privatekey,
1287 const uschar *require_ciphers,
1288 exim_gnutls_state_st **caller_state,
1292 exim_gnutls_state_st *state;
1298 if (!exim_gnutls_base_init_done)
1300 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1302 #ifdef HAVE_GNUTLS_PKCS11
1303 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1304 which loads modules from a config file, which sounds good and may be wanted
1305 by some sysadmin, but also means in common configurations that GNOME keyring
1306 environment variables are used and so breaks for users calling mailq.
1307 To prevent this, we init PKCS11 first, which is the documented approach. */
1308 if (!gnutls_allow_auto_pkcs11)
1310 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
1311 exim_gnutls_err_check(rc, US"gnutls_pkcs11_init");
1315 rc = gnutls_global_init();
1316 exim_gnutls_err_check(rc, US"gnutls_global_init");
1318 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1321 gnutls_global_set_log_function(exim_gnutls_logger_cb);
1322 /* arbitrarily chosen level; bump up to 9 for more */
1323 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
1327 #ifndef DISABLE_OCSP
1328 if (tls_ocsp_file && (gnutls_buggy_ocsp = tls_is_buggy_ocsp()))
1329 log_write(0, LOG_MAIN, "OCSP unusable with this GnuTLS library version");
1332 exim_gnutls_base_init_done = TRUE;
1337 /* For client-side sessions we allocate a context. This lets us run
1338 several in parallel. */
1339 int old_pool = store_pool;
1340 store_pool = POOL_PERM;
1341 state = store_get(sizeof(exim_gnutls_state_st));
1342 store_pool = old_pool;
1344 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1346 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1347 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1351 state = &state_server;
1352 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1354 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1355 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1357 exim_gnutls_err_check(rc, US"gnutls_init");
1361 state->tls_certificate = certificate;
1362 state->tls_privatekey = privatekey;
1363 state->tls_require_ciphers = require_ciphers;
1364 state->tls_sni = sni;
1365 state->tls_verify_certificates = cas;
1366 state->tls_crl = crl;
1368 /* This handles the variables that might get re-expanded after TLS SNI;
1369 that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1372 debug_printf("Expanding various TLS configuration options for session credentials.\n");
1373 if ((rc = tls_expand_session_files(state, errstr)) != OK) return rc;
1375 /* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1376 requires a new structure afterwards. */
1378 if ((rc = tls_set_remaining_x509(state, errstr)) != OK) return rc;
1380 /* set SNI in client, only */
1383 if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni, errstr))
1385 if (state->tlsp->sni && *state->tlsp->sni)
1388 debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1389 sz = Ustrlen(state->tlsp->sni);
1390 rc = gnutls_server_name_set(state->session,
1391 GNUTLS_NAME_DNS, state->tlsp->sni, sz);
1392 exim_gnutls_err_check(rc, US"gnutls_server_name_set");
1395 else if (state->tls_sni)
1396 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1397 "have an SNI set for a server [%s]\n", state->tls_sni);
1399 /* This is the priority string support,
1400 http://www.gnutls.org/manual/html_node/Priority-Strings.html
1401 and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1402 This was backwards incompatible, but means Exim no longer needs to track
1403 all algorithms and provide string forms for them. */
1406 if (state->tls_require_ciphers && *state->tls_require_ciphers)
1408 if (!expand_check_tlsvar(tls_require_ciphers, errstr))
1410 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1412 p = state->exp_tls_require_ciphers;
1413 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n", p);
1418 p = exim_default_gnutls_priority;
1420 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n", p);
1422 rc = gnutls_priority_init(&state->priority_cache, CCS p, &errpos);
1424 exim_gnutls_err_check(rc, string_sprintf(
1425 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1426 p, errpos - CS p, errpos));
1428 rc = gnutls_priority_set(state->session, state->priority_cache);
1429 exim_gnutls_err_check(rc, US"gnutls_priority_set");
1431 gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1433 /* Reduce security in favour of increased compatibility, if the admin
1434 decides to make that trade-off. */
1435 if (gnutls_compat_mode)
1437 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1438 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1439 gnutls_session_enable_compatibility_mode(state->session);
1441 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1445 *caller_state = state;
1451 /*************************************************
1452 * Extract peer information *
1453 *************************************************/
1455 /* Called from both server and client code.
1456 Only this is allowed to set state->peerdn and state->have_set_peerdn
1457 and we use that to detect double-calls.
1459 NOTE: the state blocks last while the TLS connection is up, which is fine
1460 for logging in the server side, but for the client side, we log after teardown
1461 in src/deliver.c. While the session is up, we can twist about states and
1462 repoint tls_* globals, but those variables used for logging or other variable
1463 expansion that happens _after_ delivery need to have a longer life-time.
1465 So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1466 doing this more than once per generation of a state context. We set them in
1467 the state context, and repoint tls_* to them. After the state goes away, the
1468 tls_* copies of the pointers remain valid and client delivery logging is happy.
1470 tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1474 state exim_gnutls_state_st *
1475 errstr pointer to error string
1477 Returns: OK/DEFER/FAIL
1481 peer_status(exim_gnutls_state_st *state, uschar ** errstr)
1483 uschar cipherbuf[256];
1484 const gnutls_datum_t *cert_list;
1486 unsigned int cert_list_size = 0;
1487 gnutls_protocol_t protocol;
1488 gnutls_cipher_algorithm_t cipher;
1489 gnutls_kx_algorithm_t kx;
1490 gnutls_mac_algorithm_t mac;
1491 gnutls_certificate_type_t ct;
1492 gnutls_x509_crt_t crt;
1496 if (state->have_set_peerdn)
1498 state->have_set_peerdn = TRUE;
1500 state->peerdn = NULL;
1503 cipher = gnutls_cipher_get(state->session);
1504 protocol = gnutls_protocol_get_version(state->session);
1505 mac = gnutls_mac_get(state->session);
1507 #ifdef GNUTLS_TLS1_3
1508 protocol >= GNUTLS_TLS1_3 ? 0 :
1510 gnutls_kx_get(state->session);
1512 old_pool = store_pool;
1514 store_pool = POOL_PERM;
1516 #ifdef SUPPORT_GNUTLS_SESS_DESC
1519 uschar * s = US gnutls_session_get_desc(state->session), c;
1521 /* Nikos M suggests we use this by preference. It returns like:
1522 (TLS1.3)-(ECDHE-SECP256R1)-(RSA-PSS-RSAE-SHA256)-(AES-256-GCM)
1524 For partial back-compat, put a colon after the TLS version, replace the
1525 )-( grouping with __, replace in-group - with _ and append the :keysize. */
1527 /* debug_printf("peer_status: gnutls_session_get_desc %s\n", s); */
1529 for (s++; (c = *s) && c != ')'; s++) g = string_catn(g, s, 1);
1530 g = string_catn(g, US":", 1);
1531 if (*s) s++; /* now on _ between groups */
1534 for (*++s && ++s; (c = *s) && c != ')'; s++) g = string_catn(g, c == '-' ? US"_" : s, 1);
1535 /* now on ) closing group */
1536 if ((c = *s) && *++s == '-') g = string_catn(g, US"__", 2);
1537 /* now on _ between groups */
1539 g = string_catn(g, US":", 1);
1540 g = string_cat(g, string_sprintf("%d", (int) gnutls_cipher_get_key_size(cipher) * 8));
1541 state->ciphersuite = string_from_gstring(g);
1544 state->ciphersuite = string_sprintf("%s:%s:%d",
1545 gnutls_protocol_get_name(protocol),
1546 gnutls_cipher_suite_get_name(kx, cipher, mac),
1547 (int) gnutls_cipher_get_key_size(cipher) * 8);
1549 /* I don't see a way that spaces could occur, in the current GnuTLS
1550 code base, but it was a concern in the old code and perhaps older GnuTLS
1551 releases did return "TLS 1.0"; play it safe, just in case. */
1553 for (uschar * p = state->ciphersuite; *p; p++) if (isspace(*p)) *p = '-';
1556 /* debug_printf("peer_status: ciphersuite %s\n", state->ciphersuite); */
1558 state->tlsp->cipher = state->ciphersuite;
1559 state->tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
1561 store_pool = old_pool;
1562 state->tlsp->cipher = state->ciphersuite;
1565 cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
1567 if (cert_list == NULL || cert_list_size == 0)
1569 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1570 cert_list, cert_list_size);
1571 if (state->verify_requirement >= VERIFY_REQUIRED)
1572 return tls_error(US"certificate verification failed",
1573 US"no certificate received from peer", state->host, errstr);
1577 ct = gnutls_certificate_type_get(state->session);
1578 if (ct != GNUTLS_CRT_X509)
1580 const uschar *ctn = US gnutls_certificate_type_get_name(ct);
1582 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1583 if (state->verify_requirement >= VERIFY_REQUIRED)
1584 return tls_error(US"certificate verification not possible, unhandled type",
1585 ctn, state->host, errstr);
1589 #define exim_gnutls_peer_err(Label) \
1591 if (rc != GNUTLS_E_SUCCESS) \
1593 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1594 (Label), gnutls_strerror(rc)); \
1595 if (state->verify_requirement >= VERIFY_REQUIRED) \
1596 return tls_error((Label), US gnutls_strerror(rc), state->host, errstr); \
1601 rc = import_cert(&cert_list[0], &crt);
1602 exim_gnutls_peer_err(US"cert 0");
1604 state->tlsp->peercert = state->peercert = crt;
1607 rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1608 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1610 exim_gnutls_peer_err(US"getting size for cert DN failed");
1611 return FAIL; /* should not happen */
1613 dn_buf = store_get_perm(sz);
1614 rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1615 exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1617 state->peerdn = dn_buf;
1620 #undef exim_gnutls_peer_err
1626 /*************************************************
1627 * Verify peer certificate *
1628 *************************************************/
1630 /* Called from both server and client code.
1631 *Should* be using a callback registered with
1632 gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1633 the peer information, but that's too new for some OSes.
1636 state exim_gnutls_state_st *
1637 errstr where to put an error message
1640 FALSE if the session should be rejected
1641 TRUE if the cert is okay or we just don't care
1645 verify_certificate(exim_gnutls_state_st * state, uschar ** errstr)
1650 if (state->verify_requirement == VERIFY_NONE)
1653 DEBUG(D_tls) debug_printf("TLS: checking peer certificate\n");
1656 if ((rc = peer_status(state, errstr)) != OK)
1658 verify = GNUTLS_CERT_INVALID;
1659 *errstr = US"certificate not supplied";
1665 if (state->verify_requirement == VERIFY_DANE && state->host)
1667 /* Using dane_verify_session_crt() would be easy, as it does it all for us
1668 including talking to a DNS resolver. But we want to do that bit ourselves
1669 as the testsuite intercepts and fakes its own DNS environment. */
1674 const gnutls_datum_t * certlist =
1675 gnutls_certificate_get_peers(state->session, &lsize);
1676 int usage = tls_out.tlsa_usage;
1678 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1679 /* Split the TLSA records into two sets, TA and EE selectors. Run the
1680 dane-verification separately so that we know which selector verified;
1681 then we know whether to do name-verification (needed for TA but not EE). */
1683 if (usage == ((1<<DANESSL_USAGE_DANE_TA) | (1<<DANESSL_USAGE_DANE_EE)))
1684 { /* a mixed-usage bundle */
1689 for(nrec = 0; state->dane_data_len[nrec]; ) nrec++;
1692 dd = store_get(nrec * sizeof(uschar *));
1693 ddl = store_get(nrec * sizeof(int));
1696 if ((rc = dane_state_init(&s, 0)))
1699 for (usage = DANESSL_USAGE_DANE_EE;
1700 usage >= DANESSL_USAGE_DANE_TA; usage--)
1701 { /* take records with this usage */
1702 for (j = i = 0; i < nrec; i++)
1703 if (state->dane_data[i][0] == usage)
1705 dd[j] = state->dane_data[i];
1706 ddl[j++] = state->dane_data_len[i];
1713 if ((rc = dane_raw_tlsa(s, &r, (char * const *)dd, ddl, 1, 0)))
1716 if ((rc = dane_verify_crt_raw(s, certlist, lsize,
1717 gnutls_certificate_type_get(state->session),
1719 usage == DANESSL_USAGE_DANE_EE
1720 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1724 debug_printf("TLSA record problem: %s\n", dane_strerror(rc));
1726 else if (verify == 0) /* verification passed */
1734 if (rc) goto tlsa_prob;
1739 if ( (rc = dane_state_init(&s, 0))
1740 || (rc = dane_raw_tlsa(s, &r, state->dane_data, state->dane_data_len,
1742 || (rc = dane_verify_crt_raw(s, certlist, lsize,
1743 gnutls_certificate_type_get(state->session),
1745 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1746 usage == (1 << DANESSL_USAGE_DANE_EE)
1747 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1756 if (verify != 0) /* verification failed */
1759 (void) dane_verification_status_print(verify, &str, 0);
1760 *errstr = US str.data; /* don't bother to free */
1764 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1765 /* If a TA-mode TLSA record was used for verification we must additionally
1766 verify the cert name (but not the CA chain). For EE-mode, skip it. */
1768 if (usage & (1 << DANESSL_USAGE_DANE_EE))
1771 state->peer_dane_verified = state->peer_cert_verified = TRUE;
1774 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1775 /* Assume that the name on the A-record is the one that should be matching
1776 the cert. An alternate view is that the domain part of the email address
1777 is also permissible. */
1779 if (gnutls_x509_crt_check_hostname(state->tlsp->peercert,
1780 CS state->host->name))
1782 state->peer_dane_verified = state->peer_cert_verified = TRUE;
1787 #endif /*SUPPORT_DANE*/
1789 rc = gnutls_certificate_verify_peers2(state->session, &verify);
1792 /* Handle the result of verification. INVALID is set if any others are. */
1794 if (rc < 0 || verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED))
1796 state->peer_cert_verified = FALSE;
1799 #ifdef GNUTLS_CERT_VFY_STATUS_PRINT
1804 if (gnutls_certificate_verification_status_print(verify,
1805 gnutls_certificate_type_get(state->session), &txt, 0)
1806 == GNUTLS_E_SUCCESS)
1808 debug_printf("%s\n", txt.data);
1809 gnutls_free(txt.data);
1813 *errstr = verify & GNUTLS_CERT_REVOKED
1814 ? US"certificate revoked" : US"certificate invalid";
1818 debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
1819 *errstr, state->peerdn ? state->peerdn : US"<unset>");
1821 if (state->verify_requirement >= VERIFY_REQUIRED)
1824 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1829 /* Client side, check the server's certificate name versus the name on the
1830 A-record for the connection we made. What to do for server side - what name
1831 to use for client? We document that there is no such checking for server
1834 if ( state->exp_tls_verify_cert_hostnames
1835 && !gnutls_x509_crt_check_hostname(state->tlsp->peercert,
1836 CS state->exp_tls_verify_cert_hostnames)
1840 debug_printf("TLS certificate verification failed: cert name mismatch\n");
1841 if (state->verify_requirement >= VERIFY_REQUIRED)
1846 state->peer_cert_verified = TRUE;
1847 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
1848 state->peerdn ? state->peerdn : US"<unset>");
1852 state->tlsp->peerdn = state->peerdn;
1857 *errstr = string_sprintf("TLSA record problem: %s",
1858 rc == DANE_E_REQUESTED_DATA_NOT_AVAILABLE ? "none usable" : dane_strerror(rc));
1862 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1869 /* ------------------------------------------------------------------------ */
1872 /* Logging function which can be registered with
1873 * gnutls_global_set_log_function()
1874 * gnutls_global_set_log_level() 0..9
1876 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1878 exim_gnutls_logger_cb(int level, const char *message)
1880 size_t len = strlen(message);
1883 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1886 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1887 message[len-1] == '\n' ? "" : "\n");
1892 /* Called after client hello, should handle SNI work.
1893 This will always set tls_sni (state->received_sni) if available,
1894 and may trigger presenting different certificates,
1895 if state->trigger_sni_changes is TRUE.
1897 Should be registered with
1898 gnutls_handshake_set_post_client_hello_function()
1900 "This callback must return 0 on success or a gnutls error code to terminate the
1903 For inability to get SNI information, we return 0.
1904 We only return non-zero if re-setup failed.
1905 Only used for server-side TLS.
1909 exim_sni_handling_cb(gnutls_session_t session)
1911 char sni_name[MAX_HOST_LEN];
1912 size_t data_len = MAX_HOST_LEN;
1913 exim_gnutls_state_st *state = &state_server;
1914 unsigned int sni_type;
1916 uschar * dummy_errstr;
1918 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1919 if (rc != GNUTLS_E_SUCCESS)
1922 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1923 debug_printf("TLS: no SNI presented in handshake.\n");
1925 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1926 gnutls_strerror(rc), rc);
1931 if (sni_type != GNUTLS_NAME_DNS)
1933 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1937 /* We now have a UTF-8 string in sni_name */
1938 old_pool = store_pool;
1939 store_pool = POOL_PERM;
1940 state->received_sni = string_copyn(US sni_name, data_len);
1941 store_pool = old_pool;
1943 /* We set this one now so that variable expansions below will work */
1944 state->tlsp->sni = state->received_sni;
1946 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1947 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1949 if (!state->trigger_sni_changes)
1952 if ((rc = tls_expand_session_files(state, &dummy_errstr)) != OK)
1954 /* If the setup of certs/etc failed before handshake, TLS would not have
1955 been offered. The best we can do now is abort. */
1956 return GNUTLS_E_APPLICATION_ERROR_MIN;
1959 rc = tls_set_remaining_x509(state, &dummy_errstr);
1960 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1967 #ifndef DISABLE_OCSP
1970 server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1971 gnutls_datum_t * ocsp_response)
1974 DEBUG(D_tls) debug_printf("OCSP stapling callback: %s\n", US ptr);
1976 if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1978 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1980 tls_in.ocsp = OCSP_NOT_RESP;
1981 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1984 tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1991 #ifndef DISABLE_EVENT
1993 We use this callback to get observability and detail-level control
1994 for an exim TLS connection (either direction), raising a tls:cert event
1995 for each cert in the chain presented by the peer. Any event
1996 can deny verification.
1998 Return 0 for the handshake to continue or non-zero to terminate.
2002 verify_cb(gnutls_session_t session)
2004 const gnutls_datum_t * cert_list;
2005 unsigned int cert_list_size = 0;
2006 gnutls_x509_crt_t crt;
2009 exim_gnutls_state_st * state = gnutls_session_get_ptr(session);
2011 if ((cert_list = gnutls_certificate_get_peers(session, &cert_list_size)))
2012 while (cert_list_size--)
2014 if ((rc = import_cert(&cert_list[cert_list_size], &crt)) != GNUTLS_E_SUCCESS)
2016 DEBUG(D_tls) debug_printf("TLS: peer cert problem: depth %d: %s\n",
2017 cert_list_size, gnutls_strerror(rc));
2021 state->tlsp->peercert = crt;
2022 if ((yield = event_raise(state->event_action,
2023 US"tls:cert", string_sprintf("%d", cert_list_size))))
2025 log_write(0, LOG_MAIN,
2026 "SSL verify denied by event-action: depth=%d: %s",
2027 cert_list_size, yield);
2028 return 1; /* reject */
2030 state->tlsp->peercert = NULL;
2040 /* ------------------------------------------------------------------------ */
2041 /* Exported functions */
2046 /*************************************************
2047 * Start a TLS session in a server *
2048 *************************************************/
2050 /* This is called when Exim is running as a server, after having received
2051 the STARTTLS command. It must respond to that command, and then negotiate
2055 require_ciphers list of allowed ciphers or NULL
2056 errstr pointer to error string
2058 Returns: OK on success
2059 DEFER for errors before the start of the negotiation
2060 FAIL for errors during the negotiation; the server can't
2065 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
2068 exim_gnutls_state_st * state = NULL;
2070 /* Check for previous activation */
2071 if (tls_in.active.sock >= 0)
2073 tls_error(US"STARTTLS received after TLS started", US "", NULL, errstr);
2074 smtp_printf("554 Already in TLS\r\n", FALSE);
2078 /* Initialize the library. If it fails, it will already have logged the error
2079 and sent an SMTP response. */
2081 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
2083 if ((rc = tls_init(NULL, tls_certificate, tls_privatekey,
2084 NULL, tls_verify_certificates, tls_crl,
2085 require_ciphers, &state, &tls_in, errstr)) != OK) return rc;
2087 /* If this is a host for which certificate verification is mandatory or
2088 optional, set up appropriately. */
2090 if (verify_check_host(&tls_verify_hosts) == OK)
2093 debug_printf("TLS: a client certificate will be required.\n");
2094 state->verify_requirement = VERIFY_REQUIRED;
2095 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2097 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2100 debug_printf("TLS: a client certificate will be requested but not required.\n");
2101 state->verify_requirement = VERIFY_OPTIONAL;
2102 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2107 debug_printf("TLS: a client certificate will not be requested.\n");
2108 state->verify_requirement = VERIFY_NONE;
2109 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2112 #ifndef DISABLE_EVENT
2115 state->event_action = event_action;
2116 gnutls_session_set_ptr(state->session, state);
2117 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2121 /* Register SNI handling; always, even if not in tls_certificate, so that the
2122 expansion variable $tls_sni is always available. */
2124 gnutls_handshake_set_post_client_hello_function(state->session,
2125 exim_sni_handling_cb);
2127 /* Set context and tell client to go ahead, except in the case of TLS startup
2128 on connection, where outputting anything now upsets the clients and tends to
2129 make them disconnect. We need to have an explicit fflush() here, to force out
2130 the response. Other smtp_printf() calls do not need it, because in non-TLS
2131 mode, the fflush() happens when smtp_getc() is called. */
2133 if (!state->tlsp->on_connect)
2135 smtp_printf("220 TLS go ahead\r\n", FALSE);
2139 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2140 that the GnuTLS library doesn't.
2141 From 3.1.0 there is gnutls_handshake_set_timeout() - but it requires you
2142 to set (and clear down afterwards) up a pull-timeout callback function that does
2143 a select, so we're no better off unless avoiding signals becomes an issue. */
2145 gnutls_transport_set_ptr2(state->session,
2146 (gnutls_transport_ptr_t)(long) fileno(smtp_in),
2147 (gnutls_transport_ptr_t)(long) fileno(smtp_out));
2148 state->fd_in = fileno(smtp_in);
2149 state->fd_out = fileno(smtp_out);
2151 sigalrm_seen = FALSE;
2152 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2154 rc = gnutls_handshake(state->session);
2155 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2158 if (rc != GNUTLS_E_SUCCESS)
2160 /* It seems that, except in the case of a timeout, we have to close the
2161 connection right here; otherwise if the other end is running OpenSSL it hangs
2162 until the server times out. */
2166 tls_error(US"gnutls_handshake", US"timed out", NULL, errstr);
2167 gnutls_db_remove_session(state->session);
2171 tls_error(US"gnutls_handshake", US gnutls_strerror(rc), NULL, errstr);
2172 (void) gnutls_alert_send_appropriate(state->session, rc);
2173 gnutls_deinit(state->session);
2174 gnutls_certificate_free_credentials(state->x509_cred);
2176 shutdown(state->fd_out, SHUT_WR);
2177 for (rc = 1024; fgetc(smtp_in) != EOF && rc > 0; ) rc--; /* drain skt */
2178 (void)fclose(smtp_out);
2179 (void)fclose(smtp_in);
2180 smtp_out = smtp_in = NULL;
2186 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
2188 /* Verify after the fact */
2190 if (!verify_certificate(state, errstr))
2192 if (state->verify_requirement != VERIFY_OPTIONAL)
2194 (void) tls_error(US"certificate verification failed", *errstr, NULL, errstr);
2198 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
2202 /* Figure out peer DN, and if authenticated, etc. */
2204 if ((rc = peer_status(state, NULL)) != OK) return rc;
2206 /* Sets various Exim expansion variables; always safe within server */
2208 extract_exim_vars_from_tls_state(state);
2210 /* TLS has been set up. Adjust the input functions to read via TLS,
2211 and initialize appropriately. */
2213 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2215 receive_getc = tls_getc;
2216 receive_getbuf = tls_getbuf;
2217 receive_get_cache = tls_get_cache;
2218 receive_ungetc = tls_ungetc;
2219 receive_feof = tls_feof;
2220 receive_ferror = tls_ferror;
2221 receive_smtp_buffered = tls_smtp_buffered;
2230 tls_client_setup_hostname_checks(host_item * host, exim_gnutls_state_st * state,
2231 smtp_transport_options_block * ob)
2233 if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
2235 state->exp_tls_verify_cert_hostnames =
2237 string_domain_utf8_to_alabel(host->name, NULL);
2242 debug_printf("TLS: server cert verification includes hostname: \"%s\".\n",
2243 state->exp_tls_verify_cert_hostnames);
2251 /* Given our list of RRs from the TLSA lookup, build a lookup block in
2252 GnuTLS-DANE's preferred format. Hang it on the state str for later
2253 use in DANE verification.
2255 We point at the dnsa data not copy it, so it must remain valid until
2256 after verification is done.*/
2259 dane_tlsa_load(exim_gnutls_state_st * state, dns_answer * dnsa)
2264 const char ** dane_data;
2265 int * dane_data_len;
2267 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS), i = 1;
2269 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2270 ) if (rr->type == T_TLSA) i++;
2272 dane_data = store_get(i * sizeof(uschar *));
2273 dane_data_len = store_get(i * sizeof(int));
2275 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS), i = 0;
2277 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2278 ) if (rr->type == T_TLSA && rr->size > 3)
2280 const uschar * p = rr->data;
2281 uint8_t usage = p[0], sel = p[1], type = p[2];
2284 debug_printf("TLSA: %d %d %d size %d\n", usage, sel, type, rr->size);
2286 if ( (usage != DANESSL_USAGE_DANE_TA && usage != DANESSL_USAGE_DANE_EE)
2287 || (sel != 0 && sel != 1)
2292 case 0: /* Full: cannot check at present */
2294 case 1: if (rr->size != 3 + 256/8) continue; /* sha2-256 */
2296 case 2: if (rr->size != 3 + 512/8) continue; /* sha2-512 */
2301 tls_out.tlsa_usage |= 1<<usage;
2302 dane_data[i] = CS p;
2303 dane_data_len[i++] = rr->size;
2306 if (!i) return FALSE;
2308 dane_data[i] = NULL;
2309 dane_data_len[i] = 0;
2311 state->dane_data = (char * const *)dane_data;
2312 state->dane_data_len = dane_data_len;
2319 /*************************************************
2320 * Start a TLS session in a client *
2321 *************************************************/
2323 /* Called from the smtp transport after STARTTLS has been accepted.
2326 fd the fd of the connection
2327 host connected host (for messages and option-tests)
2328 addr the first address (not used)
2329 tb transport (always smtp)
2330 tlsa_dnsa non-NULL, either request or require dane for this host, and
2331 a TLSA record found. Therefore, dane verify required.
2332 Which implies cert must be requested and supplied, dane
2333 verify must pass, and cert verify irrelevant (incl.
2334 hostnames), and (caller handled) require_tls
2335 tlsp record details of channel configuration
2336 errstr error string pointer
2338 Returns: Pointer to TLS session context, or NULL on error
2342 tls_client_start(int fd, host_item *host,
2343 address_item *addr ARG_UNUSED,
2344 transport_instance * tb,
2346 dns_answer * tlsa_dnsa,
2348 tls_support * tlsp, uschar ** errstr)
2350 smtp_transport_options_block *ob = tb
2351 ? (smtp_transport_options_block *)tb->options_block
2352 : &smtp_transport_option_defaults;
2354 exim_gnutls_state_st * state = NULL;
2355 uschar *cipher_list = NULL;
2357 #ifndef DISABLE_OCSP
2359 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
2360 BOOL request_ocsp = require_ocsp ? TRUE
2361 : verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2364 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
2367 if (tlsa_dnsa && ob->dane_require_tls_ciphers)
2369 /* not using expand_check_tlsvar because not yet in state */
2370 if (!expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2371 &cipher_list, errstr))
2373 cipher_list = cipher_list && *cipher_list
2374 ? ob->dane_require_tls_ciphers : ob->tls_require_ciphers;
2379 cipher_list = ob->tls_require_ciphers;
2381 if (tls_init(host, ob->tls_certificate, ob->tls_privatekey,
2382 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
2383 cipher_list, &state, tlsp, errstr) != OK)
2387 int dh_min_bits = ob->tls_dh_min_bits;
2388 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
2391 debug_printf("WARNING: tls_dh_min_bits far too low,"
2392 " clamping %d up to %d\n",
2393 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
2394 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
2397 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
2398 " acceptable bits to %d\n",
2400 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
2403 /* Stick to the old behaviour for compatibility if tls_verify_certificates is
2404 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
2405 the specified host patterns if one of them is defined */
2408 if (tlsa_dnsa && dane_tlsa_load(state, tlsa_dnsa))
2411 debug_printf("TLS: server certificate DANE required.\n");
2412 state->verify_requirement = VERIFY_DANE;
2413 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2417 if ( ( state->exp_tls_verify_certificates
2418 && !ob->tls_verify_hosts
2419 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2421 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
2424 tls_client_setup_hostname_checks(host, state, ob);
2426 debug_printf("TLS: server certificate verification required.\n");
2427 state->verify_requirement = VERIFY_REQUIRED;
2428 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2430 else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
2432 tls_client_setup_hostname_checks(host, state, ob);
2434 debug_printf("TLS: server certificate verification optional.\n");
2435 state->verify_requirement = VERIFY_OPTIONAL;
2436 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2441 debug_printf("TLS: server certificate verification not required.\n");
2442 state->verify_requirement = VERIFY_NONE;
2443 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2446 #ifndef DISABLE_OCSP
2447 /* supported since GnuTLS 3.1.3 */
2450 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
2451 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
2452 NULL, 0, NULL)) != OK)
2454 tls_error(US"cert-status-req", US gnutls_strerror(rc), state->host, errstr);
2457 tlsp->ocsp = OCSP_NOT_RESP;
2461 #ifndef DISABLE_EVENT
2462 if (tb && tb->event_action)
2464 state->event_action = tb->event_action;
2465 gnutls_session_set_ptr(state->session, state);
2466 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2470 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr_t)(long) fd);
2474 DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
2475 /* There doesn't seem to be a built-in timeout on connection. */
2477 sigalrm_seen = FALSE;
2478 ALARM(ob->command_timeout);
2480 rc = gnutls_handshake(state->session);
2481 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2484 if (rc != GNUTLS_E_SUCCESS)
2488 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_USER_CANCELED);
2489 tls_error(US"gnutls_handshake", US"timed out", state->host, errstr);
2492 tls_error(US"gnutls_handshake", US gnutls_strerror(rc), state->host, errstr);
2496 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
2500 if (!verify_certificate(state, errstr))
2502 tls_error(US"certificate verification failed", *errstr, state->host, errstr);
2506 #ifndef DISABLE_OCSP
2511 gnutls_datum_t stapling;
2512 gnutls_ocsp_resp_t resp;
2513 gnutls_datum_t printed;
2514 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
2515 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
2516 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
2517 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
2520 debug_printf("%.4096s", printed.data);
2521 gnutls_free(printed.data);
2524 (void) tls_error(US"ocsp decode", US gnutls_strerror(rc), state->host, errstr);
2527 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
2529 tlsp->ocsp = OCSP_FAILED;
2530 tls_error(US"certificate status check failed", NULL, state->host, errstr);
2536 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
2537 tlsp->ocsp = OCSP_VFIED;
2542 /* Figure out peer DN, and if authenticated, etc. */
2544 if (peer_status(state, errstr) != OK)
2547 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
2549 extract_exim_vars_from_tls_state(state);
2557 /*************************************************
2558 * Close down a TLS session *
2559 *************************************************/
2561 /* This is also called from within a delivery subprocess forked from the
2562 daemon, to shut down the TLS library, without actually doing a shutdown (which
2563 would tamper with the TLS session in the parent process).
2566 ct_ctx client context pointer, or NULL for the one global server context
2567 shutdown 1 if TLS close-alert is to be sent,
2568 2 if also response to be waited for
2574 tls_close(void * ct_ctx, int shutdown)
2576 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
2578 if (!state->tlsp || state->tlsp->active.sock < 0) return; /* TLS was not active */
2582 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
2583 shutdown > 1 ? " (with response-wait)" : "");
2586 gnutls_bye(state->session, shutdown > 1 ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
2590 gnutls_deinit(state->session);
2591 gnutls_certificate_free_credentials(state->x509_cred);
2594 state->tlsp->active.sock = -1;
2595 state->tlsp->active.tls_ctx = NULL;
2596 if (state->xfer_buffer) store_free(state->xfer_buffer);
2597 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
2604 tls_refill(unsigned lim)
2606 exim_gnutls_state_st * state = &state_server;
2609 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
2610 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
2612 sigalrm_seen = FALSE;
2613 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2616 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
2617 MIN(ssl_xfer_buffer_size, lim));
2618 while (inbytes == GNUTLS_E_AGAIN);
2620 if (smtp_receive_timeout > 0) ALARM_CLR(0);
2622 if (had_command_timeout) /* set by signal handler */
2623 smtp_command_timeout_exit(); /* does not return */
2624 if (had_command_sigterm)
2625 smtp_command_sigterm_exit();
2626 if (had_data_timeout)
2627 smtp_data_timeout_exit();
2628 if (had_data_sigint)
2629 smtp_data_sigint_exit();
2631 /* Timeouts do not get this far. A zero-byte return appears to mean that the
2632 TLS session has been closed down, not that the socket itself has been closed
2633 down. Revert to non-TLS handling. */
2637 DEBUG(D_tls) debug_printf("Got tls read timeout\n");
2638 state->xfer_error = TRUE;
2642 else if (inbytes == 0)
2644 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2646 receive_getc = smtp_getc;
2647 receive_getbuf = smtp_getbuf;
2648 receive_get_cache = smtp_get_cache;
2649 receive_ungetc = smtp_ungetc;
2650 receive_feof = smtp_feof;
2651 receive_ferror = smtp_ferror;
2652 receive_smtp_buffered = smtp_buffered;
2654 gnutls_deinit(state->session);
2655 gnutls_certificate_free_credentials(state->x509_cred);
2657 state->session = NULL;
2658 state->tlsp->active.sock = -1;
2659 state->tlsp->active.tls_ctx = NULL;
2660 state->tlsp->bits = 0;
2661 state->tlsp->certificate_verified = FALSE;
2662 tls_channelbinding_b64 = NULL;
2663 state->tlsp->cipher = NULL;
2664 state->tlsp->peercert = NULL;
2665 state->tlsp->peerdn = NULL;
2670 /* Handle genuine errors */
2672 else if (inbytes < 0)
2674 DEBUG(D_tls) debug_printf("%s: err from gnutls_record_recv(\n", __FUNCTION__);
2675 record_io_error(state, (int) inbytes, US"recv", NULL);
2676 state->xfer_error = TRUE;
2679 #ifndef DISABLE_DKIM
2680 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
2682 state->xfer_buffer_hwm = (int) inbytes;
2683 state->xfer_buffer_lwm = 0;
2687 /*************************************************
2688 * TLS version of getc *
2689 *************************************************/
2691 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
2692 it refills the buffer via the GnuTLS reading function.
2693 Only used by the server-side TLS.
2695 This feeds DKIM and should be used for all message-body reads.
2697 Arguments: lim Maximum amount to read/buffer
2698 Returns: the next character or EOF
2702 tls_getc(unsigned lim)
2704 exim_gnutls_state_st * state = &state_server;
2706 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2707 if (!tls_refill(lim))
2708 return state->xfer_error ? EOF : smtp_getc(lim);
2710 /* Something in the buffer; return next uschar */
2712 return state->xfer_buffer[state->xfer_buffer_lwm++];
2716 tls_getbuf(unsigned * len)
2718 exim_gnutls_state_st * state = &state_server;
2722 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2723 if (!tls_refill(*len))
2725 if (!state->xfer_error) return smtp_getbuf(len);
2730 if ((size = state->xfer_buffer_hwm - state->xfer_buffer_lwm) > *len)
2732 buf = &state->xfer_buffer[state->xfer_buffer_lwm];
2733 state->xfer_buffer_lwm += size;
2742 #ifndef DISABLE_DKIM
2743 exim_gnutls_state_st * state = &state_server;
2744 int n = state->xfer_buffer_hwm - state->xfer_buffer_lwm;
2746 dkim_exim_verify_feed(state->xfer_buffer+state->xfer_buffer_lwm, n);
2752 tls_could_read(void)
2754 return state_server.xfer_buffer_lwm < state_server.xfer_buffer_hwm
2755 || gnutls_record_check_pending(state_server.session) > 0;
2761 /*************************************************
2762 * Read bytes from TLS channel *
2763 *************************************************/
2765 /* This does not feed DKIM, so if the caller uses this for reading message body,
2766 then the caller must feed DKIM.
2769 ct_ctx client context pointer, or NULL for the one global server context
2773 Returns: the number of bytes read
2774 -1 after a failed read, including EOF
2778 tls_read(void * ct_ctx, uschar *buff, size_t len)
2780 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
2786 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
2788 debug_printf("*** PROBABLY A BUG *** " \
2789 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
2790 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
2793 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
2794 state->session, buff, len);
2797 inbytes = gnutls_record_recv(state->session, buff, len);
2798 while (inbytes == GNUTLS_E_AGAIN);
2800 if (inbytes > 0) return inbytes;
2803 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2807 DEBUG(D_tls) debug_printf("%s: err from gnutls_record_recv(\n", __FUNCTION__);
2808 record_io_error(state, (int)inbytes, US"recv", NULL);
2817 /*************************************************
2818 * Write bytes down TLS channel *
2819 *************************************************/
2823 ct_ctx client context pointer, or NULL for the one global server context
2826 more more data expected soon
2828 Returns: the number of bytes after a successful write,
2829 -1 after a failed write
2833 tls_write(void * ct_ctx, const uschar * buff, size_t len, BOOL more)
2837 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
2840 if (more && !state->corked)
2842 DEBUG(D_tls) debug_printf("gnutls_record_cork(session=%p)\n", state->session);
2843 gnutls_record_cork(state->session);
2844 state->corked = TRUE;
2848 DEBUG(D_tls) debug_printf("%s(%p, " SIZE_T_FMT "%s)\n", __FUNCTION__,
2849 buff, left, more ? ", more" : "");
2853 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
2857 outbytes = gnutls_record_send(state->session, buff, left);
2858 while (outbytes == GNUTLS_E_AGAIN);
2860 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
2864 DEBUG(D_tls) debug_printf("%s: gnutls_record_send err\n", __FUNCTION__);
2865 record_io_error(state, outbytes, US"send", NULL);
2870 record_io_error(state, 0, US"send", US"TLS channel closed on write");
2881 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
2887 if (!more && state->corked)
2889 DEBUG(D_tls) debug_printf("gnutls_record_uncork(session=%p)\n", state->session);
2891 /* We can't use GNUTLS_RECORD_WAIT here, as it retries on
2892 GNUTLS_E_AGAIN || GNUTLS_E_INTR, which would break our timeout set by alarm().
2893 The GNUTLS_E_AGAIN should not happen ever, as our sockets are blocking anyway.
2894 But who knows. (That all relies on the fact that GNUTLS_E_INTR and GNUTLS_E_AGAIN
2895 match the EINTR and EAGAIN errno values.) */
2896 outbytes = gnutls_record_uncork(state->session, 0);
2897 while (outbytes == GNUTLS_E_AGAIN);
2901 record_io_error(state, len, US"uncork", NULL);
2905 state->corked = FALSE;
2915 /*************************************************
2916 * Random number generation *
2917 *************************************************/
2919 /* Pseudo-random number generation. The result is not expected to be
2920 cryptographically strong but not so weak that someone will shoot themselves
2921 in the foot using it as a nonce in input in some email header scheme or
2922 whatever weirdness they'll twist this into. The result should handle fork()
2923 and avoid repeating sequences. OpenSSL handles that for us.
2927 Returns a random number in range [0, max-1]
2930 #ifdef HAVE_GNUTLS_RND
2932 vaguely_random_number(int max)
2937 uschar smallbuf[sizeof(r)];
2942 needed_len = sizeof(r);
2943 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
2944 * asked for a number less than 10. */
2945 for (r = max, i = 0; r; ++i)
2951 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2954 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2955 return vaguely_random_number_fallback(max);
2958 for (p = smallbuf; needed_len; --needed_len, ++p)
2964 /* We don't particularly care about weighted results; if someone wants
2965 * smooth distribution and cares enough then they should submit a patch then. */
2968 #else /* HAVE_GNUTLS_RND */
2970 vaguely_random_number(int max)
2972 return vaguely_random_number_fallback(max);
2974 #endif /* HAVE_GNUTLS_RND */
2979 /*************************************************
2980 * Let tls_require_ciphers be checked at startup *
2981 *************************************************/
2983 /* The tls_require_ciphers option, if set, must be something which the
2986 Returns: NULL on success, or error message
2990 tls_validate_require_cipher(void)
2993 uschar *expciphers = NULL;
2994 gnutls_priority_t priority_cache;
2996 uschar * dummy_errstr;
2998 #define validate_check_rc(Label) do { \
2999 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
3000 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
3001 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
3003 if (exim_gnutls_base_init_done)
3004 log_write(0, LOG_MAIN|LOG_PANIC,
3005 "already initialised GnuTLS, Exim developer bug");
3007 #ifdef HAVE_GNUTLS_PKCS11
3008 if (!gnutls_allow_auto_pkcs11)
3010 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
3011 validate_check_rc(US"gnutls_pkcs11_init");
3014 rc = gnutls_global_init();
3015 validate_check_rc(US"gnutls_global_init()");
3016 exim_gnutls_base_init_done = TRUE;
3018 if (!(tls_require_ciphers && *tls_require_ciphers))
3019 return_deinit(NULL);
3021 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3023 return_deinit(US"failed to expand tls_require_ciphers");
3025 if (!(expciphers && *expciphers))
3026 return_deinit(NULL);
3029 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3031 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
3032 validate_check_rc(string_sprintf(
3033 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
3034 expciphers, errpos - CS expciphers, errpos));
3036 #undef return_deinit
3037 #undef validate_check_rc
3038 gnutls_global_deinit();
3046 /*************************************************
3047 * Report the library versions. *
3048 *************************************************/
3050 /* See a description in tls-openssl.c for an explanation of why this exists.
3052 Arguments: a FILE* to print the results to
3057 tls_version_report(FILE *f)
3059 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
3062 gnutls_check_version(NULL));
3067 /* End of tls-gnu.c */