1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2009 */
6 /* See the file NOTICE for conditions of use and distribution. */
8 /* This module provides TLS (aka SSL) support for Exim using the GnuTLS
9 library. It is #included into tls.c when that library is used. The code herein
10 is based on a patch that was contributed by Nikos Mavroyanopoulos.
12 No cryptographic code is included in Exim. All this module does is to call
13 functions from the GnuTLS library. */
15 /* Note: This appears to be using an old API from compat.h; it is likely that
16 someone familiary with GnuTLS programming could rework a lot of this to a
17 modern API and perhaps remove the explicit knowledge of crypto algorithms from
18 Exim. Such a re-work would be most welcome and we'd sacrifice support for
19 older GnuTLS releases without too many qualms -- maturity and experience
20 in crypto libraries tends to improve their robustness against attack.
21 Frankly, if you maintain it, you decide what's supported and what isn't. */
23 /* Heading stuff for GnuTLS */
25 #include <gnutls/gnutls.h>
26 #include <gnutls/x509.h>
29 #define UNKNOWN_NAME "unknown"
31 #define PARAM_SIZE 2*1024
34 /* Values for verify_requirment */
36 enum { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED };
38 /* Local static variables for GNUTLS */
40 static host_item *client_host;
42 static gnutls_dh_params dh_params = NULL;
44 static gnutls_certificate_server_credentials x509_cred = NULL;
45 static gnutls_session tls_session = NULL;
47 static char ssl_errstring[256];
49 static int ssl_session_timeout = 200;
50 static int verify_requirement;
52 /* Priorities for TLS algorithms to use. In each case there's a default table,
53 and space into which it can be copied and altered. */
55 static const int default_proto_priority[16] = {
56 /* These are gnutls_protocol_t enum values */
57 #if GNUTLS_VERSION_MAJOR > 1 || GNUTLS_VERSION_MINOR >= 7
60 #if GNUTLS_VERSION_MAJOR > 1 || GNUTLS_VERSION_MINOR >= 2
67 static int proto_priority[16];
69 static const int default_kx_priority[16] = {
75 static int kx_priority[16];
77 static int default_cipher_priority[16] = {
78 GNUTLS_CIPHER_AES_256_CBC,
79 GNUTLS_CIPHER_AES_128_CBC,
80 GNUTLS_CIPHER_3DES_CBC,
81 GNUTLS_CIPHER_ARCFOUR_128,
84 static int cipher_priority[16];
86 static const int default_mac_priority[16] = {
91 static int mac_priority[16];
93 /* These two are currently not changeable. */
95 static const int comp_priority[16] = { GNUTLS_COMP_NULL, 0 };
96 static const int cert_type_priority[16] = { GNUTLS_CRT_X509, 0 };
98 /* Tables of priority names and equivalent numbers */
100 typedef struct pri_item {
106 #if GNUTLS_VERSION_MAJOR > 1 || GNUTLS_VERSION_MINOR >= 7
107 static int tls1_2_codes[] = { GNUTLS_TLS1_2, 0 };
109 #if GNUTLS_VERSION_MAJOR > 1 || GNUTLS_VERSION_MINOR >= 2
110 static int tls1_1_codes[] = { GNUTLS_TLS1_1, 0 };
112 /* more recent libraries define this as an equivalent value to the
113 canonical GNUTLS_TLS1_0; since they're the same, we stick to the
115 static int tls1_0_codes[] = { GNUTLS_TLS1, 0 };
116 static int ssl3_codes[] = { GNUTLS_SSL3, 0 };
118 static pri_item proto_index[] = {
119 #if GNUTLS_VERSION_MAJOR > 1 || GNUTLS_VERSION_MINOR >= 7
120 { US"TLS1.2", tls1_2_codes },
122 #if GNUTLS_VERSION_MAJOR > 1 || GNUTLS_VERSION_MINOR >= 2
123 { US"TLS1.1", tls1_1_codes },
125 { US"TLS1.0", tls1_0_codes },
126 { US"TLS1", tls1_0_codes },
127 { US"SSL3", ssl3_codes }
131 static int kx_rsa_codes[] = { GNUTLS_KX_RSA,
132 GNUTLS_KX_DHE_RSA, 0 };
133 static int kx_dhe_codes[] = { GNUTLS_KX_DHE_DSS,
134 GNUTLS_KX_DHE_RSA, 0 };
135 static int kx_dhe_dss_codes[] = { GNUTLS_KX_DHE_DSS, 0 };
136 static int kx_dhe_rsa_codes[] = { GNUTLS_KX_DHE_RSA, 0 };
138 static pri_item kx_index[] = {
139 { US"DHE_DSS", kx_dhe_dss_codes },
140 { US"DHE_RSA", kx_dhe_rsa_codes },
141 { US"RSA", kx_rsa_codes },
142 { US"DHE", kx_dhe_codes }
146 static int arcfour_128_codes[] = { GNUTLS_CIPHER_ARCFOUR_128, 0 };
147 static int arcfour_40_codes[] = { GNUTLS_CIPHER_ARCFOUR_40, 0 };
148 static int arcfour_codes[] = { GNUTLS_CIPHER_ARCFOUR_128,
149 GNUTLS_CIPHER_ARCFOUR_40, 0 };
150 static int aes_256_codes[] = { GNUTLS_CIPHER_AES_256_CBC, 0 };
151 static int aes_128_codes[] = { GNUTLS_CIPHER_AES_128_CBC, 0 };
152 static int aes_codes[] = { GNUTLS_CIPHER_AES_256_CBC,
153 GNUTLS_CIPHER_AES_128_CBC, 0 };
154 static int des3_codes[] = { GNUTLS_CIPHER_3DES_CBC, 0 };
156 static pri_item cipher_index[] = {
157 { US"ARCFOUR_128", arcfour_128_codes },
158 { US"ARCFOUR_40", arcfour_40_codes },
159 { US"ARCFOUR", arcfour_codes },
160 { US"AES_256", aes_256_codes },
161 { US"AES_128", aes_128_codes },
162 { US"AES", aes_codes },
163 { US"3DES", des3_codes }
167 static int mac_sha_codes[] = { GNUTLS_MAC_SHA, 0 };
168 static int mac_md5_codes[] = { GNUTLS_MAC_MD5, 0 };
170 static pri_item mac_index[] = {
171 { US"SHA", mac_sha_codes },
172 { US"SHA1", mac_sha_codes },
173 { US"MD5", mac_md5_codes }
178 /*************************************************
180 *************************************************/
182 /* Called from lots of places when errors occur before actually starting to do
183 the TLS handshake, that is, while the session is still in clear. Always returns
184 DEFER for a server and FAIL for a client so that most calls can use "return
185 tls_error(...)" to do this processing and then give an appropriate return. A
186 single function is used for both server and client, because it is called from
187 some shared functions.
190 prefix text to include in the logged error
191 host NULL if setting up a server;
192 the connected host if setting up a client
193 msg additional error string (may be NULL)
194 usually obtained from gnutls_strerror()
196 Returns: OK/DEFER/FAIL
200 tls_error(uschar *prefix, host_item *host, const char *msg)
204 uschar *conn_info = smtp_get_connection_info();
205 if (strncmp(conn_info, "SMTP ", 5) == 0)
207 log_write(0, LOG_MAIN, "TLS error on %s (%s)%s%s",
208 conn_info, prefix, msg ? ": " : "", msg ? msg : "");
213 log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s)%s%s",
214 host->name, host->address, prefix, msg ? ": " : "", msg ? msg : "");
221 /*************************************************
222 * Verify certificate *
223 *************************************************/
225 /* Called after a successful handshake, when certificate verification is
226 required or optional, for both server and client.
229 session GNUTLS session
230 error where to put text giving a reason for failure
236 verify_certificate(gnutls_session session, const char **error)
239 uschar *dn_string = US"";
240 const gnutls_datum *cert;
241 unsigned int verify, cert_size = 0;
245 /* Get the peer's certificate. If it sent one, extract it's DN, and then
246 attempt to verify the certificate. If no certificate is supplied, verification
247 is forced to fail. */
249 cert = gnutls_certificate_get_peers(session, &cert_size);
253 gnutls_x509_crt gcert;
255 gnutls_x509_crt_init(&gcert);
256 dn_string = US"unknown";
258 if (gnutls_x509_crt_import(gcert, cert, GNUTLS_X509_FMT_DER) == 0)
260 size_t bufsize = sizeof(buff);
261 if (gnutls_x509_crt_get_dn(gcert, CS buff, &bufsize) >= 0)
262 dn_string = string_copy_malloc(buff);
265 rc = gnutls_certificate_verify_peers2(session, &verify);
269 DEBUG(D_tls) debug_printf("no peer certificate supplied\n");
270 verify = GNUTLS_CERT_INVALID;
271 *error = "not supplied";
274 /* Handle the result of verification. INVALID seems to be set as well
275 as REVOKED, but leave the test for both. */
277 if ((rc < 0) || (verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED)) != 0)
279 tls_certificate_verified = FALSE;
280 if (*error == NULL) *error = ((verify & GNUTLS_CERT_REVOKED) != 0)?
281 "revoked" : "invalid";
282 if (verify_requirement == VERIFY_REQUIRED)
284 DEBUG(D_tls) debug_printf("TLS certificate verification failed (%s): "
285 "peerdn=%s\n", *error, dn_string);
286 gnutls_alert_send(session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
287 return FALSE; /* reject */
289 DEBUG(D_tls) debug_printf("TLS certificate verify failure (%s) overridden "
290 "(host in tls_try_verify_hosts): peerdn=%s\n", *error, dn_string);
294 tls_certificate_verified = TRUE;
295 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=%s\n",
299 tls_peerdn = dn_string;
300 return TRUE; /* accept */
305 /*************************************************
306 * Setup up DH parameters *
307 *************************************************/
309 /* Generating the D-H parameters may take a long time. They only need to
310 be re-generated every so often, depending on security policy. What we do is to
311 keep these parameters in a file in the spool directory. If the file does not
312 exist, we generate them. This means that it is easy to cause a regeneration.
314 The new file is written as a temporary file and renamed, so that an incomplete
315 file is never present. If two processes both compute some new parameters, you
316 waste a bit of effort, but it doesn't seem worth messing around with locking to
320 host NULL for server, server for client (for error handling)
322 Returns: OK/DEFER/FAIL
326 init_dh(host_item *host)
331 uschar filename[200];
333 /* Initialize the data structures for holding the parameters */
335 ret = gnutls_dh_params_init(&dh_params);
336 if (ret < 0) return tls_error(US"init dh_params", host, gnutls_strerror(ret));
338 /* Set up the name of the cache file */
340 if (!string_format(filename, sizeof(filename), "%s/gnutls-params",
342 return tls_error(US"overlong filename", host, NULL);
344 /* Open the cache file for reading and if successful, read it and set up the
347 fd = Uopen(filename, O_RDONLY, 0);
351 if (fstat(fd, &statbuf) < 0)
354 return tls_error(US"TLS cache stat failed", host, strerror(errno));
357 m.size = statbuf.st_size;
358 m.data = malloc(m.size);
360 return tls_error(US"memory allocation failed", host, strerror(errno));
362 if (read(fd, m.data, m.size) != m.size)
363 return tls_error(US"TLS cache read failed", host, strerror(errno));
366 ret = gnutls_dh_params_import_pkcs3(dh_params, &m, GNUTLS_X509_FMT_PEM);
368 return tls_error(US"DH params import", host, gnutls_strerror(ret));
369 DEBUG(D_tls) debug_printf("read D-H parameters from file\n");
374 /* If the file does not exist, fall through to compute new data and cache it.
375 If there was any other opening error, it is serious. */
377 else if (errno == ENOENT)
381 debug_printf("parameter cache file %s does not exist\n", filename);
384 return tls_error(string_open_failed(errno, "%s for reading", filename),
387 /* If ret < 0, either the cache file does not exist, or the data it contains
388 is not useful. One particular case of this is when upgrading from an older
389 release of Exim in which the data was stored in a different format. We don't
390 try to be clever and support both formats; we just regenerate new data in this
395 uschar tempfilename[sizeof(filename) + 10];
397 DEBUG(D_tls) debug_printf("generating %d bit Diffie-Hellman key...\n",
399 ret = gnutls_dh_params_generate2(dh_params, DH_BITS);
400 if (ret < 0) return tls_error(US"D-H key generation", host, gnutls_strerror(ret));
402 /* Write the parameters to a file in the spool directory so that we
403 can use them from other Exim processes. */
405 sprintf(CS tempfilename, "%s-%d", filename, (int)getpid());
406 fd = Uopen(tempfilename, O_WRONLY|O_CREAT, 0400);
408 return tls_error(string_open_failed(errno, "%s for writing", filename),
410 (void)fchown(fd, exim_uid, exim_gid); /* Probably not necessary */
412 /* export the parameters in a format that can be generated using GNUTLS'
413 * certtool or other programs.
415 * The commands for certtool are:
416 * $ certtool --generate-dh-params --bits 1024 > params
420 m.data = malloc(m.size);
422 return tls_error(US"memory allocation failed", host, strerror(errno));
425 ret = gnutls_dh_params_export_pkcs3(dh_params, GNUTLS_X509_FMT_PEM, m.data,
428 return tls_error(US"DH params export", host, gnutls_strerror(ret));
430 m.size = Ustrlen(m.data);
432 if (write(fd, m.data, m.size) != m.size || write(fd, "\n", 1) != 1)
433 return tls_error(US"TLS cache write failed", host, strerror(errno));
438 if (rename(CS tempfilename, CS filename) < 0)
439 return tls_error(string_sprintf("failed to rename %s as %s",
440 tempfilename, filename), host, strerror(errno));
442 DEBUG(D_tls) debug_printf("wrote D-H parameters to file %s\n", filename);
445 DEBUG(D_tls) debug_printf("initialized D-H parameters\n");
452 /*************************************************
453 * Initialize for GnuTLS *
454 *************************************************/
456 /* Called from both server and client code. In the case of a server, errors
457 before actual TLS negotiation return DEFER.
460 host connected host, if client; NULL if server
461 certificate certificate file
462 privatekey private key file
466 Returns: OK/DEFER/FAIL
470 tls_init(host_item *host, uschar *certificate, uschar *privatekey, uschar *cas,
474 uschar *cert_expanded, *key_expanded, *cas_expanded, *crl_expanded;
478 rc = gnutls_global_init();
479 if (rc < 0) return tls_error(US"tls-init", host, gnutls_strerror(rc));
481 /* Create D-H parameters, or read them from the cache file. This function does
482 its own SMTP error messaging. */
485 if (rc != OK) return rc;
487 /* Create the credentials structure */
489 rc = gnutls_certificate_allocate_credentials(&x509_cred);
491 return tls_error(US"certificate_allocate_credentials",
492 host, gnutls_strerror(rc));
494 /* This stuff must be done for each session, because different certificates
495 may be required for different sessions. */
497 if (!expand_check(certificate, US"tls_certificate", &cert_expanded))
501 if (privatekey != NULL)
503 if (!expand_check(privatekey, US"tls_privatekey", &key_expanded))
507 /* If expansion was forced to fail, key_expanded will be NULL. If the result of
508 the expansion is an empty string, ignore it also, and assume that the private
509 key is in the same file as the certificate. */
511 if (key_expanded == NULL || *key_expanded == 0)
512 key_expanded = cert_expanded;
514 /* Set the certificate and private keys */
516 if (cert_expanded != NULL)
518 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
519 cert_expanded, key_expanded);
520 rc = gnutls_certificate_set_x509_key_file(x509_cred, CS cert_expanded,
521 CS key_expanded, GNUTLS_X509_FMT_PEM);
524 uschar *msg = string_sprintf("cert/key setup: cert=%s key=%s",
525 cert_expanded, key_expanded);
526 return tls_error(msg, host, gnutls_strerror(rc));
530 /* A certificate is mandatory in a server, but not in a client */
535 return tls_error(US"no TLS server certificate is specified", NULL, NULL);
536 DEBUG(D_tls) debug_printf("no TLS client certificate is specified\n");
539 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
540 provided. Experiment shows that, if the certificate file is empty, an unhelpful
541 error message is provided. However, if we just refrain from setting anything up
542 in that case, certificate verification fails, which seems to be the correct
549 if (!expand_check(cas, US"tls_verify_certificates", &cas_expanded))
552 if (stat(CS cas_expanded, &statbuf) < 0)
554 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
555 "(tls_verify_certificates): %s", cas_expanded, strerror(errno));
559 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
560 cas_expanded, statbuf.st_size);
562 /* If the cert file is empty, there's no point in loading the CRL file. */
564 if (statbuf.st_size > 0)
566 rc = gnutls_certificate_set_x509_trust_file(x509_cred, CS cas_expanded,
567 GNUTLS_X509_FMT_PEM);
568 if (rc < 0) return tls_error(US"setup_certs", host, gnutls_strerror(rc));
570 if (crl != NULL && *crl != 0)
572 if (!expand_check(crl, US"tls_crl", &crl_expanded))
574 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", crl_expanded);
575 rc = gnutls_certificate_set_x509_crl_file(x509_cred, CS crl_expanded,
576 GNUTLS_X509_FMT_PEM);
577 if (rc < 0) return tls_error(US"CRL setup", host, gnutls_strerror(rc));
582 /* Associate the parameters with the x509 credentials structure. */
584 gnutls_certificate_set_dh_params(x509_cred, dh_params);
586 DEBUG(D_tls) debug_printf("initialized certificate stuff\n");
593 /*************************************************
594 * Remove from a priority list *
595 *************************************************/
597 /* Cautiously written so that it will remove duplicates if present.
600 list a zero-terminated list
601 remove_list a zero-terminated list to be removed
607 remove_priority(int *list, int *remove_list)
609 for (; *remove_list != 0; remove_list++)
614 if (*p == *remove_list)
617 do { pp[0] = pp[1]; pp++; } while (*pp != 0);
626 /*************************************************
627 * Add to a priority list *
628 *************************************************/
630 /* Cautiously written to check the list size
633 list a zero-terminated list
634 list_max maximum offset in the list
635 add_list a zero-terminated list to be added
637 Returns: TRUE if OK; FALSE if list overflows
641 add_priority(int *list, int list_max, int *add_list)
644 while (list[next] != 0) next++;
645 while (*add_list != 0)
647 if (next >= list_max) return FALSE;
648 list[next++] = *add_list++;
656 /*************************************************
657 * Adjust a priority list *
658 *************************************************/
660 /* This function is called to adjust the lists of cipher algorithms, MAC
661 algorithms, key-exchange methods, and protocols.
664 plist the appropriate priority list
665 psize the length of the list
666 s the configuation string
667 index the index of recognized strings
668 isize the length of the index
671 which text for an error message
673 Returns: FALSE if the table overflows, else TRUE
677 set_priority(int *plist, int psize, uschar *s, pri_item *index, int isize,
684 while ((t = string_nextinlist(&s, &sep, big_buffer, big_buffer_size)) != NULL)
687 BOOL exclude = t[0] == '!';
688 if (first && !exclude) plist[0] = 0;
690 for (i = 0; i < isize; i++)
692 uschar *ss = strstric(t, index[i].name, FALSE);
695 uschar *endss = ss + Ustrlen(index[i].name);
696 if ((ss == t || !isalnum(ss[-1])) && !isalnum(*endss))
699 remove_priority(plist, index[i].values);
702 if (!add_priority(plist, psize, index[i].values))
704 log_write(0, LOG_MAIN|LOG_PANIC, "GnuTLS init failed: %s "
705 "priority table overflow", which);
717 debug_printf("adjusted %s priorities:", which);
718 while (*ptr != 0) debug_printf(" %d", *ptr++);
728 /*************************************************
729 * Initialize a single GNUTLS session *
730 *************************************************/
732 /* Set the algorithm, the db backend, whether to request certificates etc.
734 TLS in Exim was first implemented using OpenSSL. This has a function to which
735 you pass a list of cipher suites that are permitted/not permitted. GnuTLS works
736 differently. It operates using priority lists for the different components of
739 For compatibility of configuration, we scan a list of cipher suites and set
740 priorities therefrom. However, at the moment, we pay attention only to the bulk
744 side one of GNUTLS_SERVER, GNUTLS_CLIENT
745 expciphers expanded ciphers list or NULL
746 expmac expanded MAC list or NULL
747 expkx expanded key-exchange list or NULL
748 expproto expanded protocol list or NULL
750 Returns: a gnutls_session, or NULL if there is a problem
753 static gnutls_session
754 tls_session_init(int side, uschar *expciphers, uschar *expmac, uschar *expkx,
757 gnutls_session session;
759 gnutls_init(&session, side);
761 /* Initialize the lists of permitted protocols, key-exchange methods, ciphers,
764 memcpy(cipher_priority, default_cipher_priority, sizeof(cipher_priority));
765 memcpy(mac_priority, default_mac_priority, sizeof(mac_priority));
766 memcpy(kx_priority, default_kx_priority, sizeof(kx_priority));
767 memcpy(proto_priority, default_proto_priority, sizeof(proto_priority));
769 /* The names OpenSSL uses in tls_require_ciphers are of the form DES-CBC3-SHA,
770 using hyphen separators. GnuTLS uses underscore separators. So that I can use
771 either form for tls_require_ciphers in my tests, and also for general
772 convenience, we turn hyphens into underscores before scanning the list. */
774 if (expciphers != NULL)
776 uschar *s = expciphers;
777 while (*s != 0) { if (*s == '-') *s = '_'; s++; }
780 if ((expciphers != NULL &&
781 !set_priority(cipher_priority, sizeof(cipher_priority)/sizeof(int),
782 expciphers, cipher_index, sizeof(cipher_index)/sizeof(pri_item),
785 !set_priority(mac_priority, sizeof(mac_priority)/sizeof(int),
786 expmac, mac_index, sizeof(mac_index)/sizeof(pri_item),
789 !set_priority(kx_priority, sizeof(kx_priority)/sizeof(int),
790 expkx, kx_index, sizeof(kx_index)/sizeof(pri_item),
791 US"key-exchange")) ||
793 !set_priority(proto_priority, sizeof(proto_priority)/sizeof(int),
794 expproto, proto_index, sizeof(proto_index)/sizeof(pri_item),
797 gnutls_deinit(session);
801 /* Define the various priorities */
803 gnutls_cipher_set_priority(session, cipher_priority);
804 gnutls_compression_set_priority(session, comp_priority);
805 gnutls_kx_set_priority(session, kx_priority);
806 gnutls_protocol_set_priority(session, proto_priority);
807 gnutls_mac_set_priority(session, mac_priority);
809 gnutls_cred_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);
811 gnutls_dh_set_prime_bits(session, DH_BITS);
813 /* Request or demand a certificate of the peer, as configured. This will
814 happen only in a server. */
816 if (verify_requirement != VERIFY_NONE)
817 gnutls_certificate_server_set_request(session,
818 (verify_requirement == VERIFY_OPTIONAL)?
819 GNUTLS_CERT_REQUEST : GNUTLS_CERT_REQUIRE);
821 gnutls_db_set_cache_expiration(session, ssl_session_timeout);
823 /* Reduce security in favour of increased compatibility, if the admin
824 decides to make that trade-off. */
825 if (gnutls_compat_mode)
827 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
828 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
829 gnutls_session_enable_compatibility_mode(session);
831 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
835 DEBUG(D_tls) debug_printf("initialized GnuTLS session\n");
841 /*************************************************
842 * Get name of cipher in use *
843 *************************************************/
845 /* The answer is left in a static buffer, and tls_cipher is set to point
848 Argument: pointer to a GnuTLS session
853 construct_cipher_name(gnutls_session session)
855 static uschar cipherbuf[256];
857 int bits, c, kx, mac, rc;
858 #ifdef GNUTLS_CB_TLS_UNIQUE
859 gnutls_datum_t channel;
863 US gnutls_protocol_get_name(gnutls_protocol_get_version(session)));
864 if (Ustrncmp(ver, "TLS ", 4) == 0) ver[3] = '-'; /* Don't want space */
866 c = gnutls_cipher_get(session);
867 bits = gnutls_cipher_get_key_size(c);
869 mac = gnutls_mac_get(session);
870 kx = gnutls_kx_get(session);
872 string_format(cipherbuf, sizeof(cipherbuf), "%s:%s:%u", ver,
873 gnutls_cipher_suite_get_name(kx, c, mac), bits);
874 tls_cipher = cipherbuf;
876 DEBUG(D_tls) debug_printf("cipher: %s\n", cipherbuf);
878 if (tls_channelbinding_b64)
879 free(tls_channelbinding_b64);
880 tls_channelbinding_b64 = NULL;
882 #ifdef GNUTLS_CB_TLS_UNIQUE
883 channel = { NULL, 0 };
884 rc = gnutls_session_channel_binding(session, GNUTLS_CB_TLS_UNIQUE, &channel);
886 DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc));
888 tls_channelbinding_b64 = auth_b64encode(channel.data, (int)channel.size);
889 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
896 /*************************************************
897 * Start a TLS session in a server *
898 *************************************************/
900 /* This is called when Exim is running as a server, after having received
901 the STARTTLS command. It must respond to that command, and then negotiate
905 require_ciphers list of allowed ciphers or NULL
906 require_mac list of allowed MACs or NULL
907 require_kx list of allowed key_exchange methods or NULL
908 require_proto list of allowed protocols or NULL
910 Returns: OK on success
911 DEFER for errors before the start of the negotiation
912 FAIL for errors during the negotation; the server can't
917 tls_server_start(uschar *require_ciphers, uschar *require_mac,
918 uschar *require_kx, uschar *require_proto)
922 uschar *expciphers = NULL;
923 uschar *expmac = NULL;
924 uschar *expkx = NULL;
925 uschar *expproto = NULL;
927 /* Check for previous activation */
931 tls_error("STARTTLS received after TLS started", NULL, "");
932 smtp_printf("554 Already in TLS\r\n");
936 /* Initialize the library. If it fails, it will already have logged the error
937 and sent an SMTP response. */
939 DEBUG(D_tls) debug_printf("initializing GnuTLS as a server\n");
941 rc = tls_init(NULL, tls_certificate, tls_privatekey, tls_verify_certificates,
943 if (rc != OK) return rc;
945 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers) ||
946 !expand_check(require_mac, US"gnutls_require_mac", &expmac) ||
947 !expand_check(require_kx, US"gnutls_require_kx", &expkx) ||
948 !expand_check(require_proto, US"gnutls_require_proto", &expproto))
951 /* If this is a host for which certificate verification is mandatory or
952 optional, set up appropriately. */
954 tls_certificate_verified = FALSE;
955 verify_requirement = VERIFY_NONE;
957 if (verify_check_host(&tls_verify_hosts) == OK)
958 verify_requirement = VERIFY_REQUIRED;
959 else if (verify_check_host(&tls_try_verify_hosts) == OK)
960 verify_requirement = VERIFY_OPTIONAL;
962 /* Prepare for new connection */
964 tls_session = tls_session_init(GNUTLS_SERVER, expciphers, expmac, expkx,
966 if (tls_session == NULL)
967 return tls_error(US"tls_session_init", NULL,
968 gnutls_strerror(GNUTLS_E_MEMORY_ERROR));
970 /* Set context and tell client to go ahead, except in the case of TLS startup
971 on connection, where outputting anything now upsets the clients and tends to
972 make them disconnect. We need to have an explicit fflush() here, to force out
973 the response. Other smtp_printf() calls do not need it, because in non-TLS
974 mode, the fflush() happens when smtp_getc() is called. */
978 smtp_printf("220 TLS go ahead\r\n");
982 /* Now negotiate the TLS session. We put our own timer on it, since it seems
983 that the GnuTLS library doesn't. */
985 gnutls_transport_set_ptr2(tls_session, (gnutls_transport_ptr)fileno(smtp_in),
986 (gnutls_transport_ptr)fileno(smtp_out));
988 sigalrm_seen = FALSE;
989 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
990 rc = gnutls_handshake(tls_session);
995 tls_error(US"gnutls_handshake", NULL,
996 sigalrm_seen ? "timed out" : gnutls_strerror(rc));
998 /* It seems that, except in the case of a timeout, we have to close the
999 connection right here; otherwise if the other end is running OpenSSL it hangs
1000 until the server times out. */
1004 (void)fclose(smtp_out);
1005 (void)fclose(smtp_in);
1011 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1013 if (verify_requirement != VERIFY_NONE &&
1014 !verify_certificate(tls_session, &error))
1016 tls_error(US"certificate verification failed", NULL, error);
1020 construct_cipher_name(tls_session);
1022 /* TLS has been set up. Adjust the input functions to read via TLS,
1023 and initialize appropriately. */
1025 ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1026 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
1027 ssl_xfer_eof = ssl_xfer_error = 0;
1029 receive_getc = tls_getc;
1030 receive_ungetc = tls_ungetc;
1031 receive_feof = tls_feof;
1032 receive_ferror = tls_ferror;
1033 receive_smtp_buffered = tls_smtp_buffered;
1035 tls_active = fileno(smtp_out);
1043 /*************************************************
1044 * Start a TLS session in a client *
1045 *************************************************/
1047 /* Called from the smtp transport after STARTTLS has been accepted.
1050 fd the fd of the connection
1051 host connected host (for messages)
1052 addr the first address (not used)
1053 dhparam DH parameter file
1054 certificate certificate file
1055 privatekey private key file
1056 verify_certs file for certificate verify
1057 verify_crl CRL for verify
1058 require_ciphers list of allowed ciphers or NULL
1059 require_mac list of allowed MACs or NULL
1060 require_kx list of allowed key_exchange methods or NULL
1061 require_proto list of allowed protocols or NULL
1062 timeout startup timeout
1064 Returns: OK/DEFER/FAIL (because using common functions),
1065 but for a client, DEFER and FAIL have the same meaning
1069 tls_client_start(int fd, host_item *host, address_item *addr, uschar *dhparam,
1070 uschar *certificate, uschar *privatekey, uschar *verify_certs,
1071 uschar *verify_crl, uschar *require_ciphers, uschar *require_mac,
1072 uschar *require_kx, uschar *require_proto, int timeout)
1074 const gnutls_datum *server_certs;
1075 uschar *expciphers = NULL;
1076 uschar *expmac = NULL;
1077 uschar *expkx = NULL;
1078 uschar *expproto = NULL;
1080 unsigned int server_certs_size;
1083 DEBUG(D_tls) debug_printf("initializing GnuTLS as a client\n");
1085 verify_requirement = (verify_certs == NULL)? VERIFY_NONE : VERIFY_REQUIRED;
1086 rc = tls_init(host, certificate, privatekey, verify_certs, verify_crl);
1087 if (rc != OK) return rc;
1089 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers) ||
1090 !expand_check(require_mac, US"gnutls_require_mac", &expmac) ||
1091 !expand_check(require_kx, US"gnutls_require_kx", &expkx) ||
1092 !expand_check(require_proto, US"gnutls_require_proto", &expproto))
1095 tls_session = tls_session_init(GNUTLS_CLIENT, expciphers, expmac, expkx,
1098 if (tls_session == NULL)
1099 return tls_error(US "tls_session_init", host,
1100 gnutls_strerror(GNUTLS_E_MEMORY_ERROR));
1102 gnutls_transport_set_ptr(tls_session, (gnutls_transport_ptr)fd);
1104 /* There doesn't seem to be a built-in timeout on connection. */
1106 sigalrm_seen = FALSE;
1108 rc = gnutls_handshake(tls_session);
1112 return tls_error(US "gnutls_handshake", host,
1113 sigalrm_seen ? "timed out" : gnutls_strerror(rc));
1115 server_certs = gnutls_certificate_get_peers(tls_session, &server_certs_size);
1117 if (server_certs != NULL)
1120 gnutls_x509_crt gcert;
1122 gnutls_x509_crt_init(&gcert);
1123 tls_peerdn = US"unknown";
1125 if (gnutls_x509_crt_import(gcert, server_certs, GNUTLS_X509_FMT_DER) == 0)
1127 size_t bufsize = sizeof(buff);
1128 if (gnutls_x509_crt_get_dn(gcert, CS buff, &bufsize) >= 0)
1129 tls_peerdn = string_copy_malloc(buff);
1133 /* Should we also verify the hostname here? */
1135 if (verify_requirement != VERIFY_NONE &&
1136 !verify_certificate(tls_session, &error))
1137 return tls_error(US"certificate verification failed", host, error);
1139 construct_cipher_name(tls_session); /* Sets tls_cipher */
1146 /*************************************************
1147 * Deal with logging errors during I/O *
1148 *************************************************/
1150 /* We have to get the identity of the peer from saved data.
1153 ec the GnuTLS error code, or 0 if it's a local error
1154 when text identifying read or write
1155 text local error text when ec is 0
1161 record_io_error(int ec, uschar *when, uschar *text)
1165 if (ec == GNUTLS_E_FATAL_ALERT_RECEIVED)
1166 msg = string_sprintf("%s: %s", gnutls_strerror(ec),
1167 gnutls_alert_get_name(gnutls_alert_get(tls_session)));
1169 msg = gnutls_strerror(ec);
1171 tls_error(when, client_host, msg);
1176 /*************************************************
1177 * TLS version of getc *
1178 *************************************************/
1180 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
1181 it refills the buffer via the GnuTLS reading function.
1184 Returns: the next character or EOF
1190 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
1194 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%lx, %lx, %u)\n",
1195 (long) tls_session, (long) ssl_xfer_buffer, ssl_xfer_buffer_size);
1197 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1198 inbytes = gnutls_record_recv(tls_session, CS ssl_xfer_buffer,
1199 ssl_xfer_buffer_size);
1202 /* A zero-byte return appears to mean that the TLS session has been
1203 closed down, not that the socket itself has been closed down. Revert to
1204 non-TLS handling. */
1208 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1210 receive_getc = smtp_getc;
1211 receive_ungetc = smtp_ungetc;
1212 receive_feof = smtp_feof;
1213 receive_ferror = smtp_ferror;
1214 receive_smtp_buffered = smtp_buffered;
1216 gnutls_deinit(tls_session);
1225 /* Handle genuine errors */
1227 else if (inbytes < 0)
1229 record_io_error(inbytes, US"recv", NULL);
1233 #ifndef DISABLE_DKIM
1234 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
1236 ssl_xfer_buffer_hwm = inbytes;
1237 ssl_xfer_buffer_lwm = 0;
1241 /* Something in the buffer; return next uschar */
1243 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
1248 /*************************************************
1249 * Read bytes from TLS channel *
1250 *************************************************/
1257 Returns: the number of bytes read
1258 -1 after a failed read
1262 tls_read(uschar *buff, size_t len)
1266 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%lx, %lx, %u)\n",
1267 (long) tls_session, (long) buff, len);
1269 inbytes = gnutls_record_recv(tls_session, CS buff, len);
1270 if (inbytes > 0) return inbytes;
1273 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1275 else record_io_error(inbytes, US"recv", NULL);
1282 /*************************************************
1283 * Write bytes down TLS channel *
1284 *************************************************/
1291 Returns: the number of bytes after a successful write,
1292 -1 after a failed write
1296 tls_write(const uschar *buff, size_t len)
1301 DEBUG(D_tls) debug_printf("tls_do_write(%lx, %d)\n", (long) buff, left);
1304 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %lx, %d)\n", (long)buff,
1306 outbytes = gnutls_record_send(tls_session, CS buff, left);
1308 DEBUG(D_tls) debug_printf("outbytes=%d\n", outbytes);
1311 record_io_error(outbytes, US"send", NULL);
1316 record_io_error(0, US"send", US"TLS channel closed on write");
1329 /*************************************************
1330 * Close down a TLS session *
1331 *************************************************/
1333 /* This is also called from within a delivery subprocess forked from the
1334 daemon, to shut down the TLS library, without actually doing a shutdown (which
1335 would tamper with the TLS session in the parent process).
1337 Arguments: TRUE if gnutls_bye is to be called
1342 tls_close(BOOL shutdown)
1344 if (tls_active < 0) return; /* TLS was not active */
1348 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
1349 gnutls_bye(tls_session, GNUTLS_SHUT_WR);
1352 gnutls_deinit(tls_session);
1354 gnutls_global_deinit();
1362 /*************************************************
1363 * Report the library versions. *
1364 *************************************************/
1366 /* See a description in tls-openssl.c for an explanation of why this exists.
1368 Arguments: a FILE* to print the results to
1373 tls_version_report(FILE *f)
1375 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
1378 gnutls_check_version(NULL));
1381 /* End of tls-gnu.c */