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