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;
91 const uschar *tls_certificate;
92 const uschar *tls_privatekey;
93 const uschar *tls_sni; /* client send only, not received */
94 const uschar *tls_verify_certificates;
95 const uschar *tls_crl;
96 const uschar *tls_require_ciphers;
97 uschar *exp_tls_certificate;
98 uschar *exp_tls_privatekey;
100 uschar *exp_tls_verify_certificates;
102 uschar *exp_tls_require_ciphers;
104 tls_support *tlsp; /* set in tls_init() */
111 } exim_gnutls_state_st;
113 static const exim_gnutls_state_st exim_gnutls_state_init = {
114 NULL, NULL, NULL, VERIFY_NONE, -1, -1, FALSE, FALSE, FALSE,
115 NULL, NULL, NULL, NULL,
116 NULL, NULL, NULL, NULL, NULL, NULL,
117 NULL, NULL, NULL, NULL, NULL, NULL,
122 /* Not only do we have our own APIs which don't pass around state, assuming
123 it's held in globals, GnuTLS doesn't appear to let us register callback data
124 for callbacks, or as part of the session, so we have to keep a "this is the
125 context we're currently dealing with" pointer and rely upon being
126 single-threaded to keep from processing data on an inbound TLS connection while
127 talking to another TLS connection for an outbound check. This does mean that
128 there's no way for heart-beats to be responded to, for the duration of the
129 second connection. */
131 static exim_gnutls_state_st state_server, state_client;
133 /* dh_params are initialised once within the lifetime of a process using TLS;
134 if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
135 don't want to repeat this. */
137 static gnutls_dh_params_t dh_server_params = NULL;
139 /* No idea how this value was chosen; preserving it. Default is 3600. */
141 static const int ssl_session_timeout = 200;
143 static const char * const exim_default_gnutls_priority = "NORMAL";
145 /* Guard library core initialisation */
147 static BOOL exim_gnutls_base_init_done = FALSE;
150 /* ------------------------------------------------------------------------ */
153 #define MAX_HOST_LEN 255
155 /* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
156 the library logging; a value less than 0 disables the calls to set up logging
158 #ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
159 #define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
162 #ifndef EXIM_CLIENT_DH_MIN_BITS
163 #define EXIM_CLIENT_DH_MIN_BITS 1024
166 /* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
167 can ask for a bit-strength. Without that, we stick to the constant we had
169 #ifndef EXIM_SERVER_DH_BITS_PRE2_12
170 #define EXIM_SERVER_DH_BITS_PRE2_12 1024
173 #define exim_gnutls_err_check(Label) do { \
174 if (rc != GNUTLS_E_SUCCESS) { return tls_error((Label), gnutls_strerror(rc), host); } } while (0)
176 #define expand_check_tlsvar(Varname) expand_check(state->Varname, US #Varname, &state->exp_##Varname)
178 #if GNUTLS_VERSION_NUMBER >= 0x020c00
179 #define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
180 #define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
181 #define HAVE_GNUTLS_RND
182 /* The security fix we provide with the gnutls_allow_auto_pkcs11 option
183 * (4.82 PP/09) introduces a compatibility regression. The symbol simply
184 * isn't available sometimes, so this needs to become a conditional
185 * compilation; the sanest way to deal with this being a problem on
186 * older OSes is to block it in the Local/Makefile with this compiler
188 #ifndef AVOID_GNUTLS_PKCS11
189 #define HAVE_GNUTLS_PKCS11
190 #endif /* AVOID_GNUTLS_PKCS11 */
196 /* ------------------------------------------------------------------------ */
197 /* Callback declarations */
199 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
200 static void exim_gnutls_logger_cb(int level, const char *message);
203 static int exim_sni_handling_cb(gnutls_session_t session);
208 /* ------------------------------------------------------------------------ */
209 /* Static functions */
211 /*************************************************
213 *************************************************/
215 /* Called from lots of places when errors occur before actually starting to do
216 the TLS handshake, that is, while the session is still in clear. Always returns
217 DEFER for a server and FAIL for a client so that most calls can use "return
218 tls_error(...)" to do this processing and then give an appropriate return. A
219 single function is used for both server and client, because it is called from
220 some shared functions.
223 prefix text to include in the logged error
224 msg additional error string (may be NULL)
225 usually obtained from gnutls_strerror()
226 host NULL if setting up a server;
227 the connected host if setting up a client
229 Returns: OK/DEFER/FAIL
233 tls_error(const uschar *prefix, const char *msg, const host_item *host)
237 log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s)%s%s",
238 host->name, host->address, prefix, msg ? ": " : "", msg ? msg : "");
243 uschar *conn_info = smtp_get_connection_info();
244 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
246 log_write(0, LOG_MAIN, "TLS error on %s (%s)%s%s",
247 conn_info, prefix, msg ? ": " : "", msg ? msg : "");
255 /*************************************************
256 * Deal with logging errors during I/O *
257 *************************************************/
259 /* We have to get the identity of the peer from saved data.
262 state the current GnuTLS exim state container
263 rc the GnuTLS error code, or 0 if it's a local error
264 when text identifying read or write
265 text local error text when ec is 0
271 record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
275 if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
276 msg = CS string_sprintf("%s: %s", US gnutls_strerror(rc),
277 US gnutls_alert_get_name(gnutls_alert_get(state->session)));
279 msg = gnutls_strerror(rc);
281 tls_error(when, msg, state->host);
287 /*************************************************
288 * Set various Exim expansion vars *
289 *************************************************/
291 /* We set various Exim global variables from the state, once a session has
292 been established. With TLS callouts, may need to change this to stack
293 variables, or just re-call it with the server state after client callout
296 Make sure anything set here is inset in tls_getc().
300 tls_bits strength indicator
301 tls_certificate_verified bool indicator
302 tls_channelbinding_b64 for some SASL mechanisms
305 tls_sni a (UTF-8) string
308 state the relevant exim_gnutls_state_st *
312 extract_exim_vars_from_tls_state(exim_gnutls_state_st *state, BOOL is_server)
314 gnutls_cipher_algorithm_t cipher;
315 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
318 gnutls_datum_t channel;
321 state->tlsp->active = state->fd_out;
323 cipher = gnutls_cipher_get(state->session);
324 /* returns size in "bytes" */
325 state->tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
327 state->tlsp->cipher = state->ciphersuite;
329 DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
331 state->tlsp->certificate_verified = state->peer_cert_verified;
333 /* note that tls_channelbinding_b64 is not saved to the spool file, since it's
334 only available for use for authenticators while this TLS session is running. */
336 tls_channelbinding_b64 = NULL;
337 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
340 rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel);
342 DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc));
344 old_pool = store_pool;
345 store_pool = POOL_PERM;
346 tls_channelbinding_b64 = auth_b64encode(channel.data, (int)channel.size);
347 store_pool = old_pool;
348 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
352 state->tlsp->peerdn = state->peerdn;
353 state->tlsp->sni = state->received_sni;
359 /*************************************************
360 * Setup up DH parameters *
361 *************************************************/
363 /* Generating the D-H parameters may take a long time. They only need to
364 be re-generated every so often, depending on security policy. What we do is to
365 keep these parameters in a file in the spool directory. If the file does not
366 exist, we generate them. This means that it is easy to cause a regeneration.
368 The new file is written as a temporary file and renamed, so that an incomplete
369 file is never present. If two processes both compute some new parameters, you
370 waste a bit of effort, but it doesn't seem worth messing around with locking to
373 Returns: OK/DEFER/FAIL
380 unsigned int dh_bits;
382 uschar filename_buf[PATH_MAX];
383 uschar *filename = NULL;
385 uschar *exp_tls_dhparam;
386 BOOL use_file_in_spool = FALSE;
387 BOOL use_fixed_file = FALSE;
388 host_item *host = NULL; /* dummy for macros */
390 DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
392 rc = gnutls_dh_params_init(&dh_server_params);
393 exim_gnutls_err_check(US"gnutls_dh_params_init");
398 if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam))
401 if (!exp_tls_dhparam)
403 DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
404 m.data = US std_dh_prime_default();
405 m.size = Ustrlen(m.data);
407 else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
408 use_file_in_spool = TRUE;
409 else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
411 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
414 else if (exp_tls_dhparam[0] != '/')
416 m.data = US std_dh_prime_named(exp_tls_dhparam);
418 return tls_error(US"No standard prime named", CS exp_tls_dhparam, NULL);
419 m.size = Ustrlen(m.data);
423 use_fixed_file = TRUE;
424 filename = exp_tls_dhparam;
429 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
430 exim_gnutls_err_check(US"gnutls_dh_params_import_pkcs3");
431 DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
435 #ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
436 /* If you change this constant, also change dh_param_fn_ext so that we can use a
437 different filename and ensure we have sufficient bits. */
438 dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
440 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL);
442 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
445 dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
447 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
451 /* Some clients have hard-coded limits. */
452 if (dh_bits > tls_dh_max_bits)
455 debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
457 dh_bits = tls_dh_max_bits;
460 if (use_file_in_spool)
462 if (!string_format(filename_buf, sizeof(filename_buf),
463 "%s/gnutls-params-%d", spool_directory, dh_bits))
464 return tls_error(US"overlong filename", NULL, NULL);
465 filename = filename_buf;
468 /* Open the cache file for reading and if successful, read it and set up the
471 fd = Uopen(filename, O_RDONLY, 0);
478 if (fstat(fd, &statbuf) < 0) /* EIO */
482 return tls_error(US"TLS cache stat failed", strerror(saved_errno), NULL);
484 if (!S_ISREG(statbuf.st_mode))
487 return tls_error(US"TLS cache not a file", NULL, NULL);
489 fp = fdopen(fd, "rb");
494 return tls_error(US"fdopen(TLS cache stat fd) failed",
495 strerror(saved_errno), NULL);
498 m.size = statbuf.st_size;
499 m.data = malloc(m.size);
503 return tls_error(US"malloc failed", strerror(errno), NULL);
505 sz = fread(m.data, m.size, 1, fp);
511 return tls_error(US"fread failed", strerror(saved_errno), NULL);
515 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
517 exim_gnutls_err_check(US"gnutls_dh_params_import_pkcs3");
518 DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
521 /* If the file does not exist, fall through to compute new data and cache it.
522 If there was any other opening error, it is serious. */
524 else if (errno == ENOENT)
528 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
531 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
534 /* If ret < 0, either the cache file does not exist, or the data it contains
535 is not useful. One particular case of this is when upgrading from an older
536 release of Exim in which the data was stored in a different format. We don't
537 try to be clever and support both formats; we just regenerate new data in this
543 unsigned int dh_bits_gen = dh_bits;
545 if ((PATH_MAX - Ustrlen(filename)) < 10)
546 return tls_error(US"Filename too long to generate replacement",
549 temp_fn = string_copy(US "%s.XXXXXXX");
550 fd = mkstemp(CS temp_fn); /* modifies temp_fn */
552 return tls_error(US"Unable to open temp file", strerror(errno), NULL);
553 (void)fchown(fd, exim_uid, exim_gid); /* Probably not necessary */
555 /* GnuTLS overshoots!
556 * If we ask for 2236, we might get 2237 or more.
557 * But there's no way to ask GnuTLS how many bits there really are.
558 * We can ask how many bits were used in a TLS session, but that's it!
559 * The prime itself is hidden behind too much abstraction.
560 * So we ask for less, and proceed on a wing and a prayer.
561 * First attempt, subtracted 3 for 2233 and got 2240.
563 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
565 dh_bits_gen = dh_bits - 10;
567 debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
572 debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
574 rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen);
575 exim_gnutls_err_check(US"gnutls_dh_params_generate2");
577 /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
578 and I confirmed that a NULL call to get the size first is how the GnuTLS
579 sample apps handle this. */
583 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
585 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
586 exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3(NULL) sizing");
588 m.data = malloc(m.size);
590 return tls_error(US"memory allocation failed", strerror(errno), NULL);
591 /* this will return a size 1 less than the allocation size above */
592 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
594 if (rc != GNUTLS_E_SUCCESS)
597 exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3() real");
599 m.size = sz; /* shrink by 1, probably */
601 sz = write_to_fd_buf(fd, m.data, (size_t) m.size);
605 return tls_error(US"TLS cache write D-H params failed",
606 strerror(errno), NULL);
609 sz = write_to_fd_buf(fd, US"\n", 1);
611 return tls_error(US"TLS cache write D-H params final newline failed",
612 strerror(errno), NULL);
616 return tls_error(US"TLS cache write close() failed",
617 strerror(errno), NULL);
619 if (Urename(temp_fn, filename) < 0)
620 return tls_error(string_sprintf("failed to rename \"%s\" as \"%s\"",
621 temp_fn, filename), strerror(errno), NULL);
623 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
626 DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
633 /*************************************************
634 * Variables re-expanded post-SNI *
635 *************************************************/
637 /* Called from both server and client code, via tls_init(), and also from
638 the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
640 We can tell the two apart by state->received_sni being non-NULL in callback.
642 The callback should not call us unless state->trigger_sni_changes is true,
643 which we are responsible for setting on the first pass through.
646 state exim_gnutls_state_st *
648 Returns: OK/DEFER/FAIL
652 tls_expand_session_files(exim_gnutls_state_st *state)
656 const host_item *host = state->host; /* macro should be reconsidered? */
657 uschar *saved_tls_certificate = NULL;
658 uschar *saved_tls_privatekey = NULL;
659 uschar *saved_tls_verify_certificates = NULL;
660 uschar *saved_tls_crl = NULL;
663 /* We check for tls_sni *before* expansion. */
664 if (!host) /* server */
666 if (!state->received_sni)
668 if (state->tls_certificate &&
669 (Ustrstr(state->tls_certificate, US"tls_sni") ||
670 Ustrstr(state->tls_certificate, US"tls_in_sni") ||
671 Ustrstr(state->tls_certificate, US"tls_out_sni")
674 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
675 state->trigger_sni_changes = TRUE;
680 /* useful for debugging */
681 saved_tls_certificate = state->exp_tls_certificate;
682 saved_tls_privatekey = state->exp_tls_privatekey;
683 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
684 saved_tls_crl = state->exp_tls_crl;
688 rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
689 exim_gnutls_err_check(US"gnutls_certificate_allocate_credentials");
691 /* remember: expand_check_tlsvar() is expand_check() but fiddling with
692 state members, assuming consistent naming; and expand_check() returns
693 false if expansion failed, unless expansion was forced to fail. */
695 /* check if we at least have a certificate, before doing expensive
698 if (!expand_check_tlsvar(tls_certificate))
701 /* certificate is mandatory in server, optional in client */
703 if ((state->exp_tls_certificate == NULL) ||
704 (*state->exp_tls_certificate == '\0'))
707 return tls_error(US"no TLS server certificate is specified", NULL, NULL);
709 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
712 if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey))
715 /* tls_privatekey is optional, defaulting to same file as certificate */
717 if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
719 state->tls_privatekey = state->tls_certificate;
720 state->exp_tls_privatekey = state->exp_tls_certificate;
724 if (state->exp_tls_certificate && *state->exp_tls_certificate)
726 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
727 state->exp_tls_certificate, state->exp_tls_privatekey);
729 if (state->received_sni)
731 if ((Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0) &&
732 (Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0))
734 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
738 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
742 rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
743 CS state->exp_tls_certificate, CS state->exp_tls_privatekey,
744 GNUTLS_X509_FMT_PEM);
745 exim_gnutls_err_check(
746 string_sprintf("cert/key setup: cert=%s key=%s",
747 state->exp_tls_certificate, state->exp_tls_privatekey));
748 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
749 } /* tls_certificate */
752 /* Set the OCSP stapling server info */
754 #ifdef EXPERIMENTAL_OCSP
755 if ( !host /* server */
762 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file", &expanded))
765 /* Lazy way; would like callback to emit debug on actual response */
767 rc = gnutls_certificate_set_ocsp_status_request_file(state->x509_cred,
769 exim_gnutls_err_check(US"gnutls_certificate_set_ocsp_status_request_file");
770 DEBUG(D_tls) debug_printf("Set OCSP response file %s\n", expanded);
775 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
776 provided. Experiment shows that, if the certificate file is empty, an unhelpful
777 error message is provided. However, if we just refrain from setting anything up
778 in that case, certificate verification fails, which seems to be the correct
781 if (state->tls_verify_certificates && *state->tls_verify_certificates)
783 if (!expand_check_tlsvar(tls_verify_certificates))
785 if (state->tls_crl && *state->tls_crl)
786 if (!expand_check_tlsvar(tls_crl))
789 if (!(state->exp_tls_verify_certificates &&
790 *state->exp_tls_verify_certificates))
793 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
794 /* With no tls_verify_certificates, we ignore tls_crl too */
801 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
805 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
807 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
808 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
813 /* The test suite passes in /dev/null; we could check for that path explicitly,
814 but who knows if someone has some weird FIFO which always dumps some certs, or
815 other weirdness. The thing we really want to check is that it's not a
816 directory, since while OpenSSL supports that, GnuTLS does not.
817 So s/!S_ISREG/S_ISDIR/ and change some messsaging ... */
818 if (S_ISDIR(statbuf.st_mode))
821 debug_printf("verify certificates path is a dir: \"%s\"\n",
822 state->exp_tls_verify_certificates);
823 log_write(0, LOG_MAIN|LOG_PANIC,
824 "tls_verify_certificates \"%s\" is a directory",
825 state->exp_tls_verify_certificates);
829 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
830 state->exp_tls_verify_certificates, statbuf.st_size);
832 if (statbuf.st_size == 0)
835 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
839 cert_count = gnutls_certificate_set_x509_trust_file(state->x509_cred,
840 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
844 exim_gnutls_err_check(US"gnutls_certificate_set_x509_trust_file");
846 DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
848 if (state->tls_crl && *state->tls_crl &&
849 state->exp_tls_crl && *state->exp_tls_crl)
851 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
852 cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
853 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM);
857 exim_gnutls_err_check(US"gnutls_certificate_set_x509_crl_file");
859 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
868 /*************************************************
869 * Set X.509 state variables *
870 *************************************************/
872 /* In GnuTLS, the registered cert/key are not replaced by a later
873 set of a cert/key, so for SNI support we need a whole new x509_cred
874 structure. Which means various other non-re-expanded pieces of state
875 need to be re-set in the new struct, so the setting logic is pulled
879 state exim_gnutls_state_st *
881 Returns: OK/DEFER/FAIL
885 tls_set_remaining_x509(exim_gnutls_state_st *state)
888 const host_item *host = state->host; /* macro should be reconsidered? */
890 /* Create D-H parameters, or read them from the cache file. This function does
891 its own SMTP error messaging. This only happens for the server, TLS D-H ignores
892 client-side params. */
896 if (!dh_server_params)
898 rc = init_server_dh();
899 if (rc != OK) return rc;
901 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
904 /* Link the credentials to the session. */
906 rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
907 exim_gnutls_err_check(US"gnutls_credentials_set");
912 /*************************************************
913 * Initialize for GnuTLS *
914 *************************************************/
916 /* Called from both server and client code. In the case of a server, errors
917 before actual TLS negotiation return DEFER.
920 host connected host, if client; NULL if server
921 certificate certificate file
922 privatekey private key file
923 sni TLS SNI to send, sometimes when client; else NULL
926 require_ciphers tls_require_ciphers setting
927 caller_state returned state-info structure
929 Returns: OK/DEFER/FAIL
934 const host_item *host,
935 const uschar *certificate,
936 const uschar *privatekey,
940 const uschar *require_ciphers,
941 exim_gnutls_state_st **caller_state)
943 exim_gnutls_state_st *state;
948 BOOL want_default_priorities;
950 if (!exim_gnutls_base_init_done)
952 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
954 #ifdef HAVE_GNUTLS_PKCS11
955 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
956 which loads modules from a config file, which sounds good and may be wanted
957 by some sysadmin, but also means in common configurations that GNOME keyring
958 environment variables are used and so breaks for users calling mailq.
959 To prevent this, we init PKCS11 first, which is the documented approach. */
960 if (!gnutls_allow_auto_pkcs11)
962 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
963 exim_gnutls_err_check(US"gnutls_pkcs11_init");
967 rc = gnutls_global_init();
968 exim_gnutls_err_check(US"gnutls_global_init");
970 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
973 gnutls_global_set_log_function(exim_gnutls_logger_cb);
974 /* arbitrarily chosen level; bump upto 9 for more */
975 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
979 exim_gnutls_base_init_done = TRUE;
984 state = &state_client;
985 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
986 state->tlsp = &tls_out;
987 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
988 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
992 state = &state_server;
993 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
994 state->tlsp = &tls_in;
995 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
996 rc = gnutls_init(&state->session, GNUTLS_SERVER);
998 exim_gnutls_err_check(US"gnutls_init");
1002 state->tls_certificate = certificate;
1003 state->tls_privatekey = privatekey;
1004 state->tls_require_ciphers = require_ciphers;
1005 state->tls_sni = sni;
1006 state->tls_verify_certificates = cas;
1007 state->tls_crl = crl;
1009 /* This handles the variables that might get re-expanded after TLS SNI;
1010 that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1013 debug_printf("Expanding various TLS configuration options for session credentials.\n");
1014 rc = tls_expand_session_files(state);
1015 if (rc != OK) return rc;
1017 /* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1018 requires a new structure afterwards. */
1020 rc = tls_set_remaining_x509(state);
1021 if (rc != OK) return rc;
1023 /* set SNI in client, only */
1026 if (!expand_check(state->tlsp->sni, US"tls_out_sni", &state->exp_tls_sni))
1028 if (state->exp_tls_sni && *state->exp_tls_sni)
1031 debug_printf("Setting TLS client SNI to \"%s\"\n", state->exp_tls_sni);
1032 sz = Ustrlen(state->exp_tls_sni);
1033 rc = gnutls_server_name_set(state->session,
1034 GNUTLS_NAME_DNS, state->exp_tls_sni, sz);
1035 exim_gnutls_err_check(US"gnutls_server_name_set");
1038 else if (state->tls_sni)
1039 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1040 "have an SNI set for a client [%s]\n", state->tls_sni);
1042 /* This is the priority string support,
1043 http://www.gnutls.org/manual/html_node/Priority-Strings.html
1044 and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1045 This was backwards incompatible, but means Exim no longer needs to track
1046 all algorithms and provide string forms for them. */
1048 want_default_priorities = TRUE;
1050 if (state->tls_require_ciphers && *state->tls_require_ciphers)
1052 if (!expand_check_tlsvar(tls_require_ciphers))
1054 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1056 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n",
1057 state->exp_tls_require_ciphers);
1059 rc = gnutls_priority_init(&state->priority_cache,
1060 CS state->exp_tls_require_ciphers, &errpos);
1061 want_default_priorities = FALSE;
1062 p = state->exp_tls_require_ciphers;
1065 if (want_default_priorities)
1068 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n",
1069 exim_default_gnutls_priority);
1070 rc = gnutls_priority_init(&state->priority_cache,
1071 exim_default_gnutls_priority, &errpos);
1072 p = US exim_default_gnutls_priority;
1075 exim_gnutls_err_check(string_sprintf(
1076 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1077 p, errpos - CS p, errpos));
1079 rc = gnutls_priority_set(state->session, state->priority_cache);
1080 exim_gnutls_err_check(US"gnutls_priority_set");
1082 gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1084 /* Reduce security in favour of increased compatibility, if the admin
1085 decides to make that trade-off. */
1086 if (gnutls_compat_mode)
1088 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1089 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1090 gnutls_session_enable_compatibility_mode(state->session);
1092 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1096 *caller_state = state;
1103 /*************************************************
1104 * Extract peer information *
1105 *************************************************/
1107 /* Called from both server and client code.
1108 Only this is allowed to set state->peerdn and state->have_set_peerdn
1109 and we use that to detect double-calls.
1111 NOTE: the state blocks last while the TLS connection is up, which is fine
1112 for logging in the server side, but for the client side, we log after teardown
1113 in src/deliver.c. While the session is up, we can twist about states and
1114 repoint tls_* globals, but those variables used for logging or other variable
1115 expansion that happens _after_ delivery need to have a longer life-time.
1117 So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1118 doing this more than once per generation of a state context. We set them in
1119 the state context, and repoint tls_* to them. After the state goes away, the
1120 tls_* copies of the pointers remain valid and client delivery logging is happy.
1122 tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1126 state exim_gnutls_state_st *
1128 Returns: OK/DEFER/FAIL
1132 peer_status(exim_gnutls_state_st *state)
1134 uschar cipherbuf[256];
1135 const gnutls_datum *cert_list;
1137 unsigned int cert_list_size = 0;
1138 gnutls_protocol_t protocol;
1139 gnutls_cipher_algorithm_t cipher;
1140 gnutls_kx_algorithm_t kx;
1141 gnutls_mac_algorithm_t mac;
1142 gnutls_certificate_type_t ct;
1143 gnutls_x509_crt_t crt;
1147 if (state->have_set_peerdn)
1149 state->have_set_peerdn = TRUE;
1151 state->peerdn = NULL;
1154 cipher = gnutls_cipher_get(state->session);
1155 protocol = gnutls_protocol_get_version(state->session);
1156 mac = gnutls_mac_get(state->session);
1157 kx = gnutls_kx_get(state->session);
1159 string_format(cipherbuf, sizeof(cipherbuf),
1161 gnutls_protocol_get_name(protocol),
1162 gnutls_cipher_suite_get_name(kx, cipher, mac),
1163 (int) gnutls_cipher_get_key_size(cipher) * 8);
1165 /* I don't see a way that spaces could occur, in the current GnuTLS
1166 code base, but it was a concern in the old code and perhaps older GnuTLS
1167 releases did return "TLS 1.0"; play it safe, just in case. */
1168 for (p = cipherbuf; *p != '\0'; ++p)
1171 old_pool = store_pool;
1172 store_pool = POOL_PERM;
1173 state->ciphersuite = string_copy(cipherbuf);
1174 store_pool = old_pool;
1175 state->tlsp->cipher = state->ciphersuite;
1178 cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
1180 if (cert_list == NULL || cert_list_size == 0)
1182 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1183 cert_list, cert_list_size);
1184 if (state->verify_requirement == VERIFY_REQUIRED)
1185 return tls_error(US"certificate verification failed",
1186 "no certificate received from peer", state->host);
1190 ct = gnutls_certificate_type_get(state->session);
1191 if (ct != GNUTLS_CRT_X509)
1193 const char *ctn = gnutls_certificate_type_get_name(ct);
1195 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1196 if (state->verify_requirement == VERIFY_REQUIRED)
1197 return tls_error(US"certificate verification not possible, unhandled type",
1202 #define exim_gnutls_peer_err(Label) do { \
1203 if (rc != GNUTLS_E_SUCCESS) { \
1204 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", (Label), gnutls_strerror(rc)); \
1205 if (state->verify_requirement == VERIFY_REQUIRED) { return tls_error((Label), gnutls_strerror(rc), state->host); } \
1206 return OK; } } while (0)
1208 rc = gnutls_x509_crt_init(&crt);
1209 exim_gnutls_peer_err(US"gnutls_x509_crt_init (crt)");
1211 rc = gnutls_x509_crt_import(crt, &cert_list[0], GNUTLS_X509_FMT_DER);
1212 exim_gnutls_peer_err(US"failed to import certificate [gnutls_x509_crt_import(cert 0)]");
1214 rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1215 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1217 exim_gnutls_peer_err(US"getting size for cert DN failed");
1218 return FAIL; /* should not happen */
1220 dn_buf = store_get_perm(sz);
1221 rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1222 exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1223 state->peerdn = dn_buf;
1226 #undef exim_gnutls_peer_err
1232 /*************************************************
1233 * Verify peer certificate *
1234 *************************************************/
1236 /* Called from both server and client code.
1237 *Should* be using a callback registered with
1238 gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1239 the peer information, but that's too new for some OSes.
1242 state exim_gnutls_state_st *
1243 error where to put an error message
1246 FALSE if the session should be rejected
1247 TRUE if the cert is okay or we just don't care
1251 verify_certificate(exim_gnutls_state_st *state, const char **error)
1254 unsigned int verify;
1258 if ((rc = peer_status(state)) != OK)
1260 verify = GNUTLS_CERT_INVALID;
1261 *error = "certificate not supplied";
1264 rc = gnutls_certificate_verify_peers2(state->session, &verify);
1266 /* Handle the result of verification. INVALID seems to be set as well
1267 as REVOKED, but leave the test for both. */
1269 if (rc < 0 || verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED))
1271 state->peer_cert_verified = FALSE;
1273 *error = verify & GNUTLS_CERT_REVOKED
1274 ? "certificate revoked" : "certificate invalid";
1277 debug_printf("TLS certificate verification failed (%s): peerdn=%s\n",
1278 *error, state->peerdn ? state->peerdn : US"<unset>");
1280 if (state->verify_requirement == VERIFY_REQUIRED)
1282 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1286 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1290 state->peer_cert_verified = TRUE;
1291 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=%s\n",
1292 state->peerdn ? state->peerdn : US"<unset>");
1295 state->tlsp->peerdn = state->peerdn;
1303 /* ------------------------------------------------------------------------ */
1306 /* Logging function which can be registered with
1307 * gnutls_global_set_log_function()
1308 * gnutls_global_set_log_level() 0..9
1310 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1312 exim_gnutls_logger_cb(int level, const char *message)
1314 size_t len = strlen(message);
1317 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1320 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1321 message[len-1] == '\n' ? "" : "\n");
1326 /* Called after client hello, should handle SNI work.
1327 This will always set tls_sni (state->received_sni) if available,
1328 and may trigger presenting different certificates,
1329 if state->trigger_sni_changes is TRUE.
1331 Should be registered with
1332 gnutls_handshake_set_post_client_hello_function()
1334 "This callback must return 0 on success or a gnutls error code to terminate the
1337 For inability to get SNI information, we return 0.
1338 We only return non-zero if re-setup failed.
1339 Only used for server-side TLS.
1343 exim_sni_handling_cb(gnutls_session_t session)
1345 char sni_name[MAX_HOST_LEN];
1346 size_t data_len = MAX_HOST_LEN;
1347 exim_gnutls_state_st *state = &state_server;
1348 unsigned int sni_type;
1351 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1352 if (rc != GNUTLS_E_SUCCESS)
1355 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1356 debug_printf("TLS: no SNI presented in handshake.\n");
1358 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1359 gnutls_strerror(rc), rc);
1364 if (sni_type != GNUTLS_NAME_DNS)
1366 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1370 /* We now have a UTF-8 string in sni_name */
1371 old_pool = store_pool;
1372 store_pool = POOL_PERM;
1373 state->received_sni = string_copyn(US sni_name, data_len);
1374 store_pool = old_pool;
1376 /* We set this one now so that variable expansions below will work */
1377 state->tlsp->sni = state->received_sni;
1379 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1380 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1382 if (!state->trigger_sni_changes)
1385 rc = tls_expand_session_files(state);
1388 /* If the setup of certs/etc failed before handshake, TLS would not have
1389 been offered. The best we can do now is abort. */
1390 return GNUTLS_E_APPLICATION_ERROR_MIN;
1393 rc = tls_set_remaining_x509(state);
1394 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1402 /* ------------------------------------------------------------------------ */
1403 /* Exported functions */
1408 /*************************************************
1409 * Start a TLS session in a server *
1410 *************************************************/
1412 /* This is called when Exim is running as a server, after having received
1413 the STARTTLS command. It must respond to that command, and then negotiate
1417 require_ciphers list of allowed ciphers or NULL
1419 Returns: OK on success
1420 DEFER for errors before the start of the negotiation
1421 FAIL for errors during the negotation; the server can't
1426 tls_server_start(const uschar *require_ciphers)
1430 exim_gnutls_state_st *state = NULL;
1432 /* Check for previous activation */
1433 if (tls_in.active >= 0)
1435 tls_error(US"STARTTLS received after TLS started", "", NULL);
1436 smtp_printf("554 Already in TLS\r\n");
1440 /* Initialize the library. If it fails, it will already have logged the error
1441 and sent an SMTP response. */
1443 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
1445 rc = tls_init(NULL, tls_certificate, tls_privatekey,
1446 NULL, tls_verify_certificates, tls_crl,
1447 require_ciphers, &state);
1448 if (rc != OK) return rc;
1450 /* If this is a host for which certificate verification is mandatory or
1451 optional, set up appropriately. */
1453 if (verify_check_host(&tls_verify_hosts) == OK)
1455 DEBUG(D_tls) debug_printf("TLS: a client certificate will be required.\n");
1456 state->verify_requirement = VERIFY_REQUIRED;
1457 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1459 else if (verify_check_host(&tls_try_verify_hosts) == OK)
1461 DEBUG(D_tls) debug_printf("TLS: a client certificate will be requested but not required.\n");
1462 state->verify_requirement = VERIFY_OPTIONAL;
1463 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1467 DEBUG(D_tls) debug_printf("TLS: a client certificate will not be requested.\n");
1468 state->verify_requirement = VERIFY_NONE;
1469 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1472 /* Register SNI handling; always, even if not in tls_certificate, so that the
1473 expansion variable $tls_sni is always available. */
1475 gnutls_handshake_set_post_client_hello_function(state->session,
1476 exim_sni_handling_cb);
1478 /* Set context and tell client to go ahead, except in the case of TLS startup
1479 on connection, where outputting anything now upsets the clients and tends to
1480 make them disconnect. We need to have an explicit fflush() here, to force out
1481 the response. Other smtp_printf() calls do not need it, because in non-TLS
1482 mode, the fflush() happens when smtp_getc() is called. */
1484 if (!state->tlsp->on_connect)
1486 smtp_printf("220 TLS go ahead\r\n");
1487 fflush(smtp_out); /*XXX JGH */
1490 /* Now negotiate the TLS session. We put our own timer on it, since it seems
1491 that the GnuTLS library doesn't. */
1493 gnutls_transport_set_ptr2(state->session,
1494 (gnutls_transport_ptr)fileno(smtp_in),
1495 (gnutls_transport_ptr)fileno(smtp_out));
1496 state->fd_in = fileno(smtp_in);
1497 state->fd_out = fileno(smtp_out);
1499 sigalrm_seen = FALSE;
1500 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1503 rc = gnutls_handshake(state->session);
1504 } while ((rc == GNUTLS_E_AGAIN) ||
1505 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
1508 if (rc != GNUTLS_E_SUCCESS)
1510 tls_error(US"gnutls_handshake",
1511 sigalrm_seen ? "timed out" : gnutls_strerror(rc), NULL);
1512 /* It seems that, except in the case of a timeout, we have to close the
1513 connection right here; otherwise if the other end is running OpenSSL it hangs
1514 until the server times out. */
1518 (void)fclose(smtp_out);
1519 (void)fclose(smtp_in);
1525 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1527 /* Verify after the fact */
1529 if (state->verify_requirement != VERIFY_NONE)
1531 if (!verify_certificate(state, &error))
1533 if (state->verify_requirement == VERIFY_OPTIONAL)
1536 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
1541 tls_error(US"certificate verification failed", error, NULL);
1547 /* Figure out peer DN, and if authenticated, etc. */
1549 rc = peer_status(state);
1550 if (rc != OK) return rc;
1552 /* Sets various Exim expansion variables; always safe within server */
1554 extract_exim_vars_from_tls_state(state, TRUE);
1556 /* TLS has been set up. Adjust the input functions to read via TLS,
1557 and initialize appropriately. */
1559 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1561 receive_getc = tls_getc;
1562 receive_ungetc = tls_ungetc;
1563 receive_feof = tls_feof;
1564 receive_ferror = tls_ferror;
1565 receive_smtp_buffered = tls_smtp_buffered;
1573 /*************************************************
1574 * Start a TLS session in a client *
1575 *************************************************/
1577 /* Called from the smtp transport after STARTTLS has been accepted.
1580 fd the fd of the connection
1581 host connected host (for messages)
1582 addr the first address (not used)
1583 certificate certificate file
1584 privatekey private key file
1585 sni TLS SNI to send to remote host
1586 verify_certs file for certificate verify
1587 verify_crl CRL for verify
1588 require_ciphers list of allowed ciphers or NULL
1589 hosts_require_ocsp hosts for which to request certificate-status (OCSP)
1590 dh_min_bits minimum number of bits acceptable in server's DH prime
1591 timeout startup timeout
1592 verify_hosts mandatory client verification
1593 try_verify_hosts optional client verification
1595 Returns: OK/DEFER/FAIL (because using common functions),
1596 but for a client, DEFER and FAIL have the same meaning
1600 tls_client_start(int fd, host_item *host,
1601 address_item *addr ARG_UNUSED,
1602 uschar *certificate, uschar *privatekey, uschar *sni,
1603 uschar *verify_certs, uschar *verify_crl,
1604 uschar *require_ciphers,
1605 #ifdef EXPERIMENTAL_OCSP
1606 uschar *hosts_require_ocsp,
1608 int dh_min_bits, int timeout,
1609 uschar *verify_hosts, uschar *try_verify_hosts)
1613 exim_gnutls_state_st *state = NULL;
1614 #ifdef EXPERIMENTAL_OCSP
1615 BOOL require_ocsp = verify_check_this_host(&hosts_require_ocsp,
1616 NULL, host->name, host->address, NULL) == OK;
1619 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
1621 if ((rc = tls_init(host, certificate, privatekey,
1622 sni, verify_certs, verify_crl, require_ciphers, &state)) != OK)
1625 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
1628 debug_printf("WARNING: tls_dh_min_bits far too low, clamping %d up to %d\n",
1629 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
1630 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
1633 DEBUG(D_tls) debug_printf("Setting D-H prime minimum acceptable bits to %d\n",
1635 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
1637 /* Stick to the old behaviour for compatibility if tls_verify_certificates is
1638 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
1639 the specified host patterns if one of them is defined */
1641 if (( state->exp_tls_verify_certificates
1643 && !try_verify_hosts
1646 verify_check_host(&verify_hosts) == OK
1649 DEBUG(D_tls) debug_printf("TLS: server certificate verification required.\n");
1650 state->verify_requirement = VERIFY_REQUIRED;
1651 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1653 else if (verify_check_host(&try_verify_hosts) == OK)
1655 DEBUG(D_tls) debug_printf("TLS: server certificate verification optional.\n");
1656 state->verify_requirement = VERIFY_OPTIONAL;
1657 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1661 DEBUG(D_tls) debug_printf("TLS: server certificate verification not required.\n");
1662 state->verify_requirement = VERIFY_NONE;
1663 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1666 #ifdef EXPERIMENTAL_OCSP /* since GnuTLS 3.1.3 */
1668 (rc = gnutls_ocsp_status_request_enable_client(state->session, NULL, 0, NULL))
1670 return tls_error(US"cert-status-req", gnutls_strerror(rc), state->host);
1673 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr)fd);
1677 /* There doesn't seem to be a built-in timeout on connection. */
1679 sigalrm_seen = FALSE;
1683 rc = gnutls_handshake(state->session);
1684 } while ((rc == GNUTLS_E_AGAIN) ||
1685 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
1688 if (rc != GNUTLS_E_SUCCESS)
1689 return tls_error(US"gnutls_handshake",
1690 sigalrm_seen ? "timed out" : gnutls_strerror(rc), state->host);
1692 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1696 if (state->verify_requirement != VERIFY_NONE &&
1697 !verify_certificate(state, &error))
1698 return tls_error(US"certificate verification failed", error, state->host);
1700 #ifdef EXPERIMENTAL_OCSP
1705 gnutls_datum_t stapling;
1706 gnutls_ocsp_resp_t resp;
1707 gnutls_datum_t printed;
1708 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
1709 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
1710 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
1711 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
1714 fprintf(stderr, "%.4096s", printed.data);
1715 gnutls_free(printed.data);
1718 (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host);
1721 fprintf(stderr, "%s: checking ocsp\n", __FUNCTION__);
1722 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
1723 return tls_error(US"certificate status check failed", NULL, state->host);
1724 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
1728 /* Figure out peer DN, and if authenticated, etc. */
1730 if ((rc = peer_status(state)) != OK)
1733 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
1735 extract_exim_vars_from_tls_state(state, FALSE);
1743 /*************************************************
1744 * Close down a TLS session *
1745 *************************************************/
1747 /* This is also called from within a delivery subprocess forked from the
1748 daemon, to shut down the TLS library, without actually doing a shutdown (which
1749 would tamper with the TLS session in the parent process).
1751 Arguments: TRUE if gnutls_bye is to be called
1756 tls_close(BOOL is_server, BOOL shutdown)
1758 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
1760 if (!state->tlsp || state->tlsp->active < 0) return; /* TLS was not active */
1764 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
1765 gnutls_bye(state->session, GNUTLS_SHUT_WR);
1768 gnutls_deinit(state->session);
1770 state->tlsp->active = -1;
1771 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1773 if ((state_server.session == NULL) && (state_client.session == NULL))
1775 gnutls_global_deinit();
1776 exim_gnutls_base_init_done = FALSE;
1784 /*************************************************
1785 * TLS version of getc *
1786 *************************************************/
1788 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
1789 it refills the buffer via the GnuTLS reading function.
1790 Only used by the server-side TLS.
1792 This feeds DKIM and should be used for all message-body reads.
1795 Returns: the next character or EOF
1801 exim_gnutls_state_st *state = &state_server;
1802 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
1806 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
1807 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
1809 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1810 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
1811 ssl_xfer_buffer_size);
1814 /* A zero-byte return appears to mean that the TLS session has been
1815 closed down, not that the socket itself has been closed down. Revert to
1816 non-TLS handling. */
1820 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1822 receive_getc = smtp_getc;
1823 receive_ungetc = smtp_ungetc;
1824 receive_feof = smtp_feof;
1825 receive_ferror = smtp_ferror;
1826 receive_smtp_buffered = smtp_buffered;
1828 gnutls_deinit(state->session);
1829 state->session = NULL;
1830 state->tlsp->active = -1;
1831 state->tlsp->bits = 0;
1832 state->tlsp->certificate_verified = FALSE;
1833 tls_channelbinding_b64 = NULL; /*XXX JGH */
1834 state->tlsp->cipher = NULL;
1835 state->tlsp->peerdn = NULL;
1840 /* Handle genuine errors */
1842 else if (inbytes < 0)
1844 record_io_error(state, (int) inbytes, US"recv", NULL);
1845 state->xfer_error = 1;
1848 #ifndef DISABLE_DKIM
1849 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
1851 state->xfer_buffer_hwm = (int) inbytes;
1852 state->xfer_buffer_lwm = 0;
1855 /* Something in the buffer; return next uschar */
1857 return state->xfer_buffer[state->xfer_buffer_lwm++];
1863 /*************************************************
1864 * Read bytes from TLS channel *
1865 *************************************************/
1867 /* This does not feed DKIM, so if the caller uses this for reading message body,
1868 then the caller must feed DKIM.
1874 Returns: the number of bytes read
1875 -1 after a failed read
1879 tls_read(BOOL is_server, uschar *buff, size_t len)
1881 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
1887 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
1889 debug_printf("*** PROBABLY A BUG *** " \
1890 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
1891 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
1894 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
1895 state->session, buff, len);
1897 inbytes = gnutls_record_recv(state->session, buff, len);
1898 if (inbytes > 0) return inbytes;
1901 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1903 else record_io_error(state, (int)inbytes, US"recv", NULL);
1911 /*************************************************
1912 * Write bytes down TLS channel *
1913 *************************************************/
1917 is_server channel specifier
1921 Returns: the number of bytes after a successful write,
1922 -1 after a failed write
1926 tls_write(BOOL is_server, const uschar *buff, size_t len)
1930 exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
1932 DEBUG(D_tls) debug_printf("tls_do_write(%p, " SIZE_T_FMT ")\n", buff, left);
1935 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
1937 outbytes = gnutls_record_send(state->session, buff, left);
1939 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
1942 record_io_error(state, outbytes, US"send", NULL);
1947 record_io_error(state, 0, US"send", US"TLS channel closed on write");
1958 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
1969 /*************************************************
1970 * Random number generation *
1971 *************************************************/
1973 /* Pseudo-random number generation. The result is not expected to be
1974 cryptographically strong but not so weak that someone will shoot themselves
1975 in the foot using it as a nonce in input in some email header scheme or
1976 whatever weirdness they'll twist this into. The result should handle fork()
1977 and avoid repeating sequences. OpenSSL handles that for us.
1981 Returns a random number in range [0, max-1]
1984 #ifdef HAVE_GNUTLS_RND
1986 vaguely_random_number(int max)
1991 uschar smallbuf[sizeof(r)];
1996 needed_len = sizeof(r);
1997 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
1998 * asked for a number less than 10. */
1999 for (r = max, i = 0; r; ++i)
2005 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2008 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2009 return vaguely_random_number_fallback(max);
2012 for (p = smallbuf; needed_len; --needed_len, ++p)
2018 /* We don't particularly care about weighted results; if someone wants
2019 * smooth distribution and cares enough then they should submit a patch then. */
2022 #else /* HAVE_GNUTLS_RND */
2024 vaguely_random_number(int max)
2026 return vaguely_random_number_fallback(max);
2028 #endif /* HAVE_GNUTLS_RND */
2033 /*************************************************
2034 * Let tls_require_ciphers be checked at startup *
2035 *************************************************/
2037 /* The tls_require_ciphers option, if set, must be something which the
2040 Returns: NULL on success, or error message
2044 tls_validate_require_cipher(void)
2047 uschar *expciphers = NULL;
2048 gnutls_priority_t priority_cache;
2051 #define validate_check_rc(Label) do { \
2052 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
2053 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
2054 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
2056 if (exim_gnutls_base_init_done)
2057 log_write(0, LOG_MAIN|LOG_PANIC,
2058 "already initialised GnuTLS, Exim developer bug");
2060 #ifdef HAVE_GNUTLS_PKCS11
2061 if (!gnutls_allow_auto_pkcs11)
2063 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2064 validate_check_rc(US"gnutls_pkcs11_init");
2067 rc = gnutls_global_init();
2068 validate_check_rc(US"gnutls_global_init()");
2069 exim_gnutls_base_init_done = TRUE;
2071 if (!(tls_require_ciphers && *tls_require_ciphers))
2072 return_deinit(NULL);
2074 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers))
2075 return_deinit(US"failed to expand tls_require_ciphers");
2077 if (!(expciphers && *expciphers))
2078 return_deinit(NULL);
2081 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2083 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2084 validate_check_rc(string_sprintf(
2085 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
2086 expciphers, errpos - CS expciphers, errpos));
2088 #undef return_deinit
2089 #undef validate_check_rc
2090 gnutls_global_deinit();
2098 /*************************************************
2099 * Report the library versions. *
2100 *************************************************/
2102 /* See a description in tls-openssl.c for an explanation of why this exists.
2104 Arguments: a FILE* to print the results to
2109 tls_version_report(FILE *f)
2111 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2114 gnutls_check_version(NULL));
2119 /* End of tls-gnu.c */