1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
8 /* This module provides TLS (aka SSL) support for Exim. The code for OpenSSL is
9 based on a patch that was originally contributed by Steve Haslam. It was
10 adapted from stunnel, a GPL program by Michal Trojnara. The code for GNU TLS is
11 based on a patch contributed by Nikos Mavrogiannopoulos. Because these packages
12 are so very different, the functions for each are kept in separate files. The
13 relevant file is #included as required, after any any common functions.
15 No cryptographic code is included in Exim. All this module does is to call
16 functions from the OpenSSL or GNU TLS libraries. */
20 #include "transports/smtp.h"
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
27 #if defined(MACRO_PREDEF) && !defined(DISABLE_TLS)
28 # include "macro_predef.h"
32 # include "tls-openssl.c"
38 /* This module is compiled only when it is specifically requested in the
39 build-time configuration. However, some compilers don't like compiling empty
40 modules, so keep them happy with a dummy when skipping the rest. Make it
41 reference itself to stop picky compilers complaining that it is unused, and put
42 in a dummy argument to stop even pickier compilers complaining about infinite
46 static void dummy(int x) { dummy(x-1); }
49 /* Static variables that are used for buffering data by both sets of
50 functions and the common functions below.
52 We're moving away from this; GnuTLS is already using a state, which
53 can switch, so we can do TLS callouts during ACLs. */
55 static const int ssl_xfer_buffer_size = 4096;
57 static uschar *ssl_xfer_buffer = NULL;
58 static int ssl_xfer_buffer_lwm = 0;
59 static int ssl_xfer_buffer_hwm = 0;
60 static int ssl_xfer_eof = FALSE;
61 static BOOL ssl_xfer_error = FALSE;
65 /*************************************************
66 * Expand string; give error on failure *
67 *************************************************/
69 /* If expansion is forced to fail, set the result NULL and return TRUE.
70 Other failures return FALSE. For a server, an SMTP response is given.
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
77 Returns: TRUE if OK; result may still be NULL after forced failure
81 expand_check(const uschar *s, const uschar *name, uschar **result, uschar ** errstr)
85 else if ( !(*result = expand_string(US s)) /* need to clean up const more */
86 && !f.expand_string_forcedfail
89 *errstr = US"Internal error";
90 log_write(0, LOG_MAIN|LOG_PANIC, "expansion of %s failed: %s", name,
91 expand_string_message);
98 /*************************************************
99 * Timezone environment flipping *
100 *************************************************/
105 uschar * old = US getenv("TZ");
106 (void) setenv("TZ", CCS tz, 1);
112 restore_tz(uschar * tz)
115 (void) setenv("TZ", CCS tz, 1);
117 (void) os_unsetenv(US"TZ");
121 /*************************************************
122 * Many functions are package-specific *
123 *************************************************/
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)
136 # include "tls-openssl.c"
137 # include "tlscert-openssl.c"
142 /*************************************************
143 * TLS version of ungetc *
144 *************************************************/
146 /* Puts a character back in the input buffer. Only ever
148 Only used by the server-side TLS.
153 Returns: the character
159 ssl_xfer_buffer[--ssl_xfer_buffer_lwm] = ch;
165 /*************************************************
166 * TLS version of feof *
167 *************************************************/
169 /* Tests for a previous EOF
170 Only used by the server-side TLS.
173 Returns: non-zero if the eof flag is set
179 return (int)ssl_xfer_eof;
184 /*************************************************
185 * TLS version of ferror *
186 *************************************************/
188 /* Tests for a previous read error, and returns with errno
189 restored to what it was when the error was detected.
190 Only used by the server-side TLS.
192 >>>>> Hmm. Errno not handled yet. Where do we get it from? >>>>>
195 Returns: non-zero if the error flag is set
201 return (int)ssl_xfer_error;
205 /*************************************************
206 * TLS version of smtp_buffered *
207 *************************************************/
209 /* Tests for unused chars in the TLS input buffer.
210 Only used by the server-side TLS.
217 tls_smtp_buffered(void)
219 return ssl_xfer_buffer_lwm < ssl_xfer_buffer_hwm;
223 #endif /*DISABLE_TLS*/
226 tls_modify_variables(tls_support * dest_tsp)
228 modify_variable(US"tls_bits", &dest_tsp->bits);
229 modify_variable(US"tls_certificate_verified", &dest_tsp->certificate_verified);
230 modify_variable(US"tls_cipher", &dest_tsp->cipher);
231 modify_variable(US"tls_peerdn", &dest_tsp->peerdn);
233 modify_variable(US"tls_sni", &dest_tsp->sni);
239 /************************************************
240 * TLS certificate name operations *
241 ************************************************/
243 /* Convert an rfc4514 DN to an exim comma-sep list.
244 Backslashed commas need to be replaced by doublecomma
245 for Exim's list quoting. We modify the given string
250 dn_to_list(uschar * dn)
252 for (uschar * cp = dn; *cp; cp++)
253 if (cp[0] == '\\' && cp[1] == ',')
258 /* Extract fields of a given type from an RFC4514-
259 format Distinguished Name. Return an Exim list.
260 NOTE: We modify the supplied dn string during operation.
263 dn Distinguished Name string
264 mod list containing optional output list-sep and
265 field selector match, comma-separated
267 allocated string with list of matching fields,
272 tls_field_from_dn(uschar * dn, const uschar * mod)
275 uschar outsep = '\n';
277 uschar * match = NULL;
279 gstring * list = NULL;
281 while ((ele = string_nextinlist(&mod, &insep, NULL, 0)))
283 match = ele; /* field tag to match */
285 outsep = ele[1]; /* nondefault output separator */
289 len = match ? Ustrlen(match) : -1;
290 while ((ele = string_nextinlist(CUSS &dn, &insep, NULL, 0)))
292 || Ustrncmp(ele, match, len) == 0 && ele[len] == '='
294 list = string_append_listele(list, outsep, ele+len+1);
295 return string_from_gstring(list);
299 /* Compare a domain name with a possibly-wildcarded name. Wildcards
300 are restricted to a single one, as the first element of patterns
301 having at least three dot-separated elements. Case-independent.
302 Return TRUE for a match
305 is_name_match(const uschar * name, const uschar * pat)
308 return *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;
318 /* Compare a list of names with the dnsname elements
319 of the Subject Alternate Name, if any, and the
323 namelist names to compare
331 tls_is_name_for_cert(const uschar * namelist, void * cert)
333 uschar * altnames = tls_cert_subject_altname(cert, US"dns");
339 if ((altnames = tls_cert_subject_altname(cert, US"dns")))
342 while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0)))
344 const uschar * an = altnames;
345 while ((certname = string_nextinlist(&an, &alt_sep, NULL, 0)))
346 if (is_name_match(cmpname, certname))
351 else if ((subjdn = tls_cert_subject(cert, NULL)))
356 while ((cmpname = string_nextinlist(&namelist, &cmp_sep, NULL, 0)))
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)
372 /* Environment cleanup: The GnuTLS library uses SSLKEYLOGFILE in the environment
373 and writes a file by that name. Our OpenSSL code does the same, using keying
374 info from the library API.
375 The GnuTLS support only works if exim is run by root, not taking advantage of
377 You can use either the external environment (modulo the keep_environment config)
378 or the add_environment config option for SSLKEYLOGFILE; the latter takes
381 If the path is absolute, require it starts with the spooldir; otherwise delete
382 the env variable. If relative, prefix the spooldir.
387 uschar * path = US getenv("SSLKEYLOGFILE");
390 unsetenv("SSLKEYLOGFILE");
391 else if (*path != '/')
394 debug_printf("prepending spooldir to env SSLKEYLOGFILE\n");
395 setenv("SSLKEYLOGFILE", CCS string_sprintf("%s/%s", spool_directory, path), 1);
397 else if (Ustrncmp(path, spool_directory, Ustrlen(spool_directory)) != 0)
400 debug_printf("removing env SSLKEYLOGFILE=%s: not under spooldir\n", path);
401 unsetenv("SSLKEYLOGFILE");
405 /*************************************************
406 * Drop privs for checking TLS config *
407 *************************************************/
409 /* We want to validate TLS options during readconf, but do not want to be
410 root when we call into the TLS library, in case of library linkage errors
411 which cause segfaults; before this check, those were always done as the Exim
412 runtime user and it makes sense to continue with that.
414 Assumes: 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
418 Returns: bool for "okay"; false will cause caller to immediately exit.
422 tls_dropprivs_validate_require_cipher(BOOL nowarn)
424 const uschar *errmsg;
427 void (*oldsignal)(int);
429 /* If TLS will never be used, no point checking ciphers */
431 if ( !tls_advertise_hosts
432 || !*tls_advertise_hosts
433 || Ustrcmp(tls_advertise_hosts, ":") == 0
436 else 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");
441 oldsignal = signal(SIGCHLD, SIG_DFL);
444 if ((pid = fork()) < 0)
445 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "fork failed for TLS check");
449 /* in some modes, will have dropped privilege already */
451 exim_setugid(exim_uid, exim_gid, FALSE,
452 US"calling tls_validate_require_cipher");
454 if ((errmsg = tls_validate_require_cipher()))
455 log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
456 "tls_require_ciphers invalid: %s", errmsg);
458 exim_underbar_exit(0);
462 rc = waitpid(pid, &status, 0);
463 } while (rc < 0 && errno == EINTR);
466 debug_printf("tls_validate_require_cipher child %d ended: status=0x%x\n",
469 signal(SIGCHLD, oldsignal);
477 #endif /*!DISABLE_TLS*/
478 #endif /*!MACRO_PREDEF*/