Events: dns:fail Bug 3011
[exim.git] / src / src / tls.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2023 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
9
10 /* This module provides TLS (aka SSL) support for Exim. The code for OpenSSL is
11 based on a patch that was originally contributed by Steve Haslam. It was
12 adapted from stunnel, a GPL program by Michal Trojnara. The code for GNU TLS is
13 based on a patch contributed by Nikos Mavrogiannopoulos. Because these packages
14 are so very different, the functions for each are kept in separate files. The
15 relevant file is #included as required, after any any common functions.
16
17 No cryptographic code is included in Exim. All this module does is to call
18 functions from the OpenSSL or GNU TLS libraries. */
19
20
21 #include "exim.h"
22 #include "transports/smtp.h"
23
24 #if !defined(DISABLE_TLS) && !defined(USE_OPENSSL) && !defined(USE_GNUTLS)
25 # error One of USE_OPENSSL or USE_GNUTLS must be defined for a TLS build
26 #endif
27
28
29 #if defined(MACRO_PREDEF) && !defined(DISABLE_TLS)
30 # include "macro_predef.h"
31 # ifdef USE_GNUTLS
32 #  include "tls-gnu.c"
33 # else
34 #  include "tls-openssl.c"
35 # endif
36 #endif
37
38 #ifndef MACRO_PREDEF
39
40 static void tls_per_lib_daemon_init(void);
41 static void tls_per_lib_daemon_tick(void);
42 static unsigned  tls_server_creds_init(void);
43 static void tls_server_creds_invalidate(void);
44 static void tls_client_creds_init(transport_instance *, BOOL);
45 static void tls_client_creds_invalidate(transport_instance *);
46 static void tls_daemon_creds_reload(void);
47 static BOOL opt_set_and_noexpand(const uschar *);
48 static BOOL opt_unset_or_noexpand(const uschar *);
49
50
51
52 /* This module is compiled only when it is specifically requested in the
53 build-time configuration. However, some compilers don't like compiling empty
54 modules, so keep them happy with a dummy when skipping the rest. Make it
55 reference itself to stop picky compilers complaining that it is unused, and put
56 in a dummy argument to stop even pickier compilers complaining about infinite
57 loops. */
58
59 #ifdef DISABLE_TLS
60 static void dummy(int x) { dummy(x-1); }
61 #else   /* most of the rest of the file */
62
63 const exim_tlslib_state null_tls_preload = {0};
64
65 /* Static variables that are used for buffering data by both sets of
66 functions and the common functions below.
67
68 We're moving away from this; GnuTLS is already using a state, which
69 can switch, so we can do TLS callouts during ACLs. */
70
71 static const int ssl_xfer_buffer_size = 4096;
72 #ifdef USE_OPENSSL
73 static uschar *ssl_xfer_buffer = NULL;
74 static int ssl_xfer_buffer_lwm = 0;
75 static int ssl_xfer_buffer_hwm = 0;
76 static int ssl_xfer_eof = FALSE;
77 static BOOL ssl_xfer_error = FALSE;
78 #endif
79
80 #ifdef EXIM_HAVE_KEVENT
81 # define KEV_SIZE 16    /* Eight file,dir pairs */
82 static struct kevent kev[KEV_SIZE];
83 static int kev_used = 0;
84 #endif
85
86 static unsigned tls_creds_expire = 0;
87
88 /*************************************************
89 *       Expand string; give error on failure     *
90 *************************************************/
91
92 /* If expansion is forced to fail, set the result NULL and return TRUE.
93 Other failures return FALSE. For a server, an SMTP response is given.
94
95 Arguments:
96   s         the string to expand; if NULL just return TRUE
97   name      name of string being expanded (for error)
98   result    where to put the result
99
100 Returns:    TRUE if OK; result may still be NULL after forced failure
101 */
102
103 static BOOL
104 expand_check(const uschar * s, const uschar * name,
105   uschar ** result, uschar ** errstr)
106 {
107 if (!s)
108   {
109   f.expand_string_forcedfail = FALSE;
110   *result = NULL;
111   }
112 else if (  !(*result = expand_string(US s)) /* need to clean up const more */
113         && !f.expand_string_forcedfail
114         )
115   {
116   *errstr = US"Internal error";
117   log_write(0, LOG_MAIN|LOG_PANIC, "expansion of %s failed: %s", name,
118     expand_string_message);
119   return FALSE;
120   }
121 return TRUE;
122 }
123
124
125 #if defined(EXIM_HAVE_INOTIFY) || defined(EXIM_HAVE_KEVENT)
126 /* Add the directory for a filename to the inotify handle, creating that if
127 needed.  This is enough to see changes to files in that dir.
128 Return boolean success.
129
130 The word "system" fails, which is on the safe side as we don't know what
131 directory it implies nor if the TLS library handles a watch for us.
132
133 The string "system,cache" is recognised and explicitly accepted without
134 setting a watch.  This permits the system CA bundle to be cached even though
135 we have no way to tell when it gets modified by an update.
136 The call chain for OpenSSL uses a (undocumented) call into the library
137 to discover the actual file.  We don't know what GnuTLS uses.
138
139 A full set of caching including the CAs takes 35ms output off of the
140 server tls_init() (GnuTLS, Fedora 32, 2018-class x86_64 laptop hardware).
141 */
142 static BOOL
143 tls_set_one_watch(const uschar * filename)
144 # ifdef EXIM_HAVE_INOTIFY
145 {
146 uschar buf[PATH_MAX];
147 ssize_t len;
148 uschar * s;
149
150 if (Ustrcmp(filename, "system,cache") == 0) return TRUE;
151 if (!(s = Ustrrchr(filename, '/'))) return FALSE;
152
153 for (unsigned loop = 20;
154      (len = readlink(CCS filename, CS buf, sizeof(buf))) >= 0; )
155   {                                             /* a symlink */
156   if (--loop == 0) { errno = ELOOP; return FALSE; }
157   filename = buf[0] == '/'
158     ? string_copyn(buf, (unsigned)len)  /* mem released by tls_set_watch */
159     : string_sprintf("%.*s/%.*s", (int)(s - filename), filename, (int)len, buf);
160   s = Ustrrchr(filename, '/');
161   }
162 if (errno != EINVAL)
163   return FALSE;                                 /* other error */
164
165 /* not a symlink */
166 s = string_copyn(filename, s - filename);       /* mem released by tls_set_watch */
167
168 DEBUG(D_tls) debug_printf("watch dir '%s'\n", s);
169
170 if (inotify_add_watch(tls_watch_fd, CCS s,
171       IN_ONESHOT | IN_CLOSE_WRITE | IN_DELETE | IN_DELETE_SELF
172       | IN_MOVED_FROM | IN_MOVED_TO | IN_MOVE_SELF) >= 0)
173   return TRUE;
174 DEBUG(D_tls) debug_printf("notify_add_watch: %s\n", strerror(errno));
175 return FALSE;
176 }
177 # endif
178 # ifdef EXIM_HAVE_KEVENT
179 {
180 uschar * s, * t;
181 int fd1, fd2, i, j, cnt = 0;
182 struct stat sb;
183 #ifdef OpenBSD
184 struct kevent k_dummy;
185 struct timespec ts = {0};
186 #endif
187
188 errno = 0;
189 if (Ustrcmp(filename, "system,cache") == 0) return TRUE;
190
191 for (;;)
192   {
193   if (kev_used > KEV_SIZE-2) { s = US"out of kev space"; goto bad; }
194   if (!(s = Ustrrchr(filename, '/'))) return FALSE;
195   s = string_copyn(filename, s - filename);     /* mem released by tls_set_watch */
196
197   /* The dir open will fail if there is a symlink on the path. Fine; it's too
198   much effort to handle all possible cases; just refuse the preload. */
199
200   if ((fd2 = open(CCS s, O_RDONLY | O_NOFOLLOW)) < 0) { s = US"open dir"; goto bad; }
201
202   if ((lstat(CCS filename, &sb)) < 0) { s = US"lstat"; goto bad; }
203   if (!S_ISLNK(sb.st_mode))
204     {
205     if ((fd1 = open(CCS filename, O_RDONLY | O_NOFOLLOW)) < 0)
206       { s = US"open file"; goto bad; }
207     DEBUG(D_tls) debug_printf("watch file '%s':\t%d\n", filename, fd1);
208     EV_SET(&kev[kev_used++],
209         (uintptr_t)fd1,
210         EVFILT_VNODE,
211         EV_ADD | EV_ENABLE | EV_ONESHOT,
212         NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND
213         | NOTE_ATTRIB | NOTE_RENAME | NOTE_REVOKE,
214         0,
215         NULL);
216     cnt++;
217     }
218   DEBUG(D_tls) debug_printf("watch dir  '%s':\t%d\n", s, fd2);
219   EV_SET(&kev[kev_used++],
220         (uintptr_t)fd2,
221         EVFILT_VNODE,
222         EV_ADD | EV_ENABLE | EV_ONESHOT,
223         NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND
224         | NOTE_ATTRIB | NOTE_RENAME | NOTE_REVOKE,
225         0,
226         NULL);
227   cnt++;
228
229   if (!(S_ISLNK(sb.st_mode))) break;
230
231   t = store_get(1024, GET_UNTAINTED);
232   Ustrncpy(t, s, 1022);
233   j = Ustrlen(s);
234   t[j++] = '/';
235   if ((i = readlink(CCS filename, (void *)(t+j), 1023-j)) < 0) { s = US"readlink"; goto bad; }
236   filename = t;
237   *(t += i+j) = '\0';
238   store_release_above(t+1);
239   }
240
241 #ifdef OpenBSD
242 if (kevent(tls_watch_fd, &kev[kev_used-cnt], cnt, &k_dummy, 1, &ts) >= 0)
243   return TRUE;
244 #else
245 if (kevent(tls_watch_fd, &kev[kev_used-cnt], cnt, NULL, 0, NULL) >= 0)
246   return TRUE;
247 #endif
248 s = US"kevent";
249
250 bad:
251 DEBUG(D_tls)
252   if (errno)
253     debug_printf("%s: %s: %s\n", __FUNCTION__, s, strerror(errno));
254   else
255     debug_printf("%s: %s\n", __FUNCTION__, s);
256 return FALSE;
257 }
258 # endif /*EXIM_HAVE_KEVENT*/
259
260
261 /* Create an inotify facility if needed.
262 Then set watches on the dir containing the given file or (optionally)
263 list of files.  Return boolean success. */
264
265 static BOOL
266 tls_set_watch(const uschar * filename, BOOL list)
267 {
268 rmark r;
269 BOOL rc = FALSE;
270
271 if (!filename || !*filename) return TRUE;
272 if (Ustrncmp(filename, "system", 6) == 0) return TRUE;
273
274 DEBUG(D_tls) debug_printf("tls_set_watch: '%s'\n", filename);
275
276 if (  tls_watch_fd < 0
277 # ifdef EXIM_HAVE_INOTIFY
278    && (tls_watch_fd = inotify_init1(O_CLOEXEC)) < 0
279 # endif
280 # ifdef EXIM_HAVE_KEVENT
281    && (tls_watch_fd = kqueue()) < 0
282 # endif
283    )
284     {
285     DEBUG(D_tls) debug_printf("inotify_init: %s\n", strerror(errno));
286     return FALSE;
287     }
288
289 r = store_mark();
290
291 if (list)
292   {
293   int sep = 0;
294   for (uschar * s; s = string_nextinlist(&filename, &sep, NULL, 0); )
295     if (!(rc = tls_set_one_watch(s))) break;
296   }
297 else
298   rc = tls_set_one_watch(filename);
299
300 store_reset(r);
301 if (!rc) DEBUG(D_tls) debug_printf("tls_set_watch() fail on '%s': %s\n", filename, strerror(errno));
302 return rc;
303 }
304
305
306 void
307 tls_watch_discard_event(int fd)
308 {
309 #ifdef EXIM_HAVE_INOTIFY
310 (void) read(fd, big_buffer, big_buffer_size);
311 #endif
312 #ifdef EXIM_HAVE_KEVENT
313 struct kevent kev;
314 struct timespec t = {0};
315 (void) kevent(fd, NULL, 0, &kev, 1, &t);
316 #endif
317 }
318 #endif  /*EXIM_HAVE_INOTIFY*/
319
320
321 void
322 tls_client_creds_reload(BOOL watch)
323 {
324 for(transport_instance * t = transports; t; t = t->next)
325   if (Ustrcmp(t->driver_name, "smtp") == 0)
326     {
327     tls_client_creds_invalidate(t);
328     tls_client_creds_init(t, watch);
329     }
330 }
331
332
333 void
334 tls_watch_invalidate(void)
335 {
336 if (tls_watch_fd < 0) return;
337
338 #ifdef EXIM_HAVE_KEVENT
339 /* Close the files we had open for kevent */
340 for (int i = 0; i < kev_used; i++)
341   {
342   DEBUG(D_tls) debug_printf("closing watch fd: %d\n", (int) kev[i].ident);
343   (void) close((int) kev[i].ident);
344   kev[i].ident = (uintptr_t)-1;
345   }
346 kev_used = 0;
347 #endif
348
349 close(tls_watch_fd);
350 tls_watch_fd = -1;
351 }
352
353
354 static void
355 tls_daemon_creds_reload(void)
356 {
357 unsigned lifetime;
358
359 #ifdef EXIM_HAVE_KEVENT
360 tls_watch_invalidate();
361 #endif
362
363 tls_server_creds_invalidate();
364
365 /* _expire is for a time-limited selfsign server cert */
366 tls_creds_expire = (lifetime = tls_server_creds_init())
367   ? time(NULL) + lifetime : 0;
368
369 tls_client_creds_reload(TRUE);
370 }
371
372
373 /* Utility predicates for use by the per-library code */
374 static BOOL
375 opt_set_and_noexpand(const uschar * opt)
376 { return opt && *opt && Ustrchr(opt, '$') == NULL; }
377
378 static BOOL
379 opt_unset_or_noexpand(const uschar * opt)
380 { return !opt || Ustrchr(opt, '$') == NULL; }
381
382
383
384 /* Called every time round the daemon loop.
385
386 If we reloaded fd-watcher, return the old watch fd
387 having modified the global for the new one. Otherwise
388 return -1.
389 */
390
391 int
392 tls_daemon_tick(void)
393 {
394 int old_watch_fd = tls_watch_fd;
395
396 tls_per_lib_daemon_tick();
397 #if defined(EXIM_HAVE_INOTIFY) || defined(EXIM_HAVE_KEVENT)
398 if (tls_creds_expire && time(NULL) >= tls_creds_expire)
399   {
400   /* The server cert is a selfsign, with limited lifetime.  Dump it and
401   generate a new one.  Reload the rest of the creds also as the machinery
402   is all there. */
403
404   DEBUG(D_tls) debug_printf("selfsign cert rotate\n");
405   tls_creds_expire = 0;
406   tls_daemon_creds_reload();
407   return old_watch_fd;
408   }
409 else if (tls_watch_trigger_time && time(NULL) >= tls_watch_trigger_time + 5)
410   {
411   /* Called, after a delay for multiple file ops to get done, from
412   the daemon when any of the watches added (above) fire.
413   Dump the set of watches and arrange to reload cached creds (which
414   will set up new watches). */
415
416   DEBUG(D_tls) debug_printf("watch triggered\n");
417   tls_watch_trigger_time = tls_creds_expire = 0;
418   tls_daemon_creds_reload();
419   return old_watch_fd;
420   }
421 #endif
422 return -1;
423 }
424
425 /* Called once at daemon startup */
426
427 void
428 tls_daemon_init(void)
429 {
430 tls_per_lib_daemon_init();
431 }
432
433
434 /*************************************************
435 *        Timezone environment flipping           *
436 *************************************************/
437
438 static uschar *
439 to_tz(uschar * tz)
440 {
441 uschar * old = US getenv("TZ");
442 (void) setenv("TZ", CCS tz, 1);
443 tzset();
444 return old;
445 }
446
447 static void
448 restore_tz(uschar * tz)
449 {
450 if (tz)
451   (void) setenv("TZ", CCS tz, 1);
452 else
453   (void) os_unsetenv(US"TZ");
454 tzset();
455 }
456
457 /*************************************************
458 *        Many functions are package-specific     *
459 *************************************************/
460 /* Forward decl. */
461 static void tls_client_resmption_key(tls_support *, smtp_connect_args *,
462   smtp_transport_options_block *);
463
464
465 #ifdef USE_GNUTLS
466 # include "tls-gnu.c"
467 # include "tlscert-gnu.c"
468 # define ssl_xfer_buffer (state_server.xfer_buffer)
469 # define ssl_xfer_buffer_lwm (state_server.xfer_buffer_lwm)
470 # define ssl_xfer_buffer_hwm (state_server.xfer_buffer_hwm)
471 # define ssl_xfer_eof (state_server.xfer_eof)
472 # define ssl_xfer_error (state_server.xfer_error)
473 #endif
474
475 #ifdef USE_OPENSSL
476 # include "tls-openssl.c"
477 # include "tlscert-openssl.c"
478 #endif
479
480
481
482 /*************************************************
483 *           TLS version of ungetc                *
484 *************************************************/
485
486 /* Puts a character back in the input buffer. Only ever
487 called once.
488 Only used by the server-side TLS.
489
490 Arguments:
491   ch           the character
492
493 Returns:       the character
494 */
495
496 int
497 tls_ungetc(int ch)
498 {
499 if (ssl_xfer_buffer_lwm <= 0)
500   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "buffer underflow in tls_ungetc");
501
502 ssl_xfer_buffer[--ssl_xfer_buffer_lwm] = ch;
503 return ch;
504 }
505
506
507
508 /*************************************************
509 *           TLS version of feof                  *
510 *************************************************/
511
512 /* Tests for a previous EOF
513 Only used by the server-side TLS.
514
515 Arguments:     none
516 Returns:       non-zero if the eof flag is set
517 */
518
519 int
520 tls_feof(void)
521 {
522 return (int)ssl_xfer_eof;
523 }
524
525
526
527 /*************************************************
528 *              TLS version of ferror             *
529 *************************************************/
530
531 /* Tests for a previous read error, and returns with errno
532 restored to what it was when the error was detected.
533 Only used by the server-side TLS.
534
535 >>>>> Hmm. Errno not handled yet. Where do we get it from?  >>>>>
536
537 Arguments:     none
538 Returns:       non-zero if the error flag is set
539 */
540
541 int
542 tls_ferror(void)
543 {
544 return (int)ssl_xfer_error;
545 }
546
547
548 /*************************************************
549 *           TLS version of smtp_buffered         *
550 *************************************************/
551
552 /* Tests for unused chars in the TLS input buffer.
553 Only used by the server-side TLS.
554
555 Arguments:     none
556 Returns:       TRUE/FALSE
557 */
558
559 BOOL
560 tls_smtp_buffered(void)
561 {
562 return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm;
563 }
564
565
566 #endif  /*DISABLE_TLS*/
567
568 void
569 tls_modify_variables(tls_support * dest_tsp)
570 {
571 modify_variable(US"tls_bits",                 &dest_tsp->bits);
572 modify_variable(US"tls_certificate_verified", &dest_tsp->certificate_verified);
573 modify_variable(US"tls_cipher",               &dest_tsp->cipher);
574 modify_variable(US"tls_peerdn",               &dest_tsp->peerdn);
575 #ifdef USE_OPENSSL
576 modify_variable(US"tls_sni",                  &dest_tsp->sni);
577 #endif
578 }
579
580
581 #ifndef DISABLE_TLS
582 /************************************************
583 *       TLS certificate name operations         *
584 ************************************************/
585
586 /* Convert an rfc4514 DN to an exim comma-sep list.
587 Backslashed commas need to be replaced by doublecomma
588 for Exim's list quoting.  We modify the given string
589 inplace.
590 */
591
592 static void
593 dn_to_list(uschar * dn)
594 {
595 for (uschar * cp = dn; *cp; cp++)
596   if (cp[0] == '\\' && cp[1] == ',')
597     *cp++ = ',';
598 }
599
600
601 /* Extract fields of a given type from an RFC4514-
602 format Distinguished Name.  Return an Exim list.
603 NOTE: We modify the supplied dn string during operation.
604
605 Arguments:
606         dn      Distinguished Name string
607         mod     list containing optional output list-sep and
608                 field selector match, comma-separated
609 Return:
610         allocated string with list of matching fields,
611         field type stripped
612 */
613
614 uschar *
615 tls_field_from_dn(uschar * dn, const uschar * mod)
616 {
617 int insep = ',';
618 uschar outsep = '\n';
619 uschar * ele;
620 uschar * match = NULL;
621 int len;
622 gstring * list = NULL;
623
624 while ((ele = string_nextinlist(&mod, &insep, NULL, 0)))
625   if (ele[0] != '>')
626     match = ele;        /* field tag to match */
627   else if (ele[1])
628     outsep = ele[1];    /* nondefault output separator */
629
630 dn_to_list(dn);
631 insep = ',';
632 len = match ? Ustrlen(match) : -1;
633 while ((ele = string_nextinlist(CUSS &dn, &insep, NULL, 0)))
634   if (  !match
635      || Ustrncmp(ele, match, len) == 0 && ele[len] == '='
636      )
637     list = string_append_listele(list, outsep, ele+len+1);
638 return string_from_gstring(list);
639 }
640
641
642 /* Compare a domain name with a possibly-wildcarded name. Wildcards
643 are restricted to a single one, as the first element of patterns
644 having at least three dot-separated elements.  Case-independent.
645 Return TRUE for a match
646 */
647 static BOOL
648 is_name_match(const uschar * name, const uschar * pat)
649 {
650 uschar * cp;
651 return *pat == '*'              /* possible wildcard match */
652   ?    *++pat == '.'            /* starts star, dot              */
653     && !Ustrchr(++pat, '*')     /* has no more stars             */
654     && Ustrchr(pat, '.')        /* and has another dot.          */
655     && (cp = Ustrchr(name, '.'))/* The name has at least one dot */
656     && strcmpic(++cp, pat) == 0 /* and we only compare after it. */
657   :    !Ustrchr(pat+1, '*')
658     && strcmpic(name, pat) == 0;
659 }
660
661 /* Compare a list of names with the dnsname elements
662 of the Subject Alternate Name, if any, and the
663 Subject otherwise.
664
665 Arguments:
666         namelist names to compare
667         cert     certificate
668
669 Returns:
670         TRUE/FALSE
671 */
672
673 BOOL
674 tls_is_name_for_cert(const uschar * namelist, void * cert)
675 {
676 uschar * altnames, * subjdn, * certname, * cmpname;
677 int cmp_sep = 0;
678
679 if ((altnames = tls_cert_subject_altname(cert, US"dns")))
680   {
681   int alt_sep = '\n';
682   DEBUG(D_tls|D_lookup) debug_printf_indent("cert has SAN\n");
683   while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0)))
684     {
685     const uschar * an = altnames;
686     DEBUG(D_tls|D_lookup) debug_printf_indent(" %s in SANs?", cmpname);
687     while ((certname = string_nextinlist(&an, &alt_sep, NULL, 0)))
688       if (is_name_match(cmpname, certname))
689         {
690         DEBUG(D_tls|D_lookup) debug_printf_indent("  yes (matched %s)\n", certname);
691         return TRUE;
692         }
693     DEBUG(D_tls|D_lookup) debug_printf_indent(" no (end of SAN list)\n");
694     }
695   }
696
697 else if ((subjdn = tls_cert_subject(cert, NULL)))
698   {
699   int sn_sep = ',';
700
701   dn_to_list(subjdn);
702   while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0)))
703     {
704     const uschar * sn = subjdn;
705     DEBUG(D_tls|D_lookup) debug_printf_indent(" %s in SN?", cmpname);
706     while ((certname = string_nextinlist(&sn, &sn_sep, NULL, 0)))
707       if (  *certname++ == 'C'
708          && *certname++ == 'N'
709          && *certname++ == '='
710          && is_name_match(cmpname, certname)
711          )
712         {
713         DEBUG(D_tls|D_lookup) debug_printf_indent("  yes (matched %s)\n", certname);
714         return TRUE;
715         }
716     DEBUG(D_tls|D_lookup) debug_printf_indent(" no (end of CN)\n");
717     }
718   }
719 return FALSE;
720 }
721
722 /* Environment cleanup: The GnuTLS library uses SSLKEYLOGFILE in the environment
723 and writes a file by that name.  Our OpenSSL code does the same, using keying
724 info from the library API.
725 The GnuTLS support only works if exim is run by root, not taking advantage of
726 the setuid bit.
727 You can use either the external environment (modulo the keep_environment config)
728 or the add_environment config option for SSLKEYLOGFILE; the latter takes
729 precedence.
730
731 If the path is absolute, require it starts with the spooldir; otherwise delete
732 the env variable.  If relative, prefix the spooldir.
733 */
734 void
735 tls_clean_env(void)
736 {
737 uschar * path = US getenv("SSLKEYLOGFILE");
738 if (path)
739   if (!*path)
740     unsetenv("SSLKEYLOGFILE");
741   else if (*path != '/')
742     {
743     DEBUG(D_tls)
744       debug_printf("prepending spooldir to  env SSLKEYLOGFILE\n");
745     setenv("SSLKEYLOGFILE", CCS string_sprintf("%s/%s", spool_directory, path), 1);
746     }
747   else if (Ustrncmp(path, spool_directory, Ustrlen(spool_directory)) != 0)
748     {
749     DEBUG(D_tls)
750       debug_printf("removing env SSLKEYLOGFILE=%s: not under spooldir\n", path);
751     unsetenv("SSLKEYLOGFILE");
752     }
753 }
754
755 /*************************************************
756 *       Drop privs for checking TLS config      *
757 *************************************************/
758
759 /* We want to validate TLS options during readconf, but do not want to be
760 root when we call into the TLS library, in case of library linkage errors
761 which cause segfaults; before this check, those were always done as the Exim
762 runtime user and it makes sense to continue with that.
763
764 Assumes:  tls_require_ciphers has been set, if it will be
765           exim_user has been set, if it will be
766           exim_group has been set, if it will be
767
768 Returns:  bool for "okay"; false will cause caller to immediately exit.
769 */
770
771 BOOL
772 tls_dropprivs_validate_require_cipher(BOOL nowarn)
773 {
774 const uschar *errmsg;
775 pid_t pid;
776 int rc, status;
777 void (*oldsignal)(int);
778
779 /* If TLS will never be used, no point checking ciphers */
780
781 if (  !tls_advertise_hosts
782    || !*tls_advertise_hosts
783    || Ustrcmp(tls_advertise_hosts, ":") == 0
784    )
785   return TRUE;
786 else if (!nowarn && !tls_certificate)
787   log_write(0, LOG_MAIN,
788     "Warning: No server certificate defined; will use a selfsigned one.\n"
789     " Suggested action: either install a certificate or change tls_advertise_hosts option");
790
791 oldsignal = signal(SIGCHLD, SIG_DFL);
792
793 fflush(NULL);
794 if ((pid = exim_fork(US"cipher-validate")) < 0)
795   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "fork failed for TLS check");
796
797 if (pid == 0)
798   {
799   /* in some modes, will have dropped privilege already */
800   if (!geteuid())
801     exim_setugid(exim_uid, exim_gid, FALSE,
802         US"calling tls_validate_require_cipher");
803
804   if ((errmsg = tls_validate_require_cipher()))
805     log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
806         "tls_require_ciphers invalid: %s", errmsg);
807   fflush(NULL);
808   exim_underbar_exit(EXIT_SUCCESS);
809   }
810
811 do {
812   rc = waitpid(pid, &status, 0);
813 } while (rc < 0 && errno == EINTR);
814
815 DEBUG(D_tls)
816   debug_printf("tls_validate_require_cipher child %d ended: status=0x%x\n",
817       (int)pid, status);
818
819 signal(SIGCHLD, oldsignal);
820
821 return status == 0;
822 }
823
824
825
826
827 static void
828 tls_client_resmption_key(tls_support * tlsp, smtp_connect_args * conn_args,
829   smtp_transport_options_block * ob)
830 {
831 #ifndef DISABLE_TLS_RESUME
832 hctx * h = &tlsp->resume_hctx;
833 blob b;
834 gstring * g;
835
836 DEBUG(D_tls) if (conn_args->host_lbserver)
837   debug_printf("TLS: lbserver '%s'\n", conn_args->host_lbserver);
838
839 # ifdef EXIM_HAVE_SHA2
840 exim_sha_init(h, HASH_SHA2_256);
841 # else
842 exim_sha_init(h, HASH_SHA1);
843 # endif
844 exim_sha_update_string(h, conn_args->host_lbserver);
845 # ifdef SUPPORT_DANE
846 if (conn_args->dane)
847   exim_sha_update(h,  CUS &conn_args->tlsa_dnsa, sizeof(dns_answer));
848 # endif
849 exim_sha_update_string(h, conn_args->host->address);
850 exim_sha_update(h,   CUS &conn_args->host->port, sizeof(conn_args->host->port));
851 exim_sha_update_string(h, conn_args->sending_ip_address);
852 exim_sha_update_string(h, openssl_options);
853 exim_sha_update_string(h, ob->tls_require_ciphers);
854 exim_sha_update_string(h, tlsp->sni);
855 # ifdef EXIM_HAVE_ALPN
856 exim_sha_update_string(h, ob->tls_alpn);
857 # endif
858 exim_sha_finish(h, &b);
859 for (g = string_get(b.len*2+1); b.len-- > 0; )
860   g = string_fmt_append(g, "%02x", *b.data++);
861 tlsp->resume_index = string_from_gstring(g);
862 DEBUG(D_tls) debug_printf("TLS: resume session index %s\n", tlsp->resume_index);
863 #endif
864 }
865
866
867
868 /* Start TLS as a client for an ajunct connection, eg. readsocket
869 Return boolean success.
870 */
871
872 BOOL
873 tls_client_adjunct_start(host_item * host, client_conn_ctx * cctx,
874   const uschar * sni, uschar ** errmsg)
875 {
876 union sockaddr_46 interface_sock;
877 EXIM_SOCKLEN_T size = sizeof(interface_sock);
878 smtp_connect_args conn_args = {.host = host };
879 tls_support tls_dummy = { .sni = NULL };
880 uschar * errstr;
881
882 if (getsockname(cctx->sock, (struct sockaddr *) &interface_sock, &size) == 0)
883   conn_args.sending_ip_address = host_ntoa(-1, &interface_sock, NULL, NULL);
884 else
885   {
886   *errmsg = string_sprintf("getsockname failed: %s", strerror(errno));
887   return FALSE;
888   }
889
890 /* To handle SNI we need to emulate more of a real transport because the
891 base tls code assumes that is where the SNI string lives. */
892
893 if (*sni)
894   {
895   transport_instance * tb;
896   smtp_transport_options_block * ob;
897
898   conn_args.tblock = tb = store_get(sizeof(*tb), GET_UNTAINTED);
899   memset(tb, 0, sizeof(*tb));
900
901   tb->options_block = ob = store_get(sizeof(*ob), GET_UNTAINTED);
902   memcpy(ob, &smtp_transport_option_defaults, sizeof(*ob));
903
904   ob->tls_sni = sni;
905   }
906
907 if (!tls_client_start(cctx, &conn_args, NULL, &tls_dummy, &errstr))
908   {
909   *errmsg = string_sprintf("TLS connect failed: %s", errstr);
910   return FALSE;
911   }
912 return TRUE;
913 }
914
915
916
917 #endif  /*!DISABLE_TLS*/
918 #endif  /*!MACRO_PREDEF*/
919
920 /* vi: aw ai sw=2
921 */
922 /* End of tls.c */