1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
8 /* Copyright (c) Phil Pennock 2012 */
10 /* This file provides TLS/SSL support for Exim using the GnuTLS library,
11 one of the available supported implementations. This file is #included into
12 tls.c when USE_GNUTLS has been set.
14 The code herein is a revamp of GnuTLS integration using the current APIs; the
15 original tls-gnu.c was based on a patch which was contributed by Nikos
16 Mavrogiannopoulos. The revamp is partially a rewrite, partially cut&paste as
19 APIs current as of GnuTLS 2.12.18; note that the GnuTLS manual is for GnuTLS 3,
20 which is not widely deployed by OS vendors. Will note issues below, which may
21 assist in updating the code in the future. Another sources of hints is
22 mod_gnutls for Apache (SNI callback registration and handling).
24 Keeping client and server variables more split than before and is currently
25 the norm, in anticipation of TLS in ACL callouts.
27 I wanted to switch to gnutls_certificate_set_verify_function() so that
28 certificate rejection could happen during handshake where it belongs, rather
29 than being dropped afterwards, but that was introduced in 2.10.0 and Debian
30 (6.0.5) is still on 2.8.6. So for now we have to stick with sub-par behaviour.
32 (I wasn't looking for libraries quite that old, when updating to get rid of
33 compiler warnings of deprecated APIs. If it turns out that a lot of the rest
34 require current GnuTLS, then we'll drop support for the ancient libraries).
37 #include <gnutls/gnutls.h>
38 /* needed for cert checks in verification and DN extraction: */
39 #include <gnutls/x509.h>
40 /* man-page is incorrect, gnutls_rnd() is not in gnutls.h: */
41 #include <gnutls/crypto.h>
43 /* needed to disable PKCS11 autoload unless requested */
44 #if GNUTLS_VERSION_NUMBER >= 0x020c00
45 # include <gnutls/pkcs11.h>
46 # define SUPPORT_PARAM_TO_PK_BITS
48 #if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
49 # warning "GnuTLS library version too old; define DISABLE_OCSP in Makefile"
52 #if GNUTLS_VERSION_NUMBER < 0x020a00 && !defined(DISABLE_EVENT)
53 # warning "GnuTLS library version too old; tls:cert event unsupported"
54 # define DISABLE_EVENT
56 #if GNUTLS_VERSION_NUMBER >= 0x030306
57 # define SUPPORT_CA_DIR
59 # undef SUPPORT_CA_DIR
61 #if GNUTLS_VERSION_NUMBER >= 0x030014
62 # define SUPPORT_SYSDEFAULT_CABUNDLE
64 #if GNUTLS_VERSION_NUMBER >= 0x030104
65 # define GNUTLS_CERT_VFY_STATUS_PRINT
67 #if GNUTLS_VERSION_NUMBER >= 0x030109
70 #if GNUTLS_VERSION_NUMBER >= 0x03010a
71 # define SUPPORT_GNUTLS_SESS_DESC
73 #if GNUTLS_VERSION_NUMBER >= 0x030500
74 # define SUPPORT_GNUTLS_KEYLOG
76 #if GNUTLS_VERSION_NUMBER >= 0x030506 && !defined(DISABLE_OCSP)
77 # define SUPPORT_SRV_OCSP_STACK
81 # if GNUTLS_VERSION_NUMBER >= 0x030000
82 # define DANESSL_USAGE_DANE_TA 2
83 # define DANESSL_USAGE_DANE_EE 3
85 # error GnuTLS version too early for DANE
87 # if GNUTLS_VERSION_NUMBER < 0x999999
88 # define GNUTLS_BROKEN_DANE_VALIDATION
93 # include <gnutls/ocsp.h>
96 # include <gnutls/dane.h>
99 #include "tls-cipher-stdname.c"
106 # ifdef EXPERIMENTAL_TLS_RESUME
107 builtin_macro_create_var(US"_RESUME_DECODE", RESUME_DECODE_STRING );
116 gnutls_global_set_audit_log_function()
119 gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
122 /* Local static variables for GnuTLS */
124 /* Values for verify_requirement */
126 enum peer_verify_requirement
127 { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED, VERIFY_DANE };
129 /* This holds most state for server or client; with this, we can set up an
130 outbound TLS-enabled connection in an ACL callout, while not stomping all
131 over the TLS variables available for expansion.
133 Some of these correspond to variables in globals.c; those variables will
134 be set to point to content in one of these instances, as appropriate for
135 the stage of the process lifetime.
137 Not handled here: global tls_channelbinding_b64.
140 typedef struct exim_gnutls_state {
141 gnutls_session_t session;
142 gnutls_certificate_credentials_t x509_cred;
143 gnutls_priority_t priority_cache;
144 enum peer_verify_requirement verify_requirement;
147 BOOL peer_cert_verified;
148 BOOL peer_dane_verified;
149 BOOL trigger_sni_changes;
150 BOOL have_set_peerdn;
151 const struct host_item *host; /* NULL if server */
152 gnutls_x509_crt_t peercert;
155 uschar *received_sni;
157 const uschar *tls_certificate;
158 const uschar *tls_privatekey;
159 const uschar *tls_sni; /* client send only, not received */
160 const uschar *tls_verify_certificates;
161 const uschar *tls_crl;
162 const uschar *tls_require_ciphers;
164 uschar *exp_tls_certificate;
165 uschar *exp_tls_privatekey;
166 uschar *exp_tls_verify_certificates;
168 uschar *exp_tls_require_ciphers;
169 const uschar *exp_tls_verify_cert_hostnames;
170 #ifndef DISABLE_EVENT
171 uschar *event_action;
174 char * const * dane_data;
175 const int * dane_data_len;
178 tls_support *tlsp; /* set in tls_init() */
183 BOOL xfer_eof; /*XXX never gets set! */
185 } exim_gnutls_state_st;
187 static const exim_gnutls_state_st exim_gnutls_state_init = {
188 /* all elements not explicitly intialised here get 0/NULL/FALSE */
193 /* Not only do we have our own APIs which don't pass around state, assuming
194 it's held in globals, GnuTLS doesn't appear to let us register callback data
195 for callbacks, or as part of the session, so we have to keep a "this is the
196 context we're currently dealing with" pointer and rely upon being
197 single-threaded to keep from processing data on an inbound TLS connection while
198 talking to another TLS connection for an outbound check. This does mean that
199 there's no way for heart-beats to be responded to, for the duration of the
201 XXX But see gnutls_session_get_ptr()
204 static exim_gnutls_state_st state_server;
206 /* dh_params are initialised once within the lifetime of a process using TLS;
207 if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
208 don't want to repeat this. */
210 static gnutls_dh_params_t dh_server_params = NULL;
212 static int ssl_session_timeout = 3600; /* One hour */
214 static const uschar * const exim_default_gnutls_priority = US"NORMAL";
216 /* Guard library core initialisation */
218 static BOOL exim_gnutls_base_init_done = FALSE;
221 static BOOL gnutls_buggy_ocsp = FALSE;
224 #ifdef EXPERIMENTAL_TLS_RESUME
225 static gnutls_datum_t server_sessticket_key;
228 /* ------------------------------------------------------------------------ */
231 #define MAX_HOST_LEN 255
233 /* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
234 the library logging; a value less than 0 disables the calls to set up logging
235 callbacks. GNuTLS also looks for an environment variable - except not for
236 setuid binaries, making it useless - "GNUTLS_DEBUG_LEVEL".
237 Allegedly the testscript line "GNUTLS_DEBUG_LEVEL=9 sudo exim ..." would work,
238 but the env var must be added to /etc/sudoers too. */
239 #ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
240 # define EXIM_GNUTLS_LIBRARY_LOG_LEVEL 9
243 #ifndef EXIM_CLIENT_DH_MIN_BITS
244 # define EXIM_CLIENT_DH_MIN_BITS 1024
247 /* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
248 can ask for a bit-strength. Without that, we stick to the constant we had
250 #ifndef EXIM_SERVER_DH_BITS_PRE2_12
251 # define EXIM_SERVER_DH_BITS_PRE2_12 1024
254 #define expand_check_tlsvar(Varname, errstr) \
255 expand_check(state->Varname, US #Varname, &state->exp_##Varname, errstr)
257 #if GNUTLS_VERSION_NUMBER >= 0x020c00
258 # define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
259 # define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
260 # define HAVE_GNUTLS_RND
261 /* The security fix we provide with the gnutls_allow_auto_pkcs11 option
262 * (4.82 PP/09) introduces a compatibility regression. The symbol simply
263 * isn't available sometimes, so this needs to become a conditional
264 * compilation; the sanest way to deal with this being a problem on
265 * older OSes is to block it in the Local/Makefile with this compiler
267 # ifndef AVOID_GNUTLS_PKCS11
268 # define HAVE_GNUTLS_PKCS11
269 # endif /* AVOID_GNUTLS_PKCS11 */
275 /* ------------------------------------------------------------------------ */
276 /* Callback declarations */
278 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
279 static void exim_gnutls_logger_cb(int level, const char *message);
282 static int exim_sni_handling_cb(gnutls_session_t session);
285 static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
286 gnutls_datum_t * ocsp_response);
291 /* Daemon one-time initialisation */
293 tls_daemon_init(void)
295 #ifdef EXPERIMENTAL_TLS_RESUME
296 /* We are dependent on the GnuTLS implementation of the Session Ticket
297 encryption; both the strength and the key rotation period. We hope that
298 the strength at least matches that of the ciphersuite (but GnuTLS does not
301 static BOOL once = FALSE;
304 gnutls_session_ticket_key_generate(&server_sessticket_key); /* >= 2.10.0 */
305 if (f.running_in_test_harness) ssl_session_timeout = 6;
309 /* ------------------------------------------------------------------------ */
310 /* Static functions */
312 /*************************************************
314 *************************************************/
316 /* Called from lots of places when errors occur before actually starting to do
317 the TLS handshake, that is, while the session is still in clear. Always returns
318 DEFER for a server and FAIL for a client so that most calls can use "return
319 tls_error(...)" to do this processing and then give an appropriate return. A
320 single function is used for both server and client, because it is called from
321 some shared functions.
324 prefix text to include in the logged error
325 msg additional error string (may be NULL)
326 usually obtained from gnutls_strerror()
327 host NULL if setting up a server;
328 the connected host if setting up a client
329 errstr pointer to returned error string
331 Returns: OK/DEFER/FAIL
335 tls_error(const uschar *prefix, const uschar *msg, const host_item *host,
339 *errstr = string_sprintf("(%s)%s%s", prefix, msg ? ": " : "", msg ? msg : US"");
340 return host ? FAIL : DEFER;
345 tls_error_gnu(const uschar *prefix, int err, const host_item *host,
348 return tls_error(prefix, US gnutls_strerror(err), host, errstr);
352 tls_error_sys(const uschar *prefix, int err, const host_item *host,
355 return tls_error(prefix, US strerror(err), host, errstr);
359 /*************************************************
360 * Deal with logging errors during I/O *
361 *************************************************/
363 /* We have to get the identity of the peer from saved data.
366 state the current GnuTLS exim state container
367 rc the GnuTLS error code, or 0 if it's a local error
368 when text identifying read or write
369 text local error text when rc is 0
375 record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
380 if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
381 msg = string_sprintf("A TLS fatal alert has been received: %s",
382 US gnutls_alert_get_name(gnutls_alert_get(state->session)));
384 msg = US gnutls_strerror(rc);
386 (void) tls_error(when, msg, state->host, &errstr);
389 log_write(0, LOG_MAIN, "H=%s [%s] TLS error on connection %s",
390 state->host->name, state->host->address, errstr);
393 uschar * conn_info = smtp_get_connection_info();
394 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0) conn_info += 5;
395 /* I'd like to get separated H= here, but too hard for now */
396 log_write(0, LOG_MAIN, "TLS error on %s %s", conn_info, errstr);
403 /*************************************************
404 * Set various Exim expansion vars *
405 *************************************************/
407 #define exim_gnutls_cert_err(Label) \
410 if (rc != GNUTLS_E_SUCCESS) \
412 DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", \
413 (Label), gnutls_strerror(rc)); \
419 import_cert(const gnutls_datum_t * cert, gnutls_x509_crt_t * crtp)
423 rc = gnutls_x509_crt_init(crtp);
424 exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
426 rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
427 exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
432 #undef exim_gnutls_cert_err
435 /* We set various Exim global variables from the state, once a session has
436 been established. With TLS callouts, may need to change this to stack
437 variables, or just re-call it with the server state after client callout
440 Make sure anything set here is unset in tls_getc().
444 tls_bits strength indicator
445 tls_certificate_verified bool indicator
446 tls_channelbinding_b64 for some SASL mechanisms
448 tls_peercert pointer to library internal
450 tls_sni a (UTF-8) string
451 tls_ourcert pointer to library internal
454 state the relevant exim_gnutls_state_st *
458 extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
460 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
463 gnutls_datum_t channel;
465 tls_support * tlsp = state->tlsp;
467 tlsp->active.sock = state->fd_out;
468 tlsp->active.tls_ctx = state;
470 DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
472 tlsp->certificate_verified = state->peer_cert_verified;
474 tlsp->dane_verified = state->peer_dane_verified;
477 /* note that tls_channelbinding_b64 is not saved to the spool file, since it's
478 only available for use for authenticators while this TLS session is running. */
480 tls_channelbinding_b64 = NULL;
481 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
484 if ((rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel)))
485 { DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc)); }
488 old_pool = store_pool;
489 store_pool = POOL_PERM;
490 tls_channelbinding_b64 = b64encode(CUS channel.data, (int)channel.size);
491 store_pool = old_pool;
492 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
496 /* peercert is set in peer_status() */
497 tlsp->peerdn = state->peerdn;
498 tlsp->sni = state->received_sni;
500 /* record our certificate */
502 const gnutls_datum_t * cert = gnutls_certificate_get_ours(state->session);
503 gnutls_x509_crt_t crt;
505 tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
512 /*************************************************
513 * Setup up DH parameters *
514 *************************************************/
516 /* Generating the D-H parameters may take a long time. They only need to
517 be re-generated every so often, depending on security policy. What we do is to
518 keep these parameters in a file in the spool directory. If the file does not
519 exist, we generate them. This means that it is easy to cause a regeneration.
521 The new file is written as a temporary file and renamed, so that an incomplete
522 file is never present. If two processes both compute some new parameters, you
523 waste a bit of effort, but it doesn't seem worth messing around with locking to
526 Returns: OK/DEFER/FAIL
530 init_server_dh(uschar ** errstr)
533 unsigned int dh_bits;
535 uschar filename_buf[PATH_MAX];
536 uschar *filename = NULL;
538 uschar *exp_tls_dhparam;
539 BOOL use_file_in_spool = FALSE;
540 host_item *host = NULL; /* dummy for macros */
542 DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
544 if ((rc = gnutls_dh_params_init(&dh_server_params)))
545 return tls_error_gnu(US"gnutls_dh_params_init", rc, host, errstr);
550 if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam, errstr))
553 if (!exp_tls_dhparam)
555 DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
556 m.data = US std_dh_prime_default();
557 m.size = Ustrlen(m.data);
559 else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
560 use_file_in_spool = TRUE;
561 else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
563 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
566 else if (exp_tls_dhparam[0] != '/')
568 if (!(m.data = US std_dh_prime_named(exp_tls_dhparam)))
569 return tls_error(US"No standard prime named", exp_tls_dhparam, NULL, errstr);
570 m.size = Ustrlen(m.data);
573 filename = exp_tls_dhparam;
577 if ((rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM)))
578 return tls_error_gnu(US"gnutls_dh_params_import_pkcs3", rc, host, errstr);
579 DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
583 #ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
584 /* If you change this constant, also change dh_param_fn_ext so that we can use a
585 different filename and ensure we have sufficient bits. */
587 if (!(dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL)))
588 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL, errstr);
590 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
593 dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
595 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
599 /* Some clients have hard-coded limits. */
600 if (dh_bits > tls_dh_max_bits)
603 debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
605 dh_bits = tls_dh_max_bits;
608 if (use_file_in_spool)
610 if (!string_format(filename_buf, sizeof(filename_buf),
611 "%s/gnutls-params-%d", spool_directory, dh_bits))
612 return tls_error(US"overlong filename", NULL, NULL, errstr);
613 filename = filename_buf;
616 /* Open the cache file for reading and if successful, read it and set up the
619 if ((fd = Uopen(filename, O_RDONLY, 0)) >= 0)
625 if (fstat(fd, &statbuf) < 0) /* EIO */
629 return tls_error_sys(US"TLS cache stat failed", saved_errno, NULL, errstr);
631 if (!S_ISREG(statbuf.st_mode))
634 return tls_error(US"TLS cache not a file", NULL, NULL, errstr);
636 if (!(fp = fdopen(fd, "rb")))
640 return tls_error_sys(US"fdopen(TLS cache stat fd) failed",
641 saved_errno, NULL, errstr);
644 m.size = statbuf.st_size;
645 if (!(m.data = malloc(m.size)))
648 return tls_error_sys(US"malloc failed", errno, NULL, errstr);
650 if (!(sz = fread(m.data, m.size, 1, fp)))
655 return tls_error_sys(US"fread failed", saved_errno, NULL, errstr);
659 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
662 return tls_error_gnu(US"gnutls_dh_params_import_pkcs3", rc, host, errstr);
663 DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
666 /* If the file does not exist, fall through to compute new data and cache it.
667 If there was any other opening error, it is serious. */
669 else if (errno == ENOENT)
673 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
676 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
679 /* If ret < 0, either the cache file does not exist, or the data it contains
680 is not useful. One particular case of this is when upgrading from an older
681 release of Exim in which the data was stored in a different format. We don't
682 try to be clever and support both formats; we just regenerate new data in this
688 unsigned int dh_bits_gen = dh_bits;
690 if ((PATH_MAX - Ustrlen(filename)) < 10)
691 return tls_error(US"Filename too long to generate replacement",
692 filename, NULL, errstr);
694 temp_fn = string_copy(US"%s.XXXXXXX");
695 if ((fd = mkstemp(CS temp_fn)) < 0) /* modifies temp_fn */
696 return tls_error_sys(US"Unable to open temp file", errno, NULL, errstr);
697 (void)exim_chown(temp_fn, exim_uid, exim_gid); /* Probably not necessary */
699 /* GnuTLS overshoots!
700 * If we ask for 2236, we might get 2237 or more.
701 * But there's no way to ask GnuTLS how many bits there really are.
702 * We can ask how many bits were used in a TLS session, but that's it!
703 * The prime itself is hidden behind too much abstraction.
704 * So we ask for less, and proceed on a wing and a prayer.
705 * First attempt, subtracted 3 for 2233 and got 2240.
707 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
709 dh_bits_gen = dh_bits - 10;
711 debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
716 debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
718 if ((rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen)))
719 return tls_error_gnu(US"gnutls_dh_params_generate2", rc, host, errstr);
721 /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
722 and I confirmed that a NULL call to get the size first is how the GnuTLS
723 sample apps handle this. */
727 if ( (rc = gnutls_dh_params_export_pkcs3(dh_server_params,
728 GNUTLS_X509_FMT_PEM, m.data, &sz))
729 && rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
730 return tls_error_gnu(US"gnutls_dh_params_export_pkcs3(NULL) sizing",
733 if (!(m.data = malloc(m.size)))
734 return tls_error_sys(US"memory allocation failed", errno, NULL, errstr);
736 /* this will return a size 1 less than the allocation size above */
737 if ((rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
741 return tls_error_gnu(US"gnutls_dh_params_export_pkcs3() real", rc, host, errstr);
743 m.size = sz; /* shrink by 1, probably */
745 if ((sz = write_to_fd_buf(fd, m.data, (size_t) m.size)) != m.size)
748 return tls_error_sys(US"TLS cache write D-H params failed",
749 errno, NULL, errstr);
752 if ((sz = write_to_fd_buf(fd, US"\n", 1)) != 1)
753 return tls_error_sys(US"TLS cache write D-H params final newline failed",
754 errno, NULL, errstr);
756 if ((rc = close(fd)))
757 return tls_error_sys(US"TLS cache write close() failed", errno, NULL, errstr);
759 if (Urename(temp_fn, filename) < 0)
760 return tls_error_sys(string_sprintf("failed to rename \"%s\" as \"%s\"",
761 temp_fn, filename), errno, NULL, errstr);
763 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
766 DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
773 /* Create and install a selfsigned certificate, for use in server mode */
776 tls_install_selfsign(exim_gnutls_state_st * state, uschar ** errstr)
778 gnutls_x509_crt_t cert = NULL;
780 gnutls_x509_privkey_t pkey = NULL;
781 const uschar * where;
784 where = US"initialising pkey";
785 if ((rc = gnutls_x509_privkey_init(&pkey))) goto err;
787 where = US"initialising cert";
788 if ((rc = gnutls_x509_crt_init(&cert))) goto err;
790 where = US"generating pkey";
791 if ((rc = gnutls_x509_privkey_generate(pkey, GNUTLS_PK_RSA,
792 #ifdef SUPPORT_PARAM_TO_PK_BITS
793 # ifndef GNUTLS_SEC_PARAM_MEDIUM
794 # define GNUTLS_SEC_PARAM_MEDIUM GNUTLS_SEC_PARAM_HIGH
796 gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_MEDIUM),
803 where = US"configuring cert";
805 if ( (rc = gnutls_x509_crt_set_version(cert, 3))
806 || (rc = gnutls_x509_crt_set_serial(cert, &now, sizeof(now)))
807 || (rc = gnutls_x509_crt_set_activation_time(cert, now = time(NULL)))
808 || (rc = gnutls_x509_crt_set_expiration_time(cert, now + 60 * 60)) /* 1 hr */
809 || (rc = gnutls_x509_crt_set_key(cert, pkey))
811 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
812 GNUTLS_OID_X520_COUNTRY_NAME, 0, "UK", 2))
813 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
814 GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "Exim Developers", 15))
815 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
816 GNUTLS_OID_X520_COMMON_NAME, 0,
817 smtp_active_hostname, Ustrlen(smtp_active_hostname)))
821 where = US"signing cert";
822 if ((rc = gnutls_x509_crt_sign(cert, cert, pkey))) goto err;
824 where = US"installing selfsign cert";
826 if ((rc = gnutls_certificate_set_x509_key(state->x509_cred, &cert, 1, pkey)))
832 if (cert) gnutls_x509_crt_deinit(cert);
833 if (pkey) gnutls_x509_privkey_deinit(pkey);
837 rc = tls_error_gnu(where, rc, NULL, errstr);
844 /* Add certificate and key, from files.
847 Zero or negative: good. Negate value for certificate index if < 0.
848 Greater than zero: FAIL or DEFER code.
852 tls_add_certfile(exim_gnutls_state_st * state, const host_item * host,
853 uschar * certfile, uschar * keyfile, uschar ** errstr)
855 int rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
856 CS certfile, CS keyfile, GNUTLS_X509_FMT_PEM);
858 return tls_error_gnu(
859 string_sprintf("cert/key setup: cert=%s key=%s", certfile, keyfile),
865 /*************************************************
866 * Variables re-expanded post-SNI *
867 *************************************************/
869 /* Called from both server and client code, via tls_init(), and also from
870 the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
872 We can tell the two apart by state->received_sni being non-NULL in callback.
874 The callback should not call us unless state->trigger_sni_changes is true,
875 which we are responsible for setting on the first pass through.
878 state exim_gnutls_state_st *
879 errstr error string pointer
881 Returns: OK/DEFER/FAIL
885 tls_expand_session_files(exim_gnutls_state_st * state, uschar ** errstr)
889 const host_item *host = state->host; /* macro should be reconsidered? */
890 uschar *saved_tls_certificate = NULL;
891 uschar *saved_tls_privatekey = NULL;
892 uschar *saved_tls_verify_certificates = NULL;
893 uschar *saved_tls_crl = NULL;
896 /* We check for tls_sni *before* expansion. */
897 if (!host) /* server */
898 if (!state->received_sni)
900 if ( state->tls_certificate
901 && ( Ustrstr(state->tls_certificate, US"tls_sni")
902 || Ustrstr(state->tls_certificate, US"tls_in_sni")
903 || Ustrstr(state->tls_certificate, US"tls_out_sni")
906 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
907 state->trigger_sni_changes = TRUE;
912 /* useful for debugging */
913 saved_tls_certificate = state->exp_tls_certificate;
914 saved_tls_privatekey = state->exp_tls_privatekey;
915 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
916 saved_tls_crl = state->exp_tls_crl;
919 if ((rc = gnutls_certificate_allocate_credentials(&state->x509_cred)))
920 return tls_error_gnu(US"gnutls_certificate_allocate_credentials",
923 #ifdef SUPPORT_SRV_OCSP_STACK
924 gnutls_certificate_set_flags(state->x509_cred, GNUTLS_CERTIFICATE_API_V2);
927 /* remember: expand_check_tlsvar() is expand_check() but fiddling with
928 state members, assuming consistent naming; and expand_check() returns
929 false if expansion failed, unless expansion was forced to fail. */
931 /* check if we at least have a certificate, before doing expensive
934 if (!expand_check_tlsvar(tls_certificate, errstr))
937 /* certificate is mandatory in server, optional in client */
939 if ( !state->exp_tls_certificate
940 || !*state->exp_tls_certificate
943 return tls_install_selfsign(state, errstr);
945 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
947 if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey, errstr))
950 /* tls_privatekey is optional, defaulting to same file as certificate */
952 if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
954 state->tls_privatekey = state->tls_certificate;
955 state->exp_tls_privatekey = state->exp_tls_certificate;
959 if (state->exp_tls_certificate && *state->exp_tls_certificate)
961 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
962 state->exp_tls_certificate, state->exp_tls_privatekey);
964 if (state->received_sni)
965 if ( Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0
966 && Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0
969 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
973 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
976 if (!host) /* server */
978 const uschar * clist = state->exp_tls_certificate;
979 const uschar * klist = state->exp_tls_privatekey;
980 const uschar * olist;
981 int csep = 0, ksep = 0, osep = 0, cnt = 0;
982 uschar * cfile, * kfile, * ofile;
985 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file", &ofile, errstr))
990 while (cfile = string_nextinlist(&clist, &csep, NULL, 0))
992 if (!(kfile = string_nextinlist(&klist, &ksep, NULL, 0)))
993 return tls_error(US"cert/key setup: out of keys", NULL, host, errstr);
994 else if (0 < (rc = tls_add_certfile(state, host, cfile, kfile, errstr)))
998 int gnutls_cert_index = -rc;
999 DEBUG(D_tls) debug_printf("TLS: cert/key %s registered\n", cfile);
1001 /* Set the OCSP stapling server info */
1003 #ifndef DISABLE_OCSP
1005 if (gnutls_buggy_ocsp)
1008 debug_printf("GnuTLS library is buggy for OCSP; avoiding\n");
1010 else if ((ofile = string_nextinlist(&olist, &osep, NULL, 0)))
1012 /* Use the full callback method for stapling just to get
1013 observability. More efficient would be to read the file once only,
1014 if it never changed (due to SNI). Would need restart on file update,
1015 or watch datestamp. */
1017 # ifdef SUPPORT_SRV_OCSP_STACK
1018 if ((rc = gnutls_certificate_set_ocsp_status_request_function2(
1019 state->x509_cred, gnutls_cert_index,
1020 server_ocsp_stapling_cb, ofile)))
1021 return tls_error_gnu(
1022 US"gnutls_certificate_set_ocsp_status_request_function2",
1028 debug_printf("oops; multiple OCSP files not supported\n");
1031 gnutls_certificate_set_ocsp_status_request_function(
1032 state->x509_cred, server_ocsp_stapling_cb, ofile);
1035 DEBUG(D_tls) debug_printf("OCSP response file = %s\n", ofile);
1038 DEBUG(D_tls) debug_printf("ran out of OCSP response files in list\n");
1044 if (0 < (rc = tls_add_certfile(state, host,
1045 state->exp_tls_certificate, state->exp_tls_privatekey, errstr)))
1047 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
1050 } /* tls_certificate */
1053 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
1054 provided. Experiment shows that, if the certificate file is empty, an unhelpful
1055 error message is provided. However, if we just refrain from setting anything up
1056 in that case, certificate verification fails, which seems to be the correct
1059 if (state->tls_verify_certificates && *state->tls_verify_certificates)
1061 if (!expand_check_tlsvar(tls_verify_certificates, errstr))
1063 #ifndef SUPPORT_SYSDEFAULT_CABUNDLE
1064 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1065 state->exp_tls_verify_certificates = NULL;
1067 if (state->tls_crl && *state->tls_crl)
1068 if (!expand_check_tlsvar(tls_crl, errstr))
1071 if (!(state->exp_tls_verify_certificates &&
1072 *state->exp_tls_verify_certificates))
1075 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
1076 /* With no tls_verify_certificates, we ignore tls_crl too */
1083 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
1087 #ifdef SUPPORT_SYSDEFAULT_CABUNDLE
1088 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1089 cert_count = gnutls_certificate_set_x509_system_trust(state->x509_cred);
1093 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
1095 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
1096 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
1101 #ifndef SUPPORT_CA_DIR
1102 /* The test suite passes in /dev/null; we could check for that path explicitly,
1103 but who knows if someone has some weird FIFO which always dumps some certs, or
1104 other weirdness. The thing we really want to check is that it's not a
1105 directory, since while OpenSSL supports that, GnuTLS does not.
1106 So s/!S_ISREG/S_ISDIR/ and change some messaging ... */
1107 if (S_ISDIR(statbuf.st_mode))
1110 debug_printf("verify certificates path is a dir: \"%s\"\n",
1111 state->exp_tls_verify_certificates);
1112 log_write(0, LOG_MAIN|LOG_PANIC,
1113 "tls_verify_certificates \"%s\" is a directory",
1114 state->exp_tls_verify_certificates);
1119 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
1120 state->exp_tls_verify_certificates, statbuf.st_size);
1122 if (statbuf.st_size == 0)
1125 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
1131 #ifdef SUPPORT_CA_DIR
1132 (statbuf.st_mode & S_IFMT) == S_IFDIR
1134 gnutls_certificate_set_x509_trust_dir(state->x509_cred,
1135 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM)
1138 gnutls_certificate_set_x509_trust_file(state->x509_cred,
1139 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
1143 return tls_error_gnu(US"setting certificate trust", cert_count, host, errstr);
1145 debug_printf("Added %d certificate authorities.\n", cert_count);
1147 if (state->tls_crl && *state->tls_crl &&
1148 state->exp_tls_crl && *state->exp_tls_crl)
1150 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
1151 if ((cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
1152 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM)) < 0)
1153 return tls_error_gnu(US"gnutls_certificate_set_x509_crl_file",
1154 cert_count, host, errstr);
1156 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
1165 /*************************************************
1166 * Set X.509 state variables *
1167 *************************************************/
1169 /* In GnuTLS, the registered cert/key are not replaced by a later
1170 set of a cert/key, so for SNI support we need a whole new x509_cred
1171 structure. Which means various other non-re-expanded pieces of state
1172 need to be re-set in the new struct, so the setting logic is pulled
1176 state exim_gnutls_state_st *
1177 errstr error string pointer
1179 Returns: OK/DEFER/FAIL
1183 tls_set_remaining_x509(exim_gnutls_state_st *state, uschar ** errstr)
1186 const host_item *host = state->host; /* macro should be reconsidered? */
1188 /* Create D-H parameters, or read them from the cache file. This function does
1189 its own SMTP error messaging. This only happens for the server, TLS D-H ignores
1190 client-side params. */
1194 if (!dh_server_params)
1195 if ((rc = init_server_dh(errstr)) != OK) return rc;
1196 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
1199 /* Link the credentials to the session. */
1201 if ((rc = gnutls_credentials_set(state->session,
1202 GNUTLS_CRD_CERTIFICATE, state->x509_cred)))
1203 return tls_error_gnu(US"gnutls_credentials_set", rc, host, errstr);
1208 /*************************************************
1209 * Initialize for GnuTLS *
1210 *************************************************/
1213 #ifndef DISABLE_OCSP
1216 tls_is_buggy_ocsp(void)
1219 uschar maj, mid, mic;
1221 s = CUS gnutls_check_version(NULL);
1225 while (*s && *s != '.') s++;
1226 mid = atoi(CCS ++s);
1233 while (*s && *s != '.') s++;
1234 mic = atoi(CCS ++s);
1235 return mic <= (mid == 3 ? 16 : 3);
1244 /* Called from both server and client code. In the case of a server, errors
1245 before actual TLS negotiation return DEFER.
1248 host connected host, if client; NULL if server
1249 certificate certificate file
1250 privatekey private key file
1251 sni TLS SNI to send, sometimes when client; else NULL
1254 require_ciphers tls_require_ciphers setting
1255 caller_state returned state-info structure
1256 errstr error string pointer
1258 Returns: OK/DEFER/FAIL
1263 const host_item *host,
1264 const uschar *certificate,
1265 const uschar *privatekey,
1269 const uschar *require_ciphers,
1270 exim_gnutls_state_st **caller_state,
1274 exim_gnutls_state_st * state;
1277 const char * errpos;
1280 if (!exim_gnutls_base_init_done)
1282 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1284 #ifdef HAVE_GNUTLS_PKCS11
1285 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1286 which loads modules from a config file, which sounds good and may be wanted
1287 by some sysadmin, but also means in common configurations that GNOME keyring
1288 environment variables are used and so breaks for users calling mailq.
1289 To prevent this, we init PKCS11 first, which is the documented approach. */
1290 if (!gnutls_allow_auto_pkcs11)
1291 if ((rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL)))
1292 return tls_error_gnu(US"gnutls_pkcs11_init", rc, host, errstr);
1295 if ((rc = gnutls_global_init()))
1296 return tls_error_gnu(US"gnutls_global_init", rc, host, errstr);
1298 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1301 gnutls_global_set_log_function(exim_gnutls_logger_cb);
1302 /* arbitrarily chosen level; bump up to 9 for more */
1303 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
1307 #ifndef DISABLE_OCSP
1308 if (tls_ocsp_file && (gnutls_buggy_ocsp = tls_is_buggy_ocsp()))
1309 log_write(0, LOG_MAIN, "OCSP unusable with this GnuTLS library version");
1312 exim_gnutls_base_init_done = TRUE;
1317 /* For client-side sessions we allocate a context. This lets us run
1318 several in parallel. */
1319 int old_pool = store_pool;
1320 store_pool = POOL_PERM;
1321 state = store_get(sizeof(exim_gnutls_state_st));
1322 store_pool = old_pool;
1324 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1326 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1327 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1331 state = &state_server;
1332 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1334 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1335 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1338 return tls_error_gnu(US"gnutls_init", rc, host, errstr);
1342 state->tls_certificate = certificate;
1343 state->tls_privatekey = privatekey;
1344 state->tls_require_ciphers = require_ciphers;
1345 state->tls_sni = sni;
1346 state->tls_verify_certificates = cas;
1347 state->tls_crl = crl;
1349 /* This handles the variables that might get re-expanded after TLS SNI;
1350 that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1353 debug_printf("Expanding various TLS configuration options for session credentials.\n");
1354 if ((rc = tls_expand_session_files(state, errstr)) != OK) return rc;
1356 /* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1357 requires a new structure afterwards. */
1359 if ((rc = tls_set_remaining_x509(state, errstr)) != OK) return rc;
1361 /* set SNI in client, only */
1364 if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni, errstr))
1366 if (state->tlsp->sni && *state->tlsp->sni)
1369 debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1370 sz = Ustrlen(state->tlsp->sni);
1371 if ((rc = gnutls_server_name_set(state->session,
1372 GNUTLS_NAME_DNS, state->tlsp->sni, sz)))
1373 return tls_error_gnu(US"gnutls_server_name_set", rc, host, errstr);
1376 else if (state->tls_sni)
1377 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1378 "have an SNI set for a server [%s]\n", state->tls_sni);
1380 /* This is the priority string support,
1381 http://www.gnutls.org/manual/html_node/Priority-Strings.html
1382 and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1383 This was backwards incompatible, but means Exim no longer needs to track
1384 all algorithms and provide string forms for them. */
1387 if (state->tls_require_ciphers && *state->tls_require_ciphers)
1389 if (!expand_check_tlsvar(tls_require_ciphers, errstr))
1391 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1393 p = state->exp_tls_require_ciphers;
1394 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n", p);
1399 p = exim_default_gnutls_priority;
1401 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n", p);
1404 if ((rc = gnutls_priority_init(&state->priority_cache, CCS p, &errpos)))
1405 return tls_error_gnu(string_sprintf(
1406 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1407 p, errpos - CS p, errpos),
1410 if ((rc = gnutls_priority_set(state->session, state->priority_cache)))
1411 return tls_error_gnu(US"gnutls_priority_set", rc, host, errstr);
1413 /* This also sets the server ticket expiration time to the same, and
1414 the STEK rotation time to 3x. */
1416 gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1418 /* Reduce security in favour of increased compatibility, if the admin
1419 decides to make that trade-off. */
1420 if (gnutls_compat_mode)
1422 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1423 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1424 gnutls_session_enable_compatibility_mode(state->session);
1426 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1430 *caller_state = state;
1436 /*************************************************
1437 * Extract peer information *
1438 *************************************************/
1440 static const uschar *
1441 cipher_stdname_kcm(gnutls_kx_algorithm_t kx, gnutls_cipher_algorithm_t cipher,
1442 gnutls_mac_algorithm_t mac)
1445 gnutls_kx_algorithm_t kx_i;
1446 gnutls_cipher_algorithm_t cipher_i;
1447 gnutls_mac_algorithm_t mac_i;
1450 gnutls_cipher_suite_info(i, cs_id, &kx_i, &cipher_i, &mac_i, NULL);
1452 if (kx_i == kx && cipher_i == cipher && mac_i == mac)
1453 return cipher_stdname(cs_id[0], cs_id[1]);
1459 /* Called from both server and client code.
1460 Only this is allowed to set state->peerdn and state->have_set_peerdn
1461 and we use that to detect double-calls.
1463 NOTE: the state blocks last while the TLS connection is up, which is fine
1464 for logging in the server side, but for the client side, we log after teardown
1465 in src/deliver.c. While the session is up, we can twist about states and
1466 repoint tls_* globals, but those variables used for logging or other variable
1467 expansion that happens _after_ delivery need to have a longer life-time.
1469 So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1470 doing this more than once per generation of a state context. We set them in
1471 the state context, and repoint tls_* to them. After the state goes away, the
1472 tls_* copies of the pointers remain valid and client delivery logging is happy.
1474 tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1478 state exim_gnutls_state_st *
1479 errstr pointer to error string
1481 Returns: OK/DEFER/FAIL
1485 peer_status(exim_gnutls_state_st * state, uschar ** errstr)
1487 gnutls_session_t session = state->session;
1488 const gnutls_datum_t * cert_list;
1490 unsigned int cert_list_size = 0;
1491 gnutls_protocol_t protocol;
1492 gnutls_cipher_algorithm_t cipher;
1493 gnutls_kx_algorithm_t kx;
1494 gnutls_mac_algorithm_t mac;
1495 gnutls_certificate_type_t ct;
1496 gnutls_x509_crt_t crt;
1500 if (state->have_set_peerdn)
1502 state->have_set_peerdn = TRUE;
1504 state->peerdn = NULL;
1507 cipher = gnutls_cipher_get(session);
1508 protocol = gnutls_protocol_get_version(session);
1509 mac = gnutls_mac_get(session);
1511 #ifdef GNUTLS_TLS1_3
1512 protocol >= GNUTLS_TLS1_3 ? 0 :
1514 gnutls_kx_get(session);
1516 old_pool = store_pool;
1518 tls_support * tlsp = state->tlsp;
1519 store_pool = POOL_PERM;
1521 #ifdef SUPPORT_GNUTLS_SESS_DESC
1524 uschar * s = US gnutls_session_get_desc(session), c;
1526 /* Nikos M suggests we use this by preference. It returns like:
1527 (TLS1.3)-(ECDHE-SECP256R1)-(RSA-PSS-RSAE-SHA256)-(AES-256-GCM)
1529 For partial back-compat, put a colon after the TLS version, replace the
1530 )-( grouping with __, replace in-group - with _ and append the :keysize. */
1532 /* debug_printf("peer_status: gnutls_session_get_desc %s\n", s); */
1534 for (s++; (c = *s) && c != ')'; s++) g = string_catn(g, s, 1);
1535 g = string_catn(g, US":", 1);
1536 if (*s) s++; /* now on _ between groups */
1539 for (*++s && ++s; (c = *s) && c != ')'; s++) g = string_catn(g, c == '-' ? US"_" : s, 1);
1540 /* now on ) closing group */
1541 if ((c = *s) && *++s == '-') g = string_catn(g, US"__", 2);
1542 /* now on _ between groups */
1544 g = string_catn(g, US":", 1);
1545 g = string_cat(g, string_sprintf("%d", (int) gnutls_cipher_get_key_size(cipher) * 8));
1546 state->ciphersuite = string_from_gstring(g);
1549 state->ciphersuite = string_sprintf("%s:%s:%d",
1550 gnutls_protocol_get_name(protocol),
1551 gnutls_cipher_suite_get_name(kx, cipher, mac),
1552 (int) gnutls_cipher_get_key_size(cipher) * 8);
1554 /* I don't see a way that spaces could occur, in the current GnuTLS
1555 code base, but it was a concern in the old code and perhaps older GnuTLS
1556 releases did return "TLS 1.0"; play it safe, just in case. */
1558 for (uschar * p = state->ciphersuite; *p; p++) if (isspace(*p)) *p = '-';
1561 /* debug_printf("peer_status: ciphersuite %s\n", state->ciphersuite); */
1563 tlsp->cipher = state->ciphersuite;
1564 tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
1566 tlsp->cipher_stdname = cipher_stdname_kcm(kx, cipher, mac);
1568 store_pool = old_pool;
1571 cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
1573 if (!cert_list || cert_list_size == 0)
1575 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1576 cert_list, cert_list_size);
1577 if (state->verify_requirement >= VERIFY_REQUIRED)
1578 return tls_error(US"certificate verification failed",
1579 US"no certificate received from peer", state->host, errstr);
1583 if ((ct = gnutls_certificate_type_get(session)) != GNUTLS_CRT_X509)
1585 const uschar * ctn = US gnutls_certificate_type_get_name(ct);
1587 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1588 if (state->verify_requirement >= VERIFY_REQUIRED)
1589 return tls_error(US"certificate verification not possible, unhandled type",
1590 ctn, state->host, errstr);
1594 #define exim_gnutls_peer_err(Label) \
1596 if (rc != GNUTLS_E_SUCCESS) \
1598 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1599 (Label), gnutls_strerror(rc)); \
1600 if (state->verify_requirement >= VERIFY_REQUIRED) \
1601 return tls_error_gnu((Label), rc, state->host, errstr); \
1606 rc = import_cert(&cert_list[0], &crt);
1607 exim_gnutls_peer_err(US"cert 0");
1609 state->tlsp->peercert = state->peercert = crt;
1612 rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1613 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1615 exim_gnutls_peer_err(US"getting size for cert DN failed");
1616 return FAIL; /* should not happen */
1618 dn_buf = store_get_perm(sz);
1619 rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1620 exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1622 state->peerdn = dn_buf;
1625 #undef exim_gnutls_peer_err
1631 /*************************************************
1632 * Verify peer certificate *
1633 *************************************************/
1635 /* Called from both server and client code.
1636 *Should* be using a callback registered with
1637 gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1638 the peer information, but that's too new for some OSes.
1641 state exim_gnutls_state_st *
1642 errstr where to put an error message
1645 FALSE if the session should be rejected
1646 TRUE if the cert is okay or we just don't care
1650 verify_certificate(exim_gnutls_state_st * state, uschar ** errstr)
1655 DEBUG(D_tls) debug_printf("TLS: checking peer certificate\n");
1657 rc = peer_status(state, errstr);
1659 if (state->verify_requirement == VERIFY_NONE)
1662 if (rc != OK || !state->peerdn)
1664 verify = GNUTLS_CERT_INVALID;
1665 *errstr = US"certificate not supplied";
1671 if (state->verify_requirement == VERIFY_DANE && state->host)
1673 /* Using dane_verify_session_crt() would be easy, as it does it all for us
1674 including talking to a DNS resolver. But we want to do that bit ourselves
1675 as the testsuite intercepts and fakes its own DNS environment. */
1680 const gnutls_datum_t * certlist =
1681 gnutls_certificate_get_peers(state->session, &lsize);
1682 int usage = tls_out.tlsa_usage;
1684 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1685 /* Split the TLSA records into two sets, TA and EE selectors. Run the
1686 dane-verification separately so that we know which selector verified;
1687 then we know whether to do name-verification (needed for TA but not EE). */
1689 if (usage == ((1<<DANESSL_USAGE_DANE_TA) | (1<<DANESSL_USAGE_DANE_EE)))
1690 { /* a mixed-usage bundle */
1695 for(nrec = 0; state->dane_data_len[nrec]; ) nrec++;
1698 dd = store_get(nrec * sizeof(uschar *));
1699 ddl = store_get(nrec * sizeof(int));
1702 if ((rc = dane_state_init(&s, 0)))
1705 for (usage = DANESSL_USAGE_DANE_EE;
1706 usage >= DANESSL_USAGE_DANE_TA; usage--)
1707 { /* take records with this usage */
1708 for (j = i = 0; i < nrec; i++)
1709 if (state->dane_data[i][0] == usage)
1711 dd[j] = state->dane_data[i];
1712 ddl[j++] = state->dane_data_len[i];
1719 if ((rc = dane_raw_tlsa(s, &r, (char * const *)dd, ddl, 1, 0)))
1722 if ((rc = dane_verify_crt_raw(s, certlist, lsize,
1723 gnutls_certificate_type_get(state->session),
1725 usage == DANESSL_USAGE_DANE_EE
1726 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1730 debug_printf("TLSA record problem: %s\n", dane_strerror(rc));
1732 else if (verify == 0) /* verification passed */
1740 if (rc) goto tlsa_prob;
1745 if ( (rc = dane_state_init(&s, 0))
1746 || (rc = dane_raw_tlsa(s, &r, state->dane_data, state->dane_data_len,
1748 || (rc = dane_verify_crt_raw(s, certlist, lsize,
1749 gnutls_certificate_type_get(state->session),
1751 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1752 usage == (1 << DANESSL_USAGE_DANE_EE)
1753 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1762 if (verify != 0) /* verification failed */
1765 (void) dane_verification_status_print(verify, &str, 0);
1766 *errstr = US str.data; /* don't bother to free */
1770 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1771 /* If a TA-mode TLSA record was used for verification we must additionally
1772 verify the cert name (but not the CA chain). For EE-mode, skip it. */
1774 if (usage & (1 << DANESSL_USAGE_DANE_EE))
1777 state->peer_dane_verified = state->peer_cert_verified = TRUE;
1780 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1781 /* Assume that the name on the A-record is the one that should be matching
1782 the cert. An alternate view is that the domain part of the email address
1783 is also permissible. */
1785 if (gnutls_x509_crt_check_hostname(state->tlsp->peercert,
1786 CS state->host->name))
1788 state->peer_dane_verified = state->peer_cert_verified = TRUE;
1793 #endif /*SUPPORT_DANE*/
1795 rc = gnutls_certificate_verify_peers2(state->session, &verify);
1798 /* Handle the result of verification. INVALID is set if any others are. */
1800 if (rc < 0 || verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED))
1802 state->peer_cert_verified = FALSE;
1805 #ifdef GNUTLS_CERT_VFY_STATUS_PRINT
1810 if (gnutls_certificate_verification_status_print(verify,
1811 gnutls_certificate_type_get(state->session), &txt, 0)
1812 == GNUTLS_E_SUCCESS)
1814 debug_printf("%s\n", txt.data);
1815 gnutls_free(txt.data);
1819 *errstr = verify & GNUTLS_CERT_REVOKED
1820 ? US"certificate revoked" : US"certificate invalid";
1824 debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
1825 *errstr, state->peerdn ? state->peerdn : US"<unset>");
1827 if (state->verify_requirement >= VERIFY_REQUIRED)
1830 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1835 /* Client side, check the server's certificate name versus the name on the
1836 A-record for the connection we made. What to do for server side - what name
1837 to use for client? We document that there is no such checking for server
1840 if ( state->exp_tls_verify_cert_hostnames
1841 && !gnutls_x509_crt_check_hostname(state->tlsp->peercert,
1842 CS state->exp_tls_verify_cert_hostnames)
1846 debug_printf("TLS certificate verification failed: cert name mismatch\n");
1847 if (state->verify_requirement >= VERIFY_REQUIRED)
1852 state->peer_cert_verified = TRUE;
1853 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
1854 state->peerdn ? state->peerdn : US"<unset>");
1858 state->tlsp->peerdn = state->peerdn;
1863 *errstr = string_sprintf("TLSA record problem: %s",
1864 rc == DANE_E_REQUESTED_DATA_NOT_AVAILABLE ? "none usable" : dane_strerror(rc));
1868 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1875 /* ------------------------------------------------------------------------ */
1878 /* Logging function which can be registered with
1879 * gnutls_global_set_log_function()
1880 * gnutls_global_set_log_level() 0..9
1882 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1884 exim_gnutls_logger_cb(int level, const char *message)
1886 size_t len = strlen(message);
1889 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1892 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1893 message[len-1] == '\n' ? "" : "\n");
1898 /* Called after client hello, should handle SNI work.
1899 This will always set tls_sni (state->received_sni) if available,
1900 and may trigger presenting different certificates,
1901 if state->trigger_sni_changes is TRUE.
1903 Should be registered with
1904 gnutls_handshake_set_post_client_hello_function()
1906 "This callback must return 0 on success or a gnutls error code to terminate the
1909 For inability to get SNI information, we return 0.
1910 We only return non-zero if re-setup failed.
1911 Only used for server-side TLS.
1915 exim_sni_handling_cb(gnutls_session_t session)
1917 char sni_name[MAX_HOST_LEN];
1918 size_t data_len = MAX_HOST_LEN;
1919 exim_gnutls_state_st *state = &state_server;
1920 unsigned int sni_type;
1922 uschar * dummy_errstr;
1924 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1925 if (rc != GNUTLS_E_SUCCESS)
1928 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1929 debug_printf("TLS: no SNI presented in handshake.\n");
1931 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1932 gnutls_strerror(rc), rc);
1937 if (sni_type != GNUTLS_NAME_DNS)
1939 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1943 /* We now have a UTF-8 string in sni_name */
1944 old_pool = store_pool;
1945 store_pool = POOL_PERM;
1946 state->received_sni = string_copyn(US sni_name, data_len);
1947 store_pool = old_pool;
1949 /* We set this one now so that variable expansions below will work */
1950 state->tlsp->sni = state->received_sni;
1952 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1953 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1955 if (!state->trigger_sni_changes)
1958 if ((rc = tls_expand_session_files(state, &dummy_errstr)) != OK)
1960 /* If the setup of certs/etc failed before handshake, TLS would not have
1961 been offered. The best we can do now is abort. */
1962 return GNUTLS_E_APPLICATION_ERROR_MIN;
1965 rc = tls_set_remaining_x509(state, &dummy_errstr);
1966 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1973 #ifndef DISABLE_OCSP
1976 server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1977 gnutls_datum_t * ocsp_response)
1980 DEBUG(D_tls) debug_printf("OCSP stapling callback: %s\n", US ptr);
1982 if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1984 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1986 tls_in.ocsp = OCSP_NOT_RESP;
1987 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1990 tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1997 #ifndef DISABLE_EVENT
1999 We use this callback to get observability and detail-level control
2000 for an exim TLS connection (either direction), raising a tls:cert event
2001 for each cert in the chain presented by the peer. Any event
2002 can deny verification.
2004 Return 0 for the handshake to continue or non-zero to terminate.
2008 verify_cb(gnutls_session_t session)
2010 const gnutls_datum_t * cert_list;
2011 unsigned int cert_list_size = 0;
2012 gnutls_x509_crt_t crt;
2015 exim_gnutls_state_st * state = gnutls_session_get_ptr(session);
2017 if ((cert_list = gnutls_certificate_get_peers(session, &cert_list_size)))
2018 while (cert_list_size--)
2020 if ((rc = import_cert(&cert_list[cert_list_size], &crt)) != GNUTLS_E_SUCCESS)
2022 DEBUG(D_tls) debug_printf("TLS: peer cert problem: depth %d: %s\n",
2023 cert_list_size, gnutls_strerror(rc));
2027 state->tlsp->peercert = crt;
2028 if ((yield = event_raise(state->event_action,
2029 US"tls:cert", string_sprintf("%d", cert_list_size))))
2031 log_write(0, LOG_MAIN,
2032 "SSL verify denied by event-action: depth=%d: %s",
2033 cert_list_size, yield);
2034 return 1; /* reject */
2036 state->tlsp->peercert = NULL;
2046 ddump(gnutls_datum_t * d)
2048 gstring * g = string_get((d->size+1) * 2);
2049 uschar * s = d->data;
2050 for (unsigned i = d->size; i > 0; i--, s++)
2052 g = string_catn(g, US "0123456789abcdef" + (*s >> 4), 1);
2053 g = string_catn(g, US "0123456789abcdef" + (*s & 0xf), 1);
2059 post_handshake_debug(exim_gnutls_state_st * state)
2061 #ifdef SUPPORT_GNUTLS_SESS_DESC
2062 debug_printf("%s\n", gnutls_session_get_desc(state->session));
2064 #ifdef SUPPORT_GNUTLS_KEYLOG
2065 # ifdef GNUTLS_TLS1_3
2066 if (gnutls_protocol_get_version(state->session) < GNUTLS_TLS1_3)
2071 gnutls_datum_t c, s;
2073 /* we only want the client random and the master secret */
2074 gnutls_session_get_random(state->session, &c, &s);
2075 gnutls_session_get_master_secret(state->session, &s);
2078 debug_printf("CLIENT_RANDOM %.*s %.*s\n", (int)gc->ptr, gc->s, (int)gs->ptr, gs->s);
2081 debug_printf("To get keying info for TLS1.3 is hard:\n"
2082 " set environment variable SSLKEYLOGFILE to a filename writable by uid exim\n"
2083 " add SSLKEYLOGFILE to keep_environment in the exim config\n"
2084 " run exim as root\n"
2085 " if using sudo, add SSLKEYLOGFILE to env_keep in /etc/sudoers\n");
2090 #ifdef EXPERIMENTAL_TLS_RESUME
2092 tls_server_ticket_cb(gnutls_session_t sess, u_int htype, unsigned when,
2093 unsigned incoming, const gnutls_datum_t * msg)
2095 DEBUG(D_tls) debug_printf("newticket cb\n");
2096 tls_in.resumption |= RESUME_CLIENT_REQUESTED;
2101 tls_server_resume_prehandshake(exim_gnutls_state_st * state)
2103 /* Should the server offer session resumption? */
2104 tls_in.resumption = RESUME_SUPPORTED;
2105 if (verify_check_host(&tls_resumption_hosts) == OK)
2108 /* GnuTLS appears to not do ticket overlap, but does emit a fresh ticket when
2109 an offered resumption is unacceptable. We lose one resumption per ticket
2110 lifetime, and sessions cannot be indefinitely re-used. There seems to be no
2111 way (3.6.7) of changing the default number of 2 TLS1.3 tickets issued, but at
2112 least they go out in a single packet. */
2114 if (!(rc = gnutls_session_ticket_enable_server(state->session,
2115 &server_sessticket_key)))
2116 tls_in.resumption |= RESUME_SERVER_TICKET;
2119 debug_printf("enabling session tickets: %s\n", US gnutls_strerror(rc));
2121 /* Try to tell if we see a ticket request */
2122 gnutls_handshake_set_hook_function(state->session,
2123 GNUTLS_HANDSHAKE_NEW_SESSION_TICKET, GNUTLS_HOOK_POST, tls_server_ticket_cb);
2128 tls_server_resume_posthandshake(exim_gnutls_state_st * state)
2130 if (gnutls_session_resumption_requested(state->session))
2132 /* This tells us the client sent a full ticket. We use a
2133 callback on session-ticket request, elsewhere, to tell
2134 if a client asked for a ticket. */
2136 tls_in.resumption |= RESUME_CLIENT_SUGGESTED;
2137 DEBUG(D_tls) debug_printf("client requested resumption\n");
2139 if (gnutls_session_is_resumed(state->session))
2141 tls_in.resumption |= RESUME_USED;
2142 DEBUG(D_tls) debug_printf("Session resumed\n");
2146 /* ------------------------------------------------------------------------ */
2147 /* Exported functions */
2152 /*************************************************
2153 * Start a TLS session in a server *
2154 *************************************************/
2156 /* This is called when Exim is running as a server, after having received
2157 the STARTTLS command. It must respond to that command, and then negotiate
2161 require_ciphers list of allowed ciphers or NULL
2162 errstr pointer to error string
2164 Returns: OK on success
2165 DEFER for errors before the start of the negotiation
2166 FAIL for errors during the negotiation; the server can't
2171 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
2174 exim_gnutls_state_st * state = NULL;
2176 /* Check for previous activation */
2177 if (tls_in.active.sock >= 0)
2179 tls_error(US"STARTTLS received after TLS started", US "", NULL, errstr);
2180 smtp_printf("554 Already in TLS\r\n", FALSE);
2184 /* Initialize the library. If it fails, it will already have logged the error
2185 and sent an SMTP response. */
2187 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
2189 if ((rc = tls_init(NULL, tls_certificate, tls_privatekey,
2190 NULL, tls_verify_certificates, tls_crl,
2191 require_ciphers, &state, &tls_in, errstr)) != OK) return rc;
2193 #ifdef EXPERIMENTAL_TLS_RESUME
2194 tls_server_resume_prehandshake(state);
2197 /* If this is a host for which certificate verification is mandatory or
2198 optional, set up appropriately. */
2200 if (verify_check_host(&tls_verify_hosts) == OK)
2203 debug_printf("TLS: a client certificate will be required.\n");
2204 state->verify_requirement = VERIFY_REQUIRED;
2205 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2207 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2210 debug_printf("TLS: a client certificate will be requested but not required.\n");
2211 state->verify_requirement = VERIFY_OPTIONAL;
2212 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2217 debug_printf("TLS: a client certificate will not be requested.\n");
2218 state->verify_requirement = VERIFY_NONE;
2219 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2222 #ifndef DISABLE_EVENT
2225 state->event_action = event_action;
2226 gnutls_session_set_ptr(state->session, state);
2227 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2231 /* Register SNI handling; always, even if not in tls_certificate, so that the
2232 expansion variable $tls_sni is always available. */
2234 gnutls_handshake_set_post_client_hello_function(state->session,
2235 exim_sni_handling_cb);
2237 /* Set context and tell client to go ahead, except in the case of TLS startup
2238 on connection, where outputting anything now upsets the clients and tends to
2239 make them disconnect. We need to have an explicit fflush() here, to force out
2240 the response. Other smtp_printf() calls do not need it, because in non-TLS
2241 mode, the fflush() happens when smtp_getc() is called. */
2243 if (!state->tlsp->on_connect)
2245 smtp_printf("220 TLS go ahead\r\n", FALSE);
2249 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2250 that the GnuTLS library doesn't.
2251 From 3.1.0 there is gnutls_handshake_set_timeout() - but it requires you
2252 to set (and clear down afterwards) up a pull-timeout callback function that does
2253 a select, so we're no better off unless avoiding signals becomes an issue. */
2255 gnutls_transport_set_ptr2(state->session,
2256 (gnutls_transport_ptr_t)(long) fileno(smtp_in),
2257 (gnutls_transport_ptr_t)(long) fileno(smtp_out));
2258 state->fd_in = fileno(smtp_in);
2259 state->fd_out = fileno(smtp_out);
2261 sigalrm_seen = FALSE;
2262 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2264 rc = gnutls_handshake(state->session);
2265 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2268 if (rc != GNUTLS_E_SUCCESS)
2270 /* It seems that, except in the case of a timeout, we have to close the
2271 connection right here; otherwise if the other end is running OpenSSL it hangs
2272 until the server times out. */
2276 tls_error(US"gnutls_handshake", US"timed out", NULL, errstr);
2277 gnutls_db_remove_session(state->session);
2281 tls_error_gnu(US"gnutls_handshake", rc, NULL, errstr);
2282 (void) gnutls_alert_send_appropriate(state->session, rc);
2283 gnutls_deinit(state->session);
2284 gnutls_certificate_free_credentials(state->x509_cred);
2286 shutdown(state->fd_out, SHUT_WR);
2287 for (int i = 1024; fgetc(smtp_in) != EOF && i > 0; ) i--; /* drain skt */
2288 (void)fclose(smtp_out);
2289 (void)fclose(smtp_in);
2290 smtp_out = smtp_in = NULL;
2296 #ifdef EXPERIMENTAL_TLS_RESUME
2297 tls_server_resume_posthandshake(state);
2300 DEBUG(D_tls) post_handshake_debug(state);
2302 /* Verify after the fact */
2304 if (!verify_certificate(state, errstr))
2306 if (state->verify_requirement != VERIFY_OPTIONAL)
2308 (void) tls_error(US"certificate verification failed", *errstr, NULL, errstr);
2312 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
2316 /* Sets various Exim expansion variables; always safe within server */
2318 extract_exim_vars_from_tls_state(state);
2320 /* TLS has been set up. Adjust the input functions to read via TLS,
2321 and initialize appropriately. */
2323 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2325 receive_getc = tls_getc;
2326 receive_getbuf = tls_getbuf;
2327 receive_get_cache = tls_get_cache;
2328 receive_ungetc = tls_ungetc;
2329 receive_feof = tls_feof;
2330 receive_ferror = tls_ferror;
2331 receive_smtp_buffered = tls_smtp_buffered;
2340 tls_client_setup_hostname_checks(host_item * host, exim_gnutls_state_st * state,
2341 smtp_transport_options_block * ob)
2343 if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
2345 state->exp_tls_verify_cert_hostnames =
2347 string_domain_utf8_to_alabel(host->name, NULL);
2352 debug_printf("TLS: server cert verification includes hostname: \"%s\".\n",
2353 state->exp_tls_verify_cert_hostnames);
2361 /* Given our list of RRs from the TLSA lookup, build a lookup block in
2362 GnuTLS-DANE's preferred format. Hang it on the state str for later
2363 use in DANE verification.
2365 We point at the dnsa data not copy it, so it must remain valid until
2366 after verification is done.*/
2369 dane_tlsa_load(exim_gnutls_state_st * state, dns_answer * dnsa)
2373 const char ** dane_data;
2374 int * dane_data_len;
2377 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
2378 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2379 ) if (rr->type == T_TLSA) i++;
2381 dane_data = store_get(i * sizeof(uschar *));
2382 dane_data_len = store_get(i * sizeof(int));
2385 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
2386 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2387 ) if (rr->type == T_TLSA && rr->size > 3)
2389 const uschar * p = rr->data;
2390 uint8_t usage = p[0], sel = p[1], type = p[2];
2393 debug_printf("TLSA: %d %d %d size %d\n", usage, sel, type, rr->size);
2395 if ( (usage != DANESSL_USAGE_DANE_TA && usage != DANESSL_USAGE_DANE_EE)
2396 || (sel != 0 && sel != 1)
2401 case 0: /* Full: cannot check at present */
2403 case 1: if (rr->size != 3 + 256/8) continue; /* sha2-256 */
2405 case 2: if (rr->size != 3 + 512/8) continue; /* sha2-512 */
2410 tls_out.tlsa_usage |= 1<<usage;
2411 dane_data[i] = CS p;
2412 dane_data_len[i++] = rr->size;
2415 if (!i) return FALSE;
2417 dane_data[i] = NULL;
2418 dane_data_len[i] = 0;
2420 state->dane_data = (char * const *)dane_data;
2421 state->dane_data_len = dane_data_len;
2428 #ifdef EXPERIMENTAL_TLS_RESUME
2429 /* On the client, get any stashed session for the given IP from hints db
2430 and apply it to the ssl-connection for attempted resumption. Although
2431 there is a gnutls_session_ticket_enable_client() interface it is
2432 documented as unnecessary (as of 3.6.7) as "session tickets are emabled
2433 by deafult". There seems to be no way to disable them, so even hosts not
2434 enabled by the transport option will be sent a ticket request. We will
2435 however avoid storing and retrieving session information. */
2438 tls_retrieve_session(tls_support * tlsp, gnutls_session_t session,
2439 host_item * host, smtp_transport_options_block * ob)
2441 tlsp->resumption = RESUME_SUPPORTED;
2442 if (verify_check_given_host(CUSS &ob->tls_resumption_hosts, host) == OK)
2444 dbdata_tls_session * dt;
2446 open_db dbblock, * dbm_file;
2449 debug_printf("check for resumable session for %s\n", host->address);
2450 tlsp->host_resumable = TRUE;
2451 tlsp->resumption |= RESUME_CLIENT_REQUESTED;
2452 if ((dbm_file = dbfn_open(US"tls", O_RDONLY, &dbblock, FALSE, FALSE)))
2454 /* key for the db is the IP */
2455 if ((dt = dbfn_read_with_length(dbm_file, host->address, &len)))
2456 if (!(rc = gnutls_session_set_data(session,
2457 CUS dt->session, (size_t)len - sizeof(dbdata_tls_session))))
2459 DEBUG(D_tls) debug_printf("good session\n");
2460 tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
2462 else DEBUG(D_tls) debug_printf("setting session resumption data: %s\n",
2463 US gnutls_strerror(rc));
2464 dbfn_close(dbm_file);
2471 tls_save_session(tls_support * tlsp, gnutls_session_t session, const host_item * host)
2473 /* TLS 1.2 - we get both the callback and the direct posthandshake call,
2474 but this flag is not set until the second. TLS 1.3 it's the other way about.
2475 Keep both calls as the session data cannot be extracted before handshake
2478 if (gnutls_session_get_flags(session) & GNUTLS_SFLAGS_SESSION_TICKET)
2483 DEBUG(D_tls) debug_printf("server offered session ticket\n");
2484 tlsp->ticket_received = TRUE;
2485 tlsp->resumption |= RESUME_SERVER_TICKET;
2487 if (tlsp->host_resumable)
2488 if (!(rc = gnutls_session_get_data2(session, &tkt)))
2490 open_db dbblock, * dbm_file;
2491 int dlen = sizeof(dbdata_tls_session) + tkt.size;
2492 dbdata_tls_session * dt = store_get(dlen);
2494 DEBUG(D_tls) debug_printf("session data size %u\n", (unsigned)tkt.size);
2495 memcpy(dt->session, tkt.data, tkt.size);
2496 gnutls_free(tkt.data);
2498 if ((dbm_file = dbfn_open(US"tls", O_RDWR, &dbblock, FALSE, FALSE)))
2500 /* key for the db is the IP */
2501 dbfn_delete(dbm_file, host->address);
2502 dbfn_write(dbm_file, host->address, dt, dlen);
2503 dbfn_close(dbm_file);
2506 debug_printf("wrote session db (len %u)\n", (unsigned)dlen);
2510 debug_printf("extract session data: %s\n", US gnutls_strerror(rc));
2515 /* With a TLS1.3 session, the ticket(s) are not seen until
2516 the first data read is attempted. And there's often two of them.
2517 Pick them up with this callback. We are also called for 1.2
2521 tls_client_ticket_cb(gnutls_session_t sess, u_int htype, unsigned when,
2522 unsigned incoming, const gnutls_datum_t * msg)
2524 exim_gnutls_state_st * state = gnutls_session_get_ptr(sess);
2525 tls_support * tlsp = state->tlsp;
2527 DEBUG(D_tls) debug_printf("newticket cb\n");
2529 if (!tlsp->ticket_received)
2530 tls_save_session(tlsp, sess, state->host);
2536 tls_client_resume_prehandshake(exim_gnutls_state_st * state,
2537 tls_support * tlsp, host_item * host,
2538 smtp_transport_options_block * ob)
2540 gnutls_session_set_ptr(state->session, state);
2541 gnutls_handshake_set_hook_function(state->session,
2542 GNUTLS_HANDSHAKE_NEW_SESSION_TICKET, GNUTLS_HOOK_POST, tls_client_ticket_cb);
2544 tls_retrieve_session(tlsp, state->session, host, ob);
2548 tls_client_resume_posthandshake(exim_gnutls_state_st * state,
2549 tls_support * tlsp, host_item * host)
2551 if (gnutls_session_is_resumed(state->session))
2553 DEBUG(D_tls) debug_printf("Session resumed\n");
2554 tlsp->resumption |= RESUME_USED;
2557 tls_save_session(tlsp, state->session, host);
2559 #endif /* EXPERIMENTAL_TLS_RESUME */
2562 /*************************************************
2563 * Start a TLS session in a client *
2564 *************************************************/
2566 /* Called from the smtp transport after STARTTLS has been accepted.
2569 cctx connection context
2570 conn_args connection details
2571 cookie datum for randomness (not used)
2572 tlsp record details of channel configuration here; must be non-NULL
2573 errstr error string pointer
2575 Returns: TRUE for success with TLS session context set in smtp context,
2580 tls_client_start(client_conn_ctx * cctx, smtp_connect_args * conn_args,
2581 void * cookie ARG_UNUSED,
2582 tls_support * tlsp, uschar ** errstr)
2584 host_item * host = conn_args->host; /* for msgs and option-tests */
2585 transport_instance * tb = conn_args->tblock; /* always smtp or NULL */
2586 smtp_transport_options_block * ob = tb
2587 ? (smtp_transport_options_block *)tb->options_block
2588 : &smtp_transport_option_defaults;
2590 exim_gnutls_state_st * state = NULL;
2591 uschar * cipher_list = NULL;
2593 #ifndef DISABLE_OCSP
2595 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
2596 BOOL request_ocsp = require_ocsp ? TRUE
2597 : verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2600 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", cctx->sock);
2603 /* If dane is flagged, have either request or require dane for this host, and
2604 a TLSA record found. Therefore, dane verify required. Which implies cert must
2605 be requested and supplied, dane verify must pass, and cert verify irrelevant
2606 (incl. hostnames), and (caller handled) require_tls */
2608 if (conn_args->dane && ob->dane_require_tls_ciphers)
2610 /* not using expand_check_tlsvar because not yet in state */
2611 if (!expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2612 &cipher_list, errstr))
2614 cipher_list = cipher_list && *cipher_list
2615 ? ob->dane_require_tls_ciphers : ob->tls_require_ciphers;
2620 cipher_list = ob->tls_require_ciphers;
2622 if (tls_init(host, ob->tls_certificate, ob->tls_privatekey,
2623 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
2624 cipher_list, &state, tlsp, errstr) != OK)
2628 int dh_min_bits = ob->tls_dh_min_bits;
2629 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
2632 debug_printf("WARNING: tls_dh_min_bits far too low,"
2633 " clamping %d up to %d\n",
2634 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
2635 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
2638 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
2639 " acceptable bits to %d\n",
2641 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
2644 /* Stick to the old behaviour for compatibility if tls_verify_certificates is
2645 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
2646 the specified host patterns if one of them is defined */
2649 if (conn_args->dane && dane_tlsa_load(state, &conn_args->tlsa_dnsa))
2652 debug_printf("TLS: server certificate DANE required.\n");
2653 state->verify_requirement = VERIFY_DANE;
2654 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2658 if ( ( state->exp_tls_verify_certificates
2659 && !ob->tls_verify_hosts
2660 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2662 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
2665 tls_client_setup_hostname_checks(host, state, ob);
2667 debug_printf("TLS: server certificate verification required.\n");
2668 state->verify_requirement = VERIFY_REQUIRED;
2669 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2671 else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
2673 tls_client_setup_hostname_checks(host, state, ob);
2675 debug_printf("TLS: server certificate verification optional.\n");
2676 state->verify_requirement = VERIFY_OPTIONAL;
2677 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2682 debug_printf("TLS: server certificate verification not required.\n");
2683 state->verify_requirement = VERIFY_NONE;
2684 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2687 #ifndef DISABLE_OCSP
2688 /* supported since GnuTLS 3.1.3 */
2691 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
2692 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
2693 NULL, 0, NULL)) != OK)
2695 tls_error_gnu(US"cert-status-req", rc, state->host, errstr);
2698 tlsp->ocsp = OCSP_NOT_RESP;
2702 #ifdef EXPERIMENTAL_TLS_RESUME
2703 tls_client_resume_prehandshake(state, tlsp, host, ob);
2706 #ifndef DISABLE_EVENT
2707 if (tb && tb->event_action)
2709 state->event_action = tb->event_action;
2710 gnutls_session_set_ptr(state->session, state);
2711 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2715 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr_t)(long) cctx->sock);
2716 state->fd_in = cctx->sock;
2717 state->fd_out = cctx->sock;
2719 DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
2720 /* There doesn't seem to be a built-in timeout on connection. */
2722 sigalrm_seen = FALSE;
2723 ALARM(ob->command_timeout);
2725 rc = gnutls_handshake(state->session);
2726 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2729 if (rc != GNUTLS_E_SUCCESS)
2733 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_USER_CANCELED);
2734 tls_error(US"gnutls_handshake", US"timed out", state->host, errstr);
2737 tls_error_gnu(US"gnutls_handshake", rc, state->host, errstr);
2741 DEBUG(D_tls) post_handshake_debug(state);
2745 if (!verify_certificate(state, errstr))
2747 tls_error(US"certificate verification failed", *errstr, state->host, errstr);
2751 #ifndef DISABLE_OCSP
2756 gnutls_datum_t stapling;
2757 gnutls_ocsp_resp_t resp;
2758 gnutls_datum_t printed;
2759 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
2760 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
2761 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
2762 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
2765 debug_printf("%.4096s", printed.data);
2766 gnutls_free(printed.data);
2769 (void) tls_error_gnu(US"ocsp decode", rc, state->host, errstr);
2772 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
2774 tlsp->ocsp = OCSP_FAILED;
2775 tls_error(US"certificate status check failed", NULL, state->host, errstr);
2778 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
2779 tlsp->ocsp = OCSP_VFIED;
2783 #ifdef EXPERIMENTAL_TLS_RESUME
2784 tls_client_resume_posthandshake(state, tlsp, host);
2787 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
2789 extract_exim_vars_from_tls_state(state);
2791 cctx->tls_ctx = state;
2798 /*************************************************
2799 * Close down a TLS session *
2800 *************************************************/
2802 /* This is also called from within a delivery subprocess forked from the
2803 daemon, to shut down the TLS library, without actually doing a shutdown (which
2804 would tamper with the TLS session in the parent process).
2807 ct_ctx client context pointer, or NULL for the one global server context
2808 shutdown 1 if TLS close-alert is to be sent,
2809 2 if also response to be waited for
2815 tls_close(void * ct_ctx, int shutdown)
2817 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
2819 if (!state->tlsp || state->tlsp->active.sock < 0) return; /* TLS was not active */
2823 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
2824 shutdown > 1 ? " (with response-wait)" : "");
2827 gnutls_bye(state->session, shutdown > 1 ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
2831 gnutls_deinit(state->session);
2832 gnutls_certificate_free_credentials(state->x509_cred);
2835 state->tlsp->active.sock = -1;
2836 state->tlsp->active.tls_ctx = NULL;
2837 if (state->xfer_buffer) store_free(state->xfer_buffer);
2838 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
2845 tls_refill(unsigned lim)
2847 exim_gnutls_state_st * state = &state_server;
2850 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
2851 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
2853 sigalrm_seen = FALSE;
2854 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2857 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
2858 MIN(ssl_xfer_buffer_size, lim));
2859 while (inbytes == GNUTLS_E_AGAIN);
2861 if (smtp_receive_timeout > 0) ALARM_CLR(0);
2863 if (had_command_timeout) /* set by signal handler */
2864 smtp_command_timeout_exit(); /* does not return */
2865 if (had_command_sigterm)
2866 smtp_command_sigterm_exit();
2867 if (had_data_timeout)
2868 smtp_data_timeout_exit();
2869 if (had_data_sigint)
2870 smtp_data_sigint_exit();
2872 /* Timeouts do not get this far. A zero-byte return appears to mean that the
2873 TLS session has been closed down, not that the socket itself has been closed
2874 down. Revert to non-TLS handling. */
2878 DEBUG(D_tls) debug_printf("Got tls read timeout\n");
2879 state->xfer_error = TRUE;
2883 else if (inbytes == 0)
2885 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2887 receive_getc = smtp_getc;
2888 receive_getbuf = smtp_getbuf;
2889 receive_get_cache = smtp_get_cache;
2890 receive_ungetc = smtp_ungetc;
2891 receive_feof = smtp_feof;
2892 receive_ferror = smtp_ferror;
2893 receive_smtp_buffered = smtp_buffered;
2895 gnutls_deinit(state->session);
2896 gnutls_certificate_free_credentials(state->x509_cred);
2898 state->session = NULL;
2899 state->tlsp->active.sock = -1;
2900 state->tlsp->active.tls_ctx = NULL;
2901 state->tlsp->bits = 0;
2902 state->tlsp->certificate_verified = FALSE;
2903 tls_channelbinding_b64 = NULL;
2904 state->tlsp->cipher = NULL;
2905 state->tlsp->peercert = NULL;
2906 state->tlsp->peerdn = NULL;
2911 /* Handle genuine errors */
2913 else if (inbytes < 0)
2915 DEBUG(D_tls) debug_printf("%s: err from gnutls_record_recv\n", __FUNCTION__);
2916 record_io_error(state, (int) inbytes, US"recv", NULL);
2917 state->xfer_error = TRUE;
2920 #ifndef DISABLE_DKIM
2921 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
2923 state->xfer_buffer_hwm = (int) inbytes;
2924 state->xfer_buffer_lwm = 0;
2928 /*************************************************
2929 * TLS version of getc *
2930 *************************************************/
2932 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
2933 it refills the buffer via the GnuTLS reading function.
2934 Only used by the server-side TLS.
2936 This feeds DKIM and should be used for all message-body reads.
2938 Arguments: lim Maximum amount to read/buffer
2939 Returns: the next character or EOF
2943 tls_getc(unsigned lim)
2945 exim_gnutls_state_st * state = &state_server;
2947 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2948 if (!tls_refill(lim))
2949 return state->xfer_error ? EOF : smtp_getc(lim);
2951 /* Something in the buffer; return next uschar */
2953 return state->xfer_buffer[state->xfer_buffer_lwm++];
2957 tls_getbuf(unsigned * len)
2959 exim_gnutls_state_st * state = &state_server;
2963 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2964 if (!tls_refill(*len))
2966 if (!state->xfer_error) return smtp_getbuf(len);
2971 if ((size = state->xfer_buffer_hwm - state->xfer_buffer_lwm) > *len)
2973 buf = &state->xfer_buffer[state->xfer_buffer_lwm];
2974 state->xfer_buffer_lwm += size;
2983 #ifndef DISABLE_DKIM
2984 exim_gnutls_state_st * state = &state_server;
2985 int n = state->xfer_buffer_hwm - state->xfer_buffer_lwm;
2987 dkim_exim_verify_feed(state->xfer_buffer+state->xfer_buffer_lwm, n);
2993 tls_could_read(void)
2995 return state_server.xfer_buffer_lwm < state_server.xfer_buffer_hwm
2996 || gnutls_record_check_pending(state_server.session) > 0;
3002 /*************************************************
3003 * Read bytes from TLS channel *
3004 *************************************************/
3006 /* This does not feed DKIM, so if the caller uses this for reading message body,
3007 then the caller must feed DKIM.
3010 ct_ctx client context pointer, or NULL for the one global server context
3014 Returns: the number of bytes read
3015 -1 after a failed read, including EOF
3019 tls_read(void * ct_ctx, uschar *buff, size_t len)
3021 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
3027 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
3029 debug_printf("*** PROBABLY A BUG *** " \
3030 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
3031 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
3034 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
3035 state->session, buff, len);
3038 inbytes = gnutls_record_recv(state->session, buff, len);
3039 while (inbytes == GNUTLS_E_AGAIN);
3041 if (inbytes > 0) return inbytes;
3044 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
3048 DEBUG(D_tls) debug_printf("%s: err from gnutls_record_recv\n", __FUNCTION__);
3049 record_io_error(state, (int)inbytes, US"recv", NULL);
3058 /*************************************************
3059 * Write bytes down TLS channel *
3060 *************************************************/
3064 ct_ctx client context pointer, or NULL for the one global server context
3067 more more data expected soon
3069 Returns: the number of bytes after a successful write,
3070 -1 after a failed write
3074 tls_write(void * ct_ctx, const uschar * buff, size_t len, BOOL more)
3078 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
3080 static BOOL corked = FALSE;
3082 if (more && !corked) gnutls_record_cork(state->session);
3085 DEBUG(D_tls) debug_printf("%s(%p, " SIZE_T_FMT "%s)\n", __FUNCTION__,
3086 buff, left, more ? ", more" : "");
3090 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
3094 outbytes = gnutls_record_send(state->session, buff, left);
3095 while (outbytes == GNUTLS_E_AGAIN);
3097 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
3100 DEBUG(D_tls) debug_printf("%s: gnutls_record_send err\n", __FUNCTION__);
3101 record_io_error(state, outbytes, US"send", NULL);
3106 record_io_error(state, 0, US"send", US"TLS channel closed on write");
3117 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
3125 if (!more) (void) gnutls_record_uncork(state->session, 0);
3136 /*************************************************
3137 * Random number generation *
3138 *************************************************/
3140 /* Pseudo-random number generation. The result is not expected to be
3141 cryptographically strong but not so weak that someone will shoot themselves
3142 in the foot using it as a nonce in input in some email header scheme or
3143 whatever weirdness they'll twist this into. The result should handle fork()
3144 and avoid repeating sequences. OpenSSL handles that for us.
3148 Returns a random number in range [0, max-1]
3151 #ifdef HAVE_GNUTLS_RND
3153 vaguely_random_number(int max)
3157 uschar smallbuf[sizeof(r)];
3162 needed_len = sizeof(r);
3163 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
3164 asked for a number less than 10. */
3166 for (r = max, i = 0; r; ++i)
3172 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
3175 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
3176 return vaguely_random_number_fallback(max);
3179 for (uschar * p = smallbuf; needed_len; --needed_len, ++p)
3182 /* We don't particularly care about weighted results; if someone wants
3183 * smooth distribution and cares enough then they should submit a patch then. */
3186 #else /* HAVE_GNUTLS_RND */
3188 vaguely_random_number(int max)
3190 return vaguely_random_number_fallback(max);
3192 #endif /* HAVE_GNUTLS_RND */
3197 /*************************************************
3198 * Let tls_require_ciphers be checked at startup *
3199 *************************************************/
3201 /* The tls_require_ciphers option, if set, must be something which the
3204 Returns: NULL on success, or error message
3208 tls_validate_require_cipher(void)
3211 uschar *expciphers = NULL;
3212 gnutls_priority_t priority_cache;
3214 uschar * dummy_errstr;
3216 #define validate_check_rc(Label) do { \
3217 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
3218 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
3219 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
3221 if (exim_gnutls_base_init_done)
3222 log_write(0, LOG_MAIN|LOG_PANIC,
3223 "already initialised GnuTLS, Exim developer bug");
3225 #ifdef HAVE_GNUTLS_PKCS11
3226 if (!gnutls_allow_auto_pkcs11)
3228 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
3229 validate_check_rc(US"gnutls_pkcs11_init");
3232 rc = gnutls_global_init();
3233 validate_check_rc(US"gnutls_global_init()");
3234 exim_gnutls_base_init_done = TRUE;
3236 if (!(tls_require_ciphers && *tls_require_ciphers))
3237 return_deinit(NULL);
3239 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3241 return_deinit(US"failed to expand tls_require_ciphers");
3243 if (!(expciphers && *expciphers))
3244 return_deinit(NULL);
3247 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3249 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
3250 validate_check_rc(string_sprintf(
3251 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
3252 expciphers, errpos - CS expciphers, errpos));
3254 #undef return_deinit
3255 #undef validate_check_rc
3256 gnutls_global_deinit();
3264 /*************************************************
3265 * Report the library versions. *
3266 *************************************************/
3268 /* See a description in tls-openssl.c for an explanation of why this exists.
3270 Arguments: a FILE* to print the results to
3275 tls_version_report(FILE *f)
3277 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
3280 gnutls_check_version(NULL));
3283 #endif /*!MACRO_PREDEF*/
3286 /* End of tls-gnu.c */