1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2017 */
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>
42 /* needed to disable PKCS11 autoload unless requested */
43 #if GNUTLS_VERSION_NUMBER >= 0x020c00
44 # include <gnutls/pkcs11.h>
45 # define SUPPORT_PARAM_TO_PK_BITS
47 #if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
48 # warning "GnuTLS library version too old; define DISABLE_OCSP in Makefile"
51 #if GNUTLS_VERSION_NUMBER < 0x020a00 && !defined(DISABLE_EVENT)
52 # warning "GnuTLS library version too old; tls:cert event unsupported"
53 # define DISABLE_EVENT
55 #if GNUTLS_VERSION_NUMBER >= 0x030306
56 # define SUPPORT_CA_DIR
58 # undef SUPPORT_CA_DIR
60 #if GNUTLS_VERSION_NUMBER >= 0x030014
61 # define SUPPORT_SYSDEFAULT_CABUNDLE
63 #if GNUTLS_VERSION_NUMBER >= 0x030109
66 #if GNUTLS_VERSION_NUMBER >= 0x030506 && !defined(DISABLE_OCSP)
67 # define SUPPORT_SRV_OCSP_STACK
69 #if GNUTLS_VERSION_NUMBER >= 0x030000 && defined(EXPERIMENTAL_DANE)
71 # define DANESSL_USAGE_DANE_TA 2
72 # define DANESSL_USAGE_DANE_EE 3
74 #if GNUTLS_VERSION_NUMBER < 0x999999 && defined(EXPERIMENTAL_DANE)
75 # define GNUTLS_BROKEN_DANE_VALIDATION
79 # include <gnutls/ocsp.h>
82 # include <gnutls/dane.h>
88 gnutls_global_set_audit_log_function()
91 gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
94 /* Local static variables for GnuTLS */
96 /* Values for verify_requirement */
98 enum peer_verify_requirement
99 { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED, VERIFY_DANE };
101 /* This holds most state for server or client; with this, we can set up an
102 outbound TLS-enabled connection in an ACL callout, while not stomping all
103 over the TLS variables available for expansion.
105 Some of these correspond to variables in globals.c; those variables will
106 be set to point to content in one of these instances, as appropriate for
107 the stage of the process lifetime.
109 Not handled here: global tls_channelbinding_b64.
112 typedef struct exim_gnutls_state {
113 gnutls_session_t session;
114 gnutls_certificate_credentials_t x509_cred;
115 gnutls_priority_t priority_cache;
116 enum peer_verify_requirement verify_requirement;
119 BOOL peer_cert_verified;
120 BOOL peer_dane_verified;
121 BOOL trigger_sni_changes;
122 BOOL have_set_peerdn;
123 const struct host_item *host;
124 gnutls_x509_crt_t peercert;
127 uschar *received_sni;
129 const uschar *tls_certificate;
130 const uschar *tls_privatekey;
131 const uschar *tls_sni; /* client send only, not received */
132 const uschar *tls_verify_certificates;
133 const uschar *tls_crl;
134 const uschar *tls_require_ciphers;
136 uschar *exp_tls_certificate;
137 uschar *exp_tls_privatekey;
138 uschar *exp_tls_verify_certificates;
140 uschar *exp_tls_require_ciphers;
141 const uschar *exp_tls_verify_cert_hostnames;
142 #ifndef DISABLE_EVENT
143 uschar *event_action;
146 char * const * dane_data;
147 const int * dane_data_len;
150 tls_support *tlsp; /* set in tls_init() */
157 } exim_gnutls_state_st;
159 static const exim_gnutls_state_st exim_gnutls_state_init = {
162 .priority_cache = NULL,
163 .verify_requirement = VERIFY_NONE,
166 .peer_cert_verified = FALSE,
167 .peer_dane_verified = FALSE,
168 .trigger_sni_changes =FALSE,
169 .have_set_peerdn = FALSE,
174 .received_sni = NULL,
176 .tls_certificate = NULL,
177 .tls_privatekey = NULL,
179 .tls_verify_certificates = NULL,
181 .tls_require_ciphers =NULL,
183 .exp_tls_certificate = NULL,
184 .exp_tls_privatekey = NULL,
185 .exp_tls_verify_certificates = NULL,
187 .exp_tls_require_ciphers = NULL,
188 .exp_tls_verify_cert_hostnames = NULL,
189 #ifndef DISABLE_EVENT
190 .event_action = NULL,
195 .xfer_buffer_lwm = 0,
196 .xfer_buffer_hwm = 0,
201 /* Not only do we have our own APIs which don't pass around state, assuming
202 it's held in globals, GnuTLS doesn't appear to let us register callback data
203 for callbacks, or as part of the session, so we have to keep a "this is the
204 context we're currently dealing with" pointer and rely upon being
205 single-threaded to keep from processing data on an inbound TLS connection while
206 talking to another TLS connection for an outbound check. This does mean that
207 there's no way for heart-beats to be responded to, for the duration of the
209 XXX But see gnutls_session_get_ptr()
212 static exim_gnutls_state_st state_server, state_client;
214 /* dh_params are initialised once within the lifetime of a process using TLS;
215 if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
216 don't want to repeat this. */
218 static gnutls_dh_params_t dh_server_params = NULL;
220 /* No idea how this value was chosen; preserving it. Default is 3600. */
222 static const int ssl_session_timeout = 200;
224 static const char * const exim_default_gnutls_priority = "NORMAL";
226 /* Guard library core initialisation */
228 static BOOL exim_gnutls_base_init_done = FALSE;
231 static BOOL gnutls_buggy_ocsp = FALSE;
235 /* ------------------------------------------------------------------------ */
238 #define MAX_HOST_LEN 255
240 /* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
241 the library logging; a value less than 0 disables the calls to set up logging
242 callbacks. Possibly GNuTLS also looks for an environment variable
243 "GNUTLS_DEBUG_LEVEL". */
244 #ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
245 # define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
248 #ifndef EXIM_CLIENT_DH_MIN_BITS
249 # define EXIM_CLIENT_DH_MIN_BITS 1024
252 /* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
253 can ask for a bit-strength. Without that, we stick to the constant we had
255 #ifndef EXIM_SERVER_DH_BITS_PRE2_12
256 # define EXIM_SERVER_DH_BITS_PRE2_12 1024
259 #define exim_gnutls_err_check(rc, Label) do { \
260 if ((rc) != GNUTLS_E_SUCCESS) \
261 return tls_error((Label), gnutls_strerror(rc), host, errstr); \
264 #define expand_check_tlsvar(Varname, errstr) \
265 expand_check(state->Varname, US #Varname, &state->exp_##Varname, errstr)
267 #if GNUTLS_VERSION_NUMBER >= 0x020c00
268 # define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
269 # define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
270 # define HAVE_GNUTLS_RND
271 /* The security fix we provide with the gnutls_allow_auto_pkcs11 option
272 * (4.82 PP/09) introduces a compatibility regression. The symbol simply
273 * isn't available sometimes, so this needs to become a conditional
274 * compilation; the sanest way to deal with this being a problem on
275 * older OSes is to block it in the Local/Makefile with this compiler
277 # ifndef AVOID_GNUTLS_PKCS11
278 # define HAVE_GNUTLS_PKCS11
279 # endif /* AVOID_GNUTLS_PKCS11 */
285 /* ------------------------------------------------------------------------ */
286 /* Callback declarations */
288 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
289 static void exim_gnutls_logger_cb(int level, const char *message);
292 static int exim_sni_handling_cb(gnutls_session_t session);
295 static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
296 gnutls_datum_t * ocsp_response);
301 /* ------------------------------------------------------------------------ */
302 /* Static functions */
304 /*************************************************
306 *************************************************/
308 /* Called from lots of places when errors occur before actually starting to do
309 the TLS handshake, that is, while the session is still in clear. Always returns
310 DEFER for a server and FAIL for a client so that most calls can use "return
311 tls_error(...)" to do this processing and then give an appropriate return. A
312 single function is used for both server and client, because it is called from
313 some shared functions.
316 prefix text to include in the logged error
317 msg additional error string (may be NULL)
318 usually obtained from gnutls_strerror()
319 host NULL if setting up a server;
320 the connected host if setting up a client
321 errstr pointer to returned error string
323 Returns: OK/DEFER/FAIL
327 tls_error(const uschar *prefix, const char *msg, const host_item *host,
331 *errstr = string_sprintf("(%s)%s%s", prefix, msg ? ": " : "", msg ? msg : "");
332 return host ? FAIL : DEFER;
338 /*************************************************
339 * Deal with logging errors during I/O *
340 *************************************************/
342 /* We have to get the identity of the peer from saved data.
345 state the current GnuTLS exim state container
346 rc the GnuTLS error code, or 0 if it's a local error
347 when text identifying read or write
348 text local error text when ec is 0
354 record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
359 if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
360 msg = CS string_sprintf("%s: %s", US gnutls_strerror(rc),
361 US gnutls_alert_get_name(gnutls_alert_get(state->session)));
363 msg = gnutls_strerror(rc);
365 (void) tls_error(when, msg, state->host, &errstr);
368 log_write(0, LOG_MAIN, "H=%s [%s] TLS error on connection %s",
369 state->host->name, state->host->address, errstr);
372 uschar * conn_info = smtp_get_connection_info();
373 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0) conn_info += 5;
374 /* I'd like to get separated H= here, but too hard for now */
375 log_write(0, LOG_MAIN, "TLS error on %s %s", conn_info, errstr);
382 /*************************************************
383 * Set various Exim expansion vars *
384 *************************************************/
386 #define exim_gnutls_cert_err(Label) \
389 if (rc != GNUTLS_E_SUCCESS) \
391 DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", \
392 (Label), gnutls_strerror(rc)); \
398 import_cert(const gnutls_datum_t * cert, gnutls_x509_crt_t * crtp)
402 rc = gnutls_x509_crt_init(crtp);
403 exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
405 rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
406 exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
411 #undef exim_gnutls_cert_err
414 /* We set various Exim global variables from the state, once a session has
415 been established. With TLS callouts, may need to change this to stack
416 variables, or just re-call it with the server state after client callout
419 Make sure anything set here is unset in tls_getc().
423 tls_bits strength indicator
424 tls_certificate_verified bool indicator
425 tls_channelbinding_b64 for some SASL mechanisms
427 tls_peercert pointer to library internal
429 tls_sni a (UTF-8) string
430 tls_ourcert pointer to library internal
433 state the relevant exim_gnutls_state_st *
437 extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
439 gnutls_cipher_algorithm_t cipher;
440 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
443 gnutls_datum_t channel;
445 tls_support * tlsp = state->tlsp;
447 tlsp->active = state->fd_out;
449 cipher = gnutls_cipher_get(state->session);
450 /* returns size in "bytes" */
451 tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
453 tlsp->cipher = state->ciphersuite;
455 DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
457 tlsp->certificate_verified = state->peer_cert_verified;
459 tlsp->dane_verified = state->peer_dane_verified;
462 /* note that tls_channelbinding_b64 is not saved to the spool file, since it's
463 only available for use for authenticators while this TLS session is running. */
465 tls_channelbinding_b64 = NULL;
466 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
469 rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel);
471 DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc));
473 old_pool = store_pool;
474 store_pool = POOL_PERM;
475 tls_channelbinding_b64 = b64encode(channel.data, (int)channel.size);
476 store_pool = old_pool;
477 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
481 /* peercert is set in peer_status() */
482 tlsp->peerdn = state->peerdn;
483 tlsp->sni = state->received_sni;
485 /* record our certificate */
487 const gnutls_datum_t * cert = gnutls_certificate_get_ours(state->session);
488 gnutls_x509_crt_t crt;
490 tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
497 /*************************************************
498 * Setup up DH parameters *
499 *************************************************/
501 /* Generating the D-H parameters may take a long time. They only need to
502 be re-generated every so often, depending on security policy. What we do is to
503 keep these parameters in a file in the spool directory. If the file does not
504 exist, we generate them. This means that it is easy to cause a regeneration.
506 The new file is written as a temporary file and renamed, so that an incomplete
507 file is never present. If two processes both compute some new parameters, you
508 waste a bit of effort, but it doesn't seem worth messing around with locking to
511 Returns: OK/DEFER/FAIL
515 init_server_dh(uschar ** errstr)
518 unsigned int dh_bits;
520 uschar filename_buf[PATH_MAX];
521 uschar *filename = NULL;
523 uschar *exp_tls_dhparam;
524 BOOL use_file_in_spool = FALSE;
525 BOOL use_fixed_file = FALSE;
526 host_item *host = NULL; /* dummy for macros */
528 DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
530 rc = gnutls_dh_params_init(&dh_server_params);
531 exim_gnutls_err_check(rc, US"gnutls_dh_params_init");
536 if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam, errstr))
539 if (!exp_tls_dhparam)
541 DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
542 m.data = US std_dh_prime_default();
543 m.size = Ustrlen(m.data);
545 else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
546 use_file_in_spool = TRUE;
547 else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
549 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
552 else if (exp_tls_dhparam[0] != '/')
554 if (!(m.data = US std_dh_prime_named(exp_tls_dhparam)))
555 return tls_error(US"No standard prime named", CS exp_tls_dhparam, NULL, errstr);
556 m.size = Ustrlen(m.data);
560 use_fixed_file = TRUE;
561 filename = exp_tls_dhparam;
566 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
567 exim_gnutls_err_check(rc, US"gnutls_dh_params_import_pkcs3");
568 DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
572 #ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
573 /* If you change this constant, also change dh_param_fn_ext so that we can use a
574 different filename and ensure we have sufficient bits. */
575 dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
577 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL, errstr);
579 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
582 dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
584 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
588 /* Some clients have hard-coded limits. */
589 if (dh_bits > tls_dh_max_bits)
592 debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
594 dh_bits = tls_dh_max_bits;
597 if (use_file_in_spool)
599 if (!string_format(filename_buf, sizeof(filename_buf),
600 "%s/gnutls-params-%d", spool_directory, dh_bits))
601 return tls_error(US"overlong filename", NULL, NULL, errstr);
602 filename = filename_buf;
605 /* Open the cache file for reading and if successful, read it and set up the
608 if ((fd = Uopen(filename, O_RDONLY, 0)) >= 0)
614 if (fstat(fd, &statbuf) < 0) /* EIO */
618 return tls_error(US"TLS cache stat failed", strerror(saved_errno), NULL, errstr);
620 if (!S_ISREG(statbuf.st_mode))
623 return tls_error(US"TLS cache not a file", NULL, NULL, errstr);
625 if (!(fp = fdopen(fd, "rb")))
629 return tls_error(US"fdopen(TLS cache stat fd) failed",
630 strerror(saved_errno), NULL, errstr);
633 m.size = statbuf.st_size;
634 if (!(m.data = malloc(m.size)))
637 return tls_error(US"malloc failed", strerror(errno), NULL, errstr);
639 if (!(sz = fread(m.data, m.size, 1, fp)))
644 return tls_error(US"fread failed", strerror(saved_errno), NULL, errstr);
648 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
650 exim_gnutls_err_check(rc, US"gnutls_dh_params_import_pkcs3");
651 DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
654 /* If the file does not exist, fall through to compute new data and cache it.
655 If there was any other opening error, it is serious. */
657 else if (errno == ENOENT)
661 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
664 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
667 /* If ret < 0, either the cache file does not exist, or the data it contains
668 is not useful. One particular case of this is when upgrading from an older
669 release of Exim in which the data was stored in a different format. We don't
670 try to be clever and support both formats; we just regenerate new data in this
676 unsigned int dh_bits_gen = dh_bits;
678 if ((PATH_MAX - Ustrlen(filename)) < 10)
679 return tls_error(US"Filename too long to generate replacement",
680 CS filename, NULL, errstr);
682 temp_fn = string_copy(US "%s.XXXXXXX");
683 if ((fd = mkstemp(CS temp_fn)) < 0) /* modifies temp_fn */
684 return tls_error(US"Unable to open temp file", strerror(errno), NULL, errstr);
685 (void)fchown(fd, exim_uid, exim_gid); /* Probably not necessary */
687 /* GnuTLS overshoots!
688 * If we ask for 2236, we might get 2237 or more.
689 * But there's no way to ask GnuTLS how many bits there really are.
690 * We can ask how many bits were used in a TLS session, but that's it!
691 * The prime itself is hidden behind too much abstraction.
692 * So we ask for less, and proceed on a wing and a prayer.
693 * First attempt, subtracted 3 for 2233 and got 2240.
695 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
697 dh_bits_gen = dh_bits - 10;
699 debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
704 debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
706 rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen);
707 exim_gnutls_err_check(rc, US"gnutls_dh_params_generate2");
709 /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
710 and I confirmed that a NULL call to get the size first is how the GnuTLS
711 sample apps handle this. */
715 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
717 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
718 exim_gnutls_err_check(rc, US"gnutls_dh_params_export_pkcs3(NULL) sizing");
720 if (!(m.data = malloc(m.size)))
721 return tls_error(US"memory allocation failed", strerror(errno), NULL, errstr);
723 /* this will return a size 1 less than the allocation size above */
724 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
726 if (rc != GNUTLS_E_SUCCESS)
729 exim_gnutls_err_check(rc, US"gnutls_dh_params_export_pkcs3() real");
731 m.size = sz; /* shrink by 1, probably */
733 if ((sz = write_to_fd_buf(fd, m.data, (size_t) m.size)) != m.size)
736 return tls_error(US"TLS cache write D-H params failed",
737 strerror(errno), NULL, errstr);
740 if ((sz = write_to_fd_buf(fd, US"\n", 1)) != 1)
741 return tls_error(US"TLS cache write D-H params final newline failed",
742 strerror(errno), NULL, errstr);
744 if ((rc = close(fd)))
745 return tls_error(US"TLS cache write close() failed", strerror(errno), NULL, errstr);
747 if (Urename(temp_fn, filename) < 0)
748 return tls_error(string_sprintf("failed to rename \"%s\" as \"%s\"",
749 temp_fn, filename), strerror(errno), NULL, errstr);
751 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
754 DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
761 /* Create and install a selfsigned certificate, for use in server mode */
764 tls_install_selfsign(exim_gnutls_state_st * state, uschar ** errstr)
766 gnutls_x509_crt_t cert = NULL;
768 gnutls_x509_privkey_t pkey = NULL;
769 const uschar * where;
772 where = US"initialising pkey";
773 if ((rc = gnutls_x509_privkey_init(&pkey))) goto err;
775 where = US"initialising cert";
776 if ((rc = gnutls_x509_crt_init(&cert))) goto err;
778 where = US"generating pkey";
779 if ((rc = gnutls_x509_privkey_generate(pkey, GNUTLS_PK_RSA,
780 #ifdef SUPPORT_PARAM_TO_PK_BITS
781 gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_LOW),
788 where = US"configuring cert";
790 if ( (rc = gnutls_x509_crt_set_version(cert, 3))
791 || (rc = gnutls_x509_crt_set_serial(cert, &now, sizeof(now)))
792 || (rc = gnutls_x509_crt_set_activation_time(cert, now = time(NULL)))
793 || (rc = gnutls_x509_crt_set_expiration_time(cert, now + 60 * 60)) /* 1 hr */
794 || (rc = gnutls_x509_crt_set_key(cert, pkey))
796 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
797 GNUTLS_OID_X520_COUNTRY_NAME, 0, "UK", 2))
798 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
799 GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "Exim Developers", 15))
800 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
801 GNUTLS_OID_X520_COMMON_NAME, 0,
802 smtp_active_hostname, Ustrlen(smtp_active_hostname)))
806 where = US"signing cert";
807 if ((rc = gnutls_x509_crt_sign(cert, cert, pkey))) goto err;
809 where = US"installing selfsign cert";
811 if ((rc = gnutls_certificate_set_x509_key(state->x509_cred, &cert, 1, pkey)))
817 if (cert) gnutls_x509_crt_deinit(cert);
818 if (pkey) gnutls_x509_privkey_deinit(pkey);
822 rc = tls_error(where, gnutls_strerror(rc), NULL, errstr);
829 /* Add certificate and key, from files.
832 Zero or negative: good. Negate value for certificate index if < 0.
833 Greater than zero: FAIL or DEFER code.
837 tls_add_certfile(exim_gnutls_state_st * state, const host_item * host,
838 uschar * certfile, uschar * keyfile, uschar ** errstr)
840 int rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
841 CS certfile, CS keyfile, GNUTLS_X509_FMT_PEM);
844 string_sprintf("cert/key setup: cert=%s key=%s", certfile, keyfile),
845 gnutls_strerror(rc), host, errstr);
850 /*************************************************
851 * Variables re-expanded post-SNI *
852 *************************************************/
854 /* Called from both server and client code, via tls_init(), and also from
855 the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
857 We can tell the two apart by state->received_sni being non-NULL in callback.
859 The callback should not call us unless state->trigger_sni_changes is true,
860 which we are responsible for setting on the first pass through.
863 state exim_gnutls_state_st *
864 errstr error string pointer
866 Returns: OK/DEFER/FAIL
870 tls_expand_session_files(exim_gnutls_state_st * state, uschar ** errstr)
874 const host_item *host = state->host; /* macro should be reconsidered? */
875 uschar *saved_tls_certificate = NULL;
876 uschar *saved_tls_privatekey = NULL;
877 uschar *saved_tls_verify_certificates = NULL;
878 uschar *saved_tls_crl = NULL;
881 /* We check for tls_sni *before* expansion. */
882 if (!host) /* server */
883 if (!state->received_sni)
885 if ( state->tls_certificate
886 && ( Ustrstr(state->tls_certificate, US"tls_sni")
887 || Ustrstr(state->tls_certificate, US"tls_in_sni")
888 || Ustrstr(state->tls_certificate, US"tls_out_sni")
891 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
892 state->trigger_sni_changes = TRUE;
897 /* useful for debugging */
898 saved_tls_certificate = state->exp_tls_certificate;
899 saved_tls_privatekey = state->exp_tls_privatekey;
900 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
901 saved_tls_crl = state->exp_tls_crl;
904 rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
905 exim_gnutls_err_check(rc, US"gnutls_certificate_allocate_credentials");
907 #ifdef SUPPORT_SRV_OCSP_STACK
908 gnutls_certificate_set_flags(state->x509_cred, GNUTLS_CERTIFICATE_API_V2);
911 /* remember: expand_check_tlsvar() is expand_check() but fiddling with
912 state members, assuming consistent naming; and expand_check() returns
913 false if expansion failed, unless expansion was forced to fail. */
915 /* check if we at least have a certificate, before doing expensive
918 if (!expand_check_tlsvar(tls_certificate, errstr))
921 /* certificate is mandatory in server, optional in client */
923 if ( !state->exp_tls_certificate
924 || !*state->exp_tls_certificate
927 return tls_install_selfsign(state, errstr);
929 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
931 if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey, errstr))
934 /* tls_privatekey is optional, defaulting to same file as certificate */
936 if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
938 state->tls_privatekey = state->tls_certificate;
939 state->exp_tls_privatekey = state->exp_tls_certificate;
943 if (state->exp_tls_certificate && *state->exp_tls_certificate)
945 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
946 state->exp_tls_certificate, state->exp_tls_privatekey);
948 if (state->received_sni)
949 if ( Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0
950 && Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0
953 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
957 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
960 if (!host) /* server */
962 const uschar * clist = state->exp_tls_certificate;
963 const uschar * klist = state->exp_tls_privatekey;
964 const uschar * olist;
965 int csep = 0, ksep = 0, osep = 0, cnt = 0;
966 uschar * cfile, * kfile, * ofile;
969 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file", &ofile, errstr))
974 while (cfile = string_nextinlist(&clist, &csep, NULL, 0))
976 if (!(kfile = string_nextinlist(&klist, &ksep, NULL, 0)))
977 return tls_error(US"cert/key setup: out of keys", NULL, host, errstr);
978 else if (0 < (rc = tls_add_certfile(state, host, cfile, kfile, errstr)))
982 int gnutls_cert_index = -rc;
983 DEBUG(D_tls) debug_printf("TLS: cert/key %s registered\n", cfile);
985 /* Set the OCSP stapling server info */
989 if (gnutls_buggy_ocsp)
992 debug_printf("GnuTLS library is buggy for OCSP; avoiding\n");
994 else if ((ofile = string_nextinlist(&olist, &osep, NULL, 0)))
996 /* Use the full callback method for stapling just to get
997 observability. More efficient would be to read the file once only,
998 if it never changed (due to SNI). Would need restart on file update,
999 or watch datestamp. */
1001 # ifdef SUPPORT_SRV_OCSP_STACK
1002 rc = gnutls_certificate_set_ocsp_status_request_function2(
1003 state->x509_cred, gnutls_cert_index,
1004 server_ocsp_stapling_cb, ofile);
1006 exim_gnutls_err_check(rc,
1007 US"gnutls_certificate_set_ocsp_status_request_function2");
1012 debug_printf("oops; multiple OCSP files not supported\n");
1015 gnutls_certificate_set_ocsp_status_request_function(
1016 state->x509_cred, server_ocsp_stapling_cb, ofile);
1019 DEBUG(D_tls) debug_printf("OCSP response file = %s\n", ofile);
1022 DEBUG(D_tls) debug_printf("ran out of OCSP response files in list\n");
1028 if (0 < (rc = tls_add_certfile(state, host,
1029 state->exp_tls_certificate, state->exp_tls_privatekey, errstr)))
1031 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
1034 } /* tls_certificate */
1037 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
1038 provided. Experiment shows that, if the certificate file is empty, an unhelpful
1039 error message is provided. However, if we just refrain from setting anything up
1040 in that case, certificate verification fails, which seems to be the correct
1043 if (state->tls_verify_certificates && *state->tls_verify_certificates)
1045 if (!expand_check_tlsvar(tls_verify_certificates, errstr))
1047 #ifndef SUPPORT_SYSDEFAULT_CABUNDLE
1048 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1049 state->exp_tls_verify_certificates = NULL;
1051 if (state->tls_crl && *state->tls_crl)
1052 if (!expand_check_tlsvar(tls_crl, errstr))
1055 if (!(state->exp_tls_verify_certificates &&
1056 *state->exp_tls_verify_certificates))
1059 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
1060 /* With no tls_verify_certificates, we ignore tls_crl too */
1067 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
1071 #ifdef SUPPORT_SYSDEFAULT_CABUNDLE
1072 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1073 cert_count = gnutls_certificate_set_x509_system_trust(state->x509_cred);
1077 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
1079 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
1080 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
1085 #ifndef SUPPORT_CA_DIR
1086 /* The test suite passes in /dev/null; we could check for that path explicitly,
1087 but who knows if someone has some weird FIFO which always dumps some certs, or
1088 other weirdness. The thing we really want to check is that it's not a
1089 directory, since while OpenSSL supports that, GnuTLS does not.
1090 So s/!S_ISREG/S_ISDIR/ and change some messaging ... */
1091 if (S_ISDIR(statbuf.st_mode))
1094 debug_printf("verify certificates path is a dir: \"%s\"\n",
1095 state->exp_tls_verify_certificates);
1096 log_write(0, LOG_MAIN|LOG_PANIC,
1097 "tls_verify_certificates \"%s\" is a directory",
1098 state->exp_tls_verify_certificates);
1103 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
1104 state->exp_tls_verify_certificates, statbuf.st_size);
1106 if (statbuf.st_size == 0)
1109 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
1115 #ifdef SUPPORT_CA_DIR
1116 (statbuf.st_mode & S_IFMT) == S_IFDIR
1118 gnutls_certificate_set_x509_trust_dir(state->x509_cred,
1119 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM)
1122 gnutls_certificate_set_x509_trust_file(state->x509_cred,
1123 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
1129 exim_gnutls_err_check(rc, US"setting certificate trust");
1131 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
1133 if (state->tls_crl && *state->tls_crl &&
1134 state->exp_tls_crl && *state->exp_tls_crl)
1136 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
1137 cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
1138 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM);
1142 exim_gnutls_err_check(rc, US"gnutls_certificate_set_x509_crl_file");
1144 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
1153 /*************************************************
1154 * Set X.509 state variables *
1155 *************************************************/
1157 /* In GnuTLS, the registered cert/key are not replaced by a later
1158 set of a cert/key, so for SNI support we need a whole new x509_cred
1159 structure. Which means various other non-re-expanded pieces of state
1160 need to be re-set in the new struct, so the setting logic is pulled
1164 state exim_gnutls_state_st *
1165 errstr error string pointer
1167 Returns: OK/DEFER/FAIL
1171 tls_set_remaining_x509(exim_gnutls_state_st *state, uschar ** errstr)
1174 const host_item *host = state->host; /* macro should be reconsidered? */
1176 /* Create D-H parameters, or read them from the cache file. This function does
1177 its own SMTP error messaging. This only happens for the server, TLS D-H ignores
1178 client-side params. */
1182 if (!dh_server_params)
1184 rc = init_server_dh(errstr);
1185 if (rc != OK) return rc;
1187 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
1190 /* Link the credentials to the session. */
1192 rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
1193 exim_gnutls_err_check(rc, US"gnutls_credentials_set");
1198 /*************************************************
1199 * Initialize for GnuTLS *
1200 *************************************************/
1203 #ifndef DISABLE_OCSP
1206 tls_is_buggy_ocsp(void)
1209 uschar maj, mid, mic;
1211 s = CUS gnutls_check_version(NULL);
1215 while (*s && *s != '.') s++;
1216 mid = atoi(CCS ++s);
1223 while (*s && *s != '.') s++;
1224 mic = atoi(CCS ++s);
1225 return mic <= (mid == 3 ? 16 : 3);
1234 /* Called from both server and client code. In the case of a server, errors
1235 before actual TLS negotiation return DEFER.
1238 host connected host, if client; NULL if server
1239 certificate certificate file
1240 privatekey private key file
1241 sni TLS SNI to send, sometimes when client; else NULL
1244 require_ciphers tls_require_ciphers setting
1245 caller_state returned state-info structure
1246 errstr error string pointer
1248 Returns: OK/DEFER/FAIL
1253 const host_item *host,
1254 const uschar *certificate,
1255 const uschar *privatekey,
1259 const uschar *require_ciphers,
1260 exim_gnutls_state_st **caller_state,
1263 exim_gnutls_state_st *state;
1268 BOOL want_default_priorities;
1270 if (!exim_gnutls_base_init_done)
1272 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1274 #ifdef HAVE_GNUTLS_PKCS11
1275 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1276 which loads modules from a config file, which sounds good and may be wanted
1277 by some sysadmin, but also means in common configurations that GNOME keyring
1278 environment variables are used and so breaks for users calling mailq.
1279 To prevent this, we init PKCS11 first, which is the documented approach. */
1280 if (!gnutls_allow_auto_pkcs11)
1282 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
1283 exim_gnutls_err_check(rc, US"gnutls_pkcs11_init");
1287 rc = gnutls_global_init();
1288 exim_gnutls_err_check(rc, US"gnutls_global_init");
1290 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1293 gnutls_global_set_log_function(exim_gnutls_logger_cb);
1294 /* arbitrarily chosen level; bump upto 9 for more */
1295 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
1299 #ifndef DISABLE_OCSP
1300 if (tls_ocsp_file && (gnutls_buggy_ocsp = tls_is_buggy_ocsp()))
1301 log_write(0, LOG_MAIN, "OCSP unusable with this GnuTLS library version");
1304 exim_gnutls_base_init_done = TRUE;
1309 state = &state_client;
1310 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1311 state->tlsp = &tls_out;
1312 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1313 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1317 state = &state_server;
1318 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1319 state->tlsp = &tls_in;
1320 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1321 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1323 exim_gnutls_err_check(rc, US"gnutls_init");
1327 state->tls_certificate = certificate;
1328 state->tls_privatekey = privatekey;
1329 state->tls_require_ciphers = require_ciphers;
1330 state->tls_sni = sni;
1331 state->tls_verify_certificates = cas;
1332 state->tls_crl = crl;
1334 /* This handles the variables that might get re-expanded after TLS SNI;
1335 that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1338 debug_printf("Expanding various TLS configuration options for session credentials.\n");
1339 if ((rc = tls_expand_session_files(state, errstr)) != OK) return rc;
1341 /* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1342 requires a new structure afterwards. */
1344 if ((rc = tls_set_remaining_x509(state, errstr)) != OK) return rc;
1346 /* set SNI in client, only */
1349 if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni, errstr))
1351 if (state->tlsp->sni && *state->tlsp->sni)
1354 debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1355 sz = Ustrlen(state->tlsp->sni);
1356 rc = gnutls_server_name_set(state->session,
1357 GNUTLS_NAME_DNS, state->tlsp->sni, sz);
1358 exim_gnutls_err_check(rc, US"gnutls_server_name_set");
1361 else if (state->tls_sni)
1362 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1363 "have an SNI set for a server [%s]\n", state->tls_sni);
1365 /* This is the priority string support,
1366 http://www.gnutls.org/manual/html_node/Priority-Strings.html
1367 and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1368 This was backwards incompatible, but means Exim no longer needs to track
1369 all algorithms and provide string forms for them. */
1371 want_default_priorities = TRUE;
1373 if (state->tls_require_ciphers && *state->tls_require_ciphers)
1375 if (!expand_check_tlsvar(tls_require_ciphers, errstr))
1377 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1379 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n",
1380 state->exp_tls_require_ciphers);
1382 rc = gnutls_priority_init(&state->priority_cache,
1383 CS state->exp_tls_require_ciphers, &errpos);
1384 want_default_priorities = FALSE;
1385 p = state->exp_tls_require_ciphers;
1388 if (want_default_priorities)
1391 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n",
1392 exim_default_gnutls_priority);
1393 rc = gnutls_priority_init(&state->priority_cache,
1394 exim_default_gnutls_priority, &errpos);
1395 p = US exim_default_gnutls_priority;
1398 exim_gnutls_err_check(rc, string_sprintf(
1399 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1400 p, errpos - CS p, errpos));
1402 rc = gnutls_priority_set(state->session, state->priority_cache);
1403 exim_gnutls_err_check(rc, US"gnutls_priority_set");
1405 gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1407 /* Reduce security in favour of increased compatibility, if the admin
1408 decides to make that trade-off. */
1409 if (gnutls_compat_mode)
1411 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1412 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1413 gnutls_session_enable_compatibility_mode(state->session);
1415 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1419 *caller_state = state;
1425 /*************************************************
1426 * Extract peer information *
1427 *************************************************/
1429 /* Called from both server and client code.
1430 Only this is allowed to set state->peerdn and state->have_set_peerdn
1431 and we use that to detect double-calls.
1433 NOTE: the state blocks last while the TLS connection is up, which is fine
1434 for logging in the server side, but for the client side, we log after teardown
1435 in src/deliver.c. While the session is up, we can twist about states and
1436 repoint tls_* globals, but those variables used for logging or other variable
1437 expansion that happens _after_ delivery need to have a longer life-time.
1439 So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1440 doing this more than once per generation of a state context. We set them in
1441 the state context, and repoint tls_* to them. After the state goes away, the
1442 tls_* copies of the pointers remain valid and client delivery logging is happy.
1444 tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1448 state exim_gnutls_state_st *
1449 errstr pointer to error string
1451 Returns: OK/DEFER/FAIL
1455 peer_status(exim_gnutls_state_st *state, uschar ** errstr)
1457 uschar cipherbuf[256];
1458 const gnutls_datum_t *cert_list;
1460 unsigned int cert_list_size = 0;
1461 gnutls_protocol_t protocol;
1462 gnutls_cipher_algorithm_t cipher;
1463 gnutls_kx_algorithm_t kx;
1464 gnutls_mac_algorithm_t mac;
1465 gnutls_certificate_type_t ct;
1466 gnutls_x509_crt_t crt;
1470 if (state->have_set_peerdn)
1472 state->have_set_peerdn = TRUE;
1474 state->peerdn = NULL;
1477 cipher = gnutls_cipher_get(state->session);
1478 protocol = gnutls_protocol_get_version(state->session);
1479 mac = gnutls_mac_get(state->session);
1480 kx = gnutls_kx_get(state->session);
1482 string_format(cipherbuf, sizeof(cipherbuf),
1484 gnutls_protocol_get_name(protocol),
1485 gnutls_cipher_suite_get_name(kx, cipher, mac),
1486 (int) gnutls_cipher_get_key_size(cipher) * 8);
1488 /* I don't see a way that spaces could occur, in the current GnuTLS
1489 code base, but it was a concern in the old code and perhaps older GnuTLS
1490 releases did return "TLS 1.0"; play it safe, just in case. */
1491 for (p = cipherbuf; *p != '\0'; ++p)
1494 old_pool = store_pool;
1495 store_pool = POOL_PERM;
1496 state->ciphersuite = string_copy(cipherbuf);
1497 store_pool = old_pool;
1498 state->tlsp->cipher = state->ciphersuite;
1501 cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
1503 if (cert_list == NULL || cert_list_size == 0)
1505 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1506 cert_list, cert_list_size);
1507 if (state->verify_requirement >= VERIFY_REQUIRED)
1508 return tls_error(US"certificate verification failed",
1509 "no certificate received from peer", state->host, errstr);
1513 ct = gnutls_certificate_type_get(state->session);
1514 if (ct != GNUTLS_CRT_X509)
1516 const char *ctn = gnutls_certificate_type_get_name(ct);
1518 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1519 if (state->verify_requirement >= VERIFY_REQUIRED)
1520 return tls_error(US"certificate verification not possible, unhandled type",
1521 ctn, state->host, errstr);
1525 #define exim_gnutls_peer_err(Label) \
1527 if (rc != GNUTLS_E_SUCCESS) \
1529 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1530 (Label), gnutls_strerror(rc)); \
1531 if (state->verify_requirement >= VERIFY_REQUIRED) \
1532 return tls_error((Label), gnutls_strerror(rc), state->host, errstr); \
1537 rc = import_cert(&cert_list[0], &crt);
1538 exim_gnutls_peer_err(US"cert 0");
1540 state->tlsp->peercert = state->peercert = crt;
1543 rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1544 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1546 exim_gnutls_peer_err(US"getting size for cert DN failed");
1547 return FAIL; /* should not happen */
1549 dn_buf = store_get_perm(sz);
1550 rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1551 exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1553 state->peerdn = dn_buf;
1556 #undef exim_gnutls_peer_err
1562 /*************************************************
1563 * Verify peer certificate *
1564 *************************************************/
1566 /* Called from both server and client code.
1567 *Should* be using a callback registered with
1568 gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1569 the peer information, but that's too new for some OSes.
1572 state exim_gnutls_state_st *
1573 errstr where to put an error message
1576 FALSE if the session should be rejected
1577 TRUE if the cert is okay or we just don't care
1581 verify_certificate(exim_gnutls_state_st * state, uschar ** errstr)
1586 if (state->verify_requirement == VERIFY_NONE)
1591 if ((rc = peer_status(state, errstr)) != OK)
1593 verify = GNUTLS_CERT_INVALID;
1594 *errstr = US"certificate not supplied";
1600 if (state->verify_requirement == VERIFY_DANE && state->host)
1602 /* Using dane_verify_session_crt() would be easy, as it does it all for us
1603 including talking to a DNS resolver. But we want to do that bit ourselves
1604 as the testsuite intercepts and fakes its own DNS environment. */
1609 const gnutls_datum_t * certlist =
1610 gnutls_certificate_get_peers(state->session, &lsize);
1611 int usage = tls_out.tlsa_usage;
1613 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1614 /* Split the TLSA records into two sets, TA and EE selectors. Run the
1615 dane-verification separately so that we know which selector verified;
1616 then we know whether to do CA-chain-verification and name-verification
1617 (needed for TA but not EE). */
1619 if (usage == ((1<<DANESSL_USAGE_DANE_TA) | (1<<DANESSL_USAGE_DANE_EE)))
1620 { /* a mixed-usage bundle */
1625 for(nrec = 0; state->dane_data_len[nrec]; ) nrec++;
1628 dd = store_get(nrec * sizeof(uschar *));
1629 ddl = store_get(nrec * sizeof(int));
1632 if ((rc = dane_state_init(&s, 0)))
1635 for (usage = DANESSL_USAGE_DANE_EE;
1636 usage >= DANESSL_USAGE_DANE_TA; usage--)
1637 { /* take records with this usage */
1638 for (j = i = 0; i < nrec; i++)
1639 if (state->dane_data[i][0] == usage)
1641 dd[j] = state->dane_data[i];
1642 ddl[j++] = state->dane_data_len[i];
1649 if ((rc = dane_raw_tlsa(s, &r, (char * const *)dd, ddl, 1, 0)))
1652 if ((rc = dane_verify_crt_raw(s, certlist, lsize,
1653 gnutls_certificate_type_get(state->session),
1655 usage == DANESSL_USAGE_DANE_EE
1656 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1660 debug_printf("TLSA record problem: %s\n", dane_strerror(rc));
1662 else if (verify == 0) /* verification passed */
1670 if (rc) goto tlsa_prob;
1675 if ( (rc = dane_state_init(&s, 0))
1676 || (rc = dane_raw_tlsa(s, &r, state->dane_data, state->dane_data_len,
1678 || (rc = dane_verify_crt_raw(s, certlist, lsize,
1679 gnutls_certificate_type_get(state->session),
1681 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1682 usage == (1 << DANESSL_USAGE_DANE_EE)
1683 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1692 if (verify != 0) /* verification failed */
1695 (void) dane_verification_status_print(verify, &str, 0);
1696 *errstr = US str.data; /* don't bother to free */
1699 state->peer_dane_verified = TRUE;
1701 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1702 /* If a TA-mode TLSA record was used for verification we must additionally
1703 verify the CA chain and the cert name. For EE-mode, skip it. */
1705 if (usage & (1 << DANESSL_USAGE_DANE_EE))
1708 state->peer_cert_verified = TRUE;
1714 rc = gnutls_certificate_verify_peers2(state->session, &verify);
1717 /* Handle the result of verification. INVALID is set if any others are. */
1719 if (rc < 0 || verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED))
1721 state->peer_cert_verified = FALSE;
1723 *errstr = verify & GNUTLS_CERT_REVOKED
1724 ? US"certificate revoked" : US"certificate invalid";
1727 debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
1728 *errstr, state->peerdn ? state->peerdn : US"<unset>");
1730 if (state->verify_requirement >= VERIFY_REQUIRED)
1733 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1738 if (state->exp_tls_verify_cert_hostnames)
1741 const uschar * list = state->exp_tls_verify_cert_hostnames;
1743 while ((name = string_nextinlist(&list, &sep, NULL, 0)))
1744 if (gnutls_x509_crt_check_hostname(state->tlsp->peercert, CS name))
1749 debug_printf("TLS certificate verification failed: cert name mismatch\n");
1750 if (state->verify_requirement >= VERIFY_REQUIRED)
1755 state->peer_cert_verified = TRUE;
1756 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
1757 state->peerdn ? state->peerdn : US"<unset>");
1761 state->tlsp->peerdn = state->peerdn;
1766 *errstr = string_sprintf("TLSA record problem: %s", dane_strerror(rc));
1770 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1777 /* ------------------------------------------------------------------------ */
1780 /* Logging function which can be registered with
1781 * gnutls_global_set_log_function()
1782 * gnutls_global_set_log_level() 0..9
1784 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1786 exim_gnutls_logger_cb(int level, const char *message)
1788 size_t len = strlen(message);
1791 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1794 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1795 message[len-1] == '\n' ? "" : "\n");
1800 /* Called after client hello, should handle SNI work.
1801 This will always set tls_sni (state->received_sni) if available,
1802 and may trigger presenting different certificates,
1803 if state->trigger_sni_changes is TRUE.
1805 Should be registered with
1806 gnutls_handshake_set_post_client_hello_function()
1808 "This callback must return 0 on success or a gnutls error code to terminate the
1811 For inability to get SNI information, we return 0.
1812 We only return non-zero if re-setup failed.
1813 Only used for server-side TLS.
1817 exim_sni_handling_cb(gnutls_session_t session)
1819 char sni_name[MAX_HOST_LEN];
1820 size_t data_len = MAX_HOST_LEN;
1821 exim_gnutls_state_st *state = &state_server;
1822 unsigned int sni_type;
1824 uschar * dummy_errstr;
1826 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1827 if (rc != GNUTLS_E_SUCCESS)
1830 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1831 debug_printf("TLS: no SNI presented in handshake.\n");
1833 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1834 gnutls_strerror(rc), rc);
1839 if (sni_type != GNUTLS_NAME_DNS)
1841 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1845 /* We now have a UTF-8 string in sni_name */
1846 old_pool = store_pool;
1847 store_pool = POOL_PERM;
1848 state->received_sni = string_copyn(US sni_name, data_len);
1849 store_pool = old_pool;
1851 /* We set this one now so that variable expansions below will work */
1852 state->tlsp->sni = state->received_sni;
1854 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1855 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1857 if (!state->trigger_sni_changes)
1860 if ((rc = tls_expand_session_files(state, &dummy_errstr)) != OK)
1862 /* If the setup of certs/etc failed before handshake, TLS would not have
1863 been offered. The best we can do now is abort. */
1864 return GNUTLS_E_APPLICATION_ERROR_MIN;
1867 rc = tls_set_remaining_x509(state, &dummy_errstr);
1868 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1875 #ifndef DISABLE_OCSP
1878 server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1879 gnutls_datum_t * ocsp_response)
1882 DEBUG(D_tls) debug_printf("OCSP stapling callback: %s\n", US ptr);
1884 if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1886 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1888 tls_in.ocsp = OCSP_NOT_RESP;
1889 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1892 tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1899 #ifndef DISABLE_EVENT
1901 We use this callback to get observability and detail-level control
1902 for an exim TLS connection (either direction), raising a tls:cert event
1903 for each cert in the chain presented by the peer. Any event
1904 can deny verification.
1906 Return 0 for the handshake to continue or non-zero to terminate.
1910 verify_cb(gnutls_session_t session)
1912 const gnutls_datum_t * cert_list;
1913 unsigned int cert_list_size = 0;
1914 gnutls_x509_crt_t crt;
1917 exim_gnutls_state_st * state = gnutls_session_get_ptr(session);
1919 cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
1921 while (cert_list_size--)
1923 rc = import_cert(&cert_list[cert_list_size], &crt);
1924 if (rc != GNUTLS_E_SUCCESS)
1926 DEBUG(D_tls) debug_printf("TLS: peer cert problem: depth %d: %s\n",
1927 cert_list_size, gnutls_strerror(rc));
1931 state->tlsp->peercert = crt;
1932 if ((yield = event_raise(state->event_action,
1933 US"tls:cert", string_sprintf("%d", cert_list_size))))
1935 log_write(0, LOG_MAIN,
1936 "SSL verify denied by event-action: depth=%d: %s",
1937 cert_list_size, yield);
1938 return 1; /* reject */
1940 state->tlsp->peercert = NULL;
1950 /* ------------------------------------------------------------------------ */
1951 /* Exported functions */
1956 /*************************************************
1957 * Start a TLS session in a server *
1958 *************************************************/
1960 /* This is called when Exim is running as a server, after having received
1961 the STARTTLS command. It must respond to that command, and then negotiate
1965 require_ciphers list of allowed ciphers or NULL
1966 errstr pointer to error string
1968 Returns: OK on success
1969 DEFER for errors before the start of the negotiation
1970 FAIL for errors during the negotiation; the server can't
1975 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
1978 exim_gnutls_state_st * state = NULL;
1980 /* Check for previous activation */
1981 if (tls_in.active >= 0)
1983 tls_error(US"STARTTLS received after TLS started", "", NULL, errstr);
1984 smtp_printf("554 Already in TLS\r\n", FALSE);
1988 /* Initialize the library. If it fails, it will already have logged the error
1989 and sent an SMTP response. */
1991 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
1993 if ((rc = tls_init(NULL, tls_certificate, tls_privatekey,
1994 NULL, tls_verify_certificates, tls_crl,
1995 require_ciphers, &state, errstr)) != OK) return rc;
1997 /* If this is a host for which certificate verification is mandatory or
1998 optional, set up appropriately. */
2000 if (verify_check_host(&tls_verify_hosts) == OK)
2003 debug_printf("TLS: a client certificate will be required.\n");
2004 state->verify_requirement = VERIFY_REQUIRED;
2005 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2007 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2010 debug_printf("TLS: a client certificate will be requested but not required.\n");
2011 state->verify_requirement = VERIFY_OPTIONAL;
2012 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2017 debug_printf("TLS: a client certificate will not be requested.\n");
2018 state->verify_requirement = VERIFY_NONE;
2019 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2022 #ifndef DISABLE_EVENT
2025 state->event_action = event_action;
2026 gnutls_session_set_ptr(state->session, state);
2027 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2031 /* Register SNI handling; always, even if not in tls_certificate, so that the
2032 expansion variable $tls_sni is always available. */
2034 gnutls_handshake_set_post_client_hello_function(state->session,
2035 exim_sni_handling_cb);
2037 /* Set context and tell client to go ahead, except in the case of TLS startup
2038 on connection, where outputting anything now upsets the clients and tends to
2039 make them disconnect. We need to have an explicit fflush() here, to force out
2040 the response. Other smtp_printf() calls do not need it, because in non-TLS
2041 mode, the fflush() happens when smtp_getc() is called. */
2043 if (!state->tlsp->on_connect)
2045 smtp_printf("220 TLS go ahead\r\n", FALSE);
2049 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2050 that the GnuTLS library doesn't. */
2052 gnutls_transport_set_ptr2(state->session,
2053 (gnutls_transport_ptr_t)(long) fileno(smtp_in),
2054 (gnutls_transport_ptr_t)(long) fileno(smtp_out));
2055 state->fd_in = fileno(smtp_in);
2056 state->fd_out = fileno(smtp_out);
2058 sigalrm_seen = FALSE;
2059 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2061 rc = gnutls_handshake(state->session);
2062 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2065 if (rc != GNUTLS_E_SUCCESS)
2067 /* It seems that, except in the case of a timeout, we have to close the
2068 connection right here; otherwise if the other end is running OpenSSL it hangs
2069 until the server times out. */
2073 tls_error(US"gnutls_handshake", "timed out", NULL, errstr);
2074 gnutls_db_remove_session(state->session);
2078 tls_error(US"gnutls_handshake", gnutls_strerror(rc), NULL, errstr);
2079 (void) gnutls_alert_send_appropriate(state->session, rc);
2080 gnutls_deinit(state->session);
2081 gnutls_certificate_free_credentials(state->x509_cred);
2083 shutdown(state->fd_out, SHUT_WR);
2084 for (rc = 1024; fgetc(smtp_in) != EOF && rc > 0; ) rc--; /* drain skt */
2085 (void)fclose(smtp_out);
2086 (void)fclose(smtp_in);
2087 smtp_out = smtp_in = NULL;
2093 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
2095 /* Verify after the fact */
2097 if (!verify_certificate(state, errstr))
2099 if (state->verify_requirement != VERIFY_OPTIONAL)
2101 (void) tls_error(US"certificate verification failed", *errstr, NULL, errstr);
2105 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
2109 /* Figure out peer DN, and if authenticated, etc. */
2111 if ((rc = peer_status(state, NULL)) != OK) return rc;
2113 /* Sets various Exim expansion variables; always safe within server */
2115 extract_exim_vars_from_tls_state(state);
2117 /* TLS has been set up. Adjust the input functions to read via TLS,
2118 and initialize appropriately. */
2120 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2122 receive_getc = tls_getc;
2123 receive_getbuf = tls_getbuf;
2124 receive_get_cache = tls_get_cache;
2125 receive_ungetc = tls_ungetc;
2126 receive_feof = tls_feof;
2127 receive_ferror = tls_ferror;
2128 receive_smtp_buffered = tls_smtp_buffered;
2137 tls_client_setup_hostname_checks(host_item * host, exim_gnutls_state_st * state,
2138 smtp_transport_options_block * ob)
2140 if (verify_check_given_host(&ob->tls_verify_cert_hostnames, host) == OK)
2142 state->exp_tls_verify_cert_hostnames =
2144 string_domain_utf8_to_alabel(host->name, NULL);
2149 debug_printf("TLS: server cert verification includes hostname: \"%s\".\n",
2150 state->exp_tls_verify_cert_hostnames);
2158 /* Given our list of RRs from the TLSA lookup, build a lookup block in
2159 GnuTLS-DANE's preferred format. Hang it on the state str for later
2160 use in DANE verification.
2162 We point at the dnsa data not copy it, so it must remain valid until
2163 after verification is done.*/
2166 dane_tlsa_load(exim_gnutls_state_st * state, dns_answer * dnsa)
2171 const char ** dane_data;
2172 int * dane_data_len;
2174 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS), i = 1;
2176 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2177 ) if (rr->type == T_TLSA) i++;
2179 dane_data = store_get(i * sizeof(uschar *));
2180 dane_data_len = store_get(i * sizeof(int));
2182 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS), i = 0;
2184 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2185 ) if (rr->type == T_TLSA)
2187 const uschar * p = rr->data;
2188 uint8_t usage = p[0], sel = p[1], type = p[2];
2191 debug_printf("TLSA: %d %d %d size %d\n", usage, sel, type, rr->size);
2193 if ( (usage != DANESSL_USAGE_DANE_TA && usage != DANESSL_USAGE_DANE_EE)
2194 || (sel != 0 && sel != 1)
2199 case 0: /* Full: cannot check at present */
2201 case 1: if (rr->size != 3 + 256/8) continue; /* sha2-256 */
2203 case 2: if (rr->size != 3 + 512/8) continue; /* sha2-512 */
2208 tls_out.tlsa_usage |= 1<<usage;
2210 dane_data_len[i++] = rr->size;
2213 if (!i) return FALSE;
2215 dane_data[i] = NULL;
2216 dane_data_len[i] = 0;
2218 state->dane_data = (char * const *)dane_data;
2219 state->dane_data_len = dane_data_len;
2226 /*************************************************
2227 * Start a TLS session in a client *
2228 *************************************************/
2230 /* Called from the smtp transport after STARTTLS has been accepted.
2233 fd the fd of the connection
2234 host connected host (for messages)
2235 addr the first address (not used)
2236 tb transport (always smtp)
2237 tlsa_dnsa non-NULL, either request or require dane for this host, and
2238 a TLSA record found. Therefore, dane verify required.
2239 Which implies cert must be requested and supplied, dane
2240 verify must pass, and cert verify irrelevant (incl.
2241 hostnames), and (caller handled) require_tls
2242 errstr error string pointer
2244 Returns: OK/DEFER/FAIL (because using common functions),
2245 but for a client, DEFER and FAIL have the same meaning
2249 tls_client_start(int fd, host_item *host,
2250 address_item *addr ARG_UNUSED,
2251 transport_instance * tb,
2252 #ifdef EXPERIMENTAL_DANE
2253 dns_answer * tlsa_dnsa,
2257 smtp_transport_options_block *ob =
2258 (smtp_transport_options_block *)tb->options_block;
2260 exim_gnutls_state_st * state = NULL;
2261 #ifndef DISABLE_OCSP
2263 verify_check_given_host(&ob->hosts_require_ocsp, host) == OK;
2264 BOOL request_ocsp = require_ocsp ? TRUE
2265 : verify_check_given_host(&ob->hosts_request_ocsp, host) == OK;
2268 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
2270 if ((rc = tls_init(host, ob->tls_certificate, ob->tls_privatekey,
2271 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
2272 ob->tls_require_ciphers, &state, errstr)) != OK)
2276 int dh_min_bits = ob->tls_dh_min_bits;
2277 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
2280 debug_printf("WARNING: tls_dh_min_bits far too low,"
2281 " clamping %d up to %d\n",
2282 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
2283 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
2286 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
2287 " acceptable bits to %d\n",
2289 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
2292 /* Stick to the old behaviour for compatibility if tls_verify_certificates is
2293 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
2294 the specified host patterns if one of them is defined */
2297 if (tlsa_dnsa && dane_tlsa_load(state, tlsa_dnsa))
2300 debug_printf("TLS: server certificate DANE required.\n");
2301 state->verify_requirement = VERIFY_DANE;
2302 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2306 if ( ( state->exp_tls_verify_certificates
2307 && !ob->tls_verify_hosts
2308 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2310 || verify_check_given_host(&ob->tls_verify_hosts, host) == OK
2313 tls_client_setup_hostname_checks(host, state, ob);
2315 debug_printf("TLS: server certificate verification required.\n");
2316 state->verify_requirement = VERIFY_REQUIRED;
2317 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2319 else if (verify_check_given_host(&ob->tls_try_verify_hosts, host) == OK)
2321 tls_client_setup_hostname_checks(host, state, ob);
2323 debug_printf("TLS: server certificate verification optional.\n");
2324 state->verify_requirement = VERIFY_OPTIONAL;
2325 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2330 debug_printf("TLS: server certificate verification not required.\n");
2331 state->verify_requirement = VERIFY_NONE;
2332 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2335 #ifndef DISABLE_OCSP
2336 /* supported since GnuTLS 3.1.3 */
2339 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
2340 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
2341 NULL, 0, NULL)) != OK)
2342 return tls_error(US"cert-status-req",
2343 gnutls_strerror(rc), state->host, errstr);
2344 tls_out.ocsp = OCSP_NOT_RESP;
2348 #ifndef DISABLE_EVENT
2349 if (tb->event_action)
2351 state->event_action = tb->event_action;
2352 gnutls_session_set_ptr(state->session, state);
2353 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2357 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr_t)(long) fd);
2361 DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
2362 /* There doesn't seem to be a built-in timeout on connection. */
2364 sigalrm_seen = FALSE;
2365 alarm(ob->command_timeout);
2367 rc = gnutls_handshake(state->session);
2368 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2371 if (rc != GNUTLS_E_SUCCESS)
2374 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_USER_CANCELED);
2375 return tls_error(US"gnutls_handshake", "timed out", state->host, errstr);
2378 return tls_error(US"gnutls_handshake", gnutls_strerror(rc), state->host, errstr);
2380 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
2384 if (!verify_certificate(state, errstr))
2385 return tls_error(US"certificate verification failed", *errstr, state->host, errstr);
2387 #ifndef DISABLE_OCSP
2392 gnutls_datum_t stapling;
2393 gnutls_ocsp_resp_t resp;
2394 gnutls_datum_t printed;
2395 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
2396 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
2397 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
2398 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
2401 debug_printf("%.4096s", printed.data);
2402 gnutls_free(printed.data);
2405 (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host, errstr);
2408 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
2410 tls_out.ocsp = OCSP_FAILED;
2411 return tls_error(US"certificate status check failed", NULL, state->host, errstr);
2413 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
2414 tls_out.ocsp = OCSP_VFIED;
2418 /* Figure out peer DN, and if authenticated, etc. */
2420 if ((rc = peer_status(state, errstr)) != OK)
2423 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
2425 extract_exim_vars_from_tls_state(state);
2433 /*************************************************
2434 * Close down a TLS session *
2435 *************************************************/
2437 /* This is also called from within a delivery subprocess forked from the
2438 daemon, to shut down the TLS library, without actually doing a shutdown (which
2439 would tamper with the TLS session in the parent process).
2441 Arguments: TRUE if gnutls_bye is to be called
2446 tls_close(BOOL is_server, BOOL shutdown)
2448 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2450 if (!state->tlsp || state->tlsp->active < 0) return; /* TLS was not active */
2454 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
2455 gnutls_bye(state->session, GNUTLS_SHUT_WR);
2458 gnutls_deinit(state->session);
2459 gnutls_certificate_free_credentials(state->x509_cred);
2462 state->tlsp->active = -1;
2463 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
2465 if ((state_server.session == NULL) && (state_client.session == NULL))
2467 gnutls_global_deinit();
2468 exim_gnutls_base_init_done = FALSE;
2476 tls_refill(unsigned lim)
2478 exim_gnutls_state_st * state = &state_server;
2481 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
2482 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
2484 sigalrm_seen = FALSE;
2485 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2486 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
2487 MIN(ssl_xfer_buffer_size, lim));
2490 /* Timeouts do not get this far; see command_timeout_handler().
2491 A zero-byte return appears to mean that the TLS session has been
2492 closed down, not that the socket itself has been closed down. Revert to
2493 non-TLS handling. */
2497 DEBUG(D_tls) debug_printf("Got tls read timeout\n");
2498 state->xfer_error = 1;
2502 else if (inbytes == 0)
2504 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2506 receive_getc = smtp_getc;
2507 receive_getbuf = smtp_getbuf;
2508 receive_get_cache = smtp_get_cache;
2509 receive_ungetc = smtp_ungetc;
2510 receive_feof = smtp_feof;
2511 receive_ferror = smtp_ferror;
2512 receive_smtp_buffered = smtp_buffered;
2514 gnutls_deinit(state->session);
2515 gnutls_certificate_free_credentials(state->x509_cred);
2517 state->session = NULL;
2518 state->tlsp->active = -1;
2519 state->tlsp->bits = 0;
2520 state->tlsp->certificate_verified = FALSE;
2521 tls_channelbinding_b64 = NULL;
2522 state->tlsp->cipher = NULL;
2523 state->tlsp->peercert = NULL;
2524 state->tlsp->peerdn = NULL;
2529 /* Handle genuine errors */
2531 else if (inbytes < 0)
2533 record_io_error(state, (int) inbytes, US"recv", NULL);
2534 state->xfer_error = 1;
2537 #ifndef DISABLE_DKIM
2538 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
2540 state->xfer_buffer_hwm = (int) inbytes;
2541 state->xfer_buffer_lwm = 0;
2545 /*************************************************
2546 * TLS version of getc *
2547 *************************************************/
2549 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
2550 it refills the buffer via the GnuTLS reading function.
2551 Only used by the server-side TLS.
2553 This feeds DKIM and should be used for all message-body reads.
2555 Arguments: lim Maximum amount to read/bufffer
2556 Returns: the next character or EOF
2560 tls_getc(unsigned lim)
2562 exim_gnutls_state_st * state = &state_server;
2564 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2565 if (!tls_refill(lim))
2566 return state->xfer_error ? EOF : smtp_getc(lim);
2568 /* Something in the buffer; return next uschar */
2570 return state->xfer_buffer[state->xfer_buffer_lwm++];
2574 tls_getbuf(unsigned * len)
2576 exim_gnutls_state_st * state = &state_server;
2580 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2581 if (!tls_refill(*len))
2583 if (!state->xfer_error) return smtp_getbuf(len);
2588 if ((size = state->xfer_buffer_hwm - state->xfer_buffer_lwm) > *len)
2590 buf = &state->xfer_buffer[state->xfer_buffer_lwm];
2591 state->xfer_buffer_lwm += size;
2600 #ifndef DISABLE_DKIM
2601 exim_gnutls_state_st * state = &state_server;
2602 int n = state->xfer_buffer_hwm - state->xfer_buffer_lwm;
2604 dkim_exim_verify_feed(state->xfer_buffer+state->xfer_buffer_lwm, n);
2610 tls_could_read(void)
2612 return state_server.xfer_buffer_lwm < state_server.xfer_buffer_hwm
2613 || gnutls_record_check_pending(state_server.session) > 0;
2619 /*************************************************
2620 * Read bytes from TLS channel *
2621 *************************************************/
2623 /* This does not feed DKIM, so if the caller uses this for reading message body,
2624 then the caller must feed DKIM.
2630 Returns: the number of bytes read
2631 -1 after a failed read
2635 tls_read(BOOL is_server, uschar *buff, size_t len)
2637 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2643 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
2645 debug_printf("*** PROBABLY A BUG *** " \
2646 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
2647 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
2650 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
2651 state->session, buff, len);
2653 inbytes = gnutls_record_recv(state->session, buff, len);
2654 if (inbytes > 0) return inbytes;
2657 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2659 else record_io_error(state, (int)inbytes, US"recv", NULL);
2667 /*************************************************
2668 * Write bytes down TLS channel *
2669 *************************************************/
2673 is_server channel specifier
2676 more more data expected soon
2678 Returns: the number of bytes after a successful write,
2679 -1 after a failed write
2683 tls_write(BOOL is_server, const uschar *buff, size_t len, BOOL more)
2687 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2689 static BOOL corked = FALSE;
2691 if (more && !corked) gnutls_record_cork(state->session);
2694 DEBUG(D_tls) debug_printf("%s(%p, " SIZE_T_FMT "%s)\n", __FUNCTION__,
2695 buff, left, more ? ", more" : "");
2699 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
2701 outbytes = gnutls_record_send(state->session, buff, left);
2703 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
2706 record_io_error(state, outbytes, US"send", NULL);
2711 record_io_error(state, 0, US"send", US"TLS channel closed on write");
2722 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
2730 if (!more) (void) gnutls_record_uncork(state->session, 0);
2741 /*************************************************
2742 * Random number generation *
2743 *************************************************/
2745 /* Pseudo-random number generation. The result is not expected to be
2746 cryptographically strong but not so weak that someone will shoot themselves
2747 in the foot using it as a nonce in input in some email header scheme or
2748 whatever weirdness they'll twist this into. The result should handle fork()
2749 and avoid repeating sequences. OpenSSL handles that for us.
2753 Returns a random number in range [0, max-1]
2756 #ifdef HAVE_GNUTLS_RND
2758 vaguely_random_number(int max)
2763 uschar smallbuf[sizeof(r)];
2768 needed_len = sizeof(r);
2769 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
2770 * asked for a number less than 10. */
2771 for (r = max, i = 0; r; ++i)
2777 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2780 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2781 return vaguely_random_number_fallback(max);
2784 for (p = smallbuf; needed_len; --needed_len, ++p)
2790 /* We don't particularly care about weighted results; if someone wants
2791 * smooth distribution and cares enough then they should submit a patch then. */
2794 #else /* HAVE_GNUTLS_RND */
2796 vaguely_random_number(int max)
2798 return vaguely_random_number_fallback(max);
2800 #endif /* HAVE_GNUTLS_RND */
2805 /*************************************************
2806 * Let tls_require_ciphers be checked at startup *
2807 *************************************************/
2809 /* The tls_require_ciphers option, if set, must be something which the
2812 Returns: NULL on success, or error message
2816 tls_validate_require_cipher(void)
2819 uschar *expciphers = NULL;
2820 gnutls_priority_t priority_cache;
2822 uschar * dummy_errstr;
2824 #define validate_check_rc(Label) do { \
2825 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
2826 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
2827 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
2829 if (exim_gnutls_base_init_done)
2830 log_write(0, LOG_MAIN|LOG_PANIC,
2831 "already initialised GnuTLS, Exim developer bug");
2833 #ifdef HAVE_GNUTLS_PKCS11
2834 if (!gnutls_allow_auto_pkcs11)
2836 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2837 validate_check_rc(US"gnutls_pkcs11_init");
2840 rc = gnutls_global_init();
2841 validate_check_rc(US"gnutls_global_init()");
2842 exim_gnutls_base_init_done = TRUE;
2844 if (!(tls_require_ciphers && *tls_require_ciphers))
2845 return_deinit(NULL);
2847 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
2849 return_deinit(US"failed to expand tls_require_ciphers");
2851 if (!(expciphers && *expciphers))
2852 return_deinit(NULL);
2855 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2857 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2858 validate_check_rc(string_sprintf(
2859 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
2860 expciphers, errpos - CS expciphers, errpos));
2862 #undef return_deinit
2863 #undef validate_check_rc
2864 gnutls_global_deinit();
2872 /*************************************************
2873 * Report the library versions. *
2874 *************************************************/
2876 /* See a description in tls-openssl.c for an explanation of why this exists.
2878 Arguments: a FILE* to print the results to
2883 tls_version_report(FILE *f)
2885 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2888 gnutls_check_version(NULL));
2893 /* End of tls-gnu.c */