1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2014 */
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 Mavroyanopoulos. 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>
46 #ifdef EXPERIMENTAL_OCSP
47 # include <gnutls/ocsp.h>
53 gnutls_global_set_audit_log_function()
56 gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
59 /* Local static variables for GnuTLS */
61 /* Values for verify_requirement */
63 enum peer_verify_requirement { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED };
65 /* This holds most state for server or client; with this, we can set up an
66 outbound TLS-enabled connection in an ACL callout, while not stomping all
67 over the TLS variables available for expansion.
69 Some of these correspond to variables in globals.c; those variables will
70 be set to point to content in one of these instances, as appropriate for
71 the stage of the process lifetime.
73 Not handled here: global tls_channelbinding_b64.
76 typedef struct exim_gnutls_state {
77 gnutls_session_t session;
78 gnutls_certificate_credentials_t x509_cred;
79 gnutls_priority_t priority_cache;
80 enum peer_verify_requirement verify_requirement;
83 BOOL peer_cert_verified;
84 BOOL trigger_sni_changes;
86 const struct host_item *host;
87 gnutls_x509_crt_t peercert;
92 const uschar *tls_certificate;
93 const uschar *tls_privatekey;
94 const uschar *tls_sni; /* client send only, not received */
95 const uschar *tls_verify_certificates;
96 const uschar *tls_crl;
97 const uschar *tls_require_ciphers;
98 uschar *exp_tls_certificate;
99 uschar *exp_tls_privatekey;
101 uschar *exp_tls_verify_certificates;
103 uschar *exp_tls_require_ciphers;
104 uschar *exp_tls_ocsp_file;
106 tls_support *tlsp; /* set in tls_init() */
113 } exim_gnutls_state_st;
115 static const exim_gnutls_state_st exim_gnutls_state_init = {
116 NULL, NULL, NULL, VERIFY_NONE, -1, -1, FALSE, FALSE, FALSE,
117 NULL, NULL, NULL, NULL,
118 NULL, NULL, NULL, NULL, NULL, NULL,
119 NULL, NULL, NULL, NULL, NULL, NULL, NULL,
124 /* Not only do we have our own APIs which don't pass around state, assuming
125 it's held in globals, GnuTLS doesn't appear to let us register callback data
126 for callbacks, or as part of the session, so we have to keep a "this is the
127 context we're currently dealing with" pointer and rely upon being
128 single-threaded to keep from processing data on an inbound TLS connection while
129 talking to another TLS connection for an outbound check. This does mean that
130 there's no way for heart-beats to be responded to, for the duration of the
131 second connection. */
133 static exim_gnutls_state_st state_server, state_client;
135 /* dh_params are initialised once within the lifetime of a process using TLS;
136 if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
137 don't want to repeat this. */
139 static gnutls_dh_params_t dh_server_params = NULL;
141 /* No idea how this value was chosen; preserving it. Default is 3600. */
143 static const int ssl_session_timeout = 200;
145 static const char * const exim_default_gnutls_priority = "NORMAL";
147 /* Guard library core initialisation */
149 static BOOL exim_gnutls_base_init_done = FALSE;
152 /* ------------------------------------------------------------------------ */
155 #define MAX_HOST_LEN 255
157 /* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
158 the library logging; a value less than 0 disables the calls to set up logging
160 #ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
161 #define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
164 #ifndef EXIM_CLIENT_DH_MIN_BITS
165 #define EXIM_CLIENT_DH_MIN_BITS 1024
168 /* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
169 can ask for a bit-strength. Without that, we stick to the constant we had
171 #ifndef EXIM_SERVER_DH_BITS_PRE2_12
172 #define EXIM_SERVER_DH_BITS_PRE2_12 1024
175 #define exim_gnutls_err_check(Label) do { \
176 if (rc != GNUTLS_E_SUCCESS) { return tls_error((Label), gnutls_strerror(rc), host); } } while (0)
178 #define expand_check_tlsvar(Varname) expand_check(state->Varname, US #Varname, &state->exp_##Varname)
180 #if GNUTLS_VERSION_NUMBER >= 0x020c00
181 #define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
182 #define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
183 #define HAVE_GNUTLS_RND
184 /* The security fix we provide with the gnutls_allow_auto_pkcs11 option
185 * (4.82 PP/09) introduces a compatibility regression. The symbol simply
186 * isn't available sometimes, so this needs to become a conditional
187 * compilation; the sanest way to deal with this being a problem on
188 * older OSes is to block it in the Local/Makefile with this compiler
190 #ifndef AVOID_GNUTLS_PKCS11
191 #define HAVE_GNUTLS_PKCS11
192 #endif /* AVOID_GNUTLS_PKCS11 */
198 /* ------------------------------------------------------------------------ */
199 /* Callback declarations */
201 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
202 static void exim_gnutls_logger_cb(int level, const char *message);
205 static int exim_sni_handling_cb(gnutls_session_t session);
207 #ifdef EXPERIMENTAL_OCSP
208 static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
209 gnutls_datum_t * ocsp_response);
214 /* ------------------------------------------------------------------------ */
215 /* Static functions */
217 /*************************************************
219 *************************************************/
221 /* Called from lots of places when errors occur before actually starting to do
222 the TLS handshake, that is, while the session is still in clear. Always returns
223 DEFER for a server and FAIL for a client so that most calls can use "return
224 tls_error(...)" to do this processing and then give an appropriate return. A
225 single function is used for both server and client, because it is called from
226 some shared functions.
229 prefix text to include in the logged error
230 msg additional error string (may be NULL)
231 usually obtained from gnutls_strerror()
232 host NULL if setting up a server;
233 the connected host if setting up a client
235 Returns: OK/DEFER/FAIL
239 tls_error(const uschar *prefix, const char *msg, const host_item *host)
243 log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s)%s%s",
244 host->name, host->address, prefix, msg ? ": " : "", msg ? msg : "");
249 uschar *conn_info = smtp_get_connection_info();
250 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
252 log_write(0, LOG_MAIN, "TLS error on %s (%s)%s%s",
253 conn_info, prefix, msg ? ": " : "", msg ? msg : "");
261 /*************************************************
262 * Deal with logging errors during I/O *
263 *************************************************/
265 /* We have to get the identity of the peer from saved data.
268 state the current GnuTLS exim state container
269 rc the GnuTLS error code, or 0 if it's a local error
270 when text identifying read or write
271 text local error text when ec is 0
277 record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
281 if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
282 msg = CS string_sprintf("%s: %s", US gnutls_strerror(rc),
283 US gnutls_alert_get_name(gnutls_alert_get(state->session)));
285 msg = gnutls_strerror(rc);
287 tls_error(when, msg, state->host);
293 /*************************************************
294 * Set various Exim expansion vars *
295 *************************************************/
297 #define exim_gnutls_cert_err(Label) do { \
298 if (rc != GNUTLS_E_SUCCESS) { \
299 DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", (Label), gnutls_strerror(rc)); \
300 return rc; } } while (0)
303 import_cert(const gnutls_datum * cert, gnutls_x509_crt_t * crtp)
307 rc = gnutls_x509_crt_init(crtp);
308 exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
310 rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
311 exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
316 #undef exim_gnutls_cert_err
319 /* We set various Exim global variables from the state, once a session has
320 been established. With TLS callouts, may need to change this to stack
321 variables, or just re-call it with the server state after client callout
324 Make sure anything set here is unset in tls_getc().
328 tls_bits strength indicator
329 tls_certificate_verified bool indicator
330 tls_channelbinding_b64 for some SASL mechanisms
332 tls_peercert pointer to library internal
334 tls_sni a (UTF-8) string
335 tls_ourcert pointer to library internal
338 state the relevant exim_gnutls_state_st *
342 extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
344 gnutls_cipher_algorithm_t cipher;
345 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
348 gnutls_datum_t channel;
350 tls_support * tlsp = state->tlsp;
352 tlsp->active = state->fd_out;
354 cipher = gnutls_cipher_get(state->session);
355 /* returns size in "bytes" */
356 tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
358 tlsp->cipher = state->ciphersuite;
360 DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
362 tlsp->certificate_verified = state->peer_cert_verified;
364 /* note that tls_channelbinding_b64 is not saved to the spool file, since it's
365 only available for use for authenticators while this TLS session is running. */
367 tls_channelbinding_b64 = NULL;
368 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
371 rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel);
373 DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc));
375 old_pool = store_pool;
376 store_pool = POOL_PERM;
377 tls_channelbinding_b64 = auth_b64encode(channel.data, (int)channel.size);
378 store_pool = old_pool;
379 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
383 /* peercert is set in peer_status() */
384 tlsp->peerdn = state->peerdn;
385 tlsp->sni = state->received_sni;
387 /* record our certificate */
389 const gnutls_datum * cert = gnutls_certificate_get_ours(state->session);
390 gnutls_x509_crt_t crt;
392 tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
399 /*************************************************
400 * Setup up DH parameters *
401 *************************************************/
403 /* Generating the D-H parameters may take a long time. They only need to
404 be re-generated every so often, depending on security policy. What we do is to
405 keep these parameters in a file in the spool directory. If the file does not
406 exist, we generate them. This means that it is easy to cause a regeneration.
408 The new file is written as a temporary file and renamed, so that an incomplete
409 file is never present. If two processes both compute some new parameters, you
410 waste a bit of effort, but it doesn't seem worth messing around with locking to
413 Returns: OK/DEFER/FAIL
420 unsigned int dh_bits;
422 uschar filename_buf[PATH_MAX];
423 uschar *filename = NULL;
425 uschar *exp_tls_dhparam;
426 BOOL use_file_in_spool = FALSE;
427 BOOL use_fixed_file = FALSE;
428 host_item *host = NULL; /* dummy for macros */
430 DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
432 rc = gnutls_dh_params_init(&dh_server_params);
433 exim_gnutls_err_check(US"gnutls_dh_params_init");
438 if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam))
441 if (!exp_tls_dhparam)
443 DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
444 m.data = US std_dh_prime_default();
445 m.size = Ustrlen(m.data);
447 else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
448 use_file_in_spool = TRUE;
449 else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
451 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
454 else if (exp_tls_dhparam[0] != '/')
456 m.data = US std_dh_prime_named(exp_tls_dhparam);
458 return tls_error(US"No standard prime named", CS exp_tls_dhparam, NULL);
459 m.size = Ustrlen(m.data);
463 use_fixed_file = TRUE;
464 filename = exp_tls_dhparam;
469 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
470 exim_gnutls_err_check(US"gnutls_dh_params_import_pkcs3");
471 DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
475 #ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
476 /* If you change this constant, also change dh_param_fn_ext so that we can use a
477 different filename and ensure we have sufficient bits. */
478 dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
480 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL);
482 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
485 dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
487 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
491 /* Some clients have hard-coded limits. */
492 if (dh_bits > tls_dh_max_bits)
495 debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
497 dh_bits = tls_dh_max_bits;
500 if (use_file_in_spool)
502 if (!string_format(filename_buf, sizeof(filename_buf),
503 "%s/gnutls-params-%d", spool_directory, dh_bits))
504 return tls_error(US"overlong filename", NULL, NULL);
505 filename = filename_buf;
508 /* Open the cache file for reading and if successful, read it and set up the
511 fd = Uopen(filename, O_RDONLY, 0);
518 if (fstat(fd, &statbuf) < 0) /* EIO */
522 return tls_error(US"TLS cache stat failed", strerror(saved_errno), NULL);
524 if (!S_ISREG(statbuf.st_mode))
527 return tls_error(US"TLS cache not a file", NULL, NULL);
529 fp = fdopen(fd, "rb");
534 return tls_error(US"fdopen(TLS cache stat fd) failed",
535 strerror(saved_errno), NULL);
538 m.size = statbuf.st_size;
539 m.data = malloc(m.size);
543 return tls_error(US"malloc failed", strerror(errno), NULL);
545 sz = fread(m.data, m.size, 1, fp);
551 return tls_error(US"fread failed", strerror(saved_errno), NULL);
555 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
557 exim_gnutls_err_check(US"gnutls_dh_params_import_pkcs3");
558 DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
561 /* If the file does not exist, fall through to compute new data and cache it.
562 If there was any other opening error, it is serious. */
564 else if (errno == ENOENT)
568 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
571 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
574 /* If ret < 0, either the cache file does not exist, or the data it contains
575 is not useful. One particular case of this is when upgrading from an older
576 release of Exim in which the data was stored in a different format. We don't
577 try to be clever and support both formats; we just regenerate new data in this
583 unsigned int dh_bits_gen = dh_bits;
585 if ((PATH_MAX - Ustrlen(filename)) < 10)
586 return tls_error(US"Filename too long to generate replacement",
589 temp_fn = string_copy(US "%s.XXXXXXX");
590 fd = mkstemp(CS temp_fn); /* modifies temp_fn */
592 return tls_error(US"Unable to open temp file", strerror(errno), NULL);
593 (void)fchown(fd, exim_uid, exim_gid); /* Probably not necessary */
595 /* GnuTLS overshoots!
596 * If we ask for 2236, we might get 2237 or more.
597 * But there's no way to ask GnuTLS how many bits there really are.
598 * We can ask how many bits were used in a TLS session, but that's it!
599 * The prime itself is hidden behind too much abstraction.
600 * So we ask for less, and proceed on a wing and a prayer.
601 * First attempt, subtracted 3 for 2233 and got 2240.
603 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
605 dh_bits_gen = dh_bits - 10;
607 debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
612 debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
614 rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen);
615 exim_gnutls_err_check(US"gnutls_dh_params_generate2");
617 /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
618 and I confirmed that a NULL call to get the size first is how the GnuTLS
619 sample apps handle this. */
623 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
625 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
626 exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3(NULL) sizing");
628 m.data = malloc(m.size);
630 return tls_error(US"memory allocation failed", strerror(errno), NULL);
631 /* this will return a size 1 less than the allocation size above */
632 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
634 if (rc != GNUTLS_E_SUCCESS)
637 exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3() real");
639 m.size = sz; /* shrink by 1, probably */
641 sz = write_to_fd_buf(fd, m.data, (size_t) m.size);
645 return tls_error(US"TLS cache write D-H params failed",
646 strerror(errno), NULL);
649 sz = write_to_fd_buf(fd, US"\n", 1);
651 return tls_error(US"TLS cache write D-H params final newline failed",
652 strerror(errno), NULL);
656 return tls_error(US"TLS cache write close() failed",
657 strerror(errno), NULL);
659 if (Urename(temp_fn, filename) < 0)
660 return tls_error(string_sprintf("failed to rename \"%s\" as \"%s\"",
661 temp_fn, filename), strerror(errno), NULL);
663 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
666 DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
673 /*************************************************
674 * Variables re-expanded post-SNI *
675 *************************************************/
677 /* Called from both server and client code, via tls_init(), and also from
678 the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
680 We can tell the two apart by state->received_sni being non-NULL in callback.
682 The callback should not call us unless state->trigger_sni_changes is true,
683 which we are responsible for setting on the first pass through.
686 state exim_gnutls_state_st *
688 Returns: OK/DEFER/FAIL
692 tls_expand_session_files(exim_gnutls_state_st *state)
696 const host_item *host = state->host; /* macro should be reconsidered? */
697 uschar *saved_tls_certificate = NULL;
698 uschar *saved_tls_privatekey = NULL;
699 uschar *saved_tls_verify_certificates = NULL;
700 uschar *saved_tls_crl = NULL;
703 /* We check for tls_sni *before* expansion. */
704 if (!host) /* server */
706 if (!state->received_sni)
708 if (state->tls_certificate &&
709 (Ustrstr(state->tls_certificate, US"tls_sni") ||
710 Ustrstr(state->tls_certificate, US"tls_in_sni") ||
711 Ustrstr(state->tls_certificate, US"tls_out_sni")
714 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
715 state->trigger_sni_changes = TRUE;
720 /* useful for debugging */
721 saved_tls_certificate = state->exp_tls_certificate;
722 saved_tls_privatekey = state->exp_tls_privatekey;
723 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
724 saved_tls_crl = state->exp_tls_crl;
728 rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
729 exim_gnutls_err_check(US"gnutls_certificate_allocate_credentials");
731 /* remember: expand_check_tlsvar() is expand_check() but fiddling with
732 state members, assuming consistent naming; and expand_check() returns
733 false if expansion failed, unless expansion was forced to fail. */
735 /* check if we at least have a certificate, before doing expensive
738 if (!expand_check_tlsvar(tls_certificate))
741 /* certificate is mandatory in server, optional in client */
743 if ((state->exp_tls_certificate == NULL) ||
744 (*state->exp_tls_certificate == '\0'))
747 return tls_error(US"no TLS server certificate is specified", NULL, NULL);
749 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
752 if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey))
755 /* tls_privatekey is optional, defaulting to same file as certificate */
757 if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
759 state->tls_privatekey = state->tls_certificate;
760 state->exp_tls_privatekey = state->exp_tls_certificate;
764 if (state->exp_tls_certificate && *state->exp_tls_certificate)
766 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
767 state->exp_tls_certificate, state->exp_tls_privatekey);
769 if (state->received_sni)
771 if ((Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0) &&
772 (Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0))
774 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
778 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
782 rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
783 CS state->exp_tls_certificate, CS state->exp_tls_privatekey,
784 GNUTLS_X509_FMT_PEM);
785 exim_gnutls_err_check(
786 string_sprintf("cert/key setup: cert=%s key=%s",
787 state->exp_tls_certificate, state->exp_tls_privatekey));
788 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
789 } /* tls_certificate */
792 /* Set the OCSP stapling server info */
794 #ifdef EXPERIMENTAL_OCSP
795 if ( !host /* server */
799 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file",
800 &state->exp_tls_ocsp_file))
803 /* Use the full callback method for stapling just to get observability.
804 More efficient would be to read the file once only, if it never changed
805 (due to SNI). Would need restart on file update, or watch datestamp. */
807 gnutls_certificate_set_ocsp_status_request_function(state->x509_cred,
808 server_ocsp_stapling_cb, state->exp_tls_ocsp_file);
810 DEBUG(D_tls) debug_printf("Set OCSP response file %s\n", &state->exp_tls_ocsp_file);
815 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
816 provided. Experiment shows that, if the certificate file is empty, an unhelpful
817 error message is provided. However, if we just refrain from setting anything up
818 in that case, certificate verification fails, which seems to be the correct
821 if (state->tls_verify_certificates && *state->tls_verify_certificates)
823 if (!expand_check_tlsvar(tls_verify_certificates))
825 if (state->tls_crl && *state->tls_crl)
826 if (!expand_check_tlsvar(tls_crl))
829 if (!(state->exp_tls_verify_certificates &&
830 *state->exp_tls_verify_certificates))
833 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
834 /* With no tls_verify_certificates, we ignore tls_crl too */
841 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
845 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
847 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
848 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
853 /* The test suite passes in /dev/null; we could check for that path explicitly,
854 but who knows if someone has some weird FIFO which always dumps some certs, or
855 other weirdness. The thing we really want to check is that it's not a
856 directory, since while OpenSSL supports that, GnuTLS does not.
857 So s/!S_ISREG/S_ISDIR/ and change some messsaging ... */
858 if (S_ISDIR(statbuf.st_mode))
861 debug_printf("verify certificates path is a dir: \"%s\"\n",
862 state->exp_tls_verify_certificates);
863 log_write(0, LOG_MAIN|LOG_PANIC,
864 "tls_verify_certificates \"%s\" is a directory",
865 state->exp_tls_verify_certificates);
869 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
870 state->exp_tls_verify_certificates, statbuf.st_size);
872 if (statbuf.st_size == 0)
875 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
879 cert_count = gnutls_certificate_set_x509_trust_file(state->x509_cred,
880 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
884 exim_gnutls_err_check(US"gnutls_certificate_set_x509_trust_file");
886 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
888 if (state->tls_crl && *state->tls_crl &&
889 state->exp_tls_crl && *state->exp_tls_crl)
891 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
892 cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
893 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM);
897 exim_gnutls_err_check(US"gnutls_certificate_set_x509_crl_file");
899 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
908 /*************************************************
909 * Set X.509 state variables *
910 *************************************************/
912 /* In GnuTLS, the registered cert/key are not replaced by a later
913 set of a cert/key, so for SNI support we need a whole new x509_cred
914 structure. Which means various other non-re-expanded pieces of state
915 need to be re-set in the new struct, so the setting logic is pulled
919 state exim_gnutls_state_st *
921 Returns: OK/DEFER/FAIL
925 tls_set_remaining_x509(exim_gnutls_state_st *state)
928 const host_item *host = state->host; /* macro should be reconsidered? */
930 /* Create D-H parameters, or read them from the cache file. This function does
931 its own SMTP error messaging. This only happens for the server, TLS D-H ignores
932 client-side params. */
936 if (!dh_server_params)
938 rc = init_server_dh();
939 if (rc != OK) return rc;
941 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
944 /* Link the credentials to the session. */
946 rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
947 exim_gnutls_err_check(US"gnutls_credentials_set");
952 /*************************************************
953 * Initialize for GnuTLS *
954 *************************************************/
956 /* Called from both server and client code. In the case of a server, errors
957 before actual TLS negotiation return DEFER.
960 host connected host, if client; NULL if server
961 certificate certificate file
962 privatekey private key file
963 sni TLS SNI to send, sometimes when client; else NULL
966 require_ciphers tls_require_ciphers setting
967 caller_state returned state-info structure
969 Returns: OK/DEFER/FAIL
974 const host_item *host,
975 const uschar *certificate,
976 const uschar *privatekey,
980 const uschar *require_ciphers,
981 exim_gnutls_state_st **caller_state)
983 exim_gnutls_state_st *state;
988 BOOL want_default_priorities;
990 if (!exim_gnutls_base_init_done)
992 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
994 #ifdef HAVE_GNUTLS_PKCS11
995 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
996 which loads modules from a config file, which sounds good and may be wanted
997 by some sysadmin, but also means in common configurations that GNOME keyring
998 environment variables are used and so breaks for users calling mailq.
999 To prevent this, we init PKCS11 first, which is the documented approach. */
1000 if (!gnutls_allow_auto_pkcs11)
1002 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
1003 exim_gnutls_err_check(US"gnutls_pkcs11_init");
1007 rc = gnutls_global_init();
1008 exim_gnutls_err_check(US"gnutls_global_init");
1010 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1013 gnutls_global_set_log_function(exim_gnutls_logger_cb);
1014 /* arbitrarily chosen level; bump upto 9 for more */
1015 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
1019 exim_gnutls_base_init_done = TRUE;
1024 state = &state_client;
1025 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1026 state->tlsp = &tls_out;
1027 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1028 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1032 state = &state_server;
1033 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1034 state->tlsp = &tls_in;
1035 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1036 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1038 exim_gnutls_err_check(US"gnutls_init");
1042 state->tls_certificate = certificate;
1043 state->tls_privatekey = privatekey;
1044 state->tls_require_ciphers = require_ciphers;
1045 state->tls_sni = sni;
1046 state->tls_verify_certificates = cas;
1047 state->tls_crl = crl;
1049 /* This handles the variables that might get re-expanded after TLS SNI;
1050 that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1053 debug_printf("Expanding various TLS configuration options for session credentials.\n");
1054 rc = tls_expand_session_files(state);
1055 if (rc != OK) return rc;
1057 /* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1058 requires a new structure afterwards. */
1060 rc = tls_set_remaining_x509(state);
1061 if (rc != OK) return rc;
1063 /* set SNI in client, only */
1066 if (!expand_check(state->tlsp->sni, US"tls_out_sni", &state->exp_tls_sni))
1068 if (state->exp_tls_sni && *state->exp_tls_sni)
1071 debug_printf("Setting TLS client SNI to \"%s\"\n", state->exp_tls_sni);
1072 sz = Ustrlen(state->exp_tls_sni);
1073 rc = gnutls_server_name_set(state->session,
1074 GNUTLS_NAME_DNS, state->exp_tls_sni, sz);
1075 exim_gnutls_err_check(US"gnutls_server_name_set");
1078 else if (state->tls_sni)
1079 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1080 "have an SNI set for a client [%s]\n", state->tls_sni);
1082 /* This is the priority string support,
1083 http://www.gnutls.org/manual/html_node/Priority-Strings.html
1084 and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1085 This was backwards incompatible, but means Exim no longer needs to track
1086 all algorithms and provide string forms for them. */
1088 want_default_priorities = TRUE;
1090 if (state->tls_require_ciphers && *state->tls_require_ciphers)
1092 if (!expand_check_tlsvar(tls_require_ciphers))
1094 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1096 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n",
1097 state->exp_tls_require_ciphers);
1099 rc = gnutls_priority_init(&state->priority_cache,
1100 CS state->exp_tls_require_ciphers, &errpos);
1101 want_default_priorities = FALSE;
1102 p = state->exp_tls_require_ciphers;
1105 if (want_default_priorities)
1108 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n",
1109 exim_default_gnutls_priority);
1110 rc = gnutls_priority_init(&state->priority_cache,
1111 exim_default_gnutls_priority, &errpos);
1112 p = US exim_default_gnutls_priority;
1115 exim_gnutls_err_check(string_sprintf(
1116 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1117 p, errpos - CS p, errpos));
1119 rc = gnutls_priority_set(state->session, state->priority_cache);
1120 exim_gnutls_err_check(US"gnutls_priority_set");
1122 gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1124 /* Reduce security in favour of increased compatibility, if the admin
1125 decides to make that trade-off. */
1126 if (gnutls_compat_mode)
1128 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1129 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1130 gnutls_session_enable_compatibility_mode(state->session);
1132 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1136 *caller_state = state;
1142 /*************************************************
1143 * Extract peer information *
1144 *************************************************/
1146 /* Called from both server and client code.
1147 Only this is allowed to set state->peerdn and state->have_set_peerdn
1148 and we use that to detect double-calls.
1150 NOTE: the state blocks last while the TLS connection is up, which is fine
1151 for logging in the server side, but for the client side, we log after teardown
1152 in src/deliver.c. While the session is up, we can twist about states and
1153 repoint tls_* globals, but those variables used for logging or other variable
1154 expansion that happens _after_ delivery need to have a longer life-time.
1156 So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1157 doing this more than once per generation of a state context. We set them in
1158 the state context, and repoint tls_* to them. After the state goes away, the
1159 tls_* copies of the pointers remain valid and client delivery logging is happy.
1161 tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1165 state exim_gnutls_state_st *
1167 Returns: OK/DEFER/FAIL
1171 peer_status(exim_gnutls_state_st *state)
1173 uschar cipherbuf[256];
1174 const gnutls_datum *cert_list;
1176 unsigned int cert_list_size = 0;
1177 gnutls_protocol_t protocol;
1178 gnutls_cipher_algorithm_t cipher;
1179 gnutls_kx_algorithm_t kx;
1180 gnutls_mac_algorithm_t mac;
1181 gnutls_certificate_type_t ct;
1182 gnutls_x509_crt_t crt;
1186 if (state->have_set_peerdn)
1188 state->have_set_peerdn = TRUE;
1190 state->peerdn = NULL;
1193 cipher = gnutls_cipher_get(state->session);
1194 protocol = gnutls_protocol_get_version(state->session);
1195 mac = gnutls_mac_get(state->session);
1196 kx = gnutls_kx_get(state->session);
1198 string_format(cipherbuf, sizeof(cipherbuf),
1200 gnutls_protocol_get_name(protocol),
1201 gnutls_cipher_suite_get_name(kx, cipher, mac),
1202 (int) gnutls_cipher_get_key_size(cipher) * 8);
1204 /* I don't see a way that spaces could occur, in the current GnuTLS
1205 code base, but it was a concern in the old code and perhaps older GnuTLS
1206 releases did return "TLS 1.0"; play it safe, just in case. */
1207 for (p = cipherbuf; *p != '\0'; ++p)
1210 old_pool = store_pool;
1211 store_pool = POOL_PERM;
1212 state->ciphersuite = string_copy(cipherbuf);
1213 store_pool = old_pool;
1214 state->tlsp->cipher = state->ciphersuite;
1217 cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
1219 if (cert_list == NULL || cert_list_size == 0)
1221 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1222 cert_list, cert_list_size);
1223 if (state->verify_requirement == VERIFY_REQUIRED)
1224 return tls_error(US"certificate verification failed",
1225 "no certificate received from peer", state->host);
1229 ct = gnutls_certificate_type_get(state->session);
1230 if (ct != GNUTLS_CRT_X509)
1232 const char *ctn = gnutls_certificate_type_get_name(ct);
1234 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1235 if (state->verify_requirement == VERIFY_REQUIRED)
1236 return tls_error(US"certificate verification not possible, unhandled type",
1241 #define exim_gnutls_peer_err(Label) do { \
1242 if (rc != GNUTLS_E_SUCCESS) { \
1243 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", (Label), gnutls_strerror(rc)); \
1244 if (state->verify_requirement == VERIFY_REQUIRED) { return tls_error((Label), gnutls_strerror(rc), state->host); } \
1245 return OK; } } while (0)
1247 rc = import_cert(&cert_list[0], &crt);
1248 exim_gnutls_peer_err(US"cert 0");
1250 state->tlsp->peercert = state->peercert = crt;
1253 rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1254 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1256 exim_gnutls_peer_err(US"getting size for cert DN failed");
1257 return FAIL; /* should not happen */
1259 dn_buf = store_get_perm(sz);
1260 rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1261 exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1263 state->peerdn = dn_buf;
1266 #undef exim_gnutls_peer_err
1272 /*************************************************
1273 * Verify peer certificate *
1274 *************************************************/
1276 /* Called from both server and client code.
1277 *Should* be using a callback registered with
1278 gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1279 the peer information, but that's too new for some OSes.
1282 state exim_gnutls_state_st *
1283 error where to put an error message
1286 FALSE if the session should be rejected
1287 TRUE if the cert is okay or we just don't care
1291 verify_certificate(exim_gnutls_state_st *state, const char **error)
1294 unsigned int verify;
1298 if ((rc = peer_status(state)) != OK)
1300 verify = GNUTLS_CERT_INVALID;
1301 *error = "certificate not supplied";
1304 rc = gnutls_certificate_verify_peers2(state->session, &verify);
1306 /* Handle the result of verification. INVALID seems to be set as well
1307 as REVOKED, but leave the test for both. */
1309 if (rc < 0 || verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED))
1311 state->peer_cert_verified = FALSE;
1313 *error = verify & GNUTLS_CERT_REVOKED
1314 ? "certificate revoked" : "certificate invalid";
1317 debug_printf("TLS certificate verification failed (%s): peerdn=%s\n",
1318 *error, state->peerdn ? state->peerdn : US"<unset>");
1320 if (state->verify_requirement == VERIFY_REQUIRED)
1322 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1326 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1330 state->peer_cert_verified = TRUE;
1331 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=%s\n",
1332 state->peerdn ? state->peerdn : US"<unset>");
1335 state->tlsp->peerdn = state->peerdn;
1343 /* ------------------------------------------------------------------------ */
1346 /* Logging function which can be registered with
1347 * gnutls_global_set_log_function()
1348 * gnutls_global_set_log_level() 0..9
1350 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1352 exim_gnutls_logger_cb(int level, const char *message)
1354 size_t len = strlen(message);
1357 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1360 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1361 message[len-1] == '\n' ? "" : "\n");
1366 /* Called after client hello, should handle SNI work.
1367 This will always set tls_sni (state->received_sni) if available,
1368 and may trigger presenting different certificates,
1369 if state->trigger_sni_changes is TRUE.
1371 Should be registered with
1372 gnutls_handshake_set_post_client_hello_function()
1374 "This callback must return 0 on success or a gnutls error code to terminate the
1377 For inability to get SNI information, we return 0.
1378 We only return non-zero if re-setup failed.
1379 Only used for server-side TLS.
1383 exim_sni_handling_cb(gnutls_session_t session)
1385 char sni_name[MAX_HOST_LEN];
1386 size_t data_len = MAX_HOST_LEN;
1387 exim_gnutls_state_st *state = &state_server;
1388 unsigned int sni_type;
1391 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1392 if (rc != GNUTLS_E_SUCCESS)
1395 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1396 debug_printf("TLS: no SNI presented in handshake.\n");
1398 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1399 gnutls_strerror(rc), rc);
1404 if (sni_type != GNUTLS_NAME_DNS)
1406 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1410 /* We now have a UTF-8 string in sni_name */
1411 old_pool = store_pool;
1412 store_pool = POOL_PERM;
1413 state->received_sni = string_copyn(US sni_name, data_len);
1414 store_pool = old_pool;
1416 /* We set this one now so that variable expansions below will work */
1417 state->tlsp->sni = state->received_sni;
1419 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1420 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1422 if (!state->trigger_sni_changes)
1425 rc = tls_expand_session_files(state);
1428 /* If the setup of certs/etc failed before handshake, TLS would not have
1429 been offered. The best we can do now is abort. */
1430 return GNUTLS_E_APPLICATION_ERROR_MIN;
1433 rc = tls_set_remaining_x509(state);
1434 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1441 #ifdef EXPERIMENTAL_OCSP
1444 server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1445 gnutls_datum_t * ocsp_response)
1449 if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1451 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1453 tls_in.ocsp = OCSP_NOT_RESP;
1454 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1457 tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1467 /* ------------------------------------------------------------------------ */
1468 /* Exported functions */
1473 /*************************************************
1474 * Start a TLS session in a server *
1475 *************************************************/
1477 /* This is called when Exim is running as a server, after having received
1478 the STARTTLS command. It must respond to that command, and then negotiate
1482 require_ciphers list of allowed ciphers or NULL
1484 Returns: OK on success
1485 DEFER for errors before the start of the negotiation
1486 FAIL for errors during the negotation; the server can't
1491 tls_server_start(const uschar *require_ciphers)
1495 exim_gnutls_state_st *state = NULL;
1497 /* Check for previous activation */
1498 if (tls_in.active >= 0)
1500 tls_error(US"STARTTLS received after TLS started", "", NULL);
1501 smtp_printf("554 Already in TLS\r\n");
1505 /* Initialize the library. If it fails, it will already have logged the error
1506 and sent an SMTP response. */
1508 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
1510 rc = tls_init(NULL, tls_certificate, tls_privatekey,
1511 NULL, tls_verify_certificates, tls_crl,
1512 require_ciphers, &state);
1513 if (rc != OK) return rc;
1515 /* If this is a host for which certificate verification is mandatory or
1516 optional, set up appropriately. */
1518 if (verify_check_host(&tls_verify_hosts) == OK)
1520 DEBUG(D_tls) debug_printf("TLS: a client certificate will be required.\n");
1521 state->verify_requirement = VERIFY_REQUIRED;
1522 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1524 else if (verify_check_host(&tls_try_verify_hosts) == OK)
1526 DEBUG(D_tls) debug_printf("TLS: a client certificate will be requested but not required.\n");
1527 state->verify_requirement = VERIFY_OPTIONAL;
1528 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1532 DEBUG(D_tls) debug_printf("TLS: a client certificate will not be requested.\n");
1533 state->verify_requirement = VERIFY_NONE;
1534 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1537 /* Register SNI handling; always, even if not in tls_certificate, so that the
1538 expansion variable $tls_sni is always available. */
1540 gnutls_handshake_set_post_client_hello_function(state->session,
1541 exim_sni_handling_cb);
1543 /* Set context and tell client to go ahead, except in the case of TLS startup
1544 on connection, where outputting anything now upsets the clients and tends to
1545 make them disconnect. We need to have an explicit fflush() here, to force out
1546 the response. Other smtp_printf() calls do not need it, because in non-TLS
1547 mode, the fflush() happens when smtp_getc() is called. */
1549 if (!state->tlsp->on_connect)
1551 smtp_printf("220 TLS go ahead\r\n");
1555 /* Now negotiate the TLS session. We put our own timer on it, since it seems
1556 that the GnuTLS library doesn't. */
1558 gnutls_transport_set_ptr2(state->session,
1559 (gnutls_transport_ptr)(long) fileno(smtp_in),
1560 (gnutls_transport_ptr)(long) fileno(smtp_out));
1561 state->fd_in = fileno(smtp_in);
1562 state->fd_out = fileno(smtp_out);
1564 sigalrm_seen = FALSE;
1565 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1568 rc = gnutls_handshake(state->session);
1569 } while ((rc == GNUTLS_E_AGAIN) ||
1570 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
1573 if (rc != GNUTLS_E_SUCCESS)
1575 tls_error(US"gnutls_handshake",
1576 sigalrm_seen ? "timed out" : gnutls_strerror(rc), NULL);
1577 /* It seems that, except in the case of a timeout, we have to close the
1578 connection right here; otherwise if the other end is running OpenSSL it hangs
1579 until the server times out. */
1583 (void)fclose(smtp_out);
1584 (void)fclose(smtp_in);
1590 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1592 /* Verify after the fact */
1594 if ( state->verify_requirement != VERIFY_NONE
1595 && !verify_certificate(state, &error))
1597 if (state->verify_requirement != VERIFY_OPTIONAL)
1599 tls_error(US"certificate verification failed", error, NULL);
1603 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
1607 /* Figure out peer DN, and if authenticated, etc. */
1609 rc = peer_status(state);
1610 if (rc != OK) return rc;
1612 /* Sets various Exim expansion variables; always safe within server */
1614 extract_exim_vars_from_tls_state(state);
1616 /* TLS has been set up. Adjust the input functions to read via TLS,
1617 and initialize appropriately. */
1619 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1621 receive_getc = tls_getc;
1622 receive_ungetc = tls_ungetc;
1623 receive_feof = tls_feof;
1624 receive_ferror = tls_ferror;
1625 receive_smtp_buffered = tls_smtp_buffered;
1633 /*************************************************
1634 * Start a TLS session in a client *
1635 *************************************************/
1637 /* Called from the smtp transport after STARTTLS has been accepted.
1640 fd the fd of the connection
1641 host connected host (for messages)
1642 addr the first address (not used)
1643 ob smtp transport options
1645 Returns: OK/DEFER/FAIL (because using common functions),
1646 but for a client, DEFER and FAIL have the same meaning
1650 tls_client_start(int fd, host_item *host,
1651 address_item *addr ARG_UNUSED,
1654 smtp_transport_options_block *ob = v_ob;
1657 exim_gnutls_state_st *state = NULL;
1658 #ifdef EXPERIMENTAL_OCSP
1659 BOOL require_ocsp = verify_check_this_host(&ob->hosts_require_ocsp,
1660 NULL, host->name, host->address, NULL) == OK;
1661 BOOL request_ocsp = require_ocsp ? TRUE
1662 : verify_check_this_host(&ob->hosts_request_ocsp,
1663 NULL, host->name, host->address, NULL) == OK;
1666 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
1668 if ((rc = tls_init(host, ob->tls_certificate, ob->tls_privatekey,
1669 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
1670 ob->tls_require_ciphers, &state)) != OK)
1674 int dh_min_bits = ob->tls_dh_min_bits;
1675 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
1678 debug_printf("WARNING: tls_dh_min_bits far too low,"
1679 " clamping %d up to %d\n",
1680 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
1681 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
1684 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
1685 " acceptable bits to %d\n",
1687 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
1690 /* Stick to the old behaviour for compatibility if tls_verify_certificates is
1691 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
1692 the specified host patterns if one of them is defined */
1694 if (( state->exp_tls_verify_certificates
1695 && !ob->tls_verify_hosts
1696 && !ob->tls_try_verify_hosts
1699 verify_check_host(&ob->tls_verify_hosts) == OK
1702 DEBUG(D_tls) debug_printf("TLS: server certificate verification required.\n");
1703 state->verify_requirement = VERIFY_REQUIRED;
1704 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1706 else if (verify_check_host(&ob->tls_try_verify_hosts) == OK)
1708 DEBUG(D_tls) debug_printf("TLS: server certificate verification optional.\n");
1709 state->verify_requirement = VERIFY_OPTIONAL;
1710 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1714 DEBUG(D_tls) debug_printf("TLS: server certificate verification not required.\n");
1715 state->verify_requirement = VERIFY_NONE;
1716 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1719 #ifdef EXPERIMENTAL_OCSP /* since GnuTLS 3.1.3 */
1722 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
1723 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
1724 NULL, 0, NULL)) != OK)
1725 return tls_error(US"cert-status-req",
1726 gnutls_strerror(rc), state->host);
1727 tls_out.ocsp = OCSP_NOT_RESP;
1731 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr)(long) fd);
1735 DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
1736 /* There doesn't seem to be a built-in timeout on connection. */
1738 sigalrm_seen = FALSE;
1739 alarm(ob->command_timeout);
1742 rc = gnutls_handshake(state->session);
1743 } while ((rc == GNUTLS_E_AGAIN) ||
1744 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
1747 if (rc != GNUTLS_E_SUCCESS)
1748 return tls_error(US"gnutls_handshake",
1749 sigalrm_seen ? "timed out" : gnutls_strerror(rc), state->host);
1751 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1755 if (state->verify_requirement != VERIFY_NONE &&
1756 !verify_certificate(state, &error))
1757 return tls_error(US"certificate verification failed", error, state->host);
1759 #ifdef EXPERIMENTAL_OCSP
1764 gnutls_datum_t stapling;
1765 gnutls_ocsp_resp_t resp;
1766 gnutls_datum_t printed;
1767 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
1768 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
1769 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
1770 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
1773 debug_printf("%.4096s", printed.data);
1774 gnutls_free(printed.data);
1777 (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host);
1780 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
1782 tls_out.ocsp = OCSP_FAILED;
1783 return tls_error(US"certificate status check failed", NULL, state->host);
1785 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
1786 tls_out.ocsp = OCSP_VFIED;
1790 /* Figure out peer DN, and if authenticated, etc. */
1792 if ((rc = peer_status(state)) != OK)
1795 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
1797 extract_exim_vars_from_tls_state(state);
1805 /*************************************************
1806 * Close down a TLS session *
1807 *************************************************/
1809 /* This is also called from within a delivery subprocess forked from the
1810 daemon, to shut down the TLS library, without actually doing a shutdown (which
1811 would tamper with the TLS session in the parent process).
1813 Arguments: TRUE if gnutls_bye is to be called
1818 tls_close(BOOL is_server, BOOL shutdown)
1820 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
1822 if (!state->tlsp || state->tlsp->active < 0) return; /* TLS was not active */
1826 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
1827 gnutls_bye(state->session, GNUTLS_SHUT_WR);
1830 gnutls_deinit(state->session);
1832 state->tlsp->active = -1;
1833 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1835 if ((state_server.session == NULL) && (state_client.session == NULL))
1837 gnutls_global_deinit();
1838 exim_gnutls_base_init_done = FALSE;
1846 /*************************************************
1847 * TLS version of getc *
1848 *************************************************/
1850 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
1851 it refills the buffer via the GnuTLS reading function.
1852 Only used by the server-side TLS.
1854 This feeds DKIM and should be used for all message-body reads.
1857 Returns: the next character or EOF
1863 exim_gnutls_state_st *state = &state_server;
1864 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
1868 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
1869 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
1871 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1872 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
1873 ssl_xfer_buffer_size);
1876 /* A zero-byte return appears to mean that the TLS session has been
1877 closed down, not that the socket itself has been closed down. Revert to
1878 non-TLS handling. */
1882 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1884 receive_getc = smtp_getc;
1885 receive_ungetc = smtp_ungetc;
1886 receive_feof = smtp_feof;
1887 receive_ferror = smtp_ferror;
1888 receive_smtp_buffered = smtp_buffered;
1890 gnutls_deinit(state->session);
1891 state->session = NULL;
1892 state->tlsp->active = -1;
1893 state->tlsp->bits = 0;
1894 state->tlsp->certificate_verified = FALSE;
1895 tls_channelbinding_b64 = NULL;
1896 state->tlsp->cipher = NULL;
1897 state->tlsp->peercert = NULL;
1898 state->tlsp->peerdn = NULL;
1903 /* Handle genuine errors */
1905 else if (inbytes < 0)
1907 record_io_error(state, (int) inbytes, US"recv", NULL);
1908 state->xfer_error = 1;
1911 #ifndef DISABLE_DKIM
1912 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
1914 state->xfer_buffer_hwm = (int) inbytes;
1915 state->xfer_buffer_lwm = 0;
1918 /* Something in the buffer; return next uschar */
1920 return state->xfer_buffer[state->xfer_buffer_lwm++];
1926 /*************************************************
1927 * Read bytes from TLS channel *
1928 *************************************************/
1930 /* This does not feed DKIM, so if the caller uses this for reading message body,
1931 then the caller must feed DKIM.
1937 Returns: the number of bytes read
1938 -1 after a failed read
1942 tls_read(BOOL is_server, uschar *buff, size_t len)
1944 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
1950 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
1952 debug_printf("*** PROBABLY A BUG *** " \
1953 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
1954 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
1957 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
1958 state->session, buff, len);
1960 inbytes = gnutls_record_recv(state->session, buff, len);
1961 if (inbytes > 0) return inbytes;
1964 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1966 else record_io_error(state, (int)inbytes, US"recv", NULL);
1974 /*************************************************
1975 * Write bytes down TLS channel *
1976 *************************************************/
1980 is_server channel specifier
1984 Returns: the number of bytes after a successful write,
1985 -1 after a failed write
1989 tls_write(BOOL is_server, const uschar *buff, size_t len)
1993 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
1995 DEBUG(D_tls) debug_printf("tls_do_write(%p, " SIZE_T_FMT ")\n", buff, left);
1998 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
2000 outbytes = gnutls_record_send(state->session, buff, left);
2002 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
2005 record_io_error(state, outbytes, US"send", NULL);
2010 record_io_error(state, 0, US"send", US"TLS channel closed on write");
2021 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
2032 /*************************************************
2033 * Random number generation *
2034 *************************************************/
2036 /* Pseudo-random number generation. The result is not expected to be
2037 cryptographically strong but not so weak that someone will shoot themselves
2038 in the foot using it as a nonce in input in some email header scheme or
2039 whatever weirdness they'll twist this into. The result should handle fork()
2040 and avoid repeating sequences. OpenSSL handles that for us.
2044 Returns a random number in range [0, max-1]
2047 #ifdef HAVE_GNUTLS_RND
2049 vaguely_random_number(int max)
2054 uschar smallbuf[sizeof(r)];
2059 needed_len = sizeof(r);
2060 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
2061 * asked for a number less than 10. */
2062 for (r = max, i = 0; r; ++i)
2068 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2071 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2072 return vaguely_random_number_fallback(max);
2075 for (p = smallbuf; needed_len; --needed_len, ++p)
2081 /* We don't particularly care about weighted results; if someone wants
2082 * smooth distribution and cares enough then they should submit a patch then. */
2085 #else /* HAVE_GNUTLS_RND */
2087 vaguely_random_number(int max)
2089 return vaguely_random_number_fallback(max);
2091 #endif /* HAVE_GNUTLS_RND */
2096 /*************************************************
2097 * Let tls_require_ciphers be checked at startup *
2098 *************************************************/
2100 /* The tls_require_ciphers option, if set, must be something which the
2103 Returns: NULL on success, or error message
2107 tls_validate_require_cipher(void)
2110 uschar *expciphers = NULL;
2111 gnutls_priority_t priority_cache;
2114 #define validate_check_rc(Label) do { \
2115 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
2116 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
2117 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
2119 if (exim_gnutls_base_init_done)
2120 log_write(0, LOG_MAIN|LOG_PANIC,
2121 "already initialised GnuTLS, Exim developer bug");
2123 #ifdef HAVE_GNUTLS_PKCS11
2124 if (!gnutls_allow_auto_pkcs11)
2126 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2127 validate_check_rc(US"gnutls_pkcs11_init");
2130 rc = gnutls_global_init();
2131 validate_check_rc(US"gnutls_global_init()");
2132 exim_gnutls_base_init_done = TRUE;
2134 if (!(tls_require_ciphers && *tls_require_ciphers))
2135 return_deinit(NULL);
2137 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers))
2138 return_deinit(US"failed to expand tls_require_ciphers");
2140 if (!(expciphers && *expciphers))
2141 return_deinit(NULL);
2144 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2146 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2147 validate_check_rc(string_sprintf(
2148 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
2149 expciphers, errpos - CS expciphers, errpos));
2151 #undef return_deinit
2152 #undef validate_check_rc
2153 gnutls_global_deinit();
2161 /*************************************************
2162 * Report the library versions. *
2163 *************************************************/
2165 /* See a description in tls-openssl.c for an explanation of why this exists.
2167 Arguments: a FILE* to print the results to
2172 tls_version_report(FILE *f)
2174 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2177 gnutls_check_version(NULL));
2182 /* End of tls-gnu.c */