8bd5aeda41697e58ba36582b25b9d91d9d0d8f24
[exim.git] / src / src / tls-gnu.c
1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
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,
11 one of the available supported implementations. This file is #included into
12 tls.c when USE_GNUTLS has been set.
13
14 The code herein is a revamp of GnuTLS integration using the current APIs; the
15 original tls-gnu.c was based on a patch which was contributed by Nikos
16 Mavrogiannopoulos. The revamp is partially a rewrite, partially cut&paste as
17 appropriate.
18
19 APIs current as of GnuTLS 2.12.18; note that the GnuTLS manual is for GnuTLS 3,
20 which is not widely deployed by OS vendors. Will note issues below, which may
21 assist in updating the code in the future. Another sources of hints is
22 mod_gnutls for Apache (SNI callback registration and handling).
23
24 Keeping client and server variables more split than before and is currently
25 the norm, in anticipation of TLS in ACL callouts.
26
27 I wanted to switch to gnutls_certificate_set_verify_function() so that
28 certificate rejection could happen during handshake where it belongs, rather
29 than being dropped afterwards, but that was introduced in 2.10.0 and Debian
30 (6.0.5) is still on 2.8.6. So for now we have to stick with sub-par behaviour.
31
32 (I wasn't looking for libraries quite that old, when updating to get rid of
33 compiler warnings of deprecated APIs. If it turns out that a lot of the rest
34 require current GnuTLS, then we'll drop support for the ancient libraries).
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
43 /* needed to disable PKCS11 autoload unless requested */
44 #if GNUTLS_VERSION_NUMBER >= 0x020c00
45 # include <gnutls/pkcs11.h>
46 # define SUPPORT_PARAM_TO_PK_BITS
47 #endif
48 #if GNUTLS_VERSION_NUMBER < 0x030103 && !defined(DISABLE_OCSP)
49 # warning "GnuTLS library version too old; define DISABLE_OCSP in Makefile"
50 # define DISABLE_OCSP
51 #endif
52 #if GNUTLS_VERSION_NUMBER < 0x020a00 && !defined(DISABLE_EVENT)
53 # warning "GnuTLS library version too old; tls:cert event unsupported"
54 # define DISABLE_EVENT
55 #endif
56 #if GNUTLS_VERSION_NUMBER >= 0x030306
57 # define SUPPORT_CA_DIR
58 #else
59 # undef SUPPORT_CA_DIR
60 #endif
61 #if GNUTLS_VERSION_NUMBER >= 0x030014
62 # define SUPPORT_SYSDEFAULT_CABUNDLE
63 #endif
64 #if GNUTLS_VERSION_NUMBER >= 0x030104
65 # define GNUTLS_CERT_VFY_STATUS_PRINT
66 #endif
67 #if GNUTLS_VERSION_NUMBER >= 0x030109
68 # define SUPPORT_CORK
69 #endif
70 #if GNUTLS_VERSION_NUMBER >= 0x03010a
71 # define SUPPORT_GNUTLS_SESS_DESC
72 #endif
73 #if GNUTLS_VERSION_NUMBER >= 0x030500
74 # define SUPPORT_GNUTLS_KEYLOG
75 #endif
76 #if GNUTLS_VERSION_NUMBER >= 0x030506 && !defined(DISABLE_OCSP)
77 # define SUPPORT_SRV_OCSP_STACK
78 #endif
79
80 #ifdef SUPPORT_DANE
81 # if GNUTLS_VERSION_NUMBER >= 0x030000
82 # define DANESSL_USAGE_DANE_TA 2
83 # define DANESSL_USAGE_DANE_EE 3
84 # else
85 # error GnuTLS version too early for DANE
86 # endif
87 # if GNUTLS_VERSION_NUMBER < 0x999999
88 # define GNUTLS_BROKEN_DANE_VALIDATION
89 # endif
90 #endif
91
92 #ifndef DISABLE_OCSP
93 # include <gnutls/ocsp.h>
94 #endif
95 #ifdef SUPPORT_DANE
96 # include <gnutls/dane.h>
97 #endif
98
99 #include "tls-cipher-stdname.c"
100
101
102 #ifdef MACRO_PREDEF
103 void
104 options_tls(void)
105 {
106 # ifdef EXPERIMENTAL_TLS_RESUME
107 builtin_macro_create_var(US"_RESUME_DECODE", RESUME_DECODE_STRING );
108 # endif
109 }
110 #else
111
112
113 /* GnuTLS 2 vs 3
114
115 GnuTLS 3 only:
116 gnutls_global_set_audit_log_function()
117
118 Changes:
119 gnutls_certificate_verify_peers2(): is new, drop the 2 for old version
120 */
121
122 /* Local static variables for GnuTLS */
123
124 /* Values for verify_requirement */
125
126 enum peer_verify_requirement
127 { VERIFY_NONE, VERIFY_OPTIONAL, VERIFY_REQUIRED, VERIFY_DANE };
128
129 /* This holds most state for server or client; with this, we can set up an
130 outbound TLS-enabled connection in an ACL callout, while not stomping all
131 over the TLS variables available for expansion.
132
133 Some of these correspond to variables in globals.c; those variables will
134 be set to point to content in one of these instances, as appropriate for
135 the stage of the process lifetime.
136
137 Not handled here: global tls_channelbinding_b64.
138 */
139
140 typedef struct exim_gnutls_state {
141 gnutls_session_t session;
142 gnutls_certificate_credentials_t x509_cred;
143 gnutls_priority_t priority_cache;
144 enum peer_verify_requirement verify_requirement;
145 int fd_in;
146 int fd_out;
147 BOOL peer_cert_verified;
148 BOOL peer_dane_verified;
149 BOOL trigger_sni_changes;
150 BOOL have_set_peerdn;
151 const struct host_item *host; /* NULL if server */
152 gnutls_x509_crt_t peercert;
153 uschar *peerdn;
154 uschar *ciphersuite;
155 uschar *received_sni;
156
157 const uschar *tls_certificate;
158 const uschar *tls_privatekey;
159 const uschar *tls_sni; /* client send only, not received */
160 const uschar *tls_verify_certificates;
161 const uschar *tls_crl;
162 const uschar *tls_require_ciphers;
163
164 uschar *exp_tls_certificate;
165 uschar *exp_tls_privatekey;
166 uschar *exp_tls_verify_certificates;
167 uschar *exp_tls_crl;
168 uschar *exp_tls_require_ciphers;
169 const uschar *exp_tls_verify_cert_hostnames;
170 #ifndef DISABLE_EVENT
171 uschar *event_action;
172 #endif
173 #ifdef SUPPORT_DANE
174 char * const * dane_data;
175 const int * dane_data_len;
176 #endif
177
178 tls_support *tlsp; /* set in tls_init() */
179
180 uschar *xfer_buffer;
181 int xfer_buffer_lwm;
182 int xfer_buffer_hwm;
183 BOOL xfer_eof; /*XXX never gets set! */
184 BOOL xfer_error;
185 } exim_gnutls_state_st;
186
187 static const exim_gnutls_state_st exim_gnutls_state_init = {
188 /* all elements not explicitly intialised here get 0/NULL/FALSE */
189 .fd_in = -1,
190 .fd_out = -1,
191 };
192
193 /* Not only do we have our own APIs which don't pass around state, assuming
194 it's held in globals, GnuTLS doesn't appear to let us register callback data
195 for callbacks, or as part of the session, so we have to keep a "this is the
196 context we're currently dealing with" pointer and rely upon being
197 single-threaded to keep from processing data on an inbound TLS connection while
198 talking to another TLS connection for an outbound check. This does mean that
199 there's no way for heart-beats to be responded to, for the duration of the
200 second connection.
201 XXX But see gnutls_session_get_ptr()
202 */
203
204 static exim_gnutls_state_st state_server;
205
206 /* dh_params are initialised once within the lifetime of a process using TLS;
207 if we used TLS in a long-lived daemon, we'd have to reconsider this. But we
208 don't want to repeat this. */
209
210 static gnutls_dh_params_t dh_server_params = NULL;
211
212 static int ssl_session_timeout = 3600; /* One hour */
213
214 static const uschar * const exim_default_gnutls_priority = US"NORMAL";
215
216 /* Guard library core initialisation */
217
218 static BOOL exim_gnutls_base_init_done = FALSE;
219
220 #ifndef DISABLE_OCSP
221 static BOOL gnutls_buggy_ocsp = FALSE;
222 #endif
223
224 #ifdef EXPERIMENTAL_TLS_RESUME
225 static gnutls_datum_t server_sessticket_key;
226 #endif
227
228 /* ------------------------------------------------------------------------ */
229 /* macros */
230
231 #define MAX_HOST_LEN 255
232
233 /* Set this to control gnutls_global_set_log_level(); values 0 to 9 will setup
234 the library logging; a value less than 0 disables the calls to set up logging
235 callbacks. GNuTLS also looks for an environment variable - except not for
236 setuid binaries, making it useless - "GNUTLS_DEBUG_LEVEL".
237 Allegedly the testscript line "GNUTLS_DEBUG_LEVEL=9 sudo exim ..." would work,
238 but the env var must be added to /etc/sudoers too. */
239 #ifndef EXIM_GNUTLS_LIBRARY_LOG_LEVEL
240 # define EXIM_GNUTLS_LIBRARY_LOG_LEVEL -1
241 #endif
242
243 #ifndef EXIM_CLIENT_DH_MIN_BITS
244 # define EXIM_CLIENT_DH_MIN_BITS 1024
245 #endif
246
247 /* With GnuTLS 2.12.x+ we have gnutls_sec_param_to_pk_bits() with which we
248 can ask for a bit-strength. Without that, we stick to the constant we had
249 before, for now. */
250 #ifndef EXIM_SERVER_DH_BITS_PRE2_12
251 # define EXIM_SERVER_DH_BITS_PRE2_12 1024
252 #endif
253
254 #define expand_check_tlsvar(Varname, errstr) \
255 expand_check(state->Varname, US #Varname, &state->exp_##Varname, errstr)
256
257 #if GNUTLS_VERSION_NUMBER >= 0x020c00
258 # define HAVE_GNUTLS_SESSION_CHANNEL_BINDING
259 # define HAVE_GNUTLS_SEC_PARAM_CONSTANTS
260 # define HAVE_GNUTLS_RND
261 /* The security fix we provide with the gnutls_allow_auto_pkcs11 option
262 * (4.82 PP/09) introduces a compatibility regression. The symbol simply
263 * isn't available sometimes, so this needs to become a conditional
264 * compilation; the sanest way to deal with this being a problem on
265 * older OSes is to block it in the Local/Makefile with this compiler
266 * definition */
267 # ifndef AVOID_GNUTLS_PKCS11
268 # define HAVE_GNUTLS_PKCS11
269 # endif /* AVOID_GNUTLS_PKCS11 */
270 #endif
271
272
273
274
275 /* ------------------------------------------------------------------------ */
276 /* Callback declarations */
277
278 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
279 static void exim_gnutls_logger_cb(int level, const char *message);
280 #endif
281
282 static int exim_sni_handling_cb(gnutls_session_t session);
283
284 #ifndef DISABLE_OCSP
285 static int server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
286 gnutls_datum_t * ocsp_response);
287 #endif
288
289
290
291 /* Daemon one-time initialisation */
292 void
293 tls_daemon_init(void)
294 {
295 #ifdef EXPERIMENTAL_TLS_RESUME
296 /* We are dependent on the GnuTLS implementation of the Session Ticket
297 encryption; both the strength and the key rotation period. We hope that
298 the strength at least matches that of the ciphersuite (but GnuTLS does not
299 document this). */
300
301 static BOOL once = FALSE;
302 if (once) return;
303 once = TRUE;
304 gnutls_session_ticket_key_generate(&server_sessticket_key); /* >= 2.10.0 */
305 if (f.running_in_test_harness) ssl_session_timeout = 6;
306 #endif
307 }
308
309 /* ------------------------------------------------------------------------ */
310 /* Static functions */
311
312 /*************************************************
313 * Handle TLS error *
314 *************************************************/
315
316 /* Called from lots of places when errors occur before actually starting to do
317 the TLS handshake, that is, while the session is still in clear. Always returns
318 DEFER for a server and FAIL for a client so that most calls can use "return
319 tls_error(...)" to do this processing and then give an appropriate return. A
320 single function is used for both server and client, because it is called from
321 some shared functions.
322
323 Argument:
324 prefix text to include in the logged error
325 msg additional error string (may be NULL)
326 usually obtained from gnutls_strerror()
327 host NULL if setting up a server;
328 the connected host if setting up a client
329 errstr pointer to returned error string
330
331 Returns: OK/DEFER/FAIL
332 */
333
334 static int
335 tls_error(const uschar *prefix, const uschar *msg, const host_item *host,
336 uschar ** errstr)
337 {
338 if (errstr)
339 *errstr = string_sprintf("(%s)%s%s", prefix, msg ? ": " : "", msg ? msg : US"");
340 return host ? FAIL : DEFER;
341 }
342
343
344 static int
345 tls_error_gnu(const uschar *prefix, int err, const host_item *host,
346 uschar ** errstr)
347 {
348 return tls_error(prefix, US gnutls_strerror(err), host, errstr);
349 }
350
351 static int
352 tls_error_sys(const uschar *prefix, int err, const host_item *host,
353 uschar ** errstr)
354 {
355 return tls_error(prefix, US strerror(err), host, errstr);
356 }
357
358
359 /*************************************************
360 * Deal with logging errors during I/O *
361 *************************************************/
362
363 /* We have to get the identity of the peer from saved data.
364
365 Argument:
366 state the current GnuTLS exim state container
367 rc the GnuTLS error code, or 0 if it's a local error
368 when text identifying read or write
369 text local error text when rc is 0
370
371 Returns: nothing
372 */
373
374 static void
375 record_io_error(exim_gnutls_state_st *state, int rc, uschar *when, uschar *text)
376 {
377 const uschar * msg;
378 uschar * errstr;
379
380 if (rc == GNUTLS_E_FATAL_ALERT_RECEIVED)
381 msg = string_sprintf("A TLS fatal alert has been received: %s",
382 US gnutls_alert_get_name(gnutls_alert_get(state->session)));
383 else
384 msg = US gnutls_strerror(rc);
385
386 (void) tls_error(when, msg, state->host, &errstr);
387
388 if (state->host)
389 log_write(0, LOG_MAIN, "H=%s [%s] TLS error on connection %s",
390 state->host->name, state->host->address, errstr);
391 else
392 {
393 uschar * conn_info = smtp_get_connection_info();
394 if (Ustrncmp(conn_info, US"SMTP ", 5) == 0) conn_info += 5;
395 /* I'd like to get separated H= here, but too hard for now */
396 log_write(0, LOG_MAIN, "TLS error on %s %s", conn_info, errstr);
397 }
398 }
399
400
401
402
403 /*************************************************
404 * Set various Exim expansion vars *
405 *************************************************/
406
407 #define exim_gnutls_cert_err(Label) \
408 do \
409 { \
410 if (rc != GNUTLS_E_SUCCESS) \
411 { \
412 DEBUG(D_tls) debug_printf("TLS: cert problem: %s: %s\n", \
413 (Label), gnutls_strerror(rc)); \
414 return rc; \
415 } \
416 } while (0)
417
418 static int
419 import_cert(const gnutls_datum_t * cert, gnutls_x509_crt_t * crtp)
420 {
421 int rc;
422
423 rc = gnutls_x509_crt_init(crtp);
424 exim_gnutls_cert_err(US"gnutls_x509_crt_init (crt)");
425
426 rc = gnutls_x509_crt_import(*crtp, cert, GNUTLS_X509_FMT_DER);
427 exim_gnutls_cert_err(US"failed to import certificate [gnutls_x509_crt_import(cert)]");
428
429 return rc;
430 }
431
432 #undef exim_gnutls_cert_err
433
434
435 /* We set various Exim global variables from the state, once a session has
436 been established. With TLS callouts, may need to change this to stack
437 variables, or just re-call it with the server state after client callout
438 has finished.
439
440 Make sure anything set here is unset in tls_getc().
441
442 Sets:
443 tls_active fd
444 tls_bits strength indicator
445 tls_certificate_verified bool indicator
446 tls_channelbinding_b64 for some SASL mechanisms
447 tls_cipher a string
448 tls_peercert pointer to library internal
449 tls_peerdn a string
450 tls_sni a (UTF-8) string
451 tls_ourcert pointer to library internal
452
453 Argument:
454 state the relevant exim_gnutls_state_st *
455 */
456
457 static void
458 extract_exim_vars_from_tls_state(exim_gnutls_state_st * state)
459 {
460 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
461 int old_pool;
462 int rc;
463 gnutls_datum_t channel;
464 #endif
465 tls_support * tlsp = state->tlsp;
466
467 tlsp->active.sock = state->fd_out;
468 tlsp->active.tls_ctx = state;
469
470 DEBUG(D_tls) debug_printf("cipher: %s\n", state->ciphersuite);
471
472 tlsp->certificate_verified = state->peer_cert_verified;
473 #ifdef SUPPORT_DANE
474 tlsp->dane_verified = state->peer_dane_verified;
475 #endif
476
477 /* note that tls_channelbinding_b64 is not saved to the spool file, since it's
478 only available for use for authenticators while this TLS session is running. */
479
480 tls_channelbinding_b64 = NULL;
481 #ifdef HAVE_GNUTLS_SESSION_CHANNEL_BINDING
482 channel.data = NULL;
483 channel.size = 0;
484 if ((rc = gnutls_session_channel_binding(state->session, GNUTLS_CB_TLS_UNIQUE, &channel)))
485 { DEBUG(D_tls) debug_printf("Channel binding error: %s\n", gnutls_strerror(rc)); }
486 else
487 {
488 old_pool = store_pool;
489 store_pool = POOL_PERM;
490 tls_channelbinding_b64 = b64encode(CUS channel.data, (int)channel.size);
491 store_pool = old_pool;
492 DEBUG(D_tls) debug_printf("Have channel bindings cached for possible auth usage.\n");
493 }
494 #endif
495
496 /* peercert is set in peer_status() */
497 tlsp->peerdn = state->peerdn;
498 tlsp->sni = state->received_sni;
499
500 /* record our certificate */
501 {
502 const gnutls_datum_t * cert = gnutls_certificate_get_ours(state->session);
503 gnutls_x509_crt_t crt;
504
505 tlsp->ourcert = cert && import_cert(cert, &crt)==0 ? crt : NULL;
506 }
507 }
508
509
510
511
512 /*************************************************
513 * Setup up DH parameters *
514 *************************************************/
515
516 /* Generating the D-H parameters may take a long time. They only need to
517 be re-generated every so often, depending on security policy. What we do is to
518 keep these parameters in a file in the spool directory. If the file does not
519 exist, we generate them. This means that it is easy to cause a regeneration.
520
521 The new file is written as a temporary file and renamed, so that an incomplete
522 file is never present. If two processes both compute some new parameters, you
523 waste a bit of effort, but it doesn't seem worth messing around with locking to
524 prevent this.
525
526 Returns: OK/DEFER/FAIL
527 */
528
529 static int
530 init_server_dh(uschar ** errstr)
531 {
532 int fd, rc;
533 unsigned int dh_bits;
534 gnutls_datum_t m;
535 uschar filename_buf[PATH_MAX];
536 uschar *filename = NULL;
537 size_t sz;
538 uschar *exp_tls_dhparam;
539 BOOL use_file_in_spool = FALSE;
540 host_item *host = NULL; /* dummy for macros */
541
542 DEBUG(D_tls) debug_printf("Initialising GnuTLS server params.\n");
543
544 if ((rc = gnutls_dh_params_init(&dh_server_params)))
545 return tls_error_gnu(US"gnutls_dh_params_init", rc, host, errstr);
546
547 m.data = NULL;
548 m.size = 0;
549
550 if (!expand_check(tls_dhparam, US"tls_dhparam", &exp_tls_dhparam, errstr))
551 return DEFER;
552
553 if (!exp_tls_dhparam)
554 {
555 DEBUG(D_tls) debug_printf("Loading default hard-coded DH params\n");
556 m.data = US std_dh_prime_default();
557 m.size = Ustrlen(m.data);
558 }
559 else if (Ustrcmp(exp_tls_dhparam, "historic") == 0)
560 use_file_in_spool = TRUE;
561 else if (Ustrcmp(exp_tls_dhparam, "none") == 0)
562 {
563 DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
564 return OK;
565 }
566 else if (exp_tls_dhparam[0] != '/')
567 {
568 if (!(m.data = US std_dh_prime_named(exp_tls_dhparam)))
569 return tls_error(US"No standard prime named", exp_tls_dhparam, NULL, errstr);
570 m.size = Ustrlen(m.data);
571 }
572 else
573 filename = exp_tls_dhparam;
574
575 if (m.data)
576 {
577 if ((rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM)))
578 return tls_error_gnu(US"gnutls_dh_params_import_pkcs3", rc, host, errstr);
579 DEBUG(D_tls) debug_printf("Loaded fixed standard D-H parameters\n");
580 return OK;
581 }
582
583 #ifdef HAVE_GNUTLS_SEC_PARAM_CONSTANTS
584 /* If you change this constant, also change dh_param_fn_ext so that we can use a
585 different filename and ensure we have sufficient bits. */
586
587 if (!(dh_bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_NORMAL)))
588 return tls_error(US"gnutls_sec_param_to_pk_bits() failed", NULL, NULL, errstr);
589 DEBUG(D_tls)
590 debug_printf("GnuTLS tells us that for D-H PK, NORMAL is %d bits.\n",
591 dh_bits);
592 #else
593 dh_bits = EXIM_SERVER_DH_BITS_PRE2_12;
594 DEBUG(D_tls)
595 debug_printf("GnuTLS lacks gnutls_sec_param_to_pk_bits(), using %d bits.\n",
596 dh_bits);
597 #endif
598
599 /* Some clients have hard-coded limits. */
600 if (dh_bits > tls_dh_max_bits)
601 {
602 DEBUG(D_tls)
603 debug_printf("tls_dh_max_bits clamping override, using %d bits instead.\n",
604 tls_dh_max_bits);
605 dh_bits = tls_dh_max_bits;
606 }
607
608 if (use_file_in_spool)
609 {
610 if (!string_format(filename_buf, sizeof(filename_buf),
611 "%s/gnutls-params-%d", spool_directory, dh_bits))
612 return tls_error(US"overlong filename", NULL, NULL, errstr);
613 filename = filename_buf;
614 }
615
616 /* Open the cache file for reading and if successful, read it and set up the
617 parameters. */
618
619 if ((fd = Uopen(filename, O_RDONLY, 0)) >= 0)
620 {
621 struct stat statbuf;
622 FILE *fp;
623 int saved_errno;
624
625 if (fstat(fd, &statbuf) < 0) /* EIO */
626 {
627 saved_errno = errno;
628 (void)close(fd);
629 return tls_error_sys(US"TLS cache stat failed", saved_errno, NULL, errstr);
630 }
631 if (!S_ISREG(statbuf.st_mode))
632 {
633 (void)close(fd);
634 return tls_error(US"TLS cache not a file", NULL, NULL, errstr);
635 }
636 if (!(fp = fdopen(fd, "rb")))
637 {
638 saved_errno = errno;
639 (void)close(fd);
640 return tls_error_sys(US"fdopen(TLS cache stat fd) failed",
641 saved_errno, NULL, errstr);
642 }
643
644 m.size = statbuf.st_size;
645 if (!(m.data = malloc(m.size)))
646 {
647 fclose(fp);
648 return tls_error_sys(US"malloc failed", errno, NULL, errstr);
649 }
650 if (!(sz = fread(m.data, m.size, 1, fp)))
651 {
652 saved_errno = errno;
653 fclose(fp);
654 free(m.data);
655 return tls_error_sys(US"fread failed", saved_errno, NULL, errstr);
656 }
657 fclose(fp);
658
659 rc = gnutls_dh_params_import_pkcs3(dh_server_params, &m, GNUTLS_X509_FMT_PEM);
660 free(m.data);
661 if (rc)
662 return tls_error_gnu(US"gnutls_dh_params_import_pkcs3", rc, host, errstr);
663 DEBUG(D_tls) debug_printf("read D-H parameters from file \"%s\"\n", filename);
664 }
665
666 /* If the file does not exist, fall through to compute new data and cache it.
667 If there was any other opening error, it is serious. */
668
669 else if (errno == ENOENT)
670 {
671 rc = -1;
672 DEBUG(D_tls)
673 debug_printf("D-H parameter cache file \"%s\" does not exist\n", filename);
674 }
675 else
676 return tls_error(string_open_failed(errno, "\"%s\" for reading", filename),
677 NULL, NULL, errstr);
678
679 /* If ret < 0, either the cache file does not exist, or the data it contains
680 is not useful. One particular case of this is when upgrading from an older
681 release of Exim in which the data was stored in a different format. We don't
682 try to be clever and support both formats; we just regenerate new data in this
683 case. */
684
685 if (rc < 0)
686 {
687 uschar *temp_fn;
688 unsigned int dh_bits_gen = dh_bits;
689
690 if ((PATH_MAX - Ustrlen(filename)) < 10)
691 return tls_error(US"Filename too long to generate replacement",
692 filename, NULL, errstr);
693
694 temp_fn = string_copy(US"%s.XXXXXXX");
695 if ((fd = mkstemp(CS temp_fn)) < 0) /* modifies temp_fn */
696 return tls_error_sys(US"Unable to open temp file", errno, NULL, errstr);
697 (void)exim_chown(temp_fn, exim_uid, exim_gid); /* Probably not necessary */
698
699 /* GnuTLS overshoots!
700 * If we ask for 2236, we might get 2237 or more.
701 * But there's no way to ask GnuTLS how many bits there really are.
702 * We can ask how many bits were used in a TLS session, but that's it!
703 * The prime itself is hidden behind too much abstraction.
704 * So we ask for less, and proceed on a wing and a prayer.
705 * First attempt, subtracted 3 for 2233 and got 2240.
706 */
707 if (dh_bits >= EXIM_CLIENT_DH_MIN_BITS + 10)
708 {
709 dh_bits_gen = dh_bits - 10;
710 DEBUG(D_tls)
711 debug_printf("being paranoid about DH generation, make it '%d' bits'\n",
712 dh_bits_gen);
713 }
714
715 DEBUG(D_tls)
716 debug_printf("requesting generation of %d bit Diffie-Hellman prime ...\n",
717 dh_bits_gen);
718 if ((rc = gnutls_dh_params_generate2(dh_server_params, dh_bits_gen)))
719 return tls_error_gnu(US"gnutls_dh_params_generate2", rc, host, errstr);
720
721 /* gnutls_dh_params_export_pkcs3() will tell us the exact size, every time,
722 and I confirmed that a NULL call to get the size first is how the GnuTLS
723 sample apps handle this. */
724
725 sz = 0;
726 m.data = NULL;
727 if ( (rc = gnutls_dh_params_export_pkcs3(dh_server_params,
728 GNUTLS_X509_FMT_PEM, m.data, &sz))
729 && rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
730 return tls_error_gnu(US"gnutls_dh_params_export_pkcs3(NULL) sizing",
731 rc, host, errstr);
732 m.size = sz;
733 if (!(m.data = malloc(m.size)))
734 return tls_error_sys(US"memory allocation failed", errno, NULL, errstr);
735
736 /* this will return a size 1 less than the allocation size above */
737 if ((rc = gnutls_dh_params_export_pkcs3(dh_server_params, GNUTLS_X509_FMT_PEM,
738 m.data, &sz)))
739 {
740 free(m.data);
741 return tls_error_gnu(US"gnutls_dh_params_export_pkcs3() real", rc, host, errstr);
742 }
743 m.size = sz; /* shrink by 1, probably */
744
745 if ((sz = write_to_fd_buf(fd, m.data, (size_t) m.size)) != m.size)
746 {
747 free(m.data);
748 return tls_error_sys(US"TLS cache write D-H params failed",
749 errno, NULL, errstr);
750 }
751 free(m.data);
752 if ((sz = write_to_fd_buf(fd, US"\n", 1)) != 1)
753 return tls_error_sys(US"TLS cache write D-H params final newline failed",
754 errno, NULL, errstr);
755
756 if ((rc = close(fd)))
757 return tls_error_sys(US"TLS cache write close() failed", errno, NULL, errstr);
758
759 if (Urename(temp_fn, filename) < 0)
760 return tls_error_sys(string_sprintf("failed to rename \"%s\" as \"%s\"",
761 temp_fn, filename), errno, NULL, errstr);
762
763 DEBUG(D_tls) debug_printf("wrote D-H parameters to file \"%s\"\n", filename);
764 }
765
766 DEBUG(D_tls) debug_printf("initialized server D-H parameters\n");
767 return OK;
768 }
769
770
771
772
773 /* Create and install a selfsigned certificate, for use in server mode */
774
775 static int
776 tls_install_selfsign(exim_gnutls_state_st * state, uschar ** errstr)
777 {
778 gnutls_x509_crt_t cert = NULL;
779 time_t now;
780 gnutls_x509_privkey_t pkey = NULL;
781 const uschar * where;
782 int rc;
783
784 where = US"initialising pkey";
785 if ((rc = gnutls_x509_privkey_init(&pkey))) goto err;
786
787 where = US"initialising cert";
788 if ((rc = gnutls_x509_crt_init(&cert))) goto err;
789
790 where = US"generating pkey";
791 if ((rc = gnutls_x509_privkey_generate(pkey, GNUTLS_PK_RSA,
792 #ifdef SUPPORT_PARAM_TO_PK_BITS
793 # ifndef GNUTLS_SEC_PARAM_MEDIUM
794 # define GNUTLS_SEC_PARAM_MEDIUM GNUTLS_SEC_PARAM_HIGH
795 # endif
796 gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA, GNUTLS_SEC_PARAM_MEDIUM),
797 #else
798 2048,
799 #endif
800 0)))
801 goto err;
802
803 where = US"configuring cert";
804 now = 1;
805 if ( (rc = gnutls_x509_crt_set_version(cert, 3))
806 || (rc = gnutls_x509_crt_set_serial(cert, &now, sizeof(now)))
807 || (rc = gnutls_x509_crt_set_activation_time(cert, now = time(NULL)))
808 || (rc = gnutls_x509_crt_set_expiration_time(cert, now + 60 * 60)) /* 1 hr */
809 || (rc = gnutls_x509_crt_set_key(cert, pkey))
810
811 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
812 GNUTLS_OID_X520_COUNTRY_NAME, 0, "UK", 2))
813 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
814 GNUTLS_OID_X520_ORGANIZATION_NAME, 0, "Exim Developers", 15))
815 || (rc = gnutls_x509_crt_set_dn_by_oid(cert,
816 GNUTLS_OID_X520_COMMON_NAME, 0,
817 smtp_active_hostname, Ustrlen(smtp_active_hostname)))
818 )
819 goto err;
820
821 where = US"signing cert";
822 if ((rc = gnutls_x509_crt_sign(cert, cert, pkey))) goto err;
823
824 where = US"installing selfsign cert";
825 /* Since: 2.4.0 */
826 if ((rc = gnutls_certificate_set_x509_key(state->x509_cred, &cert, 1, pkey)))
827 goto err;
828
829 rc = OK;
830
831 out:
832 if (cert) gnutls_x509_crt_deinit(cert);
833 if (pkey) gnutls_x509_privkey_deinit(pkey);
834 return rc;
835
836 err:
837 rc = tls_error_gnu(where, rc, NULL, errstr);
838 goto out;
839 }
840
841
842
843
844 /* Add certificate and key, from files.
845
846 Return:
847 Zero or negative: good. Negate value for certificate index if < 0.
848 Greater than zero: FAIL or DEFER code.
849 */
850
851 static int
852 tls_add_certfile(exim_gnutls_state_st * state, const host_item * host,
853 uschar * certfile, uschar * keyfile, uschar ** errstr)
854 {
855 int rc = gnutls_certificate_set_x509_key_file(state->x509_cred,
856 CS certfile, CS keyfile, GNUTLS_X509_FMT_PEM);
857 if (rc < 0)
858 return tls_error_gnu(
859 string_sprintf("cert/key setup: cert=%s key=%s", certfile, keyfile),
860 rc, host, errstr);
861 return -rc;
862 }
863
864
865 /*************************************************
866 * Variables re-expanded post-SNI *
867 *************************************************/
868
869 /* Called from both server and client code, via tls_init(), and also from
870 the SNI callback after receiving an SNI, if tls_certificate includes "tls_sni".
871
872 We can tell the two apart by state->received_sni being non-NULL in callback.
873
874 The callback should not call us unless state->trigger_sni_changes is true,
875 which we are responsible for setting on the first pass through.
876
877 Arguments:
878 state exim_gnutls_state_st *
879 errstr error string pointer
880
881 Returns: OK/DEFER/FAIL
882 */
883
884 static int
885 tls_expand_session_files(exim_gnutls_state_st * state, uschar ** errstr)
886 {
887 struct stat statbuf;
888 int rc;
889 const host_item *host = state->host; /* macro should be reconsidered? */
890 uschar *saved_tls_certificate = NULL;
891 uschar *saved_tls_privatekey = NULL;
892 uschar *saved_tls_verify_certificates = NULL;
893 uschar *saved_tls_crl = NULL;
894 int cert_count;
895
896 /* We check for tls_sni *before* expansion. */
897 if (!host) /* server */
898 if (!state->received_sni)
899 {
900 if ( state->tls_certificate
901 && ( Ustrstr(state->tls_certificate, US"tls_sni")
902 || Ustrstr(state->tls_certificate, US"tls_in_sni")
903 || Ustrstr(state->tls_certificate, US"tls_out_sni")
904 ) )
905 {
906 DEBUG(D_tls) debug_printf("We will re-expand TLS session files if we receive SNI.\n");
907 state->trigger_sni_changes = TRUE;
908 }
909 }
910 else
911 {
912 /* useful for debugging */
913 saved_tls_certificate = state->exp_tls_certificate;
914 saved_tls_privatekey = state->exp_tls_privatekey;
915 saved_tls_verify_certificates = state->exp_tls_verify_certificates;
916 saved_tls_crl = state->exp_tls_crl;
917 }
918
919 if ((rc = gnutls_certificate_allocate_credentials(&state->x509_cred)))
920 return tls_error_gnu(US"gnutls_certificate_allocate_credentials",
921 rc, host, errstr);
922
923 #ifdef SUPPORT_SRV_OCSP_STACK
924 gnutls_certificate_set_flags(state->x509_cred, GNUTLS_CERTIFICATE_API_V2);
925 #endif
926
927 /* remember: expand_check_tlsvar() is expand_check() but fiddling with
928 state members, assuming consistent naming; and expand_check() returns
929 false if expansion failed, unless expansion was forced to fail. */
930
931 /* check if we at least have a certificate, before doing expensive
932 D-H generation. */
933
934 if (!expand_check_tlsvar(tls_certificate, errstr))
935 return DEFER;
936
937 /* certificate is mandatory in server, optional in client */
938
939 if ( !state->exp_tls_certificate
940 || !*state->exp_tls_certificate
941 )
942 if (!host)
943 return tls_install_selfsign(state, errstr);
944 else
945 DEBUG(D_tls) debug_printf("TLS: no client certificate specified; okay\n");
946
947 if (state->tls_privatekey && !expand_check_tlsvar(tls_privatekey, errstr))
948 return DEFER;
949
950 /* tls_privatekey is optional, defaulting to same file as certificate */
951
952 if (state->tls_privatekey == NULL || *state->tls_privatekey == '\0')
953 {
954 state->tls_privatekey = state->tls_certificate;
955 state->exp_tls_privatekey = state->exp_tls_certificate;
956 }
957
958
959 if (state->exp_tls_certificate && *state->exp_tls_certificate)
960 {
961 DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
962 state->exp_tls_certificate, state->exp_tls_privatekey);
963
964 if (state->received_sni)
965 if ( Ustrcmp(state->exp_tls_certificate, saved_tls_certificate) == 0
966 && Ustrcmp(state->exp_tls_privatekey, saved_tls_privatekey) == 0
967 )
968 {
969 DEBUG(D_tls) debug_printf("TLS SNI: cert and key unchanged\n");
970 }
971 else
972 {
973 DEBUG(D_tls) debug_printf("TLS SNI: have a changed cert/key pair.\n");
974 }
975
976 if (!host) /* server */
977 {
978 const uschar * clist = state->exp_tls_certificate;
979 const uschar * klist = state->exp_tls_privatekey;
980 const uschar * olist;
981 int csep = 0, ksep = 0, osep = 0, cnt = 0;
982 uschar * cfile, * kfile, * ofile;
983
984 #ifndef DISABLE_OCSP
985 if (!expand_check(tls_ocsp_file, US"tls_ocsp_file", &ofile, errstr))
986 return DEFER;
987 olist = ofile;
988 #endif
989
990 while (cfile = string_nextinlist(&clist, &csep, NULL, 0))
991
992 if (!(kfile = string_nextinlist(&klist, &ksep, NULL, 0)))
993 return tls_error(US"cert/key setup: out of keys", NULL, host, errstr);
994 else if (0 < (rc = tls_add_certfile(state, host, cfile, kfile, errstr)))
995 return rc;
996 else
997 {
998 int gnutls_cert_index = -rc;
999 DEBUG(D_tls) debug_printf("TLS: cert/key %s registered\n", cfile);
1000
1001 /* Set the OCSP stapling server info */
1002
1003 #ifndef DISABLE_OCSP
1004 if (tls_ocsp_file)
1005 if (gnutls_buggy_ocsp)
1006 {
1007 DEBUG(D_tls)
1008 debug_printf("GnuTLS library is buggy for OCSP; avoiding\n");
1009 }
1010 else if ((ofile = string_nextinlist(&olist, &osep, NULL, 0)))
1011 {
1012 /* Use the full callback method for stapling just to get
1013 observability. More efficient would be to read the file once only,
1014 if it never changed (due to SNI). Would need restart on file update,
1015 or watch datestamp. */
1016
1017 # ifdef SUPPORT_SRV_OCSP_STACK
1018 if ((rc = gnutls_certificate_set_ocsp_status_request_function2(
1019 state->x509_cred, gnutls_cert_index,
1020 server_ocsp_stapling_cb, ofile)))
1021 return tls_error_gnu(
1022 US"gnutls_certificate_set_ocsp_status_request_function2",
1023 rc, host, errstr);
1024 # else
1025 if (cnt++ > 0)
1026 {
1027 DEBUG(D_tls)
1028 debug_printf("oops; multiple OCSP files not supported\n");
1029 break;
1030 }
1031 gnutls_certificate_set_ocsp_status_request_function(
1032 state->x509_cred, server_ocsp_stapling_cb, ofile);
1033 # endif
1034
1035 DEBUG(D_tls) debug_printf("OCSP response file = %s\n", ofile);
1036 }
1037 else
1038 DEBUG(D_tls) debug_printf("ran out of OCSP response files in list\n");
1039 #endif
1040 }
1041 }
1042 else
1043 {
1044 if (0 < (rc = tls_add_certfile(state, host,
1045 state->exp_tls_certificate, state->exp_tls_privatekey, errstr)))
1046 return rc;
1047 DEBUG(D_tls) debug_printf("TLS: cert/key registered\n");
1048 }
1049
1050 } /* tls_certificate */
1051
1052
1053 /* Set the trusted CAs file if one is provided, and then add the CRL if one is
1054 provided. Experiment shows that, if the certificate file is empty, an unhelpful
1055 error message is provided. However, if we just refrain from setting anything up
1056 in that case, certificate verification fails, which seems to be the correct
1057 behaviour. */
1058
1059 if (state->tls_verify_certificates && *state->tls_verify_certificates)
1060 {
1061 if (!expand_check_tlsvar(tls_verify_certificates, errstr))
1062 return DEFER;
1063 #ifndef SUPPORT_SYSDEFAULT_CABUNDLE
1064 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1065 state->exp_tls_verify_certificates = NULL;
1066 #endif
1067 if (state->tls_crl && *state->tls_crl)
1068 if (!expand_check_tlsvar(tls_crl, errstr))
1069 return DEFER;
1070
1071 if (!(state->exp_tls_verify_certificates &&
1072 *state->exp_tls_verify_certificates))
1073 {
1074 DEBUG(D_tls)
1075 debug_printf("TLS: tls_verify_certificates expanded empty, ignoring\n");
1076 /* With no tls_verify_certificates, we ignore tls_crl too */
1077 return OK;
1078 }
1079 }
1080 else
1081 {
1082 DEBUG(D_tls)
1083 debug_printf("TLS: tls_verify_certificates not set or empty, ignoring\n");
1084 return OK;
1085 }
1086
1087 #ifdef SUPPORT_SYSDEFAULT_CABUNDLE
1088 if (Ustrcmp(state->exp_tls_verify_certificates, "system") == 0)
1089 cert_count = gnutls_certificate_set_x509_system_trust(state->x509_cred);
1090 else
1091 #endif
1092 {
1093 if (Ustat(state->exp_tls_verify_certificates, &statbuf) < 0)
1094 {
1095 log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
1096 "(tls_verify_certificates): %s", state->exp_tls_verify_certificates,
1097 strerror(errno));
1098 return DEFER;
1099 }
1100
1101 #ifndef SUPPORT_CA_DIR
1102 /* The test suite passes in /dev/null; we could check for that path explicitly,
1103 but who knows if someone has some weird FIFO which always dumps some certs, or
1104 other weirdness. The thing we really want to check is that it's not a
1105 directory, since while OpenSSL supports that, GnuTLS does not.
1106 So s/!S_ISREG/S_ISDIR/ and change some messaging ... */
1107 if (S_ISDIR(statbuf.st_mode))
1108 {
1109 DEBUG(D_tls)
1110 debug_printf("verify certificates path is a dir: \"%s\"\n",
1111 state->exp_tls_verify_certificates);
1112 log_write(0, LOG_MAIN|LOG_PANIC,
1113 "tls_verify_certificates \"%s\" is a directory",
1114 state->exp_tls_verify_certificates);
1115 return DEFER;
1116 }
1117 #endif
1118
1119 DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
1120 state->exp_tls_verify_certificates, statbuf.st_size);
1121
1122 if (statbuf.st_size == 0)
1123 {
1124 DEBUG(D_tls)
1125 debug_printf("cert file empty, no certs, no verification, ignoring any CRL\n");
1126 return OK;
1127 }
1128
1129 cert_count =
1130
1131 #ifdef SUPPORT_CA_DIR
1132 (statbuf.st_mode & S_IFMT) == S_IFDIR
1133 ?
1134 gnutls_certificate_set_x509_trust_dir(state->x509_cred,
1135 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM)
1136 :
1137 #endif
1138 gnutls_certificate_set_x509_trust_file(state->x509_cred,
1139 CS state->exp_tls_verify_certificates, GNUTLS_X509_FMT_PEM);
1140 }
1141
1142 if (cert_count < 0)
1143 return tls_error_gnu(US"setting certificate trust", cert_count, host, errstr);
1144 DEBUG(D_tls)
1145 debug_printf("Added %d certificate authorities.\n", cert_count);
1146
1147 if (state->tls_crl && *state->tls_crl &&
1148 state->exp_tls_crl && *state->exp_tls_crl)
1149 {
1150 DEBUG(D_tls) debug_printf("loading CRL file = %s\n", state->exp_tls_crl);
1151 if ((cert_count = gnutls_certificate_set_x509_crl_file(state->x509_cred,
1152 CS state->exp_tls_crl, GNUTLS_X509_FMT_PEM)) < 0)
1153 return tls_error_gnu(US"gnutls_certificate_set_x509_crl_file",
1154 cert_count, host, errstr);
1155
1156 DEBUG(D_tls) debug_printf("Processed %d CRLs.\n", cert_count);
1157 }
1158
1159 return OK;
1160 }
1161
1162
1163
1164
1165 /*************************************************
1166 * Set X.509 state variables *
1167 *************************************************/
1168
1169 /* In GnuTLS, the registered cert/key are not replaced by a later
1170 set of a cert/key, so for SNI support we need a whole new x509_cred
1171 structure. Which means various other non-re-expanded pieces of state
1172 need to be re-set in the new struct, so the setting logic is pulled
1173 out to this.
1174
1175 Arguments:
1176 state exim_gnutls_state_st *
1177 errstr error string pointer
1178
1179 Returns: OK/DEFER/FAIL
1180 */
1181
1182 static int
1183 tls_set_remaining_x509(exim_gnutls_state_st *state, uschar ** errstr)
1184 {
1185 int rc;
1186 const host_item *host = state->host; /* macro should be reconsidered? */
1187
1188 /* Create D-H parameters, or read them from the cache file. This function does
1189 its own SMTP error messaging. This only happens for the server, TLS D-H ignores
1190 client-side params. */
1191
1192 if (!state->host)
1193 {
1194 if (!dh_server_params)
1195 if ((rc = init_server_dh(errstr)) != OK) return rc;
1196 gnutls_certificate_set_dh_params(state->x509_cred, dh_server_params);
1197 }
1198
1199 /* Link the credentials to the session. */
1200
1201 if ((rc = gnutls_credentials_set(state->session,
1202 GNUTLS_CRD_CERTIFICATE, state->x509_cred)))
1203 return tls_error_gnu(US"gnutls_credentials_set", rc, host, errstr);
1204
1205 return OK;
1206 }
1207
1208 /*************************************************
1209 * Initialize for GnuTLS *
1210 *************************************************/
1211
1212
1213 #ifndef DISABLE_OCSP
1214
1215 static BOOL
1216 tls_is_buggy_ocsp(void)
1217 {
1218 const uschar * s;
1219 uschar maj, mid, mic;
1220
1221 s = CUS gnutls_check_version(NULL);
1222 maj = atoi(CCS s);
1223 if (maj == 3)
1224 {
1225 while (*s && *s != '.') s++;
1226 mid = atoi(CCS ++s);
1227 if (mid <= 2)
1228 return TRUE;
1229 else if (mid >= 5)
1230 return FALSE;
1231 else
1232 {
1233 while (*s && *s != '.') s++;
1234 mic = atoi(CCS ++s);
1235 return mic <= (mid == 3 ? 16 : 3);
1236 }
1237 }
1238 return FALSE;
1239 }
1240
1241 #endif
1242
1243
1244 /* Called from both server and client code. In the case of a server, errors
1245 before actual TLS negotiation return DEFER.
1246
1247 Arguments:
1248 host connected host, if client; NULL if server
1249 certificate certificate file
1250 privatekey private key file
1251 sni TLS SNI to send, sometimes when client; else NULL
1252 cas CA certs file
1253 crl CRL file
1254 require_ciphers tls_require_ciphers setting
1255 caller_state returned state-info structure
1256 errstr error string pointer
1257
1258 Returns: OK/DEFER/FAIL
1259 */
1260
1261 static int
1262 tls_init(
1263 const host_item *host,
1264 const uschar *certificate,
1265 const uschar *privatekey,
1266 const uschar *sni,
1267 const uschar *cas,
1268 const uschar *crl,
1269 const uschar *require_ciphers,
1270 exim_gnutls_state_st **caller_state,
1271 tls_support * tlsp,
1272 uschar ** errstr)
1273 {
1274 exim_gnutls_state_st * state;
1275 int rc;
1276 size_t sz;
1277 const char * errpos;
1278 const uschar * p;
1279
1280 if (!exim_gnutls_base_init_done)
1281 {
1282 DEBUG(D_tls) debug_printf("GnuTLS global init required.\n");
1283
1284 #ifdef HAVE_GNUTLS_PKCS11
1285 /* By default, gnutls_global_init will init PKCS11 support in auto mode,
1286 which loads modules from a config file, which sounds good and may be wanted
1287 by some sysadmin, but also means in common configurations that GNOME keyring
1288 environment variables are used and so breaks for users calling mailq.
1289 To prevent this, we init PKCS11 first, which is the documented approach. */
1290 if (!gnutls_allow_auto_pkcs11)
1291 if ((rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL)))
1292 return tls_error_gnu(US"gnutls_pkcs11_init", rc, host, errstr);
1293 #endif
1294
1295 if ((rc = gnutls_global_init()))
1296 return tls_error_gnu(US"gnutls_global_init", rc, host, errstr);
1297
1298 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1299 DEBUG(D_tls)
1300 {
1301 gnutls_global_set_log_function(exim_gnutls_logger_cb);
1302 /* arbitrarily chosen level; bump up to 9 for more */
1303 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
1304 }
1305 #endif
1306
1307 #ifndef DISABLE_OCSP
1308 if (tls_ocsp_file && (gnutls_buggy_ocsp = tls_is_buggy_ocsp()))
1309 log_write(0, LOG_MAIN, "OCSP unusable with this GnuTLS library version");
1310 #endif
1311
1312 exim_gnutls_base_init_done = TRUE;
1313 }
1314
1315 if (host)
1316 {
1317 /* For client-side sessions we allocate a context. This lets us run
1318 several in parallel. */
1319 int old_pool = store_pool;
1320 store_pool = POOL_PERM;
1321 state = store_get(sizeof(exim_gnutls_state_st));
1322 store_pool = old_pool;
1323
1324 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1325 state->tlsp = tlsp;
1326 DEBUG(D_tls) debug_printf("initialising GnuTLS client session\n");
1327 rc = gnutls_init(&state->session, GNUTLS_CLIENT);
1328 }
1329 else
1330 {
1331 state = &state_server;
1332 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
1333 state->tlsp = tlsp;
1334 DEBUG(D_tls) debug_printf("initialising GnuTLS server session\n");
1335 rc = gnutls_init(&state->session, GNUTLS_SERVER);
1336 }
1337 if (rc)
1338 return tls_error_gnu(US"gnutls_init", rc, host, errstr);
1339
1340 state->host = host;
1341
1342 state->tls_certificate = certificate;
1343 state->tls_privatekey = privatekey;
1344 state->tls_require_ciphers = require_ciphers;
1345 state->tls_sni = sni;
1346 state->tls_verify_certificates = cas;
1347 state->tls_crl = crl;
1348
1349 /* This handles the variables that might get re-expanded after TLS SNI;
1350 that's tls_certificate, tls_privatekey, tls_verify_certificates, tls_crl */
1351
1352 DEBUG(D_tls)
1353 debug_printf("Expanding various TLS configuration options for session credentials.\n");
1354 if ((rc = tls_expand_session_files(state, errstr)) != OK) return rc;
1355
1356 /* These are all other parts of the x509_cred handling, since SNI in GnuTLS
1357 requires a new structure afterwards. */
1358
1359 if ((rc = tls_set_remaining_x509(state, errstr)) != OK) return rc;
1360
1361 /* set SNI in client, only */
1362 if (host)
1363 {
1364 if (!expand_check(sni, US"tls_out_sni", &state->tlsp->sni, errstr))
1365 return DEFER;
1366 if (state->tlsp->sni && *state->tlsp->sni)
1367 {
1368 DEBUG(D_tls)
1369 debug_printf("Setting TLS client SNI to \"%s\"\n", state->tlsp->sni);
1370 sz = Ustrlen(state->tlsp->sni);
1371 if ((rc = gnutls_server_name_set(state->session,
1372 GNUTLS_NAME_DNS, state->tlsp->sni, sz)))
1373 return tls_error_gnu(US"gnutls_server_name_set", rc, host, errstr);
1374 }
1375 }
1376 else if (state->tls_sni)
1377 DEBUG(D_tls) debug_printf("*** PROBABLY A BUG *** " \
1378 "have an SNI set for a server [%s]\n", state->tls_sni);
1379
1380 /* This is the priority string support,
1381 http://www.gnutls.org/manual/html_node/Priority-Strings.html
1382 and replaces gnutls_require_kx, gnutls_require_mac & gnutls_require_protocols.
1383 This was backwards incompatible, but means Exim no longer needs to track
1384 all algorithms and provide string forms for them. */
1385
1386 p = NULL;
1387 if (state->tls_require_ciphers && *state->tls_require_ciphers)
1388 {
1389 if (!expand_check_tlsvar(tls_require_ciphers, errstr))
1390 return DEFER;
1391 if (state->exp_tls_require_ciphers && *state->exp_tls_require_ciphers)
1392 {
1393 p = state->exp_tls_require_ciphers;
1394 DEBUG(D_tls) debug_printf("GnuTLS session cipher/priority \"%s\"\n", p);
1395 }
1396 }
1397 if (!p)
1398 {
1399 p = exim_default_gnutls_priority;
1400 DEBUG(D_tls)
1401 debug_printf("GnuTLS using default session cipher/priority \"%s\"\n", p);
1402 }
1403
1404 if ((rc = gnutls_priority_init(&state->priority_cache, CCS p, &errpos)))
1405 return tls_error_gnu(string_sprintf(
1406 "gnutls_priority_init(%s) failed at offset %ld, \"%.6s..\"",
1407 p, errpos - CS p, errpos),
1408 rc, host, errstr);
1409
1410 if ((rc = gnutls_priority_set(state->session, state->priority_cache)))
1411 return tls_error_gnu(US"gnutls_priority_set", rc, host, errstr);
1412
1413 /* This also sets the server ticket expiration time to the same, and
1414 the STEK rotation time to 3x. */
1415
1416 gnutls_db_set_cache_expiration(state->session, ssl_session_timeout);
1417
1418 /* Reduce security in favour of increased compatibility, if the admin
1419 decides to make that trade-off. */
1420 if (gnutls_compat_mode)
1421 {
1422 #if LIBGNUTLS_VERSION_NUMBER >= 0x020104
1423 DEBUG(D_tls) debug_printf("lowering GnuTLS security, compatibility mode\n");
1424 gnutls_session_enable_compatibility_mode(state->session);
1425 #else
1426 DEBUG(D_tls) debug_printf("Unable to set gnutls_compat_mode - GnuTLS version too old\n");
1427 #endif
1428 }
1429
1430 *caller_state = state;
1431 return OK;
1432 }
1433
1434
1435
1436 /*************************************************
1437 * Extract peer information *
1438 *************************************************/
1439
1440 static const uschar *
1441 cipher_stdname_kcm(gnutls_kx_algorithm_t kx, gnutls_cipher_algorithm_t cipher,
1442 gnutls_mac_algorithm_t mac)
1443 {
1444 uschar cs_id[2];
1445 gnutls_kx_algorithm_t kx_i;
1446 gnutls_cipher_algorithm_t cipher_i;
1447 gnutls_mac_algorithm_t mac_i;
1448
1449 for (size_t i = 0;
1450 gnutls_cipher_suite_info(i, cs_id, &kx_i, &cipher_i, &mac_i, NULL);
1451 i++)
1452 if (kx_i == kx && cipher_i == cipher && mac_i == mac)
1453 return cipher_stdname(cs_id[0], cs_id[1]);
1454 return NULL;
1455 }
1456
1457
1458
1459 /* Called from both server and client code.
1460 Only this is allowed to set state->peerdn and state->have_set_peerdn
1461 and we use that to detect double-calls.
1462
1463 NOTE: the state blocks last while the TLS connection is up, which is fine
1464 for logging in the server side, but for the client side, we log after teardown
1465 in src/deliver.c. While the session is up, we can twist about states and
1466 repoint tls_* globals, but those variables used for logging or other variable
1467 expansion that happens _after_ delivery need to have a longer life-time.
1468
1469 So for those, we get the data from POOL_PERM; the re-invoke guard keeps us from
1470 doing this more than once per generation of a state context. We set them in
1471 the state context, and repoint tls_* to them. After the state goes away, the
1472 tls_* copies of the pointers remain valid and client delivery logging is happy.
1473
1474 tls_certificate_verified is a BOOL, so the tls_peerdn and tls_cipher issues
1475 don't apply.
1476
1477 Arguments:
1478 state exim_gnutls_state_st *
1479 errstr pointer to error string
1480
1481 Returns: OK/DEFER/FAIL
1482 */
1483
1484 static int
1485 peer_status(exim_gnutls_state_st * state, uschar ** errstr)
1486 {
1487 gnutls_session_t session = state->session;
1488 const gnutls_datum_t * cert_list;
1489 int old_pool, rc;
1490 unsigned int cert_list_size = 0;
1491 gnutls_protocol_t protocol;
1492 gnutls_cipher_algorithm_t cipher;
1493 gnutls_kx_algorithm_t kx;
1494 gnutls_mac_algorithm_t mac;
1495 gnutls_certificate_type_t ct;
1496 gnutls_x509_crt_t crt;
1497 uschar * dn_buf;
1498 size_t sz;
1499
1500 if (state->have_set_peerdn)
1501 return OK;
1502 state->have_set_peerdn = TRUE;
1503
1504 state->peerdn = NULL;
1505
1506 /* tls_cipher */
1507 cipher = gnutls_cipher_get(session);
1508 protocol = gnutls_protocol_get_version(session);
1509 mac = gnutls_mac_get(session);
1510 kx =
1511 #ifdef GNUTLS_TLS1_3
1512 protocol >= GNUTLS_TLS1_3 ? 0 :
1513 #endif
1514 gnutls_kx_get(session);
1515
1516 old_pool = store_pool;
1517 {
1518 tls_support * tlsp = state->tlsp;
1519 store_pool = POOL_PERM;
1520
1521 #ifdef SUPPORT_GNUTLS_SESS_DESC
1522 {
1523 gstring * g = NULL;
1524 uschar * s = US gnutls_session_get_desc(session), c;
1525
1526 /* Nikos M suggests we use this by preference. It returns like:
1527 (TLS1.3)-(ECDHE-SECP256R1)-(RSA-PSS-RSAE-SHA256)-(AES-256-GCM)
1528
1529 For partial back-compat, put a colon after the TLS version, replace the
1530 )-( grouping with __, replace in-group - with _ and append the :keysize. */
1531
1532 /* debug_printf("peer_status: gnutls_session_get_desc %s\n", s); */
1533
1534 for (s++; (c = *s) && c != ')'; s++) g = string_catn(g, s, 1);
1535 g = string_catn(g, US":", 1);
1536 if (*s) s++; /* now on _ between groups */
1537 while ((c = *s))
1538 {
1539 for (*++s && ++s; (c = *s) && c != ')'; s++) g = string_catn(g, c == '-' ? US"_" : s, 1);
1540 /* now on ) closing group */
1541 if ((c = *s) && *++s == '-') g = string_catn(g, US"__", 2);
1542 /* now on _ between groups */
1543 }
1544 g = string_catn(g, US":", 1);
1545 g = string_cat(g, string_sprintf("%d", (int) gnutls_cipher_get_key_size(cipher) * 8));
1546 state->ciphersuite = string_from_gstring(g);
1547 }
1548 #else
1549 state->ciphersuite = string_sprintf("%s:%s:%d",
1550 gnutls_protocol_get_name(protocol),
1551 gnutls_cipher_suite_get_name(kx, cipher, mac),
1552 (int) gnutls_cipher_get_key_size(cipher) * 8);
1553
1554 /* I don't see a way that spaces could occur, in the current GnuTLS
1555 code base, but it was a concern in the old code and perhaps older GnuTLS
1556 releases did return "TLS 1.0"; play it safe, just in case. */
1557
1558 for (uschar * p = state->ciphersuite; *p; p++) if (isspace(*p)) *p = '-';
1559 #endif
1560
1561 /* debug_printf("peer_status: ciphersuite %s\n", state->ciphersuite); */
1562
1563 tlsp->cipher = state->ciphersuite;
1564 tlsp->bits = gnutls_cipher_get_key_size(cipher) * 8;
1565
1566 tlsp->cipher_stdname = cipher_stdname_kcm(kx, cipher, mac);
1567 }
1568 store_pool = old_pool;
1569
1570 /* tls_peerdn */
1571 cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
1572
1573 if (!cert_list || cert_list_size == 0)
1574 {
1575 DEBUG(D_tls) debug_printf("TLS: no certificate from peer (%p & %d)\n",
1576 cert_list, cert_list_size);
1577 if (state->verify_requirement >= VERIFY_REQUIRED)
1578 return tls_error(US"certificate verification failed",
1579 US"no certificate received from peer", state->host, errstr);
1580 return OK;
1581 }
1582
1583 if ((ct = gnutls_certificate_type_get(session)) != GNUTLS_CRT_X509)
1584 {
1585 const uschar * ctn = US gnutls_certificate_type_get_name(ct);
1586 DEBUG(D_tls)
1587 debug_printf("TLS: peer cert not X.509 but instead \"%s\"\n", ctn);
1588 if (state->verify_requirement >= VERIFY_REQUIRED)
1589 return tls_error(US"certificate verification not possible, unhandled type",
1590 ctn, state->host, errstr);
1591 return OK;
1592 }
1593
1594 #define exim_gnutls_peer_err(Label) \
1595 do { \
1596 if (rc != GNUTLS_E_SUCCESS) \
1597 { \
1598 DEBUG(D_tls) debug_printf("TLS: peer cert problem: %s: %s\n", \
1599 (Label), gnutls_strerror(rc)); \
1600 if (state->verify_requirement >= VERIFY_REQUIRED) \
1601 return tls_error_gnu((Label), rc, state->host, errstr); \
1602 return OK; \
1603 } \
1604 } while (0)
1605
1606 rc = import_cert(&cert_list[0], &crt);
1607 exim_gnutls_peer_err(US"cert 0");
1608
1609 state->tlsp->peercert = state->peercert = crt;
1610
1611 sz = 0;
1612 rc = gnutls_x509_crt_get_dn(crt, NULL, &sz);
1613 if (rc != GNUTLS_E_SHORT_MEMORY_BUFFER)
1614 {
1615 exim_gnutls_peer_err(US"getting size for cert DN failed");
1616 return FAIL; /* should not happen */
1617 }
1618 dn_buf = store_get_perm(sz);
1619 rc = gnutls_x509_crt_get_dn(crt, CS dn_buf, &sz);
1620 exim_gnutls_peer_err(US"failed to extract certificate DN [gnutls_x509_crt_get_dn(cert 0)]");
1621
1622 state->peerdn = dn_buf;
1623
1624 return OK;
1625 #undef exim_gnutls_peer_err
1626 }
1627
1628
1629
1630
1631 /*************************************************
1632 * Verify peer certificate *
1633 *************************************************/
1634
1635 /* Called from both server and client code.
1636 *Should* be using a callback registered with
1637 gnutls_certificate_set_verify_function() to fail the handshake if we dislike
1638 the peer information, but that's too new for some OSes.
1639
1640 Arguments:
1641 state exim_gnutls_state_st *
1642 errstr where to put an error message
1643
1644 Returns:
1645 FALSE if the session should be rejected
1646 TRUE if the cert is okay or we just don't care
1647 */
1648
1649 static BOOL
1650 verify_certificate(exim_gnutls_state_st * state, uschar ** errstr)
1651 {
1652 int rc;
1653 uint verify;
1654
1655 DEBUG(D_tls) debug_printf("TLS: checking peer certificate\n");
1656 *errstr = NULL;
1657 rc = peer_status(state, errstr);
1658
1659 if (state->verify_requirement == VERIFY_NONE)
1660 return TRUE;
1661
1662 if (rc != OK || !state->peerdn)
1663 {
1664 verify = GNUTLS_CERT_INVALID;
1665 *errstr = US"certificate not supplied";
1666 }
1667 else
1668
1669 {
1670 #ifdef SUPPORT_DANE
1671 if (state->verify_requirement == VERIFY_DANE && state->host)
1672 {
1673 /* Using dane_verify_session_crt() would be easy, as it does it all for us
1674 including talking to a DNS resolver. But we want to do that bit ourselves
1675 as the testsuite intercepts and fakes its own DNS environment. */
1676
1677 dane_state_t s;
1678 dane_query_t r;
1679 uint lsize;
1680 const gnutls_datum_t * certlist =
1681 gnutls_certificate_get_peers(state->session, &lsize);
1682 int usage = tls_out.tlsa_usage;
1683
1684 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1685 /* Split the TLSA records into two sets, TA and EE selectors. Run the
1686 dane-verification separately so that we know which selector verified;
1687 then we know whether to do name-verification (needed for TA but not EE). */
1688
1689 if (usage == ((1<<DANESSL_USAGE_DANE_TA) | (1<<DANESSL_USAGE_DANE_EE)))
1690 { /* a mixed-usage bundle */
1691 int i, j, nrec;
1692 const char ** dd;
1693 int * ddl;
1694
1695 for(nrec = 0; state->dane_data_len[nrec]; ) nrec++;
1696 nrec++;
1697
1698 dd = store_get(nrec * sizeof(uschar *));
1699 ddl = store_get(nrec * sizeof(int));
1700 nrec--;
1701
1702 if ((rc = dane_state_init(&s, 0)))
1703 goto tlsa_prob;
1704
1705 for (usage = DANESSL_USAGE_DANE_EE;
1706 usage >= DANESSL_USAGE_DANE_TA; usage--)
1707 { /* take records with this usage */
1708 for (j = i = 0; i < nrec; i++)
1709 if (state->dane_data[i][0] == usage)
1710 {
1711 dd[j] = state->dane_data[i];
1712 ddl[j++] = state->dane_data_len[i];
1713 }
1714 if (j)
1715 {
1716 dd[j] = NULL;
1717 ddl[j] = 0;
1718
1719 if ((rc = dane_raw_tlsa(s, &r, (char * const *)dd, ddl, 1, 0)))
1720 goto tlsa_prob;
1721
1722 if ((rc = dane_verify_crt_raw(s, certlist, lsize,
1723 gnutls_certificate_type_get(state->session),
1724 r, 0,
1725 usage == DANESSL_USAGE_DANE_EE
1726 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1727 &verify)))
1728 {
1729 DEBUG(D_tls)
1730 debug_printf("TLSA record problem: %s\n", dane_strerror(rc));
1731 }
1732 else if (verify == 0) /* verification passed */
1733 {
1734 usage = 1 << usage;
1735 break;
1736 }
1737 }
1738 }
1739
1740 if (rc) goto tlsa_prob;
1741 }
1742 else
1743 # endif
1744 {
1745 if ( (rc = dane_state_init(&s, 0))
1746 || (rc = dane_raw_tlsa(s, &r, state->dane_data, state->dane_data_len,
1747 1, 0))
1748 || (rc = dane_verify_crt_raw(s, certlist, lsize,
1749 gnutls_certificate_type_get(state->session),
1750 r, 0,
1751 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1752 usage == (1 << DANESSL_USAGE_DANE_EE)
1753 ? DANE_VFLAG_ONLY_CHECK_EE_USAGE : 0,
1754 # else
1755 0,
1756 # endif
1757 &verify))
1758 )
1759 goto tlsa_prob;
1760 }
1761
1762 if (verify != 0) /* verification failed */
1763 {
1764 gnutls_datum_t str;
1765 (void) dane_verification_status_print(verify, &str, 0);
1766 *errstr = US str.data; /* don't bother to free */
1767 goto badcert;
1768 }
1769
1770 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1771 /* If a TA-mode TLSA record was used for verification we must additionally
1772 verify the cert name (but not the CA chain). For EE-mode, skip it. */
1773
1774 if (usage & (1 << DANESSL_USAGE_DANE_EE))
1775 # endif
1776 {
1777 state->peer_dane_verified = state->peer_cert_verified = TRUE;
1778 goto goodcert;
1779 }
1780 # ifdef GNUTLS_BROKEN_DANE_VALIDATION
1781 /* Assume that the name on the A-record is the one that should be matching
1782 the cert. An alternate view is that the domain part of the email address
1783 is also permissible. */
1784
1785 if (gnutls_x509_crt_check_hostname(state->tlsp->peercert,
1786 CS state->host->name))
1787 {
1788 state->peer_dane_verified = state->peer_cert_verified = TRUE;
1789 goto goodcert;
1790 }
1791 # endif
1792 }
1793 #endif /*SUPPORT_DANE*/
1794
1795 rc = gnutls_certificate_verify_peers2(state->session, &verify);
1796 }
1797
1798 /* Handle the result of verification. INVALID is set if any others are. */
1799
1800 if (rc < 0 || verify & (GNUTLS_CERT_INVALID|GNUTLS_CERT_REVOKED))
1801 {
1802 state->peer_cert_verified = FALSE;
1803 if (!*errstr)
1804 {
1805 #ifdef GNUTLS_CERT_VFY_STATUS_PRINT
1806 DEBUG(D_tls)
1807 {
1808 gnutls_datum_t txt;
1809
1810 if (gnutls_certificate_verification_status_print(verify,
1811 gnutls_certificate_type_get(state->session), &txt, 0)
1812 == GNUTLS_E_SUCCESS)
1813 {
1814 debug_printf("%s\n", txt.data);
1815 gnutls_free(txt.data);
1816 }
1817 }
1818 #endif
1819 *errstr = verify & GNUTLS_CERT_REVOKED
1820 ? US"certificate revoked" : US"certificate invalid";
1821 }
1822
1823 DEBUG(D_tls)
1824 debug_printf("TLS certificate verification failed (%s): peerdn=\"%s\"\n",
1825 *errstr, state->peerdn ? state->peerdn : US"<unset>");
1826
1827 if (state->verify_requirement >= VERIFY_REQUIRED)
1828 goto badcert;
1829 DEBUG(D_tls)
1830 debug_printf("TLS verify failure overridden (host in tls_try_verify_hosts)\n");
1831 }
1832
1833 else
1834 {
1835 /* Client side, check the server's certificate name versus the name on the
1836 A-record for the connection we made. What to do for server side - what name
1837 to use for client? We document that there is no such checking for server
1838 side. */
1839
1840 if ( state->exp_tls_verify_cert_hostnames
1841 && !gnutls_x509_crt_check_hostname(state->tlsp->peercert,
1842 CS state->exp_tls_verify_cert_hostnames)
1843 )
1844 {
1845 DEBUG(D_tls)
1846 debug_printf("TLS certificate verification failed: cert name mismatch\n");
1847 if (state->verify_requirement >= VERIFY_REQUIRED)
1848 goto badcert;
1849 return TRUE;
1850 }
1851
1852 state->peer_cert_verified = TRUE;
1853 DEBUG(D_tls) debug_printf("TLS certificate verified: peerdn=\"%s\"\n",
1854 state->peerdn ? state->peerdn : US"<unset>");
1855 }
1856
1857 goodcert:
1858 state->tlsp->peerdn = state->peerdn;
1859 return TRUE;
1860
1861 #ifdef SUPPORT_DANE
1862 tlsa_prob:
1863 *errstr = string_sprintf("TLSA record problem: %s",
1864 rc == DANE_E_REQUESTED_DATA_NOT_AVAILABLE ? "none usable" : dane_strerror(rc));
1865 #endif
1866
1867 badcert:
1868 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_BAD_CERTIFICATE);
1869 return FALSE;
1870 }
1871
1872
1873
1874
1875 /* ------------------------------------------------------------------------ */
1876 /* Callbacks */
1877
1878 /* Logging function which can be registered with
1879 * gnutls_global_set_log_function()
1880 * gnutls_global_set_log_level() 0..9
1881 */
1882 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
1883 static void
1884 exim_gnutls_logger_cb(int level, const char *message)
1885 {
1886 size_t len = strlen(message);
1887 if (len < 1)
1888 {
1889 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
1890 return;
1891 }
1892 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
1893 message[len-1] == '\n' ? "" : "\n");
1894 }
1895 #endif
1896
1897
1898 /* Called after client hello, should handle SNI work.
1899 This will always set tls_sni (state->received_sni) if available,
1900 and may trigger presenting different certificates,
1901 if state->trigger_sni_changes is TRUE.
1902
1903 Should be registered with
1904 gnutls_handshake_set_post_client_hello_function()
1905
1906 "This callback must return 0 on success or a gnutls error code to terminate the
1907 handshake.".
1908
1909 For inability to get SNI information, we return 0.
1910 We only return non-zero if re-setup failed.
1911 Only used for server-side TLS.
1912 */
1913
1914 static int
1915 exim_sni_handling_cb(gnutls_session_t session)
1916 {
1917 char sni_name[MAX_HOST_LEN];
1918 size_t data_len = MAX_HOST_LEN;
1919 exim_gnutls_state_st *state = &state_server;
1920 unsigned int sni_type;
1921 int rc, old_pool;
1922 uschar * dummy_errstr;
1923
1924 rc = gnutls_server_name_get(session, sni_name, &data_len, &sni_type, 0);
1925 if (rc != GNUTLS_E_SUCCESS)
1926 {
1927 DEBUG(D_tls) {
1928 if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1929 debug_printf("TLS: no SNI presented in handshake.\n");
1930 else
1931 debug_printf("TLS failure: gnutls_server_name_get(): %s [%d]\n",
1932 gnutls_strerror(rc), rc);
1933 }
1934 return 0;
1935 }
1936
1937 if (sni_type != GNUTLS_NAME_DNS)
1938 {
1939 DEBUG(D_tls) debug_printf("TLS: ignoring SNI of unhandled type %u\n", sni_type);
1940 return 0;
1941 }
1942
1943 /* We now have a UTF-8 string in sni_name */
1944 old_pool = store_pool;
1945 store_pool = POOL_PERM;
1946 state->received_sni = string_copyn(US sni_name, data_len);
1947 store_pool = old_pool;
1948
1949 /* We set this one now so that variable expansions below will work */
1950 state->tlsp->sni = state->received_sni;
1951
1952 DEBUG(D_tls) debug_printf("Received TLS SNI \"%s\"%s\n", sni_name,
1953 state->trigger_sni_changes ? "" : " (unused for certificate selection)");
1954
1955 if (!state->trigger_sni_changes)
1956 return 0;
1957
1958 if ((rc = tls_expand_session_files(state, &dummy_errstr)) != OK)
1959 {
1960 /* If the setup of certs/etc failed before handshake, TLS would not have
1961 been offered. The best we can do now is abort. */
1962 return GNUTLS_E_APPLICATION_ERROR_MIN;
1963 }
1964
1965 rc = tls_set_remaining_x509(state, &dummy_errstr);
1966 if (rc != OK) return GNUTLS_E_APPLICATION_ERROR_MIN;
1967
1968 return 0;
1969 }
1970
1971
1972
1973 #ifndef DISABLE_OCSP
1974
1975 static int
1976 server_ocsp_stapling_cb(gnutls_session_t session, void * ptr,
1977 gnutls_datum_t * ocsp_response)
1978 {
1979 int ret;
1980 DEBUG(D_tls) debug_printf("OCSP stapling callback: %s\n", US ptr);
1981
1982 if ((ret = gnutls_load_file(ptr, ocsp_response)) < 0)
1983 {
1984 DEBUG(D_tls) debug_printf("Failed to load ocsp stapling file %s\n",
1985 CS ptr);
1986 tls_in.ocsp = OCSP_NOT_RESP;
1987 return GNUTLS_E_NO_CERTIFICATE_STATUS;
1988 }
1989
1990 tls_in.ocsp = OCSP_VFY_NOT_TRIED;
1991 return 0;
1992 }
1993
1994 #endif
1995
1996
1997 #ifndef DISABLE_EVENT
1998 /*
1999 We use this callback to get observability and detail-level control
2000 for an exim TLS connection (either direction), raising a tls:cert event
2001 for each cert in the chain presented by the peer. Any event
2002 can deny verification.
2003
2004 Return 0 for the handshake to continue or non-zero to terminate.
2005 */
2006
2007 static int
2008 verify_cb(gnutls_session_t session)
2009 {
2010 const gnutls_datum_t * cert_list;
2011 unsigned int cert_list_size = 0;
2012 gnutls_x509_crt_t crt;
2013 int rc;
2014 uschar * yield;
2015 exim_gnutls_state_st * state = gnutls_session_get_ptr(session);
2016
2017 if ((cert_list = gnutls_certificate_get_peers(session, &cert_list_size)))
2018 while (cert_list_size--)
2019 {
2020 if ((rc = import_cert(&cert_list[cert_list_size], &crt)) != GNUTLS_E_SUCCESS)
2021 {
2022 DEBUG(D_tls) debug_printf("TLS: peer cert problem: depth %d: %s\n",
2023 cert_list_size, gnutls_strerror(rc));
2024 break;
2025 }
2026
2027 state->tlsp->peercert = crt;
2028 if ((yield = event_raise(state->event_action,
2029 US"tls:cert", string_sprintf("%d", cert_list_size))))
2030 {
2031 log_write(0, LOG_MAIN,
2032 "SSL verify denied by event-action: depth=%d: %s",
2033 cert_list_size, yield);
2034 return 1; /* reject */
2035 }
2036 state->tlsp->peercert = NULL;
2037 }
2038
2039 return 0;
2040 }
2041
2042 #endif
2043
2044
2045 static gstring *
2046 ddump(gnutls_datum_t * d)
2047 {
2048 gstring * g = string_get((d->size+1) * 2);
2049 uschar * s = d->data;
2050 for (unsigned i = d->size; i > 0; i--, s++)
2051 {
2052 g = string_catn(g, US "0123456789abcdef" + (*s >> 4), 1);
2053 g = string_catn(g, US "0123456789abcdef" + (*s & 0xf), 1);
2054 }
2055 return g;
2056 }
2057
2058 static void
2059 post_handshake_debug(exim_gnutls_state_st * state)
2060 {
2061 #ifdef SUPPORT_GNUTLS_SESS_DESC
2062 debug_printf("%s\n", gnutls_session_get_desc(state->session));
2063 #endif
2064 #ifdef SUPPORT_GNUTLS_KEYLOG
2065 # ifdef GNUTLS_TLS1_3
2066 if (gnutls_protocol_get_version(state->session) < GNUTLS_TLS1_3)
2067 #else
2068 if (TRUE)
2069 #endif
2070 {
2071 gnutls_datum_t c, s;
2072 gstring * gc, * gs;
2073 /* we only want the client random and the master secret */
2074 gnutls_session_get_random(state->session, &c, &s);
2075 gnutls_session_get_master_secret(state->session, &s);
2076 gc = ddump(&c);
2077 gs = ddump(&s);
2078 debug_printf("CLIENT_RANDOM %.*s %.*s\n", (int)gc->ptr, gc->s, (int)gs->ptr, gs->s);
2079 }
2080 else
2081 debug_printf("To get keying info for TLS1.3 is hard:\n"
2082 " set environment variable SSLKEYLOGFILE to a filename writable by uid exim\n"
2083 " add SSLKEYLOGFILE to keep_environment in the exim config\n"
2084 " run exim as root\n"
2085 " if using sudo, add SSLKEYLOGFILE to env_keep in /etc/sudoers\n");
2086 #endif
2087 }
2088
2089
2090 #ifdef EXPERIMENTAL_TLS_RESUME
2091 static int
2092 tls_server_ticket_cb(gnutls_session_t sess, u_int htype, unsigned when,
2093 unsigned incoming, const gnutls_datum_t * msg)
2094 {
2095 DEBUG(D_tls) debug_printf("newticket cb\n");
2096 tls_in.resumption |= RESUME_CLIENT_REQUESTED;
2097 return 0;
2098 }
2099
2100 static void
2101 tls_server_resume_prehandshake(exim_gnutls_state_st * state)
2102 {
2103 /* Should the server offer session resumption? */
2104 tls_in.resumption = RESUME_SUPPORTED;
2105 if (verify_check_host(&tls_resumption_hosts) == OK)
2106 {
2107 int rc;
2108 /* GnuTLS appears to not do ticket overlap, but does emit a fresh ticket when
2109 an offered resumption is unacceptable. We lose one resumption per ticket
2110 lifetime, and sessions cannot be indefinitely re-used. There seems to be no
2111 way (3.6.7) of changing the default number of 2 TLS1.3 tickets issued, but at
2112 least they go out in a single packet. */
2113
2114 if (!(rc = gnutls_session_ticket_enable_server(state->session,
2115 &server_sessticket_key)))
2116 tls_in.resumption |= RESUME_SERVER_TICKET;
2117 else
2118 DEBUG(D_tls)
2119 debug_printf("enabling session tickets: %s\n", US gnutls_strerror(rc));
2120
2121 /* Try to tell if we see a ticket request */
2122 gnutls_handshake_set_hook_function(state->session,
2123 GNUTLS_HANDSHAKE_NEW_SESSION_TICKET, GNUTLS_HOOK_POST, tls_server_ticket_cb);
2124 }
2125 }
2126
2127 static void
2128 tls_server_resume_posthandshake(exim_gnutls_state_st * state)
2129 {
2130 if (gnutls_session_resumption_requested(state->session))
2131 {
2132 /* This tells us the client sent a full ticket. We use a
2133 callback on session-ticket request, elsewhere, to tell
2134 if a client asked for a ticket. */
2135
2136 tls_in.resumption |= RESUME_CLIENT_SUGGESTED;
2137 DEBUG(D_tls) debug_printf("client requested resumption\n");
2138 }
2139 if (gnutls_session_is_resumed(state->session))
2140 {
2141 tls_in.resumption |= RESUME_USED;
2142 DEBUG(D_tls) debug_printf("Session resumed\n");
2143 }
2144 }
2145 #endif
2146 /* ------------------------------------------------------------------------ */
2147 /* Exported functions */
2148
2149
2150
2151
2152 /*************************************************
2153 * Start a TLS session in a server *
2154 *************************************************/
2155
2156 /* This is called when Exim is running as a server, after having received
2157 the STARTTLS command. It must respond to that command, and then negotiate
2158 a TLS session.
2159
2160 Arguments:
2161 require_ciphers list of allowed ciphers or NULL
2162 errstr pointer to error string
2163
2164 Returns: OK on success
2165 DEFER for errors before the start of the negotiation
2166 FAIL for errors during the negotiation; the server can't
2167 continue running.
2168 */
2169
2170 int
2171 tls_server_start(const uschar * require_ciphers, uschar ** errstr)
2172 {
2173 int rc;
2174 exim_gnutls_state_st * state = NULL;
2175
2176 /* Check for previous activation */
2177 if (tls_in.active.sock >= 0)
2178 {
2179 tls_error(US"STARTTLS received after TLS started", US "", NULL, errstr);
2180 smtp_printf("554 Already in TLS\r\n", FALSE);
2181 return FAIL;
2182 }
2183
2184 /* Initialize the library. If it fails, it will already have logged the error
2185 and sent an SMTP response. */
2186
2187 DEBUG(D_tls) debug_printf("initialising GnuTLS as a server\n");
2188
2189 if ((rc = tls_init(NULL, tls_certificate, tls_privatekey,
2190 NULL, tls_verify_certificates, tls_crl,
2191 require_ciphers, &state, &tls_in, errstr)) != OK) return rc;
2192
2193 #ifdef EXPERIMENTAL_TLS_RESUME
2194 tls_server_resume_prehandshake(state);
2195 #endif
2196
2197 /* If this is a host for which certificate verification is mandatory or
2198 optional, set up appropriately. */
2199
2200 if (verify_check_host(&tls_verify_hosts) == OK)
2201 {
2202 DEBUG(D_tls)
2203 debug_printf("TLS: a client certificate will be required.\n");
2204 state->verify_requirement = VERIFY_REQUIRED;
2205 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2206 }
2207 else if (verify_check_host(&tls_try_verify_hosts) == OK)
2208 {
2209 DEBUG(D_tls)
2210 debug_printf("TLS: a client certificate will be requested but not required.\n");
2211 state->verify_requirement = VERIFY_OPTIONAL;
2212 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2213 }
2214 else
2215 {
2216 DEBUG(D_tls)
2217 debug_printf("TLS: a client certificate will not be requested.\n");
2218 state->verify_requirement = VERIFY_NONE;
2219 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2220 }
2221
2222 #ifndef DISABLE_EVENT
2223 if (event_action)
2224 {
2225 state->event_action = event_action;
2226 gnutls_session_set_ptr(state->session, state);
2227 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2228 }
2229 #endif
2230
2231 /* Register SNI handling; always, even if not in tls_certificate, so that the
2232 expansion variable $tls_sni is always available. */
2233
2234 gnutls_handshake_set_post_client_hello_function(state->session,
2235 exim_sni_handling_cb);
2236
2237 /* Set context and tell client to go ahead, except in the case of TLS startup
2238 on connection, where outputting anything now upsets the clients and tends to
2239 make them disconnect. We need to have an explicit fflush() here, to force out
2240 the response. Other smtp_printf() calls do not need it, because in non-TLS
2241 mode, the fflush() happens when smtp_getc() is called. */
2242
2243 if (!state->tlsp->on_connect)
2244 {
2245 smtp_printf("220 TLS go ahead\r\n", FALSE);
2246 fflush(smtp_out);
2247 }
2248
2249 /* Now negotiate the TLS session. We put our own timer on it, since it seems
2250 that the GnuTLS library doesn't.
2251 From 3.1.0 there is gnutls_handshake_set_timeout() - but it requires you
2252 to set (and clear down afterwards) up a pull-timeout callback function that does
2253 a select, so we're no better off unless avoiding signals becomes an issue. */
2254
2255 gnutls_transport_set_ptr2(state->session,
2256 (gnutls_transport_ptr_t)(long) fileno(smtp_in),
2257 (gnutls_transport_ptr_t)(long) fileno(smtp_out));
2258 state->fd_in = fileno(smtp_in);
2259 state->fd_out = fileno(smtp_out);
2260
2261 sigalrm_seen = FALSE;
2262 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2263 do
2264 rc = gnutls_handshake(state->session);
2265 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2266 ALARM_CLR(0);
2267
2268 if (rc != GNUTLS_E_SUCCESS)
2269 {
2270 /* It seems that, except in the case of a timeout, we have to close the
2271 connection right here; otherwise if the other end is running OpenSSL it hangs
2272 until the server times out. */
2273
2274 if (sigalrm_seen)
2275 {
2276 tls_error(US"gnutls_handshake", US"timed out", NULL, errstr);
2277 gnutls_db_remove_session(state->session);
2278 }
2279 else
2280 {
2281 tls_error_gnu(US"gnutls_handshake", rc, NULL, errstr);
2282 (void) gnutls_alert_send_appropriate(state->session, rc);
2283 gnutls_deinit(state->session);
2284 gnutls_certificate_free_credentials(state->x509_cred);
2285 millisleep(500);
2286 shutdown(state->fd_out, SHUT_WR);
2287 for (int i = 1024; fgetc(smtp_in) != EOF && i > 0; ) i--; /* drain skt */
2288 (void)fclose(smtp_out);
2289 (void)fclose(smtp_in);
2290 smtp_out = smtp_in = NULL;
2291 }
2292
2293 return FAIL;
2294 }
2295
2296 #ifdef EXPERIMENTAL_TLS_RESUME
2297 tls_server_resume_posthandshake(state);
2298 #endif
2299
2300 DEBUG(D_tls) post_handshake_debug(state);
2301
2302 /* Verify after the fact */
2303
2304 if (!verify_certificate(state, errstr))
2305 {
2306 if (state->verify_requirement != VERIFY_OPTIONAL)
2307 {
2308 (void) tls_error(US"certificate verification failed", *errstr, NULL, errstr);
2309 return FAIL;
2310 }
2311 DEBUG(D_tls)
2312 debug_printf("TLS: continuing on only because verification was optional, after: %s\n",
2313 *errstr);
2314 }
2315
2316 /* Sets various Exim expansion variables; always safe within server */
2317
2318 extract_exim_vars_from_tls_state(state);
2319
2320 /* TLS has been set up. Adjust the input functions to read via TLS,
2321 and initialize appropriately. */
2322
2323 state->xfer_buffer = store_malloc(ssl_xfer_buffer_size);
2324
2325 receive_getc = tls_getc;
2326 receive_getbuf = tls_getbuf;
2327 receive_get_cache = tls_get_cache;
2328 receive_ungetc = tls_ungetc;
2329 receive_feof = tls_feof;
2330 receive_ferror = tls_ferror;
2331 receive_smtp_buffered = tls_smtp_buffered;
2332
2333 return OK;
2334 }
2335
2336
2337
2338
2339 static void
2340 tls_client_setup_hostname_checks(host_item * host, exim_gnutls_state_st * state,
2341 smtp_transport_options_block * ob)
2342 {
2343 if (verify_check_given_host(CUSS &ob->tls_verify_cert_hostnames, host) == OK)
2344 {
2345 state->exp_tls_verify_cert_hostnames =
2346 #ifdef SUPPORT_I18N
2347 string_domain_utf8_to_alabel(host->name, NULL);
2348 #else
2349 host->name;
2350 #endif
2351 DEBUG(D_tls)
2352 debug_printf("TLS: server cert verification includes hostname: \"%s\".\n",
2353 state->exp_tls_verify_cert_hostnames);
2354 }
2355 }
2356
2357
2358
2359
2360 #ifdef SUPPORT_DANE
2361 /* Given our list of RRs from the TLSA lookup, build a lookup block in
2362 GnuTLS-DANE's preferred format. Hang it on the state str for later
2363 use in DANE verification.
2364
2365 We point at the dnsa data not copy it, so it must remain valid until
2366 after verification is done.*/
2367
2368 static BOOL
2369 dane_tlsa_load(exim_gnutls_state_st * state, dns_answer * dnsa)
2370 {
2371 dns_scan dnss;
2372 int i;
2373 const char ** dane_data;
2374 int * dane_data_len;
2375
2376 i = 1;
2377 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
2378 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2379 ) if (rr->type == T_TLSA) i++;
2380
2381 dane_data = store_get(i * sizeof(uschar *));
2382 dane_data_len = store_get(i * sizeof(int));
2383
2384 i = 0;
2385 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
2386 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)
2387 ) if (rr->type == T_TLSA && rr->size > 3)
2388 {
2389 const uschar * p = rr->data;
2390 uint8_t usage = p[0], sel = p[1], type = p[2];
2391
2392 DEBUG(D_tls)
2393 debug_printf("TLSA: %d %d %d size %d\n", usage, sel, type, rr->size);
2394
2395 if ( (usage != DANESSL_USAGE_DANE_TA && usage != DANESSL_USAGE_DANE_EE)
2396 || (sel != 0 && sel != 1)
2397 )
2398 continue;
2399 switch(type)
2400 {
2401 case 0: /* Full: cannot check at present */
2402 break;
2403 case 1: if (rr->size != 3 + 256/8) continue; /* sha2-256 */
2404 break;
2405 case 2: if (rr->size != 3 + 512/8) continue; /* sha2-512 */
2406 break;
2407 default: continue;
2408 }
2409
2410 tls_out.tlsa_usage |= 1<<usage;
2411 dane_data[i] = CS p;
2412 dane_data_len[i++] = rr->size;
2413 }
2414
2415 if (!i) return FALSE;
2416
2417 dane_data[i] = NULL;
2418 dane_data_len[i] = 0;
2419
2420 state->dane_data = (char * const *)dane_data;
2421 state->dane_data_len = dane_data_len;
2422 return TRUE;
2423 }
2424 #endif
2425
2426
2427
2428 #ifdef EXPERIMENTAL_TLS_RESUME
2429 /* On the client, get any stashed session for the given IP from hints db
2430 and apply it to the ssl-connection for attempted resumption. Although
2431 there is a gnutls_session_ticket_enable_client() interface it is
2432 documented as unnecessary (as of 3.6.7) as "session tickets are emabled
2433 by deafult". There seems to be no way to disable them, so even hosts not
2434 enabled by the transport option will be sent a ticket request. We will
2435 however avoid storing and retrieving session information. */
2436
2437 static void
2438 tls_retrieve_session(tls_support * tlsp, gnutls_session_t session,
2439 host_item * host, smtp_transport_options_block * ob)
2440 {
2441 tlsp->resumption = RESUME_SUPPORTED;
2442 if (verify_check_given_host(CUSS &ob->tls_resumption_hosts, host) == OK)
2443 {
2444 dbdata_tls_session * dt;
2445 int len, rc;
2446 open_db dbblock, * dbm_file;
2447
2448 DEBUG(D_tls)
2449 debug_printf("check for resumable session for %s\n", host->address);
2450 tlsp->host_resumable = TRUE;
2451 tlsp->resumption |= RESUME_CLIENT_REQUESTED;
2452 if ((dbm_file = dbfn_open(US"tls", O_RDONLY, &dbblock, FALSE, FALSE)))
2453 {
2454 /* key for the db is the IP */
2455 if ((dt = dbfn_read_with_length(dbm_file, host->address, &len)))
2456 if (!(rc = gnutls_session_set_data(session,
2457 CUS dt->session, (size_t)len - sizeof(dbdata_tls_session))))
2458 {
2459 DEBUG(D_tls) debug_printf("good session\n");
2460 tlsp->resumption |= RESUME_CLIENT_SUGGESTED;
2461 }
2462 else DEBUG(D_tls) debug_printf("setting session resumption data: %s\n",
2463 US gnutls_strerror(rc));
2464 dbfn_close(dbm_file);
2465 }
2466 }
2467 }
2468
2469
2470 static void
2471 tls_save_session(tls_support * tlsp, gnutls_session_t session, const host_item * host)
2472 {
2473 /* TLS 1.2 - we get both the callback and the direct posthandshake call,
2474 but this flag is not set until the second. TLS 1.3 it's the other way about.
2475 Keep both calls as the session data cannot be extracted before handshake
2476 completes. */
2477
2478 if (gnutls_session_get_flags(session) & GNUTLS_SFLAGS_SESSION_TICKET)
2479 {
2480 gnutls_datum_t tkt;
2481 int rc;
2482
2483 DEBUG(D_tls) debug_printf("server offered session ticket\n");
2484 tlsp->ticket_received = TRUE;
2485 tlsp->resumption |= RESUME_SERVER_TICKET;
2486
2487 if (tlsp->host_resumable)
2488 if (!(rc = gnutls_session_get_data2(session, &tkt)))
2489 {
2490 open_db dbblock, * dbm_file;
2491 int dlen = sizeof(dbdata_tls_session) + tkt.size;
2492 dbdata_tls_session * dt = store_get(dlen);
2493
2494 DEBUG(D_tls) debug_printf("session data size %u\n", (unsigned)tkt.size);
2495 memcpy(dt->session, tkt.data, tkt.size);
2496 gnutls_free(tkt.data);
2497
2498 if ((dbm_file = dbfn_open(US"tls", O_RDWR, &dbblock, FALSE, FALSE)))
2499 {
2500 /* key for the db is the IP */
2501 dbfn_delete(dbm_file, host->address);
2502 dbfn_write(dbm_file, host->address, dt, dlen);
2503 dbfn_close(dbm_file);
2504
2505 DEBUG(D_tls)
2506 debug_printf("wrote session db (len %u)\n", (unsigned)dlen);
2507 }
2508 }
2509 else DEBUG(D_tls)
2510 debug_printf("extract session data: %s\n", US gnutls_strerror(rc));
2511 }
2512 }
2513
2514
2515 /* With a TLS1.3 session, the ticket(s) are not seen until
2516 the first data read is attempted. And there's often two of them.
2517 Pick them up with this callback. We are also called for 1.2
2518 but we do nothing.
2519 */
2520 static int
2521 tls_client_ticket_cb(gnutls_session_t sess, u_int htype, unsigned when,
2522 unsigned incoming, const gnutls_datum_t * msg)
2523 {
2524 exim_gnutls_state_st * state = gnutls_session_get_ptr(sess);
2525 tls_support * tlsp = state->tlsp;
2526
2527 DEBUG(D_tls) debug_printf("newticket cb\n");
2528
2529 if (!tlsp->ticket_received)
2530 tls_save_session(tlsp, sess, state->host);
2531 return 0;
2532 }
2533
2534
2535 static void
2536 tls_client_resume_prehandshake(exim_gnutls_state_st * state,
2537 tls_support * tlsp, host_item * host,
2538 smtp_transport_options_block * ob)
2539 {
2540 gnutls_session_set_ptr(state->session, state);
2541 gnutls_handshake_set_hook_function(state->session,
2542 GNUTLS_HANDSHAKE_NEW_SESSION_TICKET, GNUTLS_HOOK_POST, tls_client_ticket_cb);
2543
2544 tls_retrieve_session(tlsp, state->session, host, ob);
2545 }
2546
2547 static void
2548 tls_client_resume_posthandshake(exim_gnutls_state_st * state,
2549 tls_support * tlsp, host_item * host)
2550 {
2551 if (gnutls_session_is_resumed(state->session))
2552 {
2553 DEBUG(D_tls) debug_printf("Session resumed\n");
2554 tlsp->resumption |= RESUME_USED;
2555 }
2556
2557 tls_save_session(tlsp, state->session, host);
2558 }
2559 #endif /* EXPERIMENTAL_TLS_RESUME */
2560
2561
2562 /*************************************************
2563 * Start a TLS session in a client *
2564 *************************************************/
2565
2566 /* Called from the smtp transport after STARTTLS has been accepted.
2567
2568 Arguments:
2569 cctx connection context
2570 conn_args connection details
2571 cookie datum for randomness (not used)
2572 tlsp record details of channel configuration here; must be non-NULL
2573 errstr error string pointer
2574
2575 Returns: TRUE for success with TLS session context set in smtp context,
2576 FALSE on error
2577 */
2578
2579 BOOL
2580 tls_client_start(client_conn_ctx * cctx, smtp_connect_args * conn_args,
2581 void * cookie ARG_UNUSED,
2582 tls_support * tlsp, uschar ** errstr)
2583 {
2584 host_item * host = conn_args->host; /* for msgs and option-tests */
2585 transport_instance * tb = conn_args->tblock; /* always smtp or NULL */
2586 smtp_transport_options_block * ob = tb
2587 ? (smtp_transport_options_block *)tb->options_block
2588 : &smtp_transport_option_defaults;
2589 int rc;
2590 exim_gnutls_state_st * state = NULL;
2591 uschar * cipher_list = NULL;
2592
2593 #ifndef DISABLE_OCSP
2594 BOOL require_ocsp =
2595 verify_check_given_host(CUSS &ob->hosts_require_ocsp, host) == OK;
2596 BOOL request_ocsp = require_ocsp ? TRUE
2597 : verify_check_given_host(CUSS &ob->hosts_request_ocsp, host) == OK;
2598 #endif
2599
2600 DEBUG(D_tls) debug_printf("initialising GnuTLS as a client on fd %d\n", cctx->sock);
2601
2602 #ifdef SUPPORT_DANE
2603 /* If dane is flagged, have either request or require dane for this host, and
2604 a TLSA record found. Therefore, dane verify required. Which implies cert must
2605 be requested and supplied, dane verify must pass, and cert verify irrelevant
2606 (incl. hostnames), and (caller handled) require_tls */
2607
2608 if (conn_args->dane && ob->dane_require_tls_ciphers)
2609 {
2610 /* not using expand_check_tlsvar because not yet in state */
2611 if (!expand_check(ob->dane_require_tls_ciphers, US"dane_require_tls_ciphers",
2612 &cipher_list, errstr))
2613 return FALSE;
2614 cipher_list = cipher_list && *cipher_list
2615 ? ob->dane_require_tls_ciphers : ob->tls_require_ciphers;
2616 }
2617 #endif
2618
2619 if (!cipher_list)
2620 cipher_list = ob->tls_require_ciphers;
2621
2622 if (tls_init(host, ob->tls_certificate, ob->tls_privatekey,
2623 ob->tls_sni, ob->tls_verify_certificates, ob->tls_crl,
2624 cipher_list, &state, tlsp, errstr) != OK)
2625 return FALSE;
2626
2627 {
2628 int dh_min_bits = ob->tls_dh_min_bits;
2629 if (dh_min_bits < EXIM_CLIENT_DH_MIN_MIN_BITS)
2630 {
2631 DEBUG(D_tls)
2632 debug_printf("WARNING: tls_dh_min_bits far too low,"
2633 " clamping %d up to %d\n",
2634 dh_min_bits, EXIM_CLIENT_DH_MIN_MIN_BITS);
2635 dh_min_bits = EXIM_CLIENT_DH_MIN_MIN_BITS;
2636 }
2637
2638 DEBUG(D_tls) debug_printf("Setting D-H prime minimum"
2639 " acceptable bits to %d\n",
2640 dh_min_bits);
2641 gnutls_dh_set_prime_bits(state->session, dh_min_bits);
2642 }
2643
2644 /* Stick to the old behaviour for compatibility if tls_verify_certificates is
2645 set but both tls_verify_hosts and tls_try_verify_hosts are unset. Check only
2646 the specified host patterns if one of them is defined */
2647
2648 #ifdef SUPPORT_DANE
2649 if (conn_args->dane && dane_tlsa_load(state, &conn_args->tlsa_dnsa))
2650 {
2651 DEBUG(D_tls)
2652 debug_printf("TLS: server certificate DANE required.\n");
2653 state->verify_requirement = VERIFY_DANE;
2654 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2655 }
2656 else
2657 #endif
2658 if ( ( state->exp_tls_verify_certificates
2659 && !ob->tls_verify_hosts
2660 && (!ob->tls_try_verify_hosts || !*ob->tls_try_verify_hosts)
2661 )
2662 || verify_check_given_host(CUSS &ob->tls_verify_hosts, host) == OK
2663 )
2664 {
2665 tls_client_setup_hostname_checks(host, state, ob);
2666 DEBUG(D_tls)
2667 debug_printf("TLS: server certificate verification required.\n");
2668 state->verify_requirement = VERIFY_REQUIRED;
2669 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUIRE);
2670 }
2671 else if (verify_check_given_host(CUSS &ob->tls_try_verify_hosts, host) == OK)
2672 {
2673 tls_client_setup_hostname_checks(host, state, ob);
2674 DEBUG(D_tls)
2675 debug_printf("TLS: server certificate verification optional.\n");
2676 state->verify_requirement = VERIFY_OPTIONAL;
2677 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_REQUEST);
2678 }
2679 else
2680 {
2681 DEBUG(D_tls)
2682 debug_printf("TLS: server certificate verification not required.\n");
2683 state->verify_requirement = VERIFY_NONE;
2684 gnutls_certificate_server_set_request(state->session, GNUTLS_CERT_IGNORE);
2685 }
2686
2687 #ifndef DISABLE_OCSP
2688 /* supported since GnuTLS 3.1.3 */
2689 if (request_ocsp)
2690 {
2691 DEBUG(D_tls) debug_printf("TLS: will request OCSP stapling\n");
2692 if ((rc = gnutls_ocsp_status_request_enable_client(state->session,
2693 NULL, 0, NULL)) != OK)
2694 {
2695 tls_error_gnu(US"cert-status-req", rc, state->host, errstr);
2696 return FALSE;
2697 }
2698 tlsp->ocsp = OCSP_NOT_RESP;
2699 }
2700 #endif
2701
2702 #ifdef EXPERIMENTAL_TLS_RESUME
2703 tls_client_resume_prehandshake(state, tlsp, host, ob);
2704 #endif
2705
2706 #ifndef DISABLE_EVENT
2707 if (tb && tb->event_action)
2708 {
2709 state->event_action = tb->event_action;
2710 gnutls_session_set_ptr(state->session, state);
2711 gnutls_certificate_set_verify_function(state->x509_cred, verify_cb);
2712 }
2713 #endif
2714
2715 gnutls_transport_set_ptr(state->session, (gnutls_transport_ptr_t)(long) cctx->sock);
2716 state->fd_in = cctx->sock;
2717 state->fd_out = cctx->sock;
2718
2719 DEBUG(D_tls) debug_printf("about to gnutls_handshake\n");
2720 /* There doesn't seem to be a built-in timeout on connection. */
2721
2722 sigalrm_seen = FALSE;
2723 ALARM(ob->command_timeout);
2724 do
2725 rc = gnutls_handshake(state->session);
2726 while (rc == GNUTLS_E_AGAIN || rc == GNUTLS_E_INTERRUPTED && !sigalrm_seen);
2727 ALARM_CLR(0);
2728
2729 if (rc != GNUTLS_E_SUCCESS)
2730 {
2731 if (sigalrm_seen)
2732 {
2733 gnutls_alert_send(state->session, GNUTLS_AL_FATAL, GNUTLS_A_USER_CANCELED);
2734 tls_error(US"gnutls_handshake", US"timed out", state->host, errstr);
2735 }
2736 else
2737 tls_error_gnu(US"gnutls_handshake", rc, state->host, errstr);
2738 return FALSE;
2739 }
2740
2741 DEBUG(D_tls) post_handshake_debug(state);
2742
2743 /* Verify late */
2744
2745 if (!verify_certificate(state, errstr))
2746 {
2747 tls_error(US"certificate verification failed", *errstr, state->host, errstr);
2748 return FALSE;
2749 }
2750
2751 #ifndef DISABLE_OCSP
2752 if (require_ocsp)
2753 {
2754 DEBUG(D_tls)
2755 {
2756 gnutls_datum_t stapling;
2757 gnutls_ocsp_resp_t resp;
2758 gnutls_datum_t printed;
2759 if ( (rc= gnutls_ocsp_status_request_get(state->session, &stapling)) == 0
2760 && (rc= gnutls_ocsp_resp_init(&resp)) == 0
2761 && (rc= gnutls_ocsp_resp_import(resp, &stapling)) == 0
2762 && (rc= gnutls_ocsp_resp_print(resp, GNUTLS_OCSP_PRINT_FULL, &printed)) == 0
2763 )
2764 {
2765 debug_printf("%.4096s", printed.data);
2766 gnutls_free(printed.data);
2767 }
2768 else
2769 (void) tls_error_gnu(US"ocsp decode", rc, state->host, errstr);
2770 }
2771
2772 if (gnutls_ocsp_status_request_is_checked(state->session, 0) == 0)
2773 {
2774 tlsp->ocsp = OCSP_FAILED;
2775 tls_error(US"certificate status check failed", NULL, state->host, errstr);
2776 return FALSE;
2777 }
2778 DEBUG(D_tls) debug_printf("Passed OCSP checking\n");
2779 tlsp->ocsp = OCSP_VFIED;
2780 }
2781 #endif
2782
2783 #ifdef EXPERIMENTAL_TLS_RESUME
2784 tls_client_resume_posthandshake(state, tlsp, host);
2785 #endif
2786
2787 /* Sets various Exim expansion variables; may need to adjust for ACL callouts */
2788
2789 extract_exim_vars_from_tls_state(state);
2790
2791 cctx->tls_ctx = state;
2792 return TRUE;
2793 }
2794
2795
2796
2797
2798 /*************************************************
2799 * Close down a TLS session *
2800 *************************************************/
2801
2802 /* This is also called from within a delivery subprocess forked from the
2803 daemon, to shut down the TLS library, without actually doing a shutdown (which
2804 would tamper with the TLS session in the parent process).
2805
2806 Arguments:
2807 ct_ctx client context pointer, or NULL for the one global server context
2808 shutdown 1 if TLS close-alert is to be sent,
2809 2 if also response to be waited for
2810
2811 Returns: nothing
2812 */
2813
2814 void
2815 tls_close(void * ct_ctx, int shutdown)
2816 {
2817 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
2818
2819 if (!state->tlsp || state->tlsp->active.sock < 0) return; /* TLS was not active */
2820
2821 if (shutdown)
2822 {
2823 DEBUG(D_tls) debug_printf("tls_close(): shutting down TLS%s\n",
2824 shutdown > 1 ? " (with response-wait)" : "");
2825
2826 ALARM(2);
2827 gnutls_bye(state->session, shutdown > 1 ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
2828 ALARM_CLR(0);
2829 }
2830
2831 gnutls_deinit(state->session);
2832 gnutls_certificate_free_credentials(state->x509_cred);
2833
2834
2835 state->tlsp->active.sock = -1;
2836 state->tlsp->active.tls_ctx = NULL;
2837 if (state->xfer_buffer) store_free(state->xfer_buffer);
2838 memcpy(state, &exim_gnutls_state_init, sizeof(exim_gnutls_state_init));
2839 }
2840
2841
2842
2843
2844 static BOOL
2845 tls_refill(unsigned lim)
2846 {
2847 exim_gnutls_state_st * state = &state_server;
2848 ssize_t inbytes;
2849
2850 DEBUG(D_tls) debug_printf("Calling gnutls_record_recv(%p, %p, %u)\n",
2851 state->session, state->xfer_buffer, ssl_xfer_buffer_size);
2852
2853 sigalrm_seen = FALSE;
2854 if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
2855
2856 do
2857 inbytes = gnutls_record_recv(state->session, state->xfer_buffer,
2858 MIN(ssl_xfer_buffer_size, lim));
2859 while (inbytes == GNUTLS_E_AGAIN);
2860
2861 if (smtp_receive_timeout > 0) ALARM_CLR(0);
2862
2863 if (had_command_timeout) /* set by signal handler */
2864 smtp_command_timeout_exit(); /* does not return */
2865 if (had_command_sigterm)
2866 smtp_command_sigterm_exit();
2867 if (had_data_timeout)
2868 smtp_data_timeout_exit();
2869 if (had_data_sigint)
2870 smtp_data_sigint_exit();
2871
2872 /* Timeouts do not get this far. A zero-byte return appears to mean that the
2873 TLS session has been closed down, not that the socket itself has been closed
2874 down. Revert to non-TLS handling. */
2875
2876 if (sigalrm_seen)
2877 {
2878 DEBUG(D_tls) debug_printf("Got tls read timeout\n");
2879 state->xfer_error = TRUE;
2880 return FALSE;
2881 }
2882
2883 else if (inbytes == 0)
2884 {
2885 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
2886
2887 receive_getc = smtp_getc;
2888 receive_getbuf = smtp_getbuf;
2889 receive_get_cache = smtp_get_cache;
2890 receive_ungetc = smtp_ungetc;
2891 receive_feof = smtp_feof;
2892 receive_ferror = smtp_ferror;
2893 receive_smtp_buffered = smtp_buffered;
2894
2895 gnutls_deinit(state->session);
2896 gnutls_certificate_free_credentials(state->x509_cred);
2897
2898 state->session = NULL;
2899 state->tlsp->active.sock = -1;
2900 state->tlsp->active.tls_ctx = NULL;
2901 state->tlsp->bits = 0;
2902 state->tlsp->certificate_verified = FALSE;
2903 tls_channelbinding_b64 = NULL;
2904 state->tlsp->cipher = NULL;
2905 state->tlsp->peercert = NULL;
2906 state->tlsp->peerdn = NULL;
2907
2908 return FALSE;
2909 }
2910
2911 /* Handle genuine errors */
2912
2913 else if (inbytes < 0)
2914 {
2915 DEBUG(D_tls) debug_printf("%s: err from gnutls_record_recv\n", __FUNCTION__);
2916 record_io_error(state, (int) inbytes, US"recv", NULL);
2917 state->xfer_error = TRUE;
2918 return FALSE;
2919 }
2920 #ifndef DISABLE_DKIM
2921 dkim_exim_verify_feed(state->xfer_buffer, inbytes);
2922 #endif
2923 state->xfer_buffer_hwm = (int) inbytes;
2924 state->xfer_buffer_lwm = 0;
2925 return TRUE;
2926 }
2927
2928 /*************************************************
2929 * TLS version of getc *
2930 *************************************************/
2931
2932 /* This gets the next byte from the TLS input buffer. If the buffer is empty,
2933 it refills the buffer via the GnuTLS reading function.
2934 Only used by the server-side TLS.
2935
2936 This feeds DKIM and should be used for all message-body reads.
2937
2938 Arguments: lim Maximum amount to read/buffer
2939 Returns: the next character or EOF
2940 */
2941
2942 int
2943 tls_getc(unsigned lim)
2944 {
2945 exim_gnutls_state_st * state = &state_server;
2946
2947 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2948 if (!tls_refill(lim))
2949 return state->xfer_error ? EOF : smtp_getc(lim);
2950
2951 /* Something in the buffer; return next uschar */
2952
2953 return state->xfer_buffer[state->xfer_buffer_lwm++];
2954 }
2955
2956 uschar *
2957 tls_getbuf(unsigned * len)
2958 {
2959 exim_gnutls_state_st * state = &state_server;
2960 unsigned size;
2961 uschar * buf;
2962
2963 if (state->xfer_buffer_lwm >= state->xfer_buffer_hwm)
2964 if (!tls_refill(*len))
2965 {
2966 if (!state->xfer_error) return smtp_getbuf(len);
2967 *len = 0;
2968 return NULL;
2969 }
2970
2971 if ((size = state->xfer_buffer_hwm - state->xfer_buffer_lwm) > *len)
2972 size = *len;
2973 buf = &state->xfer_buffer[state->xfer_buffer_lwm];
2974 state->xfer_buffer_lwm += size;
2975 *len = size;
2976 return buf;
2977 }
2978
2979
2980 void
2981 tls_get_cache()
2982 {
2983 #ifndef DISABLE_DKIM
2984 exim_gnutls_state_st * state = &state_server;
2985 int n = state->xfer_buffer_hwm - state->xfer_buffer_lwm;
2986 if (n > 0)
2987 dkim_exim_verify_feed(state->xfer_buffer+state->xfer_buffer_lwm, n);
2988 #endif
2989 }
2990
2991
2992 BOOL
2993 tls_could_read(void)
2994 {
2995 return state_server.xfer_buffer_lwm < state_server.xfer_buffer_hwm
2996 || gnutls_record_check_pending(state_server.session) > 0;
2997 }
2998
2999
3000
3001
3002 /*************************************************
3003 * Read bytes from TLS channel *
3004 *************************************************/
3005
3006 /* This does not feed DKIM, so if the caller uses this for reading message body,
3007 then the caller must feed DKIM.
3008
3009 Arguments:
3010 ct_ctx client context pointer, or NULL for the one global server context
3011 buff buffer of data
3012 len size of buffer
3013
3014 Returns: the number of bytes read
3015 -1 after a failed read, including EOF
3016 */
3017
3018 int
3019 tls_read(void * ct_ctx, uschar *buff, size_t len)
3020 {
3021 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
3022 ssize_t inbytes;
3023
3024 if (len > INT_MAX)
3025 len = INT_MAX;
3026
3027 if (state->xfer_buffer_lwm < state->xfer_buffer_hwm)
3028 DEBUG(D_tls)
3029 debug_printf("*** PROBABLY A BUG *** " \
3030 "tls_read() called with data in the tls_getc() buffer, %d ignored\n",
3031 state->xfer_buffer_hwm - state->xfer_buffer_lwm);
3032
3033 DEBUG(D_tls)
3034 debug_printf("Calling gnutls_record_recv(%p, %p, " SIZE_T_FMT ")\n",
3035 state->session, buff, len);
3036
3037 do
3038 inbytes = gnutls_record_recv(state->session, buff, len);
3039 while (inbytes == GNUTLS_E_AGAIN);
3040
3041 if (inbytes > 0) return inbytes;
3042 if (inbytes == 0)
3043 {
3044 DEBUG(D_tls) debug_printf("Got TLS_EOF\n");
3045 }
3046 else
3047 {
3048 DEBUG(D_tls) debug_printf("%s: err from gnutls_record_recv\n", __FUNCTION__);
3049 record_io_error(state, (int)inbytes, US"recv", NULL);
3050 }
3051
3052 return -1;
3053 }
3054
3055
3056
3057
3058 /*************************************************
3059 * Write bytes down TLS channel *
3060 *************************************************/
3061
3062 /*
3063 Arguments:
3064 ct_ctx client context pointer, or NULL for the one global server context
3065 buff buffer of data
3066 len number of bytes
3067 more more data expected soon
3068
3069 Returns: the number of bytes after a successful write,
3070 -1 after a failed write
3071 */
3072
3073 int
3074 tls_write(void * ct_ctx, const uschar * buff, size_t len, BOOL more)
3075 {
3076 ssize_t outbytes;
3077 size_t left = len;
3078 exim_gnutls_state_st * state = ct_ctx ? ct_ctx : &state_server;
3079 #ifdef SUPPORT_CORK
3080 static BOOL corked = FALSE;
3081
3082 if (more && !corked) gnutls_record_cork(state->session);
3083 #endif
3084
3085 DEBUG(D_tls) debug_printf("%s(%p, " SIZE_T_FMT "%s)\n", __FUNCTION__,
3086 buff, left, more ? ", more" : "");
3087
3088 while (left > 0)
3089 {
3090 DEBUG(D_tls) debug_printf("gnutls_record_send(SSL, %p, " SIZE_T_FMT ")\n",
3091 buff, left);
3092
3093 do
3094 outbytes = gnutls_record_send(state->session, buff, left);
3095 while (outbytes == GNUTLS_E_AGAIN);
3096
3097 DEBUG(D_tls) debug_printf("outbytes=" SSIZE_T_FMT "\n", outbytes);
3098 if (outbytes < 0)
3099 {
3100 DEBUG(D_tls) debug_printf("%s: gnutls_record_send err\n", __FUNCTION__);
3101 record_io_error(state, outbytes, US"send", NULL);
3102 return -1;
3103 }
3104 if (outbytes == 0)
3105 {
3106 record_io_error(state, 0, US"send", US"TLS channel closed on write");
3107 return -1;
3108 }
3109
3110 left -= outbytes;
3111 buff += outbytes;
3112 }
3113
3114 if (len > INT_MAX)
3115 {
3116 DEBUG(D_tls)
3117 debug_printf("Whoops! Wrote more bytes (" SIZE_T_FMT ") than INT_MAX\n",
3118 len);
3119 len = INT_MAX;
3120 }
3121
3122 #ifdef SUPPORT_CORK
3123 if (more != corked)
3124 {
3125 if (!more) (void) gnutls_record_uncork(state->session, 0);
3126 corked = more;
3127 }
3128 #endif
3129
3130 return (int) len;
3131 }
3132
3133
3134
3135
3136 /*************************************************
3137 * Random number generation *
3138 *************************************************/
3139
3140 /* Pseudo-random number generation. The result is not expected to be
3141 cryptographically strong but not so weak that someone will shoot themselves
3142 in the foot using it as a nonce in input in some email header scheme or
3143 whatever weirdness they'll twist this into. The result should handle fork()
3144 and avoid repeating sequences. OpenSSL handles that for us.
3145
3146 Arguments:
3147 max range maximum
3148 Returns a random number in range [0, max-1]
3149 */
3150
3151 #ifdef HAVE_GNUTLS_RND
3152 int
3153 vaguely_random_number(int max)
3154 {
3155 unsigned int r;
3156 int i, needed_len;
3157 uschar smallbuf[sizeof(r)];
3158
3159 if (max <= 1)
3160 return 0;
3161
3162 needed_len = sizeof(r);
3163 /* Don't take 8 times more entropy than needed if int is 8 octets and we were
3164 asked for a number less than 10. */
3165
3166 for (r = max, i = 0; r; ++i)
3167 r >>= 1;
3168 i = (i + 7) / 8;
3169 if (i < needed_len)
3170 needed_len = i;
3171
3172 i = gnutls_rnd(GNUTLS_RND_NONCE, smallbuf, needed_len);
3173 if (i < 0)
3174 {
3175 DEBUG(D_all) debug_printf("gnutls_rnd() failed, using fallback.\n");
3176 return vaguely_random_number_fallback(max);
3177 }
3178 r = 0;
3179 for (uschar * p = smallbuf; needed_len; --needed_len, ++p)
3180 r = r * 256 + *p;
3181
3182 /* We don't particularly care about weighted results; if someone wants
3183 * smooth distribution and cares enough then they should submit a patch then. */
3184 return r % max;
3185 }
3186 #else /* HAVE_GNUTLS_RND */
3187 int
3188 vaguely_random_number(int max)
3189 {
3190 return vaguely_random_number_fallback(max);
3191 }
3192 #endif /* HAVE_GNUTLS_RND */
3193
3194
3195
3196
3197 /*************************************************
3198 * Let tls_require_ciphers be checked at startup *
3199 *************************************************/
3200
3201 /* The tls_require_ciphers option, if set, must be something which the
3202 library can parse.
3203
3204 Returns: NULL on success, or error message
3205 */
3206
3207 uschar *
3208 tls_validate_require_cipher(void)
3209 {
3210 int rc;
3211 uschar *expciphers = NULL;
3212 gnutls_priority_t priority_cache;
3213 const char *errpos;
3214 uschar * dummy_errstr;
3215
3216 #define validate_check_rc(Label) do { \
3217 if (rc != GNUTLS_E_SUCCESS) { if (exim_gnutls_base_init_done) gnutls_global_deinit(); \
3218 return string_sprintf("%s failed: %s", (Label), gnutls_strerror(rc)); } } while (0)
3219 #define return_deinit(Label) do { gnutls_global_deinit(); return (Label); } while (0)
3220
3221 if (exim_gnutls_base_init_done)
3222 log_write(0, LOG_MAIN|LOG_PANIC,
3223 "already initialised GnuTLS, Exim developer bug");
3224
3225 #ifdef HAVE_GNUTLS_PKCS11
3226 if (!gnutls_allow_auto_pkcs11)
3227 {
3228 rc = gnutls_pkcs11_init(GNUTLS_PKCS11_FLAG_MANUAL, NULL);
3229 validate_check_rc(US"gnutls_pkcs11_init");
3230 }
3231 #endif
3232 rc = gnutls_global_init();
3233 validate_check_rc(US"gnutls_global_init()");
3234 exim_gnutls_base_init_done = TRUE;
3235
3236 if (!(tls_require_ciphers && *tls_require_ciphers))
3237 return_deinit(NULL);
3238
3239 if (!expand_check(tls_require_ciphers, US"tls_require_ciphers", &expciphers,
3240 &dummy_errstr))
3241 return_deinit(US"failed to expand tls_require_ciphers");
3242
3243 if (!(expciphers && *expciphers))
3244 return_deinit(NULL);
3245
3246 DEBUG(D_tls)
3247 debug_printf("tls_require_ciphers expands to \"%s\"\n", expciphers);
3248
3249 rc = gnutls_priority_init(&priority_cache, CS expciphers, &errpos);
3250 validate_check_rc(string_sprintf(
3251 "gnutls_priority_init(%s) failed at offset %ld, \"%.8s..\"",
3252 expciphers, errpos - CS expciphers, errpos));
3253
3254 #undef return_deinit
3255 #undef validate_check_rc
3256 gnutls_global_deinit();
3257
3258 return NULL;
3259 }
3260
3261
3262
3263
3264 /*************************************************
3265 * Report the library versions. *
3266 *************************************************/
3267
3268 /* See a description in tls-openssl.c for an explanation of why this exists.
3269
3270 Arguments: a FILE* to print the results to
3271 Returns: nothing
3272 */
3273
3274 void
3275 tls_version_report(FILE *f)
3276 {
3277 fprintf(f, "Library version: GnuTLS: Compile: %s\n"
3278 " Runtime: %s\n",
3279 LIBGNUTLS_VERSION,
3280 gnutls_check_version(NULL));
3281 }
3282
3283 #endif /*!MACRO_PREDEF*/
3284 /* vi: aw ai sw=2
3285 */
3286 /* End of tls-gnu.c */