1 /* $Cambridge: exim/src/src/tls-gnu.c,v 1.21 2009/06/10 07:34:04 tom Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) University of Cambridge 1995 - 2007 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* This module provides TLS (aka SSL) support for Exim using the GnuTLS
11 library. It is #included into tls.c when that library is used. The code herein
12 is based on a patch that was contributed by Nikos Mavroyanopoulos.
14 No cryptographic code is included in Exim. All this module does is to call
15 functions from the GnuTLS library. */
18 /* Heading stuff for GnuTLS */
20 #include <gnutls/gnutls.h>
21 #include <gnutls/x509.h>
24 #define UNKNOWN_NAME "unknown"
26 #define PARAM_SIZE 2*1024
29 /* Values for verify_requirment */
31 enum { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED };
33 /* Local static variables for GNUTLS */
35 static host_item *client_host;
37 static gnutls_dh_params dh_params = NULL;
39 static gnutls_certificate_server_credentials x509_cred = NULL;
40 static gnutls_session tls_session = NULL;
42 static char ssl_errstring[256];
44 static int ssl_session_timeout = 200;
45 static int verify_requirement;
47 /* Priorities for TLS algorithms to use. In each case there's a default table,
48 and space into which it can be copied and altered. */
50 static const int default_proto_priority[16] = {
55 static int proto_priority[16];
57 static const int default_kx_priority[16] = {
63 static int kx_priority[16];
65 static int default_cipher_priority[16] = {
66 GNUTLS_CIPHER_AES_256_CBC,
67 GNUTLS_CIPHER_AES_128_CBC,
68 GNUTLS_CIPHER_3DES_CBC,
69 GNUTLS_CIPHER_ARCFOUR_128,
72 static int cipher_priority[16];
74 static const int default_mac_priority[16] = {
79 static int mac_priority[16];
81 /* These two are currently not changeable. */
83 static const int comp_priority[16] = { GNUTLS_COMP_NULL, 0 };
84 static const int cert_type_priority[16] = { GNUTLS_CRT_X509, 0 };
86 /* Tables of priority names and equivalent numbers */
88 typedef struct pri_item {
94 static int tls1_codes[] = { GNUTLS_TLS1, 0 };
95 static int ssl3_codes[] = { GNUTLS_SSL3, 0 };
97 static pri_item proto_index[] = {
98 { US"TLS1", tls1_codes },
99 { US"SSL3", ssl3_codes }
103 static int kx_rsa_codes[] = { GNUTLS_KX_RSA,
104 GNUTLS_KX_DHE_RSA, 0 };
105 static int kx_dhe_codes[] = { GNUTLS_KX_DHE_DSS,
106 GNUTLS_KX_DHE_RSA, 0 };
107 static int kx_dhe_dss_codes[] = { GNUTLS_KX_DHE_DSS, 0 };
108 static int kx_dhe_rsa_codes[] = { GNUTLS_KX_DHE_RSA, 0 };
110 static pri_item kx_index[] = {
111 { US"DHE_DSS", kx_dhe_dss_codes },
112 { US"DHE_RSA", kx_dhe_rsa_codes },
113 { US"RSA", kx_rsa_codes },
114 { US"DHE", kx_dhe_codes }
118 static int arcfour_128_codes[] = { GNUTLS_CIPHER_ARCFOUR_128, 0 };
119 static int arcfour_40_codes[] = { GNUTLS_CIPHER_ARCFOUR_40, 0 };
120 static int arcfour_codes[] = { GNUTLS_CIPHER_ARCFOUR_128,
121 GNUTLS_CIPHER_ARCFOUR_40, 0 };
122 static int aes_256_codes[] = { GNUTLS_CIPHER_AES_256_CBC, 0 };
123 static int aes_128_codes[] = { GNUTLS_CIPHER_AES_128_CBC, 0 };
124 static int aes_codes[] = { GNUTLS_CIPHER_AES_256_CBC,
125 GNUTLS_CIPHER_AES_128_CBC, 0 };
126 static int des3_codes[] = { GNUTLS_CIPHER_3DES_CBC, 0 };
128 static pri_item cipher_index[] = {
129 { US"ARCFOUR_128", arcfour_128_codes },
130 { US"ARCFOUR_40", arcfour_40_codes },
131 { US"ARCFOUR", arcfour_codes },
132 { US"AES_256", aes_256_codes },
133 { US"AES_128", aes_128_codes },
134 { US"AES", aes_codes },
135 { US"3DES", des3_codes }
139 static int mac_sha_codes[] = { GNUTLS_MAC_SHA, 0 };
140 static int mac_md5_codes[] = { GNUTLS_MAC_MD5, 0 };
142 static pri_item mac_index[] = {
143 { US"SHA", mac_sha_codes },
144 { US"SHA1", mac_sha_codes },
145 { US"MD5", mac_md5_codes }
150 /*************************************************
152 *************************************************/
154 /* Called from lots of places when errors occur before actually starting to do
155 the TLS handshake, that is, while the session is still in clear. Always returns
156 DEFER for a server and FAIL for a client so that most calls can use "return
157 tls_error(...)" to do this processing and then give an appropriate return. A
158 single function is used for both server and client, because it is called from
159 some shared functions.
162 prefix text to include in the logged error
163 host NULL if setting up a server;
164 the connected host if setting up a client
165 msg additional error string (may be NULL)
166 usually obtained from gnutls_strerror()
168 Returns: OK/DEFER/FAIL
172 tls_error(uschar *prefix, host_item *host, const char *msg)
176 uschar *conn_info = smtp_get_connection_info();
177 if (strncmp(conn_info, "SMTP ", 5) == 0)
179 log_write(0, LOG_MAIN, "TLS error on %s (%s)%s%s",
180 conn_info, prefix, msg ? ": " : "", msg ? msg : "");
185 log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s)%s%s",
186 host->name, host->address, prefix, msg ? ": " : "", msg ? msg : "");
193 /*************************************************
194 * Verify certificate *
195 *************************************************/
197 /* Called after a successful handshake, when certificate verification is
198 required or optional, for both server and client.
201 session GNUTLS session
202 error where to put text giving a reason for failure
208 verify_certificate(gnutls_session session, const char **error)
211 uschar *dn_string = US"";
212 const gnutls_datum *cert;
213 unsigned int cert_size = 0;
217 /* Get the peer's certificate. If it sent one, extract it's DN, and then
218 attempt to verify the certificate. If no certificate is supplied, verification
219 is forced to fail. */
221 cert = gnutls_certificate_get_peers(session, &cert_size);
225 gnutls_x509_crt gcert;
227 gnutls_x509_crt_init(&gcert);
228 dn_string = US"unknown";
230 if (gnutls_x509_crt_import(gcert, cert, GNUTLS_X509_FMT_DER) == 0)
232 size_t bufsize = sizeof(buff);
233 if (gnutls_x509_crt_get_dn(gcert, CS buff, &bufsize) >= 0)
234 dn_string = string_copy_malloc(buff);
237 verify = gnutls_certificate_verify_peers(session);
241 DEBUG(D_tls) debug_printf("no peer certificate supplied\n");
242 verify = GNUTLS_CERT_INVALID;
243 *error = "not supplied";
246 /* Handle the result of verification. INVALID seems to be set as well
247 as REVOKED, but leave the test for both. */
249 if ((verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED)) != 0)
251 tls_certificate_verified = FALSE;
252 if (*error == NULL) *error = ((verify & GNUTLS_CERT_REVOKED) != 0)?
253 "revoked" : "invalid";
254 if (verify_requirement == VERIFY_REQUIRED)
256 DEBUG(D_tls) debug_printf("TLS certificate verification failed (%s): "
257 "peerdn=%s\n", *error, dn_string);
258 gnutls_alert_send(session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
259 return FALSE; /* reject */
261 DEBUG(D_tls) debug_printf("TLS certificate verify failure (%s) overridden "
262 "(host in tls_try_verify_hosts): peerdn=%s\n", *error, dn_string);
266 tls_certificate_verified = TRUE;
267 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=%s\n",
271 tls_peerdn = dn_string;
272 return TRUE; /* accept */
277 /*************************************************
278 * Setup up DH parameters *
279 *************************************************/
281 /* Generating the D-H parameters may take a long time. They only need to
282 be re-generated every so often, depending on security policy. What we do is to
283 keep these parameters in a file in the spool directory. If the file does not
284 exist, we generate them. This means that it is easy to cause a regeneration.
286 The new file is written as a temporary file and renamed, so that an incomplete
287 file is never present. If two processes both compute some new parameters, you
288 waste a bit of effort, but it doesn't seem worth messing around with locking to
292 host NULL for server, server for client (for error handling)
294 Returns: OK/DEFER/FAIL
298 init_dh(host_item *host)
303 uschar filename[200];
305 /* Initialize the data structures for holding the parameters */
307 ret = gnutls_dh_params_init(&dh_params);
308 if (ret < 0) return tls_error(US"init dh_params", host, gnutls_strerror(ret));
310 /* Set up the name of the cache file */
312 if (!string_format(filename, sizeof(filename), "%s/gnutls-params",
314 return tls_error(US"overlong filename", host, NULL);
316 /* Open the cache file for reading and if successful, read it and set up the
319 fd = Uopen(filename, O_RDONLY, 0);
323 if (fstat(fd, &statbuf) < 0)
326 return tls_error(US"TLS cache stat failed", host, strerror(errno));
329 m.size = statbuf.st_size;
330 m.data = malloc(m.size);
332 return tls_error(US"memory allocation failed", host, strerror(errno));
334 if (read(fd, m.data, m.size) != m.size)
335 return tls_error(US"TLS cache read failed", host, strerror(errno));
338 ret = gnutls_dh_params_import_pkcs3(dh_params, &m, GNUTLS_X509_FMT_PEM);
340 return tls_error(US"DH params import", host, gnutls_strerror(ret));
341 DEBUG(D_tls) debug_printf("read D-H parameters from file\n");
346 /* If the file does not exist, fall through to compute new data and cache it.
347 If there was any other opening error, it is serious. */
349 else if (errno == ENOENT)
353 debug_printf("parameter cache file %s does not exist\n", filename);
356 return tls_error(string_open_failed(errno, "%s for reading", filename),
359 /* If ret < 0, either the cache file does not exist, or the data it contains
360 is not useful. One particular case of this is when upgrading from an older
361 release of Exim in which the data was stored in a different format. We don't
362 try to be clever and support both formats; we just regenerate new data in this
367 uschar tempfilename[sizeof(filename) + 10];
369 DEBUG(D_tls) debug_printf("generating %d bit Diffie-Hellman key...\n",
371 ret = gnutls_dh_params_generate2(dh_params, DH_BITS);
372 if (ret < 0) return tls_error(US"D-H key generation", host, gnutls_strerror(ret));
374 /* Write the parameters to a file in the spool directory so that we
375 can use them from other Exim processes. */
377 sprintf(CS tempfilename, "%s-%d", filename, (int)getpid());
378 fd = Uopen(tempfilename, O_WRONLY|O_CREAT, 0400);
380 return tls_error(string_open_failed(errno, "%s for writing", filename),
382 (void)fchown(fd, exim_uid, exim_gid); /* Probably not necessary */
384 /* export the parameters in a format that can be generated using GNUTLS'
385 * certtool or other programs.
387 * The commands for certtool are:
388 * $ certtool --generate-dh-params --bits 1024 > params
392 m.data = malloc(m.size);
394 return tls_error(US"memory allocation failed", host, strerror(errno));
397 ret = gnutls_dh_params_export_pkcs3(dh_params, GNUTLS_X509_FMT_PEM, m.data,
400 return tls_error(US"DH params export", host, gnutls_strerror(ret));
402 m.size = Ustrlen(m.data);
404 if (write(fd, m.data, m.size) != m.size || write(fd, "\n", 1) != 1)
405 return tls_error(US"TLS cache write failed", host, strerror(errno));
410 if (rename(CS tempfilename, CS filename) < 0)
411 return tls_error(string_sprintf("failed to rename %s as %s",
412 tempfilename, filename), host, strerror(errno));
414 DEBUG(D_tls) debug_printf("wrote D-H parameters to file %s\n", filename);
417 DEBUG(D_tls) debug_printf("initialized D-H parameters\n");
424 /*************************************************
425 * Initialize for GnuTLS *
426 *************************************************/
428 /* Called from both server and client code. In the case of a server, errors
429 before actual TLS negotiation return DEFER.
432 host connected host, if client; NULL if server
433 certificate certificate file
434 privatekey private key file
438 Returns: OK/DEFER/FAIL
442 tls_init(host_item *host, uschar *certificate, uschar *privatekey, uschar *cas,
446 uschar *cert_expanded, *key_expanded, *cas_expanded, *crl_expanded;
450 rc = gnutls_global_init();
451 if (rc < 0) return tls_error(US"tls-init", host, gnutls_strerror(rc));
453 /* Create D-H parameters, or read them from the cache file. This function does
454 its own SMTP error messaging. */
457 if (rc != OK) return rc;
459 /* Create the credentials structure */
461 rc = gnutls_certificate_allocate_credentials(&x509_cred);
463 return tls_error(US"certificate_allocate_credentials",
464 host, gnutls_strerror(rc));
466 /* This stuff must be done for each session, because different certificates
467 may be required for different sessions. */
469 if (!expand_check(certificate, US"tls_certificate", &cert_expanded))
473 if (privatekey != NULL)
475 if (!expand_check(privatekey, US"tls_privatekey", &key_expanded))
479 /* If expansion was forced to fail, key_expanded will be NULL. If the result of
480 the expansion is an empty string, ignore it also, and assume that the private
481 key is in the same file as the certificate. */
483 if (key_expanded == NULL || *key_expanded == 0)
484 key_expanded = cert_expanded;
486 /* Set the certificate and private keys */
488 if (cert_expanded != NULL)
490 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
491 cert_expanded, key_expanded);
492 rc = gnutls_certificate_set_x509_key_file(x509_cred, CS cert_expanded,
493 CS key_expanded, GNUTLS_X509_FMT_PEM);
496 uschar *msg = string_sprintf("cert/key setup: cert=%s key=%s",
497 cert_expanded, key_expanded);
498 return tls_error(msg, host, gnutls_strerror(rc));
502 /* A certificate is mandatory in a server, but not in a client */
507 return tls_error(US"no TLS server certificate is specified", NULL, NULL);
508 DEBUG(D_tls) debug_printf("no TLS client certificate is specified\n");
511 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
512 provided. Experiment shows that, if the certificate file is empty, an unhelpful
513 error message is provided. However, if we just refrain from setting anything up
514 in that case, certificate verification fails, which seems to be the correct
521 if (!expand_check(cas, US"tls_verify_certificates", &cas_expanded))
524 if (stat(CS cas_expanded, &statbuf) < 0)
526 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
527 "(tls_verify_certificates): %s", cas_expanded, strerror(errno));
531 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
532 cas_expanded, statbuf.st_size);
534 /* If the cert file is empty, there's no point in loading the CRL file. */
536 if (statbuf.st_size > 0)
538 rc = gnutls_certificate_set_x509_trust_file(x509_cred, CS cas_expanded,
539 GNUTLS_X509_FMT_PEM);
540 if (rc < 0) return tls_error(US"setup_certs", host, gnutls_strerror(rc));
542 if (crl != NULL && *crl != 0)
544 if (!expand_check(crl, US"tls_crl", &crl_expanded))
546 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", crl_expanded);
547 rc = gnutls_certificate_set_x509_crl_file(x509_cred, CS crl_expanded,
548 GNUTLS_X509_FMT_PEM);
549 if (rc < 0) return tls_error(US"CRL setup", host, gnutls_strerror(rc));
554 /* Associate the parameters with the x509 credentials structure. */
556 gnutls_certificate_set_dh_params(x509_cred, dh_params);
558 DEBUG(D_tls) debug_printf("initialized certificate stuff\n");
565 /*************************************************
566 * Remove from a priority list *
567 *************************************************/
569 /* Cautiously written so that it will remove duplicates if present.
572 list a zero-terminated list
573 remove_list a zero-terminated list to be removed
579 remove_priority(int *list, int *remove_list)
581 for (; *remove_list != 0; remove_list++)
586 if (*p == *remove_list)
589 do { pp[0] = pp[1]; pp++; } while (*pp != 0);
598 /*************************************************
599 * Add to a priority list *
600 *************************************************/
602 /* Cautiously written to check the list size
605 list a zero-terminated list
606 list_max maximum offset in the list
607 add_list a zero-terminated list to be added
609 Returns: TRUE if OK; FALSE if list overflows
613 add_priority(int *list, int list_max, int *add_list)
616 while (list[next] != 0) next++;
617 while (*add_list != 0)
619 if (next >= list_max) return FALSE;
620 list[next++] = *add_list++;
628 /*************************************************
629 * Adjust a priority list *
630 *************************************************/
632 /* This function is called to adjust the lists of cipher algorithms, MAC
633 algorithms, key-exchange methods, and protocols.
636 plist the appropriate priority list
637 psize the length of the list
638 s the configuation string
639 index the index of recognized strings
640 isize the length of the index
643 which text for an error message
645 Returns: FALSE if the table overflows, else TRUE
649 set_priority(int *plist, int psize, uschar *s, pri_item *index, int isize,
656 while ((t = string_nextinlist(&s, &sep, big_buffer, big_buffer_size)) != NULL)
659 BOOL exclude = t[0] == '!';
660 if (first && !exclude) plist[0] = 0;
662 for (i = 0; i < isize; i++)
664 uschar *ss = strstric(t, index[i].name, FALSE);
667 uschar *endss = ss + Ustrlen(index[i].name);
668 if ((ss == t || !isalnum(ss[-1])) && !isalnum(*endss))
671 remove_priority(plist, index[i].values);
674 if (!add_priority(plist, psize, index[i].values))
676 log_write(0, LOG_MAIN|LOG_PANIC, "GnuTLS init failed: %s "
677 "priority table overflow", which);
689 debug_printf("adjusted %s priorities:", which);
690 while (*ptr != 0) debug_printf(" %d", *ptr++);
700 /*************************************************
701 * Initialize a single GNUTLS session *
702 *************************************************/
704 /* Set the algorithm, the db backend, whether to request certificates etc.
706 TLS in Exim was first implemented using OpenSSL. This has a function to which
707 you pass a list of cipher suites that are permitted/not permitted. GnuTLS works
708 differently. It operates using priority lists for the different components of
711 For compatibility of configuration, we scan a list of cipher suites and set
712 priorities therefrom. However, at the moment, we pay attention only to the bulk
716 side one of GNUTLS_SERVER, GNUTLS_CLIENT
717 expciphers expanded ciphers list or NULL
718 expmac expanded MAC list or NULL
719 expkx expanded key-exchange list or NULL
720 expproto expanded protocol list or NULL
722 Returns: a gnutls_session, or NULL if there is a problem
725 static gnutls_session
726 tls_session_init(int side, uschar *expciphers, uschar *expmac, uschar *expkx,
729 gnutls_session session;
731 gnutls_init(&session, side);
733 /* Initialize the lists of permitted protocols, key-exchange methods, ciphers,
736 memcpy(cipher_priority, default_cipher_priority, sizeof(cipher_priority));
737 memcpy(mac_priority, default_mac_priority, sizeof(mac_priority));
738 memcpy(kx_priority, default_kx_priority, sizeof(kx_priority));
739 memcpy(proto_priority, default_proto_priority, sizeof(proto_priority));
741 /* The names OpenSSL uses in tls_require_ciphers are of the form DES-CBC3-SHA,
742 using hyphen separators. GnuTLS uses underscore separators. So that I can use
743 either form for tls_require_ciphers in my tests, and also for general
744 convenience, we turn hyphens into underscores before scanning the list. */
746 if (expciphers != NULL)
748 uschar *s = expciphers;
749 while (*s != 0) { if (*s == '-') *s = '_'; s++; }
752 if ((expciphers != NULL &&
753 !set_priority(cipher_priority, sizeof(cipher_priority)/sizeof(int),
754 expciphers, cipher_index, sizeof(cipher_index)/sizeof(pri_item),
757 !set_priority(mac_priority, sizeof(mac_priority)/sizeof(int),
758 expmac, mac_index, sizeof(mac_index)/sizeof(pri_item),
761 !set_priority(kx_priority, sizeof(kx_priority)/sizeof(int),
762 expkx, kx_index, sizeof(kx_index)/sizeof(pri_item),
763 US"key-exchange")) ||
765 !set_priority(proto_priority, sizeof(proto_priority)/sizeof(int),
766 expproto, proto_index, sizeof(proto_index)/sizeof(pri_item),
769 gnutls_deinit(session);
773 /* Define the various priorities */
775 gnutls_cipher_set_priority(session, cipher_priority);
776 gnutls_compression_set_priority(session, comp_priority);
777 gnutls_kx_set_priority(session, kx_priority);
778 gnutls_protocol_set_priority(session, proto_priority);
779 gnutls_mac_set_priority(session, mac_priority);
781 gnutls_cred_set(session, GNUTLS_CRD_CERTIFICATE, x509_cred);
783 gnutls_dh_set_prime_bits(session, DH_BITS);
785 /* Request or demand a certificate of the peer, as configured. This will
786 happen only in a server. */
788 if (verify_requirement != VERIFY_NONE)
789 gnutls_certificate_server_set_request(session,
790 (verify_requirement == VERIFY_OPTIONAL)?
791 GNUTLS_CERT_REQUEST : GNUTLS_CERT_REQUIRE);
793 gnutls_db_set_cache_expiration(session, ssl_session_timeout);
795 DEBUG(D_tls) debug_printf("initialized GnuTLS session\n");
801 /*************************************************
802 * Get name of cipher in use *
803 *************************************************/
805 /* The answer is left in a static buffer, and tls_cipher is set to point
808 Argument: pointer to a GnuTLS session
813 construct_cipher_name(gnutls_session session)
815 static uschar cipherbuf[256];
817 int bits, c, kx, mac;
820 US gnutls_protocol_get_name(gnutls_protocol_get_version(session)));
821 if (Ustrncmp(ver, "TLS ", 4) == 0) ver[3] = '-'; /* Don't want space */
823 c = gnutls_cipher_get(session);
824 bits = gnutls_cipher_get_key_size(c);
826 mac = gnutls_mac_get(session);
827 kx = gnutls_kx_get(session);
829 string_format(cipherbuf, sizeof(cipherbuf), "%s:%s:%u", ver,
830 gnutls_cipher_suite_get_name(kx, c, mac), bits);
831 tls_cipher = cipherbuf;
833 DEBUG(D_tls) debug_printf("cipher: %s\n", cipherbuf);
838 /*************************************************
839 * Start a TLS session in a server *
840 *************************************************/
842 /* This is called when Exim is running as a server, after having received
843 the STARTTLS command. It must respond to that command, and then negotiate
847 require_ciphers list of allowed ciphers or NULL
848 require_mac list of allowed MACs or NULL
849 require_kx list of allowed key_exchange methods or NULL
850 require_proto list of allowed protocols or NULL
852 Returns: OK on success
853 DEFER for errors before the start of the negotiation
854 FAIL for errors during the negotation; the server can't
859 tls_server_start(uschar *require_ciphers, uschar *require_mac,
860 uschar *require_kx, uschar *require_proto)
864 uschar *expciphers = NULL;
865 uschar *expmac = NULL;
866 uschar *expkx = NULL;
867 uschar *expproto = NULL;
869 /* Check for previous activation */
873 tls_error("STARTTLS received after TLS started", NULL, "");
874 smtp_printf("554 Already in TLS\r\n");
878 /* Initialize the library. If it fails, it will already have logged the error
879 and sent an SMTP response. */
881 DEBUG(D_tls) debug_printf("initializing GnuTLS as a server\n");
883 rc = tls_init(NULL, tls_certificate, tls_privatekey, tls_verify_certificates,
885 if (rc != OK) return rc;
887 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers) ||
888 !expand_check(require_mac, US"gnutls_require_mac", &expmac) ||
889 !expand_check(require_kx, US"gnutls_require_kx", &expkx) ||
890 !expand_check(require_proto, US"gnutls_require_proto", &expproto))
893 /* If this is a host for which certificate verification is mandatory or
894 optional, set up appropriately. */
896 tls_certificate_verified = FALSE;
897 verify_requirement = VERIFY_NONE;
899 if (verify_check_host(&tls_verify_hosts) == OK)
900 verify_requirement = VERIFY_REQUIRED;
901 else if (verify_check_host(&tls_try_verify_hosts) == OK)
902 verify_requirement = VERIFY_OPTIONAL;
904 /* Prepare for new connection */
906 tls_session = tls_session_init(GNUTLS_SERVER, expciphers, expmac, expkx,
908 if (tls_session == NULL)
909 return tls_error(US"tls_session_init", NULL,
910 gnutls_strerror(GNUTLS_E_MEMORY_ERROR));
912 /* Set context and tell client to go ahead, except in the case of TLS startup
913 on connection, where outputting anything now upsets the clients and tends to
914 make them disconnect. We need to have an explicit fflush() here, to force out
915 the response. Other smtp_printf() calls do not need it, because in non-TLS
916 mode, the fflush() happens when smtp_getc() is called. */
920 smtp_printf("220 TLS go ahead\r\n");
924 /* Now negotiate the TLS session. We put our own timer on it, since it seems
925 that the GnuTLS library doesn't. */
927 gnutls_transport_set_ptr2(tls_session, (gnutls_transport_ptr)fileno(smtp_in),
928 (gnutls_transport_ptr)fileno(smtp_out));
930 sigalrm_seen = FALSE;
931 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
932 rc = gnutls_handshake(tls_session);
937 tls_error(US"gnutls_handshake", NULL,
938 sigalrm_seen ? "timed out" : gnutls_strerror(rc));
940 /* It seems that, except in the case of a timeout, we have to close the
941 connection right here; otherwise if the other end is running OpenSSL it hangs
942 until the server times out. */
946 (void)fclose(smtp_out);
947 (void)fclose(smtp_in);
953 DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
955 if (verify_requirement != VERIFY_NONE &&
956 !verify_certificate(tls_session, &error))
958 tls_error(US"certificate verification failed", NULL, error);
962 construct_cipher_name(tls_session);
964 /* TLS has been set up. Adjust the input functions to read via TLS,
965 and initialize appropriately. */
967 ssl_xfer_buffer = store_malloc(ssl_xfer_buffer_size);
968 ssl_xfer_buffer_lwm = ssl_xfer_buffer_hwm = 0;
969 ssl_xfer_eof = ssl_xfer_error = 0;
971 receive_getc = tls_getc;
972 receive_ungetc = tls_ungetc;
973 receive_feof = tls_feof;
974 receive_ferror = tls_ferror;
975 receive_smtp_buffered = tls_smtp_buffered;
977 tls_active = fileno(smtp_out);
985 /*************************************************
986 * Start a TLS session in a client *
987 *************************************************/
989 /* Called from the smtp transport after STARTTLS has been accepted.
992 fd the fd of the connection
993 host connected host (for messages)
994 addr the first address (not used)
995 dhparam DH parameter file
996 certificate certificate file
997 privatekey private key file
998 verify_certs file for certificate verify
999 verify_crl CRL for verify
1000 require_ciphers list of allowed ciphers or NULL
1001 require_mac list of allowed MACs or NULL
1002 require_kx list of allowed key_exchange methods or NULL
1003 require_proto list of allowed protocols or NULL
1004 timeout startup timeout
1006 Returns: OK/DEFER/FAIL (because using common functions),
1007 but for a client, DEFER and FAIL have the same meaning
1011 tls_client_start(int fd, host_item *host, address_item *addr, uschar *dhparam,
1012 uschar *certificate, uschar *privatekey, uschar *verify_certs,
1013 uschar *verify_crl, uschar *require_ciphers, uschar *require_mac,
1014 uschar *require_kx, uschar *require_proto, int timeout)
1016 const gnutls_datum *server_certs;
1017 uschar *expciphers = NULL;
1018 uschar *expmac = NULL;
1019 uschar *expkx = NULL;
1020 uschar *expproto = NULL;
1022 unsigned int server_certs_size;
1025 DEBUG(D_tls) debug_printf("initializing GnuTLS as a client\n");
1027 verify_requirement = (verify_certs == NULL)? VERIFY_NONE : VERIFY_REQUIRED;
1028 rc = tls_init(host, certificate, privatekey, verify_certs, verify_crl);
1029 if (rc != OK) return rc;
1031 if (!expand_check(require_ciphers, US"tls_require_ciphers", &expciphers) ||
1032 !expand_check(require_mac, US"gnutls_require_mac", &expmac) ||
1033 !expand_check(require_kx, US"gnutls_require_kx", &expkx) ||
1034 !expand_check(require_proto, US"gnutls_require_proto", &expproto))
1037 tls_session = tls_session_init(GNUTLS_CLIENT, expciphers, expmac, expkx,
1040 if (tls_session == NULL)
1041 return tls_error(US "tls_session_init", host,
1042 gnutls_strerror(GNUTLS_E_MEMORY_ERROR));
1044 gnutls_transport_set_ptr(tls_session, (gnutls_transport_ptr)fd);
1046 /* There doesn't seem to be a built-in timeout on connection. */
1048 sigalrm_seen = FALSE;
1050 rc = gnutls_handshake(tls_session);
1054 return tls_error(US "gnutls_handshake", host,
1055 sigalrm_seen ? "timed out" : gnutls_strerror(rc));
1057 server_certs = gnutls_certificate_get_peers(tls_session, &server_certs_size);
1059 if (server_certs != NULL)
1062 gnutls_x509_crt gcert;
1064 gnutls_x509_crt_init(&gcert);
1065 tls_peerdn = US"unknown";
1067 if (gnutls_x509_crt_import(gcert, server_certs, GNUTLS_X509_FMT_DER) == 0)
1069 size_t bufsize = sizeof(buff);
1070 if (gnutls_x509_crt_get_dn(gcert, CS buff, &bufsize) >= 0)
1071 tls_peerdn = string_copy_malloc(buff);
1075 /* Should we also verify the hostname here? */
1077 if (verify_requirement != VERIFY_NONE &&
1078 !verify_certificate(tls_session, &error))
1079 return tls_error(US"certificate verification failed", host, error);
1081 construct_cipher_name(tls_session); /* Sets tls_cipher */
1088 /*************************************************
1089 * Deal with logging errors during I/O *
1090 *************************************************/
1092 /* We have to get the identity of the peer from saved data.
1095 ec the GnuTLS error code, or 0 if it's a local error
1096 when text identifying read or write
1097 text local error text when ec is 0
1103 record_io_error(int ec, uschar *when, uschar *text)
1107 if (ec == GNUTLS_E_FATAL_ALERT_RECEIVED)
1108 msg = string_sprintf("%s: %s", gnutls_strerror(ec),
1109 gnutls_alert_get_name(gnutls_alert_get(tls_session)));
1111 msg = gnutls_strerror(ec);
1113 tls_error(when, client_host, msg);
1118 /*************************************************
1119 * TLS version of getc *
1120 *************************************************/
1122 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
1123 it refills the buffer via the GnuTLS reading function.
1126 Returns: the next character or EOF
1132 if (ssl_xfer_buffer_lwm >= ssl_xfer_buffer_hwm)
1136 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%lx, %lx, %u)\n",
1137 (long) tls_session, (long) ssl_xfer_buffer, ssl_xfer_buffer_size);
1139 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1140 inbytes = gnutls_record_recv(tls_session, CS ssl_xfer_buffer,
1141 ssl_xfer_buffer_size);
1144 /* A zero-byte return appears to mean that the TLS session has been
1145 closed down, not that the socket itself has been closed down. Revert to
1146 non-TLS handling. */
1150 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1152 receive_getc = smtp_getc;
1153 receive_ungetc = smtp_ungetc;
1154 receive_feof = smtp_feof;
1155 receive_ferror = smtp_ferror;
1156 receive_smtp_buffered = smtp_buffered;
1158 gnutls_deinit(tls_session);
1167 /* Handle genuine errors */
1169 else if (inbytes < 0)
1171 record_io_error(inbytes, US"recv", NULL);
1175 #ifndef DISABLE_DKIM
1176 dkim_exim_verify_feed(ssl_xfer_buffer, inbytes);
1178 ssl_xfer_buffer_hwm = inbytes;
1179 ssl_xfer_buffer_lwm = 0;
1183 /* Something in the buffer; return next uschar */
1185 return ssl_xfer_buffer[ssl_xfer_buffer_lwm++];
1190 /*************************************************
1191 * Read bytes from TLS channel *
1192 *************************************************/
1199 Returns: the number of bytes read
1200 -1 after a failed read
1204 tls_read(uschar *buff, size_t len)
1208 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%lx, %lx, %u)\n",
1209 (long) tls_session, (long) buff, len);
1211 inbytes = gnutls_record_recv(tls_session, CS buff, len);
1212 if (inbytes > 0) return inbytes;
1215 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1217 else record_io_error(inbytes, US"recv", NULL);
1224 /*************************************************
1225 * Write bytes down TLS channel *
1226 *************************************************/
1233 Returns: the number of bytes after a successful write,
1234 -1 after a failed write
1238 tls_write(const uschar *buff, size_t len)
1243 DEBUG(D_tls) debug_printf("tls_do_write(%lx, %d)\n", (long) buff, left);
1246 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %lx, %d)\n", (long)buff,
1248 outbytes = gnutls_record_send(tls_session, CS buff, left);
1250 DEBUG(D_tls) debug_printf("outbytes=%d\n", outbytes);
1253 record_io_error(outbytes, US"send", NULL);
1258 record_io_error(0, US"send", US"TLS channel closed on write");
1271 /*************************************************
1272 * Close down a TLS session *
1273 *************************************************/
1275 /* This is also called from within a delivery subprocess forked from the
1276 daemon, to shut down the TLS library, without actually doing a shutdown (which
1277 would tamper with the TLS session in the parent process).
1279 Arguments: TRUE if gnutls_bye is to be called
1284 tls_close(BOOL shutdown)
1286 if (tls_active < 0) return; /* TLS was not active */
1290 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
1291 gnutls_bye(tls_session, GNUTLS_SHUT_WR);
1294 gnutls_deinit(tls_session);
1296 gnutls_global_deinit();
1301 /* End of tls-gnu.c */