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