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;
1765 *errstr = string_sprintf("TLSA record problem: %s", dane_strerror(rc));
1767 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1774 /* ------------------------------------------------------------------------ */
1777 /* Logging function which can be registered with
1778 * gnutls_global_set_log_function()
1779 * gnutls_global_set_log_level() 0..9
1781 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1783 exim_gnutls_logger_cb(int level, const char *message)
1785 size_t len = strlen(message);
1788 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1791 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1792 message[len-1] == '\n' ? "" : "\n");
1797 /* Called after client hello, should handle SNI work.
1798 This will always set tls_sni (state->received_sni) if available,
1799 and may trigger presenting different certificates,
1800 if state->trigger_sni_changes is TRUE.
1802 Should be registered with
1803 gnutls_handshake_set_post_client_hello_function()
1805 "This callback must return 0 on success or a gnutls error code to terminate the
1808 For inability to get SNI information, we return 0.
1809 We only return non-zero if re-setup failed.
1810 Only used for server-side TLS.
1814 exim_sni_handling_cb(gnutls_session_t session)
1816 char sni_name[MAX_HOST_LEN];
1817 size_t data_len = MAX_HOST_LEN;
1818 exim_gnutls_state_st *state = &state_server;
1819 unsigned int sni_type;
1821 uschar * dummy_errstr;
1823 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1824 if (rc != GNUTLS_E_SUCCESS)
1827 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1828 debug_printf("TLS: no SNI presented in handshake.\n");
1830 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1831 gnutls_strerror(rc), rc);
1836 if (sni_type != GNUTLS_NAME_DNS)
1838 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1842 /* We now have a UTF-8 string in sni_name */
1843 old_pool = store_pool;
1844 store_pool = POOL_PERM;
1845 state->received_sni = string_copyn(US sni_name, data_len);
1846 store_pool = old_pool;
1848 /* We set this one now so that variable expansions below will work */
1849 state->tlsp->sni = state->received_sni;
1851 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1852 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1854 if (!state->trigger_sni_changes)
1857 if ((rc = tls_expand_session_files(state, &dummy_errstr)) != OK)
1859 /* If the setup of certs/etc failed before handshake, TLS would not have
1860 been offered. The best we can do now is abort. */
1861 return GNUTLS_E_APPLICATION_ERROR_MIN;
1864 rc = tls_set_remaining_x509(state, &dummy_errstr);
1865 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1872 #ifndef DISABLE_OCSP
1875 server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1876 gnutls_datum_t * ocsp_response)
1879 DEBUG(D_tls) debug_printf("OCSP stapling callback: %s\n", US ptr);
1881 if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1883 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1885 tls_in.ocsp = OCSP_NOT_RESP;
1886 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1889 tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1896 #ifndef DISABLE_EVENT
1898 We use this callback to get observability and detail-level control
1899 for an exim TLS connection (either direction), raising a tls:cert event
1900 for each cert in the chain presented by the peer. Any event
1901 can deny verification.
1903 Return 0 for the handshake to continue or non-zero to terminate.
1907 verify_cb(gnutls_session_t session)
1909 const gnutls_datum_t * cert_list;
1910 unsigned int cert_list_size = 0;
1911 gnutls_x509_crt_t crt;
1914 exim_gnutls_state_st * state = gnutls_session_get_ptr(session);
1916 cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
1918 while (cert_list_size--)
1920 rc = import_cert(&cert_list[cert_list_size], &crt);
1921 if (rc != GNUTLS_E_SUCCESS)
1923 DEBUG(D_tls) debug_printf("TLS: peer cert problem: depth %d: %s\n",
1924 cert_list_size, gnutls_strerror(rc));
1928 state->tlsp->peercert = crt;
1929 if ((yield = event_raise(state->event_action,
1930 US"tls:cert", string_sprintf("%d", cert_list_size))))
1932 log_write(0, LOG_MAIN,
1933 "SSL verify denied by event-action: depth=%d: %s",
1934 cert_list_size, yield);
1935 return 1; /* reject */
1937 state->tlsp->peercert = NULL;
1947 /* ------------------------------------------------------------------------ */
1948 /* Exported functions */
1953 /*************************************************
1954 * Start a TLS session in a server *
1955 *************************************************/
1957 /* This is called when Exim is running as a server, after having received
1958 the STARTTLS command. It must respond to that command, and then negotiate
1962 require_ciphers list of allowed ciphers or NULL
1963 errstr pointer to error string
1965 Returns: OK on success
1966 DEFER for errors before the start of the negotiation
1967 FAIL for errors during the negotiation; the server can't
1972 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
1975 exim_gnutls_state_st * state = NULL;
1977 /* Check for previous activation */
1978 if (tls_in.active >= 0)
1980 tls_error(US"STARTTLS received after TLS started", "", NULL, errstr);
1981 smtp_printf("554 Already in TLS\r\n", FALSE);
1985 /* Initialize the library. If it fails, it will already have logged the error
1986 and sent an SMTP response. */
1988 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
1990 if ((rc = tls_init(NULL, tls_certificate, tls_privatekey,
1991 NULL, tls_verify_certificates, tls_crl,
1992 require_ciphers, &state, errstr)) != OK) return rc;
1994 /* If this is a host for which certificate verification is mandatory or
1995 optional, set up appropriately. */
1997 if (verify_check_host(&tls_verify_hosts) == OK)
2000 debug_printf("TLS: a client certificate will be required.\n");
2001 state->verify_requirement = VERIFY_REQUIRED;
2002 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2004 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2007 debug_printf("TLS: a client certificate will be requested but not required.\n");
2008 state->verify_requirement = VERIFY_OPTIONAL;
2009 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2014 debug_printf("TLS: a client certificate will not be requested.\n");
2015 state->verify_requirement = VERIFY_NONE;
2016 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2019 #ifndef DISABLE_EVENT
2022 state->event_action = event_action;
2023 gnutls_session_set_ptr(state->session, state);
2024 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2028 /* Register SNI handling; always, even if not in tls_certificate, so that the
2029 expansion variable $tls_sni is always available. */
2031 gnutls_handshake_set_post_client_hello_function(state->session,
2032 exim_sni_handling_cb);
2034 /* Set context and tell client to go ahead, except in the case of TLS startup
2035 on connection, where outputting anything now upsets the clients and tends to
2036 make them disconnect. We need to have an explicit fflush() here, to force out
2037 the response. Other smtp_printf() calls do not need it, because in non-TLS
2038 mode, the fflush() happens when smtp_getc() is called. */
2040 if (!state->tlsp->on_connect)
2042 smtp_printf("220 TLS go ahead\r\n", FALSE);
2046 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2047 that the GnuTLS library doesn't. */
2049 gnutls_transport_set_ptr2(state->session,
2050 (gnutls_transport_ptr_t)(long) fileno(smtp_in),
2051 (gnutls_transport_ptr_t)(long) fileno(smtp_out));
2052 state->fd_in = fileno(smtp_in);
2053 state->fd_out = fileno(smtp_out);
2055 sigalrm_seen = FALSE;
2056 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2058 rc = gnutls_handshake(state->session);
2059 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2062 if (rc != GNUTLS_E_SUCCESS)
2064 /* It seems that, except in the case of a timeout, we have to close the
2065 connection right here; otherwise if the other end is running OpenSSL it hangs
2066 until the server times out. */
2070 tls_error(US"gnutls_handshake", "timed out", NULL, errstr);
2071 gnutls_db_remove_session(state->session);
2075 tls_error(US"gnutls_handshake", gnutls_strerror(rc), NULL, errstr);
2076 (void) gnutls_alert_send_appropriate(state->session, rc);
2077 gnutls_deinit(state->session);
2078 gnutls_certificate_free_credentials(state->x509_cred);
2080 shutdown(state->fd_out, SHUT_WR);
2081 for (rc = 1024; fgetc(smtp_in) != EOF && rc > 0; ) rc--; /* drain skt */
2082 (void)fclose(smtp_out);
2083 (void)fclose(smtp_in);
2084 smtp_out = smtp_in = NULL;
2090 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
2092 /* Verify after the fact */
2094 if (!verify_certificate(state, errstr))
2096 if (state->verify_requirement != VERIFY_OPTIONAL)
2098 (void) tls_error(US"certificate verification failed", *errstr, NULL, errstr);
2102 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
2106 /* Figure out peer DN, and if authenticated, etc. */
2108 if ((rc = peer_status(state, NULL)) != OK) return rc;
2110 /* Sets various Exim expansion variables; always safe within server */
2112 extract_exim_vars_from_tls_state(state);
2114 /* TLS has been set up. Adjust the input functions to read via TLS,
2115 and initialize appropriately. */
2117 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2119 receive_getc = tls_getc;
2120 receive_getbuf = tls_getbuf;
2121 receive_get_cache = tls_get_cache;
2122 receive_ungetc = tls_ungetc;
2123 receive_feof = tls_feof;
2124 receive_ferror = tls_ferror;
2125 receive_smtp_buffered = tls_smtp_buffered;
2134 tls_client_setup_hostname_checks(host_item * host, exim_gnutls_state_st * state,
2135 smtp_transport_options_block * ob)
2137 if (verify_check_given_host(&ob->tls_verify_cert_hostnames, host) == OK)
2139 state->exp_tls_verify_cert_hostnames =
2141 string_domain_utf8_to_alabel(host->name, NULL);
2146 debug_printf("TLS: server cert verification includes hostname: \"%s\".\n",
2147 state->exp_tls_verify_cert_hostnames);
2155 /* Given our list of RRs from the TLSA lookup, build a lookup block in
2156 GnuTLS-DANE's preferred format. Hang it on the state str for later
2157 use in DANE verification.
2159 We point at the dnsa data not copy it, so it must remain valid until
2160 after verification is done.*/
2163 dane_tlsa_load(exim_gnutls_state_st * state, dns_answer * dnsa)
2168 const char ** dane_data;
2169 int * dane_data_len;
2171 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS), i = 1;
2173 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2174 ) if (rr->type == T_TLSA) i++;
2176 dane_data = store_get(i * sizeof(uschar *));
2177 dane_data_len = store_get(i * sizeof(int));
2179 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS), i = 0;
2181 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2182 ) if (rr->type == T_TLSA)
2184 const uschar * p = rr->data;
2185 uint8_t usage = p[0], sel = p[1], type = p[2];
2188 debug_printf("TLSA: %d %d %d size %d\n", usage, sel, type, rr->size);
2190 if ( (usage != DANESSL_USAGE_DANE_TA && usage != DANESSL_USAGE_DANE_EE)
2191 || (sel != 0 && sel != 1)
2196 case 0: /* Full: cannot check at present */
2198 case 1: if (rr->size != 3 + 256/8) continue; /* sha2-256 */
2200 case 2: if (rr->size != 3 + 512/8) continue; /* sha2-512 */
2205 tls_out.tlsa_usage |= 1<<usage;
2207 dane_data_len[i++] = rr->size;
2210 if (!i) return FALSE;
2212 dane_data[i] = NULL;
2213 dane_data_len[i] = 0;
2215 state->dane_data = (char * const *)dane_data;
2216 state->dane_data_len = dane_data_len;
2223 /*************************************************
2224 * Start a TLS session in a client *
2225 *************************************************/
2227 /* Called from the smtp transport after STARTTLS has been accepted.
2230 fd the fd of the connection
2231 host connected host (for messages)
2232 addr the first address (not used)
2233 tb transport (always smtp)
2234 tlsa_dnsa non-NULL, either request or require dane for this host, and
2235 a TLSA record found. Therefore, dane verify required.
2236 Which implies cert must be requested and supplied, dane
2237 verify must pass, and cert verify irrelevant (incl.
2238 hostnames), and (caller handled) require_tls
2239 errstr error string pointer
2241 Returns: OK/DEFER/FAIL (because using common functions),
2242 but for a client, DEFER and FAIL have the same meaning
2246 tls_client_start(int fd, host_item *host,
2247 address_item *addr ARG_UNUSED,
2248 transport_instance * tb,
2249 #ifdef EXPERIMENTAL_DANE
2250 dns_answer * tlsa_dnsa,
2254 smtp_transport_options_block *ob =
2255 (smtp_transport_options_block *)tb->options_block;
2257 exim_gnutls_state_st * state = NULL;
2258 #ifndef DISABLE_OCSP
2260 verify_check_given_host(&ob->hosts_require_ocsp, host) == OK;
2261 BOOL request_ocsp = require_ocsp ? TRUE
2262 : verify_check_given_host(&ob->hosts_request_ocsp, host) == OK;
2265 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
2267 if ((rc = tls_init(host, ob->tls_certificate, ob->tls_privatekey,
2268 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
2269 ob->tls_require_ciphers, &state, errstr)) != OK)
2273 int dh_min_bits = ob->tls_dh_min_bits;
2274 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
2277 debug_printf("WARNING: tls_dh_min_bits far too low,"
2278 " clamping %d up to %d\n",
2279 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
2280 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
2283 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
2284 " acceptable bits to %d\n",
2286 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
2289 /* Stick to the old behaviour for compatibility if tls_verify_certificates is
2290 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
2291 the specified host patterns if one of them is defined */
2294 if (tlsa_dnsa && dane_tlsa_load(state, tlsa_dnsa))
2297 debug_printf("TLS: server certificate DANE required.\n");
2298 state->verify_requirement = VERIFY_DANE;
2299 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2303 if ( ( state->exp_tls_verify_certificates
2304 && !ob->tls_verify_hosts
2305 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2307 || verify_check_given_host(&ob->tls_verify_hosts, host) == OK
2310 tls_client_setup_hostname_checks(host, state, ob);
2312 debug_printf("TLS: server certificate verification required.\n");
2313 state->verify_requirement = VERIFY_REQUIRED;
2314 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2316 else if (verify_check_given_host(&ob->tls_try_verify_hosts, host) == OK)
2318 tls_client_setup_hostname_checks(host, state, ob);
2320 debug_printf("TLS: server certificate verification optional.\n");
2321 state->verify_requirement = VERIFY_OPTIONAL;
2322 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2327 debug_printf("TLS: server certificate verification not required.\n");
2328 state->verify_requirement = VERIFY_NONE;
2329 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2332 #ifndef DISABLE_OCSP
2333 /* supported since GnuTLS 3.1.3 */
2336 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
2337 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
2338 NULL, 0, NULL)) != OK)
2339 return tls_error(US"cert-status-req",
2340 gnutls_strerror(rc), state->host, errstr);
2341 tls_out.ocsp = OCSP_NOT_RESP;
2345 #ifndef DISABLE_EVENT
2346 if (tb->event_action)
2348 state->event_action = tb->event_action;
2349 gnutls_session_set_ptr(state->session, state);
2350 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2354 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr_t)(long) fd);
2358 DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
2359 /* There doesn't seem to be a built-in timeout on connection. */
2361 sigalrm_seen = FALSE;
2362 alarm(ob->command_timeout);
2365 rc = gnutls_handshake(state->session);
2366 } while ((rc == GNUTLS_E_AGAIN) ||
2367 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
2370 if (rc != GNUTLS_E_SUCCESS)
2373 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_USER_CANCELED);
2374 return tls_error(US"gnutls_handshake", "timed out", state->host, errstr);
2377 return tls_error(US"gnutls_handshake", gnutls_strerror(rc), state->host, errstr);
2379 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
2383 if (!verify_certificate(state, errstr))
2384 return tls_error(US"certificate verification failed", *errstr, state->host, errstr);
2386 #ifndef DISABLE_OCSP
2391 gnutls_datum_t stapling;
2392 gnutls_ocsp_resp_t resp;
2393 gnutls_datum_t printed;
2394 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
2395 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
2396 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
2397 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
2400 debug_printf("%.4096s", printed.data);
2401 gnutls_free(printed.data);
2404 (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host, errstr);
2407 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
2409 tls_out.ocsp = OCSP_FAILED;
2410 return tls_error(US"certificate status check failed", NULL, state->host, errstr);
2412 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
2413 tls_out.ocsp = OCSP_VFIED;
2417 /* Figure out peer DN, and if authenticated, etc. */
2419 if ((rc = peer_status(state, errstr)) != OK)
2422 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
2424 extract_exim_vars_from_tls_state(state);
2432 /*************************************************
2433 * Close down a TLS session *
2434 *************************************************/
2436 /* This is also called from within a delivery subprocess forked from the
2437 daemon, to shut down the TLS library, without actually doing a shutdown (which
2438 would tamper with the TLS session in the parent process).
2440 Arguments: TRUE if gnutls_bye is to be called
2445 tls_close(BOOL is_server, BOOL shutdown)
2447 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2449 if (!state->tlsp || state->tlsp->active < 0) return; /* TLS was not active */
2453 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
2454 gnutls_bye(state->session, GNUTLS_SHUT_WR);
2457 gnutls_deinit(state->session);
2458 gnutls_certificate_free_credentials(state->x509_cred);
2461 state->tlsp->active = -1;
2462 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
2464 if ((state_server.session == NULL) && (state_client.session == NULL))
2466 gnutls_global_deinit();
2467 exim_gnutls_base_init_done = FALSE;
2475 tls_refill(unsigned lim)
2477 exim_gnutls_state_st * state = &state_server;
2480 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
2481 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
2483 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
2484 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
2485 MIN(ssl_xfer_buffer_size, lim));
2488 /* Timeouts do not get this far; see command_timeout_handler().
2489 A zero-byte return appears to mean that the TLS session has been
2490 closed down, not that the socket itself has been closed down. Revert to
2491 non-TLS handling. */
2495 DEBUG(D_tls) debug_printf("Got tls read timeout\n");
2496 state->xfer_error = 1;
2500 else if (inbytes == 0)
2502 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2504 receive_getc = smtp_getc;
2505 receive_getbuf = smtp_getbuf;
2506 receive_get_cache = smtp_get_cache;
2507 receive_ungetc = smtp_ungetc;
2508 receive_feof = smtp_feof;
2509 receive_ferror = smtp_ferror;
2510 receive_smtp_buffered = smtp_buffered;
2512 gnutls_deinit(state->session);
2513 gnutls_certificate_free_credentials(state->x509_cred);
2515 state->session = NULL;
2516 state->tlsp->active = -1;
2517 state->tlsp->bits = 0;
2518 state->tlsp->certificate_verified = FALSE;
2519 tls_channelbinding_b64 = NULL;
2520 state->tlsp->cipher = NULL;
2521 state->tlsp->peercert = NULL;
2522 state->tlsp->peerdn = NULL;
2527 /* Handle genuine errors */
2529 else if (inbytes < 0)
2531 record_io_error(state, (int) inbytes, US"recv", NULL);
2532 state->xfer_error = 1;
2535 #ifndef DISABLE_DKIM
2536 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
2538 state->xfer_buffer_hwm = (int) inbytes;
2539 state->xfer_buffer_lwm = 0;
2543 /*************************************************
2544 * TLS version of getc *
2545 *************************************************/
2547 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
2548 it refills the buffer via the GnuTLS reading function.
2549 Only used by the server-side TLS.
2551 This feeds DKIM and should be used for all message-body reads.
2553 Arguments: lim Maximum amount to read/bufffer
2554 Returns: the next character or EOF
2558 tls_getc(unsigned lim)
2560 exim_gnutls_state_st * state = &state_server;
2562 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2563 if (!tls_refill(lim))
2564 return state->xfer_error ? EOF : smtp_getc(lim);
2566 /* Something in the buffer; return next uschar */
2568 return state->xfer_buffer[state->xfer_buffer_lwm++];
2572 tls_getbuf(unsigned * len)
2574 exim_gnutls_state_st * state = &state_server;
2578 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2579 if (!tls_refill(*len))
2581 if (!state->xfer_error) return smtp_getbuf(len);
2586 if ((size = state->xfer_buffer_hwm - state->xfer_buffer_lwm) > *len)
2588 buf = &state->xfer_buffer[state->xfer_buffer_lwm];
2589 state->xfer_buffer_lwm += size;
2598 #ifndef DISABLE_DKIM
2599 exim_gnutls_state_st * state = &state_server;
2600 int n = state->xfer_buffer_hwm - state->xfer_buffer_lwm;
2602 dkim_exim_verify_feed(state->xfer_buffer+state->xfer_buffer_lwm, n);
2608 tls_could_read(void)
2610 return state_server.xfer_buffer_lwm < state_server.xfer_buffer_hwm
2611 || gnutls_record_check_pending(state_server.session) > 0;
2617 /*************************************************
2618 * Read bytes from TLS channel *
2619 *************************************************/
2621 /* This does not feed DKIM, so if the caller uses this for reading message body,
2622 then the caller must feed DKIM.
2628 Returns: the number of bytes read
2629 -1 after a failed read
2633 tls_read(BOOL is_server, uschar *buff, size_t len)
2635 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2641 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
2643 debug_printf("*** PROBABLY A BUG *** " \
2644 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
2645 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
2648 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
2649 state->session, buff, len);
2651 inbytes = gnutls_record_recv(state->session, buff, len);
2652 if (inbytes > 0) return inbytes;
2655 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2657 else record_io_error(state, (int)inbytes, US"recv", NULL);
2665 /*************************************************
2666 * Write bytes down TLS channel *
2667 *************************************************/
2671 is_server channel specifier
2674 more more data expected soon
2676 Returns: the number of bytes after a successful write,
2677 -1 after a failed write
2681 tls_write(BOOL is_server, const uschar *buff, size_t len, BOOL more)
2685 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2687 static BOOL corked = FALSE;
2689 if (more && !corked) gnutls_record_cork(state->session);
2692 DEBUG(D_tls) debug_printf("%s(%p, " SIZE_T_FMT "%s)\n", __FUNCTION__,
2693 buff, left, more ? ", more" : "");
2697 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
2699 outbytes = gnutls_record_send(state->session, buff, left);
2701 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
2704 record_io_error(state, outbytes, US"send", NULL);
2709 record_io_error(state, 0, US"send", US"TLS channel closed on write");
2720 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
2728 if (!more) (void) gnutls_record_uncork(state->session, 0);
2739 /*************************************************
2740 * Random number generation *
2741 *************************************************/
2743 /* Pseudo-random number generation. The result is not expected to be
2744 cryptographically strong but not so weak that someone will shoot themselves
2745 in the foot using it as a nonce in input in some email header scheme or
2746 whatever weirdness they'll twist this into. The result should handle fork()
2747 and avoid repeating sequences. OpenSSL handles that for us.
2751 Returns a random number in range [0, max-1]
2754 #ifdef HAVE_GNUTLS_RND
2756 vaguely_random_number(int max)
2761 uschar smallbuf[sizeof(r)];
2766 needed_len = sizeof(r);
2767 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
2768 * asked for a number less than 10. */
2769 for (r = max, i = 0; r; ++i)
2775 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2778 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2779 return vaguely_random_number_fallback(max);
2782 for (p = smallbuf; needed_len; --needed_len, ++p)
2788 /* We don't particularly care about weighted results; if someone wants
2789 * smooth distribution and cares enough then they should submit a patch then. */
2792 #else /* HAVE_GNUTLS_RND */
2794 vaguely_random_number(int max)
2796 return vaguely_random_number_fallback(max);
2798 #endif /* HAVE_GNUTLS_RND */
2803 /*************************************************
2804 * Let tls_require_ciphers be checked at startup *
2805 *************************************************/
2807 /* The tls_require_ciphers option, if set, must be something which the
2810 Returns: NULL on success, or error message
2814 tls_validate_require_cipher(void)
2817 uschar *expciphers = NULL;
2818 gnutls_priority_t priority_cache;
2820 uschar * dummy_errstr;
2822 #define validate_check_rc(Label) do { \
2823 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
2824 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
2825 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
2827 if (exim_gnutls_base_init_done)
2828 log_write(0, LOG_MAIN|LOG_PANIC,
2829 "already initialised GnuTLS, Exim developer bug");
2831 #ifdef HAVE_GNUTLS_PKCS11
2832 if (!gnutls_allow_auto_pkcs11)
2834 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2835 validate_check_rc(US"gnutls_pkcs11_init");
2838 rc = gnutls_global_init();
2839 validate_check_rc(US"gnutls_global_init()");
2840 exim_gnutls_base_init_done = TRUE;
2842 if (!(tls_require_ciphers && *tls_require_ciphers))
2843 return_deinit(NULL);
2845 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
2847 return_deinit(US"failed to expand tls_require_ciphers");
2849 if (!(expciphers && *expciphers))
2850 return_deinit(NULL);
2853 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2855 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2856 validate_check_rc(string_sprintf(
2857 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
2858 expciphers, errpos - CS expciphers, errpos));
2860 #undef return_deinit
2861 #undef validate_check_rc
2862 gnutls_global_deinit();
2870 /*************************************************
2871 * Report the library versions. *
2872 *************************************************/
2874 /* See a description in tls-openssl.c for an explanation of why this exists.
2876 Arguments: a FILE* to print the results to
2881 tls_version_report(FILE *f)
2883 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2886 gnutls_check_version(NULL));
2891 /* End of tls-gnu.c */