Set LC_ALL=C for doc generation
[exim.git] / src / src / tls.c
... / ...
CommitLineData
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
5/* Copyright (c) University of Cambridge 1995 - 2018 */
6/* See the file NOTICE for conditions of use and distribution. */
7
8/* This module provides TLS (aka SSL) support for Exim. The code for OpenSSL is
9based on a patch that was originally contributed by Steve Haslam. It was
10adapted from stunnel, a GPL program by Michal Trojnara. The code for GNU TLS is
11based on a patch contributed by Nikos Mavrogiannopoulos. Because these packages
12are so very different, the functions for each are kept in separate files. The
13relevant file is #included as required, after any any common functions.
14
15No cryptographic code is included in Exim. All this module does is to call
16functions from the OpenSSL or GNU TLS libraries. */
17
18
19#include "exim.h"
20#include "transports/smtp.h"
21
22#if !defined(DISABLE_TLS) && !defined(USE_OPENSSL) && !defined(USE_GNUTLS)
23# error One of USE_OPENSSL or USE_GNUTLS must be defined for a TLS build
24#endif
25
26
27#if defined(MACRO_PREDEF) && !defined(DISABLE_TLS)
28# include "macro_predef.h"
29# ifdef USE_GNUTLS
30# include "tls-gnu.c"
31# else
32# include "tls-openssl.c"
33# endif
34#endif
35
36#ifndef MACRO_PREDEF
37
38/* This module is compiled only when it is specifically requested in the
39build-time configuration. However, some compilers don't like compiling empty
40modules, so keep them happy with a dummy when skipping the rest. Make it
41reference itself to stop picky compilers complaining that it is unused, and put
42in a dummy argument to stop even pickier compilers complaining about infinite
43loops. */
44
45#ifdef DISABLE_TLS
46static void dummy(int x) { dummy(x-1); }
47#else
48
49/* Static variables that are used for buffering data by both sets of
50functions and the common functions below.
51
52We're moving away from this; GnuTLS is already using a state, which
53can switch, so we can do TLS callouts during ACLs. */
54
55static const int ssl_xfer_buffer_size = 4096;
56#ifdef USE_OPENSSL
57static uschar *ssl_xfer_buffer = NULL;
58static int ssl_xfer_buffer_lwm = 0;
59static int ssl_xfer_buffer_hwm = 0;
60static int ssl_xfer_eof = FALSE;
61static BOOL ssl_xfer_error = FALSE;
62#endif
63
64
65/*************************************************
66* Expand string; give error on failure *
67*************************************************/
68
69/* If expansion is forced to fail, set the result NULL and return TRUE.
70Other failures return FALSE. For a server, an SMTP response is given.
71
72Arguments:
73 s the string to expand; if NULL just return TRUE
74 name name of string being expanded (for error)
75 result where to put the result
76
77Returns: TRUE if OK; result may still be NULL after forced failure
78*/
79
80static BOOL
81expand_check(const uschar *s, const uschar *name, uschar **result, uschar ** errstr)
82{
83if (!s)
84 *result = NULL;
85else if ( !(*result = expand_string(US s)) /* need to clean up const more */
86 && !f.expand_string_forcedfail
87 )
88 {
89 *errstr = US"Internal error";
90 log_write(0, LOG_MAIN|LOG_PANIC, "expansion of %s failed: %s", name,
91 expand_string_message);
92 return FALSE;
93 }
94return TRUE;
95}
96
97
98/*************************************************
99* Timezone environment flipping *
100*************************************************/
101
102static uschar *
103to_tz(uschar * tz)
104{
105uschar * old = US getenv("TZ");
106(void) setenv("TZ", CCS tz, 1);
107tzset();
108return old;
109}
110
111static void
112restore_tz(uschar * tz)
113{
114if (tz)
115 (void) setenv("TZ", CCS tz, 1);
116else
117 (void) os_unsetenv(US"TZ");
118tzset();
119}
120
121/*************************************************
122* Many functions are package-specific *
123*************************************************/
124
125#ifdef USE_GNUTLS
126# include "tls-gnu.c"
127# include "tlscert-gnu.c"
128# define ssl_xfer_buffer (state_server.xfer_buffer)
129# define ssl_xfer_buffer_lwm (state_server.xfer_buffer_lwm)
130# define ssl_xfer_buffer_hwm (state_server.xfer_buffer_hwm)
131# define ssl_xfer_eof (state_server.xfer_eof)
132# define ssl_xfer_error (state_server.xfer_error)
133#endif
134
135#ifdef USE_OPENSSL
136# include "tls-openssl.c"
137# include "tlscert-openssl.c"
138#endif
139
140
141
142/*************************************************
143* TLS version of ungetc *
144*************************************************/
145
146/* Puts a character back in the input buffer. Only ever
147called once.
148Only used by the server-side TLS.
149
150Arguments:
151 ch the character
152
153Returns: the character
154*/
155
156int
157tls_ungetc(int ch)
158{
159ssl_xfer_buffer[--ssl_xfer_buffer_lwm] = ch;
160return ch;
161}
162
163
164
165/*************************************************
166* TLS version of feof *
167*************************************************/
168
169/* Tests for a previous EOF
170Only used by the server-side TLS.
171
172Arguments: none
173Returns: non-zero if the eof flag is set
174*/
175
176int
177tls_feof(void)
178{
179return (int)ssl_xfer_eof;
180}
181
182
183
184/*************************************************
185* TLS version of ferror *
186*************************************************/
187
188/* Tests for a previous read error, and returns with errno
189restored to what it was when the error was detected.
190Only used by the server-side TLS.
191
192>>>>> Hmm. Errno not handled yet. Where do we get it from? >>>>>
193
194Arguments: none
195Returns: non-zero if the error flag is set
196*/
197
198int
199tls_ferror(void)
200{
201return (int)ssl_xfer_error;
202}
203
204
205/*************************************************
206* TLS version of smtp_buffered *
207*************************************************/
208
209/* Tests for unused chars in the TLS input buffer.
210Only used by the server-side TLS.
211
212Arguments: none
213Returns: TRUE/FALSE
214*/
215
216BOOL
217tls_smtp_buffered(void)
218{
219return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm;
220}
221
222
223#endif /*DISABLE_TLS*/
224
225void
226tls_modify_variables(tls_support * dest_tsp)
227{
228modify_variable(US"tls_bits", &dest_tsp->bits);
229modify_variable(US"tls_certificate_verified", &dest_tsp->certificate_verified);
230modify_variable(US"tls_cipher", &dest_tsp->cipher);
231modify_variable(US"tls_peerdn", &dest_tsp->peerdn);
232#ifdef USE_OPENSSL
233modify_variable(US"tls_sni", &dest_tsp->sni);
234#endif
235}
236
237
238#ifndef DISABLE_TLS
239/************************************************
240* TLS certificate name operations *
241************************************************/
242
243/* Convert an rfc4514 DN to an exim comma-sep list.
244Backslashed commas need to be replaced by doublecomma
245for Exim's list quoting. We modify the given string
246inplace.
247*/
248
249static void
250dn_to_list(uschar * dn)
251{
252for (uschar * cp = dn; *cp; cp++)
253 if (cp[0] == '\\' && cp[1] == ',')
254 *cp++ = ',';
255}
256
257
258/* Extract fields of a given type from an RFC4514-
259format Distinguished Name. Return an Exim list.
260NOTE: We modify the supplied dn string during operation.
261
262Arguments:
263 dn Distinguished Name string
264 mod list containing optional output list-sep and
265 field selector match, comma-separated
266Return:
267 allocated string with list of matching fields,
268 field type stripped
269*/
270
271uschar *
272tls_field_from_dn(uschar * dn, const uschar * mod)
273{
274int insep = ',';
275uschar outsep = '\n';
276uschar * ele;
277uschar * match = NULL;
278int len;
279gstring * list = NULL;
280
281while ((ele = string_nextinlist(&mod, &insep, NULL, 0)))
282 if (ele[0] != '>')
283 match = ele; /* field tag to match */
284 else if (ele[1])
285 outsep = ele[1]; /* nondefault output separator */
286
287dn_to_list(dn);
288insep = ',';
289len = match ? Ustrlen(match) : -1;
290while ((ele = string_nextinlist(CUSS &dn, &insep, NULL, 0)))
291 if ( !match
292 || Ustrncmp(ele, match, len) == 0 && ele[len] == '='
293 )
294 list = string_append_listele(list, outsep, ele+len+1);
295return string_from_gstring(list);
296}
297
298
299/* Compare a domain name with a possibly-wildcarded name. Wildcards
300are restricted to a single one, as the first element of patterns
301having at least three dot-separated elements. Case-independent.
302Return TRUE for a match
303*/
304static BOOL
305is_name_match(const uschar * name, const uschar * pat)
306{
307uschar * cp;
308return *pat == '*' /* possible wildcard match */
309 ? *++pat == '.' /* starts star, dot */
310 && !Ustrchr(++pat, '*') /* has no more stars */
311 && Ustrchr(pat, '.') /* and has another dot. */
312 && (cp = Ustrchr(name, '.'))/* The name has at least one dot */
313 && strcmpic(++cp, pat) == 0 /* and we only compare after it. */
314 : !Ustrchr(pat+1, '*')
315 && strcmpic(name, pat) == 0;
316}
317
318/* Compare a list of names with the dnsname elements
319of the Subject Alternate Name, if any, and the
320Subject otherwise.
321
322Arguments:
323 namelist names to compare
324 cert certificate
325
326Returns:
327 TRUE/FALSE
328*/
329
330BOOL
331tls_is_name_for_cert(const uschar * namelist, void * cert)
332{
333uschar * altnames = tls_cert_subject_altname(cert, US"dns");
334uschar * subjdn;
335uschar * certname;
336int cmp_sep = 0;
337uschar * cmpname;
338
339if ((altnames = tls_cert_subject_altname(cert, US"dns")))
340 {
341 int alt_sep = '\n';
342 while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0)))
343 {
344 const uschar * an = altnames;
345 while ((certname = string_nextinlist(&an, &alt_sep, NULL, 0)))
346 if (is_name_match(cmpname, certname))
347 return TRUE;
348 }
349 }
350
351else if ((subjdn = tls_cert_subject(cert, NULL)))
352 {
353 int sn_sep = ',';
354
355 dn_to_list(subjdn);
356 while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0)))
357 {
358 const uschar * sn = subjdn;
359 while ((certname = string_nextinlist(&sn, &sn_sep, NULL, 0)))
360 if ( *certname++ == 'C'
361 && *certname++ == 'N'
362 && *certname++ == '='
363 && is_name_match(cmpname, certname)
364 )
365 return TRUE;
366 }
367 }
368return FALSE;
369}
370
371
372/* Environment cleanup: The GnuTLS library uses SSLKEYLOGFILE in the environment
373and writes a file by that name. Our OpenSSL code does the same, using keying
374info from the library API.
375The GnuTLS support only works if exim is run by root, not taking advantage of
376the setuid bit.
377You can use either the external environment (modulo the keep_environment config)
378or the add_environment config option for SSLKEYLOGFILE; the latter takes
379precedence.
380
381If the path is absolute, require it starts with the spooldir; otherwise delete
382the env variable. If relative, prefix the spooldir.
383*/
384void
385tls_clean_env(void)
386{
387uschar * path = US getenv("SSLKEYLOGFILE");
388if (path)
389 if (!*path)
390 unsetenv("SSLKEYLOGFILE");
391 else if (*path != '/')
392 {
393 DEBUG(D_tls)
394 debug_printf("prepending spooldir to env SSLKEYLOGFILE\n");
395 setenv("SSLKEYLOGFILE", CCS string_sprintf("%s/%s", spool_directory, path), 1);
396 }
397 else if (Ustrncmp(path, spool_directory, Ustrlen(spool_directory)) != 0)
398 {
399 DEBUG(D_tls)
400 debug_printf("removing env SSLKEYLOGFILE=%s: not under spooldir\n", path);
401 unsetenv("SSLKEYLOGFILE");
402 }
403}
404
405/*************************************************
406* Drop privs for checking TLS config *
407*************************************************/
408
409/* We want to validate TLS options during readconf, but do not want to be
410root when we call into the TLS library, in case of library linkage errors
411which cause segfaults; before this check, those were always done as the Exim
412runtime user and it makes sense to continue with that.
413
414Assumes: tls_require_ciphers has been set, if it will be
415 exim_user has been set, if it will be
416 exim_group has been set, if it will be
417
418Returns: bool for "okay"; false will cause caller to immediately exit.
419*/
420
421BOOL
422tls_dropprivs_validate_require_cipher(BOOL nowarn)
423{
424const uschar *errmsg;
425pid_t pid;
426int rc, status;
427void (*oldsignal)(int);
428
429/* If TLS will never be used, no point checking ciphers */
430
431if ( !tls_advertise_hosts
432 || !*tls_advertise_hosts
433 || Ustrcmp(tls_advertise_hosts, ":") == 0
434 )
435 return TRUE;
436else if (!nowarn && !tls_certificate)
437 log_write(0, LOG_MAIN,
438 "Warning: No server certificate defined; will use a selfsigned one.\n"
439 " Suggested action: either install a certificate or change tls_advertise_hosts option");
440
441oldsignal = signal(SIGCHLD, SIG_DFL);
442
443fflush(NULL);
444if ((pid = fork()) < 0)
445 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "fork failed for TLS check");
446
447if (pid == 0)
448 {
449 /* in some modes, will have dropped privilege already */
450 if (!geteuid())
451 exim_setugid(exim_uid, exim_gid, FALSE,
452 US"calling tls_validate_require_cipher");
453
454 if ((errmsg = tls_validate_require_cipher()))
455 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
456 "tls_require_ciphers invalid: %s", errmsg);
457 fflush(NULL);
458 exim_underbar_exit(0);
459 }
460
461do {
462 rc = waitpid(pid, &status, 0);
463} while (rc < 0 && errno == EINTR);
464
465DEBUG(D_tls)
466 debug_printf("tls_validate_require_cipher child %d ended: status=0x%x\n",
467 (int)pid, status);
468
469signal(SIGCHLD, oldsignal);
470
471return status == 0;
472}
473
474
475
476
477#endif /*!DISABLE_TLS*/
478#endif /*!MACRO_PREDEF*/
479
480/* vi: aw ai sw=2
481*/
482/* End of tls.c */