Imported Upstream version 4.84
[hcoop/debian/exim4.git] / src / tls-gnu.c
CommitLineData
420a0d19
CE
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
5/* Copyright (c) University of Cambridge 1995 - 2014 */
6/* See the file NOTICE for conditions of use and distribution. */
7
8/* Copyright (c) Phil Pennock 2012 */
9
10/* This file provides TLS/SSL support for Exim using the GnuTLS library,
11one of the available supported implementations. This file is #included into
12tls.c when USE_GNUTLS has been set.
13
14The code herein is a revamp of GnuTLS integration using the current APIs; the
15original tls-gnu.c was based on a patch which was contributed by Nikos
16Mavroyanopoulos. The revamp is partially a rewrite, partially cut&paste as
17appropriate.
18
19APIs current as of GnuTLS 2.12.18; note that the GnuTLS manual is for GnuTLS 3,
20which is not widely deployed by OS vendors. Will note issues below, which may
21assist in updating the code in the future. Another sources of hints is
22mod_gnutls for Apache (SNI callback registration and handling).
23
24Keeping client and server variables more split than before and is currently
25the norm, in anticipation of TLS in ACL callouts.
26
27I wanted to switch to gnutls_certificate_set_verify_function() so that
28certificate rejection could happen during handshake where it belongs, rather
29than 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.
31
32(I wasn't looking for libraries quite that old, when updating to get rid of
33compiler warnings of deprecated APIs. If it turns out that a lot of the rest
34require current GnuTLS, then we'll drop support for the ancient libraries).
35*/
36
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>
45#endif
46#if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
47# warning "GnuTLS library version too old; define DISABLE_OCSP in Makefile"
48# define DISABLE_OCSP
49#endif
50
51#ifndef DISABLE_OCSP
52# include <gnutls/ocsp.h>
53#endif
54
55/* GnuTLS 2 vs 3
56
57GnuTLS 3 only:
58 gnutls_global_set_audit_log_function()
59
60Changes:
61 gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
62*/
63
64/* Local static variables for GnuTLS */
65
66/* Values for verify_requirement */
67
68enum peer_verify_requirement
69 { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED
70#ifdef EXPERIMENTAL_CERTNAMES
71 ,VERIFY_WITHHOST
72#endif
73 };
74
75/* This holds most state for server or client; with this, we can set up an
76outbound TLS-enabled connection in an ACL callout, while not stomping all
77over the TLS variables available for expansion.
78
79Some of these correspond to variables in globals.c; those variables will
80be set to point to content in one of these instances, as appropriate for
81the stage of the process lifetime.
82
83Not handled here: global tls_channelbinding_b64.
84*/
85
86typedef struct exim_gnutls_state {
87 gnutls_session_t session;
88 gnutls_certificate_credentials_t x509_cred;
89 gnutls_priority_t priority_cache;
90 enum peer_verify_requirement verify_requirement;
91 int fd_in;
92 int fd_out;
93 BOOL peer_cert_verified;
94 BOOL trigger_sni_changes;
95 BOOL have_set_peerdn;
96 const struct host_item *host;
97 gnutls_x509_crt_t peercert;
98 uschar *peerdn;
99 uschar *ciphersuite;
100 uschar *received_sni;
101
102 const uschar *tls_certificate;
103 const uschar *tls_privatekey;
104 const uschar *tls_sni; /* client send only, not received */
105 const uschar *tls_verify_certificates;
106 const uschar *tls_crl;
107 const uschar *tls_require_ciphers;
108
109 uschar *exp_tls_certificate;
110 uschar *exp_tls_privatekey;
111 uschar *exp_tls_verify_certificates;
112 uschar *exp_tls_crl;
113 uschar *exp_tls_require_ciphers;
114 uschar *exp_tls_ocsp_file;
115#ifdef EXPERIMENTAL_CERTNAMES
116 uschar *exp_tls_verify_cert_hostnames;
117#endif
118
119 tls_support *tlsp; /* set in tls_init() */
120
121 uschar *xfer_buffer;
122 int xfer_buffer_lwm;
123 int xfer_buffer_hwm;
124 int xfer_eof;
125 int xfer_error;
126} exim_gnutls_state_st;
127
128static const exim_gnutls_state_st exim_gnutls_state_init = {
129 NULL, NULL, NULL, VERIFY_NONE, -1, -1, FALSE, FALSE, FALSE,
130 NULL, NULL, NULL, NULL,
131 NULL, NULL, NULL, NULL, NULL, NULL,
132 NULL, NULL, NULL, NULL, NULL, NULL, NULL,
133#ifdef EXPERIMENTAL_CERTNAMES
134 NULL,
135#endif
136 NULL,
137 NULL, 0, 0, 0, 0,
138};
139
140/* Not only do we have our own APIs which don't pass around state, assuming
141it's held in globals, GnuTLS doesn't appear to let us register callback data
142for callbacks, or as part of the session, so we have to keep a "this is the
143context we're currently dealing with" pointer and rely upon being
144single-threaded to keep from processing data on an inbound TLS connection while
145talking to another TLS connection for an outbound check. This does mean that
146there's no way for heart-beats to be responded to, for the duration of the
147second connection. */
148
149static exim_gnutls_state_st state_server, state_client;
150
151/* dh_params are initialised once within the lifetime of a process using TLS;
152if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
153don't want to repeat this. */
154
155static gnutls_dh_params_t dh_server_params = NULL;
156
157/* No idea how this value was chosen; preserving it. Default is 3600. */
158
159static const int ssl_session_timeout = 200;
160
161static const char * const exim_default_gnutls_priority = "NORMAL";
162
163/* Guard library core initialisation */
164
165static BOOL exim_gnutls_base_init_done = FALSE;
166
167
168/* ------------------------------------------------------------------------ */
169/* macros */
170
171#define MAX_HOST_LEN 255
172
173/* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
174the library logging; a value less than 0 disables the calls to set up logging
175callbacks. */
176#ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
177#define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
178#endif
179
180#ifndef EXIM_CLIENT_DH_MIN_BITS
181#define EXIM_CLIENT_DH_MIN_BITS 1024
182#endif
183
184/* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
185can ask for a bit-strength. Without that, we stick to the constant we had
186before, for now. */
187#ifndef EXIM_SERVER_DH_BITS_PRE2_12
188#define EXIM_SERVER_DH_BITS_PRE2_12 1024
189#endif
190
191#define exim_gnutls_err_check(Label) do { \
192 if (rc != GNUTLS_E_SUCCESS) { return tls_error((Label), gnutls_strerror(rc), host); } } while (0)
193
194#define expand_check_tlsvar(Varname) expand_check(state->Varname, US #Varname, &state->exp_##Varname)
195
196#if GNUTLS_VERSION_NUMBER >= 0x020c00
197# define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
198# define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
199# define HAVE_GNUTLS_RND
200/* The security fix we provide with the gnutls_allow_auto_pkcs11 option
201 * (4.82 PP/09) introduces a compatibility regression. The symbol simply
202 * isn't available sometimes, so this needs to become a conditional
203 * compilation; the sanest way to deal with this being a problem on
204 * older OSes is to block it in the Local/Makefile with this compiler
205 * definition */
206# ifndef AVOID_GNUTLS_PKCS11
207# define HAVE_GNUTLS_PKCS11
208# endif /* AVOID_GNUTLS_PKCS11 */
209#endif
210
211
212
213
214/* ------------------------------------------------------------------------ */
215/* Callback declarations */
216
217#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
218static void exim_gnutls_logger_cb(int level, const char *message);
219#endif
220
221static int exim_sni_handling_cb(gnutls_session_t session);
222
223#ifndef DISABLE_OCSP
224static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
225 gnutls_datum_t * ocsp_response);
226#endif
227
228
229
230/* ------------------------------------------------------------------------ */
231/* Static functions */
232
233/*************************************************
234* Handle TLS error *
235*************************************************/
236
237/* Called from lots of places when errors occur before actually starting to do
238the TLS handshake, that is, while the session is still in clear. Always returns
239DEFER for a server and FAIL for a client so that most calls can use "return
240tls_error(...)" to do this processing and then give an appropriate return. A
241single function is used for both server and client, because it is called from
242some shared functions.
243
244Argument:
245 prefix text to include in the logged error
246 msg additional error string (may be NULL)
247 usually obtained from gnutls_strerror()
248 host NULL if setting up a server;
249 the connected host if setting up a client
250
251Returns: OK/DEFER/FAIL
252*/
253
254static int
255tls_error(const uschar *prefix, const char *msg, const host_item *host)
256{
257if (host)
258 {
259 log_write(0, LOG_MAIN, "TLS error on connection to %s [%s] (%s)%s%s",
260 host->name, host->address, prefix, msg ? ": " : "", msg ? msg : "");
261 return FAIL;
262 }
263else
264 {
265 uschar *conn_info = smtp_get_connection_info();
266 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0)
267 conn_info += 5;
268 log_write(0, LOG_MAIN, "TLS error on %s (%s)%s%s",
269 conn_info, prefix, msg ? ": " : "", msg ? msg : "");
270 return DEFER;
271 }
272}
273
274
275
276
277/*************************************************
278* Deal with logging errors during I/O *
279*************************************************/
280
281/* We have to get the identity of the peer from saved data.
282
283Argument:
284 state the current GnuTLS exim state container
285 rc the GnuTLS error code, or 0 if it's a local error
286 when text identifying read or write
287 text local error text when ec is 0
288
289Returns: nothing
290*/
291
292static void
293record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
294{
295const char *msg;
296
297if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
298 msg = CS string_sprintf("%s: %s", US gnutls_strerror(rc),
299 US gnutls_alert_get_name(gnutls_alert_get(state->session)));
300else
301 msg = gnutls_strerror(rc);
302
303tls_error(when, msg, state->host);
304}
305
306
307
308
309/*************************************************
310* Set various Exim expansion vars *
311*************************************************/
312
313#define exim_gnutls_cert_err(Label) \
314 do \
315 { \
316 if (rc != GNUTLS_E_SUCCESS) \
317 { \
318 DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", \
319 (Label), gnutls_strerror(rc)); \
320 return rc; \
321 } \
322 } while (0)
323
324static int
325import_cert(const gnutls_datum * cert, gnutls_x509_crt_t * crtp)
326{
327int rc;
328
329rc = gnutls_x509_crt_init(crtp);
330exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
331
332rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
333exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
334
335return rc;
336}
337
338#undef exim_gnutls_cert_err
339
340
341/* We set various Exim global variables from the state, once a session has
342been established. With TLS callouts, may need to change this to stack
343variables, or just re-call it with the server state after client callout
344has finished.
345
346Make sure anything set here is unset in tls_getc().
347
348Sets:
349 tls_active fd
350 tls_bits strength indicator
351 tls_certificate_verified bool indicator
352 tls_channelbinding_b64 for some SASL mechanisms
353 tls_cipher a string
354 tls_peercert pointer to library internal
355 tls_peerdn a string
356 tls_sni a (UTF-8) string
357 tls_ourcert pointer to library internal
358
359Argument:
360 state the relevant exim_gnutls_state_st *
361*/
362
363static void
364extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
365{
366gnutls_cipher_algorithm_t cipher;
367#ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
368int old_pool;
369int rc;
370gnutls_datum_t channel;
371#endif
372tls_support * tlsp = state->tlsp;
373
374tlsp->active = state->fd_out;
375
376cipher = gnutls_cipher_get(state->session);
377/* returns size in "bytes" */
378tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
379
380tlsp->cipher = state->ciphersuite;
381
382DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
383
384tlsp->certificate_verified = state->peer_cert_verified;
385
386/* note that tls_channelbinding_b64 is not saved to the spool file, since it's
387only available for use for authenticators while this TLS session is running. */
388
389tls_channelbinding_b64 = NULL;
390#ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
391channel.data = NULL;
392channel.size = 0;
393rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel);
394if (rc) {
395 DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc));
396} else {
397 old_pool = store_pool;
398 store_pool = POOL_PERM;
399 tls_channelbinding_b64 = auth_b64encode(channel.data, (int)channel.size);
400 store_pool = old_pool;
401 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
402}
403#endif
404
405/* peercert is set in peer_status() */
406tlsp->peerdn = state->peerdn;
407tlsp->sni = state->received_sni;
408
409/* record our certificate */
410 {
411 const gnutls_datum * cert = gnutls_certificate_get_ours(state->session);
412 gnutls_x509_crt_t crt;
413
414 tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
415 }
416}
417
418
419
420
421/*************************************************
422* Setup up DH parameters *
423*************************************************/
424
425/* Generating the D-H parameters may take a long time. They only need to
426be re-generated every so often, depending on security policy. What we do is to
427keep these parameters in a file in the spool directory. If the file does not
428exist, we generate them. This means that it is easy to cause a regeneration.
429
430The new file is written as a temporary file and renamed, so that an incomplete
431file is never present. If two processes both compute some new parameters, you
432waste a bit of effort, but it doesn't seem worth messing around with locking to
433prevent this.
434
435Returns: OK/DEFER/FAIL
436*/
437
438static int
439init_server_dh(void)
440{
441int fd, rc;
442unsigned int dh_bits;
443gnutls_datum m;
444uschar filename_buf[PATH_MAX];
445uschar *filename = NULL;
446size_t sz;
447uschar *exp_tls_dhparam;
448BOOL use_file_in_spool = FALSE;
449BOOL use_fixed_file = FALSE;
450host_item *host = NULL; /* dummy for macros */
451
452DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
453
454rc = gnutls_dh_params_init(&dh_server_params);
455exim_gnutls_err_check(US"gnutls_dh_params_init");
456
457m.data = NULL;
458m.size = 0;
459
460if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam))
461 return DEFER;
462
463if (!exp_tls_dhparam)
464 {
465 DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
466 m.data = US std_dh_prime_default();
467 m.size = Ustrlen(m.data);
468 }
469else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
470 use_file_in_spool = TRUE;
471else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
472 {
473 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
474 return OK;
475 }
476else if (exp_tls_dhparam[0] != '/')
477 {
478 m.data = US std_dh_prime_named(exp_tls_dhparam);
479 if (m.data == NULL)
480 return tls_error(US"No standard prime named", CS exp_tls_dhparam, NULL);
481 m.size = Ustrlen(m.data);
482 }
483else
484 {
485 use_fixed_file = TRUE;
486 filename = exp_tls_dhparam;
487 }
488
489if (m.data)
490 {
491 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
492 exim_gnutls_err_check(US"gnutls_dh_params_import_pkcs3");
493 DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
494 return OK;
495 }
496
497#ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
498/* If you change this constant, also change dh_param_fn_ext so that we can use a
499different filename and ensure we have sufficient bits. */
500dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL);
501if (!dh_bits)
502 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL);
503DEBUG(D_tls)
504 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
505 dh_bits);
506#else
507dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
508DEBUG(D_tls)
509 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
510 dh_bits);
511#endif
512
513/* Some clients have hard-coded limits. */
514if (dh_bits > tls_dh_max_bits)
515 {
516 DEBUG(D_tls)
517 debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
518 tls_dh_max_bits);
519 dh_bits = tls_dh_max_bits;
520 }
521
522if (use_file_in_spool)
523 {
524 if (!string_format(filename_buf, sizeof(filename_buf),
525 "%s/gnutls-params-%d", spool_directory, dh_bits))
526 return tls_error(US"overlong filename", NULL, NULL);
527 filename = filename_buf;
528 }
529
530/* Open the cache file for reading and if successful, read it and set up the
531parameters. */
532
533fd = Uopen(filename, O_RDONLY, 0);
534if (fd >= 0)
535 {
536 struct stat statbuf;
537 FILE *fp;
538 int saved_errno;
539
540 if (fstat(fd, &statbuf) < 0) /* EIO */
541 {
542 saved_errno = errno;
543 (void)close(fd);
544 return tls_error(US"TLS cache stat failed", strerror(saved_errno), NULL);
545 }
546 if (!S_ISREG(statbuf.st_mode))
547 {
548 (void)close(fd);
549 return tls_error(US"TLS cache not a file", NULL, NULL);
550 }
551 fp = fdopen(fd, "rb");
552 if (!fp)
553 {
554 saved_errno = errno;
555 (void)close(fd);
556 return tls_error(US"fdopen(TLS cache stat fd) failed",
557 strerror(saved_errno), NULL);
558 }
559
560 m.size = statbuf.st_size;
561 m.data = malloc(m.size);
562 if (m.data == NULL)
563 {
564 fclose(fp);
565 return tls_error(US"malloc failed", strerror(errno), NULL);
566 }
567 sz = fread(m.data, m.size, 1, fp);
568 if (!sz)
569 {
570 saved_errno = errno;
571 fclose(fp);
572 free(m.data);
573 return tls_error(US"fread failed", strerror(saved_errno), NULL);
574 }
575 fclose(fp);
576
577 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
578 free(m.data);
579 exim_gnutls_err_check(US"gnutls_dh_params_import_pkcs3");
580 DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
581 }
582
583/* If the file does not exist, fall through to compute new data and cache it.
584If there was any other opening error, it is serious. */
585
586else if (errno == ENOENT)
587 {
588 rc = -1;
589 DEBUG(D_tls)
590 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
591 }
592else
593 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
594 NULL, NULL);
595
596/* If ret < 0, either the cache file does not exist, or the data it contains
597is not useful. One particular case of this is when upgrading from an older
598release of Exim in which the data was stored in a different format. We don't
599try to be clever and support both formats; we just regenerate new data in this
600case. */
601
602if (rc < 0)
603 {
604 uschar *temp_fn;
605 unsigned int dh_bits_gen = dh_bits;
606
607 if ((PATH_MAX - Ustrlen(filename)) < 10)
608 return tls_error(US"Filename too long to generate replacement",
609 CS filename, NULL);
610
611 temp_fn = string_copy(US "%s.XXXXXXX");
612 fd = mkstemp(CS temp_fn); /* modifies temp_fn */
613 if (fd < 0)
614 return tls_error(US"Unable to open temp file", strerror(errno), NULL);
615 (void)fchown(fd, exim_uid, exim_gid); /* Probably not necessary */
616
617 /* GnuTLS overshoots!
618 * If we ask for 2236, we might get 2237 or more.
619 * But there's no way to ask GnuTLS how many bits there really are.
620 * We can ask how many bits were used in a TLS session, but that's it!
621 * The prime itself is hidden behind too much abstraction.
622 * So we ask for less, and proceed on a wing and a prayer.
623 * First attempt, subtracted 3 for 2233 and got 2240.
624 */
625 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
626 {
627 dh_bits_gen = dh_bits - 10;
628 DEBUG(D_tls)
629 debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
630 dh_bits_gen);
631 }
632
633 DEBUG(D_tls)
634 debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
635 dh_bits_gen);
636 rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen);
637 exim_gnutls_err_check(US"gnutls_dh_params_generate2");
638
639 /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
640 and I confirmed that a NULL call to get the size first is how the GnuTLS
641 sample apps handle this. */
642
643 sz = 0;
644 m.data = NULL;
645 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
646 m.data, &sz);
647 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
648 exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3(NULL) sizing");
649 m.size = sz;
650 m.data = malloc(m.size);
651 if (m.data == NULL)
652 return tls_error(US"memory allocation failed", strerror(errno), NULL);
653 /* this will return a size 1 less than the allocation size above */
654 rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
655 m.data, &sz);
656 if (rc != GNUTLS_E_SUCCESS)
657 {
658 free(m.data);
659 exim_gnutls_err_check(US"gnutls_dh_params_export_pkcs3() real");
660 }
661 m.size = sz; /* shrink by 1, probably */
662
663 sz = write_to_fd_buf(fd, m.data, (size_t) m.size);
664 if (sz != m.size)
665 {
666 free(m.data);
667 return tls_error(US"TLS cache write D-H params failed",
668 strerror(errno), NULL);
669 }
670 free(m.data);
671 sz = write_to_fd_buf(fd, US"\n", 1);
672 if (sz != 1)
673 return tls_error(US"TLS cache write D-H params final newline failed",
674 strerror(errno), NULL);
675
676 rc = close(fd);
677 if (rc)
678 return tls_error(US"TLS cache write close() failed",
679 strerror(errno), NULL);
680
681 if (Urename(temp_fn, filename) < 0)
682 return tls_error(string_sprintf("failed to rename \"%s\" as \"%s\"",
683 temp_fn, filename), strerror(errno), NULL);
684
685 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
686 }
687
688DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
689return OK;
690}
691
692
693
694
695/*************************************************
696* Variables re-expanded post-SNI *
697*************************************************/
698
699/* Called from both server and client code, via tls_init(), and also from
700the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
701
702We can tell the two apart by state->received_sni being non-NULL in callback.
703
704The callback should not call us unless state->trigger_sni_changes is true,
705which we are responsible for setting on the first pass through.
706
707Arguments:
708 state exim_gnutls_state_st *
709
710Returns: OK/DEFER/FAIL
711*/
712
713static int
714tls_expand_session_files(exim_gnutls_state_st *state)
715{
716struct stat statbuf;
717int rc;
718const host_item *host = state->host; /* macro should be reconsidered? */
719uschar *saved_tls_certificate = NULL;
720uschar *saved_tls_privatekey = NULL;
721uschar *saved_tls_verify_certificates = NULL;
722uschar *saved_tls_crl = NULL;
723int cert_count;
724
725/* We check for tls_sni *before* expansion. */
726if (!host) /* server */
727 {
728 if (!state->received_sni)
729 {
730 if (state->tls_certificate &&
731 (Ustrstr(state->tls_certificate, US"tls_sni") ||
732 Ustrstr(state->tls_certificate, US"tls_in_sni") ||
733 Ustrstr(state->tls_certificate, US"tls_out_sni")
734 ))
735 {
736 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
737 state->trigger_sni_changes = TRUE;
738 }
739 }
740 else
741 {
742 /* useful for debugging */
743 saved_tls_certificate = state->exp_tls_certificate;
744 saved_tls_privatekey = state->exp_tls_privatekey;
745 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
746 saved_tls_crl = state->exp_tls_crl;
747 }
748 }
749
750rc = gnutls_certificate_allocate_credentials(&state->x509_cred);
751exim_gnutls_err_check(US"gnutls_certificate_allocate_credentials");
752
753/* remember: expand_check_tlsvar() is expand_check() but fiddling with
754state members, assuming consistent naming; and expand_check() returns
755false if expansion failed, unless expansion was forced to fail. */
756
757/* check if we at least have a certificate, before doing expensive
758D-H generation. */
759
760if (!expand_check_tlsvar(tls_certificate))
761 return DEFER;
762
763/* certificate is mandatory in server, optional in client */
764
765if ((state->exp_tls_certificate == NULL) ||
766 (*state->exp_tls_certificate == '\0'))
767 {
768 if (!host)
769 return tls_error(US"no TLS server certificate is specified", NULL, NULL);
770 else
771 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
772 }
773
774if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey))
775 return DEFER;
776
777/* tls_privatekey is optional, defaulting to same file as certificate */
778
779if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
780 {
781 state->tls_privatekey = state->tls_certificate;
782 state->exp_tls_privatekey = state->exp_tls_certificate;
783 }
784
785
786if (state->exp_tls_certificate && *state->exp_tls_certificate)
787 {
788 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
789 state->exp_tls_certificate, state->exp_tls_privatekey);
790
791 if (state->received_sni)
792 {
793 if ((Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0) &&
794 (Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0))
795 {
796 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
797 }
798 else
799 {
800 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
801 }
802 }
803
804 rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
805 CS state->exp_tls_certificate, CS state->exp_tls_privatekey,
806 GNUTLS_X509_FMT_PEM);
807 exim_gnutls_err_check(
808 string_sprintf("cert/key setup: cert=%s key=%s",
809 state->exp_tls_certificate, state->exp_tls_privatekey));
810 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
811 } /* tls_certificate */
812
813
814/* Set the OCSP stapling server info */
815
816#ifndef DISABLE_OCSP
817if ( !host /* server */
818 && tls_ocsp_file
819 )
820 {
821 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file",
822 &state->exp_tls_ocsp_file))
823 return DEFER;
824
825 /* Use the full callback method for stapling just to get observability.
826 More efficient would be to read the file once only, if it never changed
827 (due to SNI). Would need restart on file update, or watch datestamp. */
828
829 gnutls_certificate_set_ocsp_status_request_function(state->x509_cred,
830 server_ocsp_stapling_cb, state->exp_tls_ocsp_file);
831
832 DEBUG(D_tls) debug_printf("Set OCSP response file %s\n", &state->exp_tls_ocsp_file);
833 }
834#endif
835
836
837/* Set the trusted CAs file if one is provided, and then add the CRL if one is
838provided. Experiment shows that, if the certificate file is empty, an unhelpful
839error message is provided. However, if we just refrain from setting anything up
840in that case, certificate verification fails, which seems to be the correct
841behaviour. */
842
843if (state->tls_verify_certificates && *state->tls_verify_certificates)
844 {
845 if (!expand_check_tlsvar(tls_verify_certificates))
846 return DEFER;
847 if (state->tls_crl && *state->tls_crl)
848 if (!expand_check_tlsvar(tls_crl))
849 return DEFER;
850
851 if (!(state->exp_tls_verify_certificates &&
852 *state->exp_tls_verify_certificates))
853 {
854 DEBUG(D_tls)
855 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
856 /* With no tls_verify_certificates, we ignore tls_crl too */
857 return OK;
858 }
859 }
860else
861 {
862 DEBUG(D_tls)
863 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
864 return OK;
865 }
866
867if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
868 {
869 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
870 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
871 strerror(errno));
872 return DEFER;
873 }
874
875/* The test suite passes in /dev/null; we could check for that path explicitly,
876but who knows if someone has some weird FIFO which always dumps some certs, or
877other weirdness. The thing we really want to check is that it's not a
878directory, since while OpenSSL supports that, GnuTLS does not.
879So s/!S_ISREG/S_ISDIR/ and change some messsaging ... */
880if (S_ISDIR(statbuf.st_mode))
881 {
882 DEBUG(D_tls)
883 debug_printf("verify certificates path is a dir: \"%s\"\n",
884 state->exp_tls_verify_certificates);
885 log_write(0, LOG_MAIN|LOG_PANIC,
886 "tls_verify_certificates \"%s\" is a directory",
887 state->exp_tls_verify_certificates);
888 return DEFER;
889 }
890
891DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
892 state->exp_tls_verify_certificates, statbuf.st_size);
893
894if (statbuf.st_size == 0)
895 {
896 DEBUG(D_tls)
897 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
898 return OK;
899 }
900
901cert_count = gnutls_certificate_set_x509_trust_file(state->x509_cred,
902 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
903if (cert_count < 0)
904 {
905 rc = cert_count;
906 exim_gnutls_err_check(US"gnutls_certificate_set_x509_trust_file");
907 }
908DEBUG(D_tls) debug_printf("Added %d certificate authorities.\n", cert_count);
909
910if (state->tls_crl && *state->tls_crl &&
911 state->exp_tls_crl && *state->exp_tls_crl)
912 {
913 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
914 cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
915 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM);
916 if (cert_count < 0)
917 {
918 rc = cert_count;
919 exim_gnutls_err_check(US"gnutls_certificate_set_x509_crl_file");
920 }
921 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
922 }
923
924return OK;
925}
926
927
928
929
930/*************************************************
931* Set X.509 state variables *
932*************************************************/
933
934/* In GnuTLS, the registered cert/key are not replaced by a later
935set of a cert/key, so for SNI support we need a whole new x509_cred
936structure. Which means various other non-re-expanded pieces of state
937need to be re-set in the new struct, so the setting logic is pulled
938out to this.
939
940Arguments:
941 state exim_gnutls_state_st *
942
943Returns: OK/DEFER/FAIL
944*/
945
946static int
947tls_set_remaining_x509(exim_gnutls_state_st *state)
948{
949int rc;
950const host_item *host = state->host; /* macro should be reconsidered? */
951
952/* Create D-H parameters, or read them from the cache file. This function does
953its own SMTP error messaging. This only happens for the server, TLS D-H ignores
954client-side params. */
955
956if (!state->host)
957 {
958 if (!dh_server_params)
959 {
960 rc = init_server_dh();
961 if (rc != OK) return rc;
962 }
963 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
964 }
965
966/* Link the credentials to the session. */
967
968rc = gnutls_credentials_set(state->session, GNUTLS_CRD_CERTIFICATE, state->x509_cred);
969exim_gnutls_err_check(US"gnutls_credentials_set");
970
971return OK;
972}
973
974/*************************************************
975* Initialize for GnuTLS *
976*************************************************/
977
978/* Called from both server and client code. In the case of a server, errors
979before actual TLS negotiation return DEFER.
980
981Arguments:
982 host connected host, if client; NULL if server
983 certificate certificate file
984 privatekey private key file
985 sni TLS SNI to send, sometimes when client; else NULL
986 cas CA certs file
987 crl CRL file
988 require_ciphers tls_require_ciphers setting
989 caller_state returned state-info structure
990
991Returns: OK/DEFER/FAIL
992*/
993
994static int
995tls_init(
996 const host_item *host,
997 const uschar *certificate,
998 const uschar *privatekey,
999 const uschar *sni,
1000 const uschar *cas,
1001 const uschar *crl,
1002 const uschar *require_ciphers,
1003 exim_gnutls_state_st **caller_state)
1004{
1005exim_gnutls_state_st *state;
1006int rc;
1007size_t sz;
1008const char *errpos;
1009uschar *p;
1010BOOL want_default_priorities;
1011
1012if (!exim_gnutls_base_init_done)
1013 {
1014 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1015
1016#ifdef HAVE_GNUTLS_PKCS11
1017 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1018 which loads modules from a config file, which sounds good and may be wanted
1019 by some sysadmin, but also means in common configurations that GNOME keyring
1020 environment variables are used and so breaks for users calling mailq.
1021 To prevent this, we init PKCS11 first, which is the documented approach. */
1022 if (!gnutls_allow_auto_pkcs11)
1023 {
1024 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
1025 exim_gnutls_err_check(US"gnutls_pkcs11_init");
1026 }
1027#endif
1028
1029 rc = gnutls_global_init();
1030 exim_gnutls_err_check(US"gnutls_global_init");
1031
1032#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1033 DEBUG(D_tls)
1034 {
1035 gnutls_global_set_log_function(exim_gnutls_logger_cb);
1036 /* arbitrarily chosen level; bump upto 9 for more */
1037 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
1038 }
1039#endif
1040
1041 exim_gnutls_base_init_done = TRUE;
1042 }
1043
1044if (host)
1045 {
1046 state = &state_client;
1047 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1048 state->tlsp = &tls_out;
1049 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1050 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1051 }
1052else
1053 {
1054 state = &state_server;
1055 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1056 state->tlsp = &tls_in;
1057 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1058 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1059 }
1060exim_gnutls_err_check(US"gnutls_init");
1061
1062state->host = host;
1063
1064state->tls_certificate = certificate;
1065state->tls_privatekey = privatekey;
1066state->tls_require_ciphers = require_ciphers;
1067state->tls_sni = sni;
1068state->tls_verify_certificates = cas;
1069state->tls_crl = crl;
1070
1071/* This handles the variables that might get re-expanded after TLS SNI;
1072that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1073
1074DEBUG(D_tls)
1075 debug_printf("Expanding various TLS configuration options for session credentials.\n");
1076rc = tls_expand_session_files(state);
1077if (rc != OK) return rc;
1078
1079/* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1080requires a new structure afterwards. */
1081
1082rc = tls_set_remaining_x509(state);
1083if (rc != OK) return rc;
1084
1085/* set SNI in client, only */
1086if (host)
1087 {
1088 if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni))
1089 return DEFER;
1090 if (state->tlsp->sni && *state->tlsp->sni)
1091 {
1092 DEBUG(D_tls)
1093 debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1094 sz = Ustrlen(state->tlsp->sni);
1095 rc = gnutls_server_name_set(state->session,
1096 GNUTLS_NAME_DNS, state->tlsp->sni, sz);
1097 exim_gnutls_err_check(US"gnutls_server_name_set");
1098 }
1099 }
1100else if (state->tls_sni)
1101 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1102 "have an SNI set for a client [%s]\n", state->tls_sni);
1103
1104/* This is the priority string support,
1105http://www.gnutls.org/manual/html_node/Priority-Strings.html
1106and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1107This was backwards incompatible, but means Exim no longer needs to track
1108all algorithms and provide string forms for them. */
1109
1110want_default_priorities = TRUE;
1111
1112if (state->tls_require_ciphers && *state->tls_require_ciphers)
1113 {
1114 if (!expand_check_tlsvar(tls_require_ciphers))
1115 return DEFER;
1116 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1117 {
1118 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n",
1119 state->exp_tls_require_ciphers);
1120
1121 rc = gnutls_priority_init(&state->priority_cache,
1122 CS state->exp_tls_require_ciphers, &errpos);
1123 want_default_priorities = FALSE;
1124 p = state->exp_tls_require_ciphers;
1125 }
1126 }
1127if (want_default_priorities)
1128 {
1129 DEBUG(D_tls)
1130 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n",
1131 exim_default_gnutls_priority);
1132 rc = gnutls_priority_init(&state->priority_cache,
1133 exim_default_gnutls_priority, &errpos);
1134 p = US exim_default_gnutls_priority;
1135 }
1136
1137exim_gnutls_err_check(string_sprintf(
1138 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1139 p, errpos - CS p, errpos));
1140
1141rc = gnutls_priority_set(state->session, state->priority_cache);
1142exim_gnutls_err_check(US"gnutls_priority_set");
1143
1144gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1145
1146/* Reduce security in favour of increased compatibility, if the admin
1147decides to make that trade-off. */
1148if (gnutls_compat_mode)
1149 {
1150#if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1151 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1152 gnutls_session_enable_compatibility_mode(state->session);
1153#else
1154 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1155#endif
1156 }
1157
1158*caller_state = state;
1159return OK;
1160}
1161
1162
1163
1164/*************************************************
1165* Extract peer information *
1166*************************************************/
1167
1168/* Called from both server and client code.
1169Only this is allowed to set state->peerdn and state->have_set_peerdn
1170and we use that to detect double-calls.
1171
1172NOTE: the state blocks last while the TLS connection is up, which is fine
1173for logging in the server side, but for the client side, we log after teardown
1174in src/deliver.c. While the session is up, we can twist about states and
1175repoint tls_* globals, but those variables used for logging or other variable
1176expansion that happens _after_ delivery need to have a longer life-time.
1177
1178So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1179doing this more than once per generation of a state context. We set them in
1180the state context, and repoint tls_* to them. After the state goes away, the
1181tls_* copies of the pointers remain valid and client delivery logging is happy.
1182
1183tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1184don't apply.
1185
1186Arguments:
1187 state exim_gnutls_state_st *
1188
1189Returns: OK/DEFER/FAIL
1190*/
1191
1192static int
1193peer_status(exim_gnutls_state_st *state)
1194{
1195uschar cipherbuf[256];
1196const gnutls_datum *cert_list;
1197int old_pool, rc;
1198unsigned int cert_list_size = 0;
1199gnutls_protocol_t protocol;
1200gnutls_cipher_algorithm_t cipher;
1201gnutls_kx_algorithm_t kx;
1202gnutls_mac_algorithm_t mac;
1203gnutls_certificate_type_t ct;
1204gnutls_x509_crt_t crt;
1205uschar *p, *dn_buf;
1206size_t sz;
1207
1208if (state->have_set_peerdn)
1209 return OK;
1210state->have_set_peerdn = TRUE;
1211
1212state->peerdn = NULL;
1213
1214/* tls_cipher */
1215cipher = gnutls_cipher_get(state->session);
1216protocol = gnutls_protocol_get_version(state->session);
1217mac = gnutls_mac_get(state->session);
1218kx = gnutls_kx_get(state->session);
1219
1220string_format(cipherbuf, sizeof(cipherbuf),
1221 "%s:%s:%d",
1222 gnutls_protocol_get_name(protocol),
1223 gnutls_cipher_suite_get_name(kx, cipher, mac),
1224 (int) gnutls_cipher_get_key_size(cipher) * 8);
1225
1226/* I don't see a way that spaces could occur, in the current GnuTLS
1227code base, but it was a concern in the old code and perhaps older GnuTLS
1228releases did return "TLS 1.0"; play it safe, just in case. */
1229for (p = cipherbuf; *p != '\0'; ++p)
1230 if (isspace(*p))
1231 *p = '-';
1232old_pool = store_pool;
1233store_pool = POOL_PERM;
1234state->ciphersuite = string_copy(cipherbuf);
1235store_pool = old_pool;
1236state->tlsp->cipher = state->ciphersuite;
1237
1238/* tls_peerdn */
1239cert_list = gnutls_certificate_get_peers(state->session, &cert_list_size);
1240
1241if (cert_list == NULL || cert_list_size == 0)
1242 {
1243 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1244 cert_list, cert_list_size);
1245 if (state->verify_requirement >= VERIFY_REQUIRED)
1246 return tls_error(US"certificate verification failed",
1247 "no certificate received from peer", state->host);
1248 return OK;
1249 }
1250
1251ct = gnutls_certificate_type_get(state->session);
1252if (ct != GNUTLS_CRT_X509)
1253 {
1254 const char *ctn = gnutls_certificate_type_get_name(ct);
1255 DEBUG(D_tls)
1256 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1257 if (state->verify_requirement >= VERIFY_REQUIRED)
1258 return tls_error(US"certificate verification not possible, unhandled type",
1259 ctn, state->host);
1260 return OK;
1261 }
1262
1263#define exim_gnutls_peer_err(Label) \
1264 do { \
1265 if (rc != GNUTLS_E_SUCCESS) \
1266 { \
1267 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1268 (Label), gnutls_strerror(rc)); \
1269 if (state->verify_requirement >= VERIFY_REQUIRED) \
1270 return tls_error((Label), gnutls_strerror(rc), state->host); \
1271 return OK; \
1272 } \
1273 } while (0)
1274
1275rc = import_cert(&cert_list[0], &crt);
1276exim_gnutls_peer_err(US"cert 0");
1277
1278state->tlsp->peercert = state->peercert = crt;
1279
1280sz = 0;
1281rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1282if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1283 {
1284 exim_gnutls_peer_err(US"getting size for cert DN failed");
1285 return FAIL; /* should not happen */
1286 }
1287dn_buf = store_get_perm(sz);
1288rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1289exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1290
1291state->peerdn = dn_buf;
1292
1293return OK;
1294#undef exim_gnutls_peer_err
1295}
1296
1297
1298
1299
1300/*************************************************
1301* Verify peer certificate *
1302*************************************************/
1303
1304/* Called from both server and client code.
1305*Should* be using a callback registered with
1306gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1307the peer information, but that's too new for some OSes.
1308
1309Arguments:
1310 state exim_gnutls_state_st *
1311 error where to put an error message
1312
1313Returns:
1314 FALSE if the session should be rejected
1315 TRUE if the cert is okay or we just don't care
1316*/
1317
1318static BOOL
1319verify_certificate(exim_gnutls_state_st *state, const char **error)
1320{
1321int rc;
1322unsigned int verify;
1323
1324*error = NULL;
1325
1326if ((rc = peer_status(state)) != OK)
1327 {
1328 verify = GNUTLS_CERT_INVALID;
1329 *error = "certificate not supplied";
1330 }
1331else
1332 rc = gnutls_certificate_verify_peers2(state->session, &verify);
1333
1334/* Handle the result of verification. INVALID seems to be set as well
1335as REVOKED, but leave the test for both. */
1336
1337if (rc < 0 ||
1338 verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED)
1339 )
1340 {
1341 state->peer_cert_verified = FALSE;
1342 if (!*error)
1343 *error = verify & GNUTLS_CERT_REVOKED
1344 ? "certificate revoked" : "certificate invalid";
1345
1346 DEBUG(D_tls)
1347 debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
1348 *error, state->peerdn ? state->peerdn : US"<unset>");
1349
1350 if (state->verify_requirement >= VERIFY_REQUIRED)
1351 {
1352 gnutls_alert_send(state->session,
1353 GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1354 return FALSE;
1355 }
1356 DEBUG(D_tls)
1357 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1358 }
1359
1360else
1361 {
1362#ifdef EXPERIMENTAL_CERTNAMES
1363 if (state->verify_requirement == VERIFY_WITHHOST)
1364 {
1365 int sep = 0;
1366 uschar * list = state->exp_tls_verify_cert_hostnames;
1367 uschar * name;
1368 while (name = string_nextinlist(&list, &sep, NULL, 0))
1369 if (gnutls_x509_crt_check_hostname(state->tlsp->peercert, CS name))
1370 break;
1371 if (!name)
1372 {
1373 DEBUG(D_tls)
1374 debug_printf("TLS certificate verification failed: cert name mismatch\n");
1375 gnutls_alert_send(state->session,
1376 GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1377 return FALSE;
1378 }
1379 }
1380#endif
1381 state->peer_cert_verified = TRUE;
1382 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
1383 state->peerdn ? state->peerdn : US"<unset>");
1384 }
1385
1386state->tlsp->peerdn = state->peerdn;
1387
1388return TRUE;
1389}
1390
1391
1392
1393
1394/* ------------------------------------------------------------------------ */
1395/* Callbacks */
1396
1397/* Logging function which can be registered with
1398 * gnutls_global_set_log_function()
1399 * gnutls_global_set_log_level() 0..9
1400 */
1401#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1402static void
1403exim_gnutls_logger_cb(int level, const char *message)
1404{
1405 size_t len = strlen(message);
1406 if (len < 1)
1407 {
1408 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1409 return;
1410 }
1411 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1412 message[len-1] == '\n' ? "" : "\n");
1413}
1414#endif
1415
1416
1417/* Called after client hello, should handle SNI work.
1418This will always set tls_sni (state->received_sni) if available,
1419and may trigger presenting different certificates,
1420if state->trigger_sni_changes is TRUE.
1421
1422Should be registered with
1423 gnutls_handshake_set_post_client_hello_function()
1424
1425"This callback must return 0 on success or a gnutls error code to terminate the
1426handshake.".
1427
1428For inability to get SNI information, we return 0.
1429We only return non-zero if re-setup failed.
1430Only used for server-side TLS.
1431*/
1432
1433static int
1434exim_sni_handling_cb(gnutls_session_t session)
1435{
1436char sni_name[MAX_HOST_LEN];
1437size_t data_len = MAX_HOST_LEN;
1438exim_gnutls_state_st *state = &state_server;
1439unsigned int sni_type;
1440int rc, old_pool;
1441
1442rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1443if (rc != GNUTLS_E_SUCCESS)
1444 {
1445 DEBUG(D_tls) {
1446 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1447 debug_printf("TLS: no SNI presented in handshake.\n");
1448 else
1449 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1450 gnutls_strerror(rc), rc);
1451 };
1452 return 0;
1453 }
1454
1455if (sni_type != GNUTLS_NAME_DNS)
1456 {
1457 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1458 return 0;
1459 }
1460
1461/* We now have a UTF-8 string in sni_name */
1462old_pool = store_pool;
1463store_pool = POOL_PERM;
1464state->received_sni = string_copyn(US sni_name, data_len);
1465store_pool = old_pool;
1466
1467/* We set this one now so that variable expansions below will work */
1468state->tlsp->sni = state->received_sni;
1469
1470DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1471 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1472
1473if (!state->trigger_sni_changes)
1474 return 0;
1475
1476rc = tls_expand_session_files(state);
1477if (rc != OK)
1478 {
1479 /* If the setup of certs/etc failed before handshake, TLS would not have
1480 been offered. The best we can do now is abort. */
1481 return GNUTLS_E_APPLICATION_ERROR_MIN;
1482 }
1483
1484rc = tls_set_remaining_x509(state);
1485if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1486
1487return 0;
1488}
1489
1490
1491
1492#ifndef DISABLE_OCSP
1493
1494static int
1495server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1496 gnutls_datum_t * ocsp_response)
1497{
1498int ret;
1499
1500if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1501 {
1502 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1503 (char *)ptr);
1504 tls_in.ocsp = OCSP_NOT_RESP;
1505 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1506 }
1507
1508tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1509return 0;
1510}
1511
1512#endif
1513
1514
1515
1516
1517
1518/* ------------------------------------------------------------------------ */
1519/* Exported functions */
1520
1521
1522
1523
1524/*************************************************
1525* Start a TLS session in a server *
1526*************************************************/
1527
1528/* This is called when Exim is running as a server, after having received
1529the STARTTLS command. It must respond to that command, and then negotiate
1530a TLS session.
1531
1532Arguments:
1533 require_ciphers list of allowed ciphers or NULL
1534
1535Returns: OK on success
1536 DEFER for errors before the start of the negotiation
1537 FAIL for errors during the negotation; the server can't
1538 continue running.
1539*/
1540
1541int
1542tls_server_start(const uschar *require_ciphers)
1543{
1544int rc;
1545const char *error;
1546exim_gnutls_state_st *state = NULL;
1547
1548/* Check for previous activation */
1549if (tls_in.active >= 0)
1550 {
1551 tls_error(US"STARTTLS received after TLS started", "", NULL);
1552 smtp_printf("554 Already in TLS\r\n");
1553 return FAIL;
1554 }
1555
1556/* Initialize the library. If it fails, it will already have logged the error
1557and sent an SMTP response. */
1558
1559DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
1560
1561rc = tls_init(NULL, tls_certificate, tls_privatekey,
1562 NULL, tls_verify_certificates, tls_crl,
1563 require_ciphers, &state);
1564if (rc != OK) return rc;
1565
1566/* If this is a host for which certificate verification is mandatory or
1567optional, set up appropriately. */
1568
1569if (verify_check_host(&tls_verify_hosts) == OK)
1570 {
1571 DEBUG(D_tls)
1572 debug_printf("TLS: a client certificate will be required.\n");
1573 state->verify_requirement = VERIFY_REQUIRED;
1574 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1575 }
1576else if (verify_check_host(&tls_try_verify_hosts) == OK)
1577 {
1578 DEBUG(D_tls)
1579 debug_printf("TLS: a client certificate will be requested but not required.\n");
1580 state->verify_requirement = VERIFY_OPTIONAL;
1581 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1582 }
1583else
1584 {
1585 DEBUG(D_tls)
1586 debug_printf("TLS: a client certificate will not be requested.\n");
1587 state->verify_requirement = VERIFY_NONE;
1588 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1589 }
1590
1591/* Register SNI handling; always, even if not in tls_certificate, so that the
1592expansion variable $tls_sni is always available. */
1593
1594gnutls_handshake_set_post_client_hello_function(state->session,
1595 exim_sni_handling_cb);
1596
1597/* Set context and tell client to go ahead, except in the case of TLS startup
1598on connection, where outputting anything now upsets the clients and tends to
1599make them disconnect. We need to have an explicit fflush() here, to force out
1600the response. Other smtp_printf() calls do not need it, because in non-TLS
1601mode, the fflush() happens when smtp_getc() is called. */
1602
1603if (!state->tlsp->on_connect)
1604 {
1605 smtp_printf("220 TLS go ahead\r\n");
1606 fflush(smtp_out);
1607 }
1608
1609/* Now negotiate the TLS session. We put our own timer on it, since it seems
1610that the GnuTLS library doesn't. */
1611
1612gnutls_transport_set_ptr2(state->session,
1613 (gnutls_transport_ptr)(long) fileno(smtp_in),
1614 (gnutls_transport_ptr)(long) fileno(smtp_out));
1615state->fd_in = fileno(smtp_in);
1616state->fd_out = fileno(smtp_out);
1617
1618sigalrm_seen = FALSE;
1619if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1620do
1621 {
1622 rc = gnutls_handshake(state->session);
1623 } while ((rc == GNUTLS_E_AGAIN) ||
1624 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
1625alarm(0);
1626
1627if (rc != GNUTLS_E_SUCCESS)
1628 {
1629 tls_error(US"gnutls_handshake",
1630 sigalrm_seen ? "timed out" : gnutls_strerror(rc), NULL);
1631 /* It seems that, except in the case of a timeout, we have to close the
1632 connection right here; otherwise if the other end is running OpenSSL it hangs
1633 until the server times out. */
1634
1635 if (!sigalrm_seen)
1636 {
1637 (void)fclose(smtp_out);
1638 (void)fclose(smtp_in);
1639 }
1640
1641 return FAIL;
1642 }
1643
1644DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1645
1646/* Verify after the fact */
1647
1648if ( state->verify_requirement != VERIFY_NONE
1649 && !verify_certificate(state, &error))
1650 {
1651 if (state->verify_requirement != VERIFY_OPTIONAL)
1652 {
1653 tls_error(US"certificate verification failed", error, NULL);
1654 return FAIL;
1655 }
1656 DEBUG(D_tls)
1657 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
1658 error);
1659 }
1660
1661/* Figure out peer DN, and if authenticated, etc. */
1662
1663rc = peer_status(state);
1664if (rc != OK) return rc;
1665
1666/* Sets various Exim expansion variables; always safe within server */
1667
1668extract_exim_vars_from_tls_state(state);
1669
1670/* TLS has been set up. Adjust the input functions to read via TLS,
1671and initialize appropriately. */
1672
1673state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
1674
1675receive_getc = tls_getc;
1676receive_ungetc = tls_ungetc;
1677receive_feof = tls_feof;
1678receive_ferror = tls_ferror;
1679receive_smtp_buffered = tls_smtp_buffered;
1680
1681return OK;
1682}
1683
1684
1685
1686
1687/*************************************************
1688* Start a TLS session in a client *
1689*************************************************/
1690
1691/* Called from the smtp transport after STARTTLS has been accepted.
1692
1693Arguments:
1694 fd the fd of the connection
1695 host connected host (for messages)
1696 addr the first address (not used)
1697 ob smtp transport options
1698
1699Returns: OK/DEFER/FAIL (because using common functions),
1700 but for a client, DEFER and FAIL have the same meaning
1701*/
1702
1703int
1704tls_client_start(int fd, host_item *host,
1705 address_item *addr ARG_UNUSED,
1706 void *v_ob)
1707{
1708smtp_transport_options_block *ob = v_ob;
1709int rc;
1710const char *error;
1711exim_gnutls_state_st *state = NULL;
1712#ifndef DISABLE_OCSP
1713BOOL require_ocsp = verify_check_this_host(&ob->hosts_require_ocsp,
1714 NULL, host->name, host->address, NULL) == OK;
1715BOOL request_ocsp = require_ocsp ? TRUE
1716 : verify_check_this_host(&ob->hosts_request_ocsp,
1717 NULL, host->name, host->address, NULL) == OK;
1718#endif
1719
1720DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", fd);
1721
1722if ((rc = tls_init(host, ob->tls_certificate, ob->tls_privatekey,
1723 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
1724 ob->tls_require_ciphers, &state)) != OK)
1725 return rc;
1726
1727 {
1728 int dh_min_bits = ob->tls_dh_min_bits;
1729 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
1730 {
1731 DEBUG(D_tls)
1732 debug_printf("WARNING: tls_dh_min_bits far too low,"
1733 " clamping %d up to %d\n",
1734 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
1735 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
1736 }
1737
1738 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
1739 " acceptable bits to %d\n",
1740 dh_min_bits);
1741 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
1742 }
1743
1744/* Stick to the old behaviour for compatibility if tls_verify_certificates is
1745set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
1746the specified host patterns if one of them is defined */
1747
1748if (( state->exp_tls_verify_certificates
1749 && !ob->tls_verify_hosts
1750 && !ob->tls_try_verify_hosts
1751 )
1752 ||
1753 verify_check_host(&ob->tls_verify_hosts) == OK
1754 )
1755 {
1756#ifdef EXPERIMENTAL_CERTNAMES
1757 if (ob->tls_verify_cert_hostnames)
1758 {
1759 DEBUG(D_tls)
1760 debug_printf("TLS: server cert incl. hostname verification required.\n");
1761 state->verify_requirement = VERIFY_WITHHOST;
1762 if (!expand_check(ob->tls_verify_cert_hostnames,
1763 US"tls_verify_cert_hostnames",
1764 &state->exp_tls_verify_cert_hostnames))
1765 return FAIL;
1766 if (state->exp_tls_verify_cert_hostnames)
1767 DEBUG(D_tls) debug_printf("Cert hostname to check: \"%s\"\n",
1768 state->exp_tls_verify_cert_hostnames);
1769 }
1770 else
1771#endif
1772 {
1773 DEBUG(D_tls)
1774 debug_printf("TLS: server certificate verification required.\n");
1775 state->verify_requirement = VERIFY_REQUIRED;
1776 }
1777 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
1778 }
1779else if (verify_check_host(&ob->tls_try_verify_hosts) == OK)
1780 {
1781 DEBUG(D_tls)
1782 debug_printf("TLS: server certificate verification optional.\n");
1783 state->verify_requirement = VERIFY_OPTIONAL;
1784 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
1785 }
1786else
1787 {
1788 DEBUG(D_tls)
1789 debug_printf("TLS: server certificate verification not required.\n");
1790 state->verify_requirement = VERIFY_NONE;
1791 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
1792 }
1793
1794#ifndef DISABLE_OCSP
1795 /* supported since GnuTLS 3.1.3 */
1796if (request_ocsp)
1797 {
1798 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
1799 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
1800 NULL, 0, NULL)) != OK)
1801 return tls_error(US"cert-status-req",
1802 gnutls_strerror(rc), state->host);
1803 tls_out.ocsp = OCSP_NOT_RESP;
1804 }
1805#endif
1806
1807gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr)(long) fd);
1808state->fd_in = fd;
1809state->fd_out = fd;
1810
1811DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
1812/* There doesn't seem to be a built-in timeout on connection. */
1813
1814sigalrm_seen = FALSE;
1815alarm(ob->command_timeout);
1816do
1817 {
1818 rc = gnutls_handshake(state->session);
1819 } while ((rc == GNUTLS_E_AGAIN) ||
1820 (rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen));
1821alarm(0);
1822
1823if (rc != GNUTLS_E_SUCCESS)
1824 return tls_error(US"gnutls_handshake",
1825 sigalrm_seen ? "timed out" : gnutls_strerror(rc), state->host);
1826
1827DEBUG(D_tls) debug_printf("gnutls_handshake was successful\n");
1828
1829/* Verify late */
1830
1831if (state->verify_requirement != VERIFY_NONE &&
1832 !verify_certificate(state, &error))
1833 return tls_error(US"certificate verification failed", error, state->host);
1834
1835#ifndef DISABLE_OCSP
1836if (require_ocsp)
1837 {
1838 DEBUG(D_tls)
1839 {
1840 gnutls_datum_t stapling;
1841 gnutls_ocsp_resp_t resp;
1842 gnutls_datum_t printed;
1843 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
1844 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
1845 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
1846 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
1847 )
1848 {
1849 debug_printf("%.4096s", printed.data);
1850 gnutls_free(printed.data);
1851 }
1852 else
1853 (void) tls_error(US"ocsp decode", gnutls_strerror(rc), state->host);
1854 }
1855
1856 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
1857 {
1858 tls_out.ocsp = OCSP_FAILED;
1859 return tls_error(US"certificate status check failed", NULL, state->host);
1860 }
1861 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
1862 tls_out.ocsp = OCSP_VFIED;
1863 }
1864#endif
1865
1866/* Figure out peer DN, and if authenticated, etc. */
1867
1868if ((rc = peer_status(state)) != OK)
1869 return rc;
1870
1871/* Sets various Exim expansion variables; may need to adjust for ACL callouts */
1872
1873extract_exim_vars_from_tls_state(state);
1874
1875return OK;
1876}
1877
1878
1879
1880
1881/*************************************************
1882* Close down a TLS session *
1883*************************************************/
1884
1885/* This is also called from within a delivery subprocess forked from the
1886daemon, to shut down the TLS library, without actually doing a shutdown (which
1887would tamper with the TLS session in the parent process).
1888
1889Arguments: TRUE if gnutls_bye is to be called
1890Returns: nothing
1891*/
1892
1893void
1894tls_close(BOOL is_server, BOOL shutdown)
1895{
1896exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
1897
1898if (!state->tlsp || state->tlsp->active < 0) return; /* TLS was not active */
1899
1900if (shutdown)
1901 {
1902 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS\n");
1903 gnutls_bye(state->session, GNUTLS_SHUT_WR);
1904 }
1905
1906gnutls_deinit(state->session);
1907
1908state->tlsp->active = -1;
1909memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1910
1911if ((state_server.session == NULL) && (state_client.session == NULL))
1912 {
1913 gnutls_global_deinit();
1914 exim_gnutls_base_init_done = FALSE;
1915 }
1916
1917}
1918
1919
1920
1921
1922/*************************************************
1923* TLS version of getc *
1924*************************************************/
1925
1926/* This gets the next byte from the TLS input buffer. If the buffer is empty,
1927it refills the buffer via the GnuTLS reading function.
1928Only used by the server-side TLS.
1929
1930This feeds DKIM and should be used for all message-body reads.
1931
1932Arguments: none
1933Returns: the next character or EOF
1934*/
1935
1936int
1937tls_getc(void)
1938{
1939exim_gnutls_state_st *state = &state_server;
1940if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
1941 {
1942 ssize_t inbytes;
1943
1944 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
1945 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
1946
1947 if (smtp_receive_timeout > 0) alarm(smtp_receive_timeout);
1948 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
1949 ssl_xfer_buffer_size);
1950 alarm(0);
1951
1952 /* A zero-byte return appears to mean that the TLS session has been
1953 closed down, not that the socket itself has been closed down. Revert to
1954 non-TLS handling. */
1955
1956 if (inbytes == 0)
1957 {
1958 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
1959
1960 receive_getc = smtp_getc;
1961 receive_ungetc = smtp_ungetc;
1962 receive_feof = smtp_feof;
1963 receive_ferror = smtp_ferror;
1964 receive_smtp_buffered = smtp_buffered;
1965
1966 gnutls_deinit(state->session);
1967 state->session = NULL;
1968 state->tlsp->active = -1;
1969 state->tlsp->bits = 0;
1970 state->tlsp->certificate_verified = FALSE;
1971 tls_channelbinding_b64 = NULL;
1972 state->tlsp->cipher = NULL;
1973 state->tlsp->peercert = NULL;
1974 state->tlsp->peerdn = NULL;
1975
1976 return smtp_getc();
1977 }
1978
1979 /* Handle genuine errors */
1980
1981 else if (inbytes < 0)
1982 {
1983 record_io_error(state, (int) inbytes, US"recv", NULL);
1984 state->xfer_error = 1;
1985 return EOF;
1986 }
1987#ifndef DISABLE_DKIM
1988 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
1989#endif
1990 state->xfer_buffer_hwm = (int) inbytes;
1991 state->xfer_buffer_lwm = 0;
1992 }
1993
1994/* Something in the buffer; return next uschar */
1995
1996return state->xfer_buffer[state->xfer_buffer_lwm++];
1997}
1998
1999
2000
2001
2002/*************************************************
2003* Read bytes from TLS channel *
2004*************************************************/
2005
2006/* This does not feed DKIM, so if the caller uses this for reading message body,
2007then the caller must feed DKIM.
2008
2009Arguments:
2010 buff buffer of data
2011 len size of buffer
2012
2013Returns: the number of bytes read
2014 -1 after a failed read
2015*/
2016
2017int
2018tls_read(BOOL is_server, uschar *buff, size_t len)
2019{
2020exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2021ssize_t inbytes;
2022
2023if (len > INT_MAX)
2024 len = INT_MAX;
2025
2026if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
2027 DEBUG(D_tls)
2028 debug_printf("*** PROBABLY A BUG *** " \
2029 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
2030 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
2031
2032DEBUG(D_tls)
2033 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
2034 state->session, buff, len);
2035
2036inbytes = gnutls_record_recv(state->session, buff, len);
2037if (inbytes > 0) return inbytes;
2038if (inbytes == 0)
2039 {
2040 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2041 }
2042else record_io_error(state, (int)inbytes, US"recv", NULL);
2043
2044return -1;
2045}
2046
2047
2048
2049
2050/*************************************************
2051* Write bytes down TLS channel *
2052*************************************************/
2053
2054/*
2055Arguments:
2056 is_server channel specifier
2057 buff buffer of data
2058 len number of bytes
2059
2060Returns: the number of bytes after a successful write,
2061 -1 after a failed write
2062*/
2063
2064int
2065tls_write(BOOL is_server, const uschar *buff, size_t len)
2066{
2067ssize_t outbytes;
2068size_t left = len;
2069exim_gnutls_state_st *state = is_server ? &state_server : &state_client;
2070
2071DEBUG(D_tls) debug_printf("tls_do_write(%p, " SIZE_T_FMT ")\n", buff, left);
2072while (left > 0)
2073 {
2074 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
2075 buff, left);
2076 outbytes = gnutls_record_send(state->session, buff, left);
2077
2078 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
2079 if (outbytes < 0)
2080 {
2081 record_io_error(state, outbytes, US"send", NULL);
2082 return -1;
2083 }
2084 if (outbytes == 0)
2085 {
2086 record_io_error(state, 0, US"send", US"TLS channel closed on write");
2087 return -1;
2088 }
2089
2090 left -= outbytes;
2091 buff += outbytes;
2092 }
2093
2094if (len > INT_MAX)
2095 {
2096 DEBUG(D_tls)
2097 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
2098 len);
2099 len = INT_MAX;
2100 }
2101
2102return (int) len;
2103}
2104
2105
2106
2107
2108/*************************************************
2109* Random number generation *
2110*************************************************/
2111
2112/* Pseudo-random number generation. The result is not expected to be
2113cryptographically strong but not so weak that someone will shoot themselves
2114in the foot using it as a nonce in input in some email header scheme or
2115whatever weirdness they'll twist this into. The result should handle fork()
2116and avoid repeating sequences. OpenSSL handles that for us.
2117
2118Arguments:
2119 max range maximum
2120Returns a random number in range [0, max-1]
2121*/
2122
2123#ifdef HAVE_GNUTLS_RND
2124int
2125vaguely_random_number(int max)
2126{
2127unsigned int r;
2128int i, needed_len;
2129uschar *p;
2130uschar smallbuf[sizeof(r)];
2131
2132if (max <= 1)
2133 return 0;
2134
2135needed_len = sizeof(r);
2136/* Don't take 8 times more entropy than needed if int is 8 octets and we were
2137 * asked for a number less than 10. */
2138for (r = max, i = 0; r; ++i)
2139 r >>= 1;
2140i = (i + 7) / 8;
2141if (i < needed_len)
2142 needed_len = i;
2143
2144i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
2145if (i < 0)
2146 {
2147 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
2148 return vaguely_random_number_fallback(max);
2149 }
2150r = 0;
2151for (p = smallbuf; needed_len; --needed_len, ++p)
2152 {
2153 r *= 256;
2154 r += *p;
2155 }
2156
2157/* We don't particularly care about weighted results; if someone wants
2158 * smooth distribution and cares enough then they should submit a patch then. */
2159return r % max;
2160}
2161#else /* HAVE_GNUTLS_RND */
2162int
2163vaguely_random_number(int max)
2164{
2165 return vaguely_random_number_fallback(max);
2166}
2167#endif /* HAVE_GNUTLS_RND */
2168
2169
2170
2171
2172/*************************************************
2173* Let tls_require_ciphers be checked at startup *
2174*************************************************/
2175
2176/* The tls_require_ciphers option, if set, must be something which the
2177library can parse.
2178
2179Returns: NULL on success, or error message
2180*/
2181
2182uschar *
2183tls_validate_require_cipher(void)
2184{
2185int rc;
2186uschar *expciphers = NULL;
2187gnutls_priority_t priority_cache;
2188const char *errpos;
2189
2190#define validate_check_rc(Label) do { \
2191 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
2192 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
2193#define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
2194
2195if (exim_gnutls_base_init_done)
2196 log_write(0, LOG_MAIN|LOG_PANIC,
2197 "already initialised GnuTLS, Exim developer bug");
2198
2199#ifdef HAVE_GNUTLS_PKCS11
2200if (!gnutls_allow_auto_pkcs11)
2201 {
2202 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
2203 validate_check_rc(US"gnutls_pkcs11_init");
2204 }
2205#endif
2206rc = gnutls_global_init();
2207validate_check_rc(US"gnutls_global_init()");
2208exim_gnutls_base_init_done = TRUE;
2209
2210if (!(tls_require_ciphers && *tls_require_ciphers))
2211 return_deinit(NULL);
2212
2213if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers))
2214 return_deinit(US"failed to expand tls_require_ciphers");
2215
2216if (!(expciphers && *expciphers))
2217 return_deinit(NULL);
2218
2219DEBUG(D_tls)
2220 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
2221
2222rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
2223validate_check_rc(string_sprintf(
2224 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
2225 expciphers, errpos - CS expciphers, errpos));
2226
2227#undef return_deinit
2228#undef validate_check_rc
2229gnutls_global_deinit();
2230
2231return NULL;
2232}
2233
2234
2235
2236
2237/*************************************************
2238* Report the library versions. *
2239*************************************************/
2240
2241/* See a description in tls-openssl.c for an explanation of why this exists.
2242
2243Arguments: a FILE* to print the results to
2244Returns: nothing
2245*/
2246
2247void
2248tls_version_report(FILE *f)
2249{
2250fprintf(f, "Library version: GnuTLS: Compile: %s\n"
2251 " Runtime: %s\n",
2252 LIBGNUTLS_VERSION,
2253 gnutls_check_version(NULL));
2254}
2255
2256/* vi: aw ai sw=2
2257*/
2258/* End of tls-gnu.c */