1 /*++
2 /* NAME
3 /*	tls_misc 3
4 /* SUMMARY
5 /*	miscellaneous TLS support routines
6 /* SYNOPSIS
7 /* .SH Public functions
8 /* .nf
9 /* .na
10 /*	#include <tls.h>
11 /*
12 /*	void tls_log_summary(role, usage, TLScontext)
13 /*	TLS_ROLE role;
14 /*	TLS_USAGE usage;
15 /*	TLS_SESS_STATE *TLScontext;
16 /*
17 /*	const char *tls_compile_version(void)
18 /*
19 /*	const char *tls_run_version(void)
20 /*
21 /*	const char **tls_pkey_algorithms(void)
22 /*
23 /*	void	tls_pre_jail_init(TLS_ROLE)
24 /*	TLS_ROLE role;
25 /*
26 /* .SH Internal functions
27 /* .nf
28 /* .na
29 /*	#define TLS_INTERNAL
30 /*	#include <tls.h>
31 /*
32 /*	char	*var_tls_high_clist;
33 /*	char	*var_tls_medium_clist;
34 /*	char	*var_tls_low_clist;
35 /*	char	*var_tls_export_clist;
36 /*	char	*var_tls_null_clist;
37 /*	char	*var_tls_eecdh_auto;
38 /*	char	*var_tls_eecdh_strong;
39 /*	char	*var_tls_eecdh_ultra;
40 /*	char	*var_tls_dane_digests;
41 /*	int	var_tls_daemon_rand_bytes;
42 /*	bool	var_tls_append_def_CA;
43 /*	bool	var_tls_preempt_clist;
44 /*	bool	var_tls_bc_pkey_fprint;
45 /*	bool	var_tls_multi_wildcard;
46 /*	char	*var_tls_mgr_service;
47 /*	char	*var_tls_tkt_cipher;
48 /*	char	*var_openssl_path;
49 /*	char	*var_tls_server_sni_maps;
50 /*	bool	var_tls_fast_shutdown;
51 /*
52 /*	TLS_APPL_STATE *tls_alloc_app_context(ssl_ctx, log_mask)
53 /*	SSL_CTX	*ssl_ctx;
54 /*	int	log_mask;
55 /*
56 /*	void	tls_free_app_context(app_ctx)
57 /*	void	*app_ctx;
58 /*
59 /*	TLS_SESS_STATE *tls_alloc_sess_context(log_mask, namaddr)
60 /*	int	log_mask;
61 /*	const char *namaddr;
62 /*
63 /*	void	tls_free_context(TLScontext)
64 /*	TLS_SESS_STATE *TLScontext;
65 /*
66 /*	void	tls_check_version()
67 /*
68 /*	long	tls_bug_bits()
69 /*
70 /*	void	tls_param_init()
71 /*
72 /*	int	tls_proto_mask_lims(plist, floor, ceiling)
73 /*	const char *plist;
74 /*	int	*floor;
75 /*	int	*ceiling;
76 /*
77 /*	int	tls_cipher_grade(name)
78 /*	const char *name;
79 /*
80 /*	const char *str_tls_cipher_grade(grade)
81 /*	int	grade;
82 /*
83 /*	const char *tls_set_ciphers(TLScontext, grade, exclusions)
84 /*	TLS_SESS_STATE *TLScontext;
85 /*	int	grade;
86 /*	const char *exclusions;
87 /*
88 /*	void tls_get_signature_params(TLScontext)
89 /*	TLS_SESS_STATE *TLScontext;
90 /*
91 /*	void	tls_print_errors()
92 /*
93 /*	void	tls_info_callback(ssl, where, ret)
94 /*	const SSL *ssl; /* unused */
95 /*	int	where;
96 /*	int	ret;
97 /*
98 /*	long	tls_bio_dump_cb(bio, cmd, argp, len, argi, argl, ret, processed)
99 /*	BIO	*bio;
100 /*	int	cmd;
101 /*	const char *argp;
102 /*	size_t	len;
103 /*	int	argi;
104 /*	long	argl; /* unused */
105 /*	int	ret;
106 /*	size_t	*processed;
107 /*
108 /*	int	tls_log_mask(log_param, log_level)
109 /*	const char *log_param;
110 /*	const char *log_level;
111 /*
112 /*	void	 tls_update_app_logmask(app_ctx, log_mask)
113 /*	TLS_APPL_STATE *app_ctx;
114 /*	int	log_mask;
115 /*
116 /*	const EVP_MD *tls_validate_digest(dgst)
117 /*	const char *dgst;
118 /* DESCRIPTION
119 /*	This module implements public and internal routines that
120 /*	support the TLS client and server.
121 /*
122 /*	tls_log_summary() logs a summary of a completed TLS connection.
123 /*	The "role" argument must be TLS_ROLE_CLIENT for outgoing client
124 /*	connections, or TLS_ROLE_SERVER for incoming server connections,
125 /*	and the "usage" must be TLS_USAGE_NEW or TLS_USAGE_USED.
126 /*
127 /*	tls_compile_version() returns a text string description of
128 /*	the compile-time TLS library.
129 /*
130 /*	tls_run_version() is just tls_compile_version() but with the runtime
131 /*	version instead of the compile-time version.
132 /*
133 /*	tls_pkey_algorithms() returns a pointer to null-terminated
134 /*	array of string constants with the names of the supported
135 /*	public-key algorithms.
136 /*
137 /*	tls_alloc_app_context() creates an application context that
138 /*	holds the SSL context for the application and related cached state.
139 /*
140 /*	tls_free_app_context() deallocates the application context and its
141 /*	contents (the application context is stored outside the TLS library).
142 /*
143 /*	tls_alloc_sess_context() creates an initialized TLS session context
144 /*	structure with the specified log mask and peer name[addr].
145 /*
146 /*	tls_free_context() destroys a TLScontext structure
147 /*	together with OpenSSL structures that are attached to it.
148 /*
149 /*	tls_check_version() logs a warning when the run-time OpenSSL
150 /*	library differs in its major, minor or micro number from
151 /*	the compile-time OpenSSL headers.
152 /*
153 /*	tls_bug_bits() returns the bug compatibility mask appropriate
154 /*	for the run-time library. Some of the bug work-arounds are
155 /*	not appropriate for some library versions.
156 /*
157 /*	tls_param_init() loads main.cf parameters used internally in
158 /*	TLS library. Any errors are fatal.
159 /*
160 /*	tls_pre_jail_init() opens any tables that need to be opened before
161 /*	entering a chroot jail. The "role" parameter must be TLS_ROLE_CLIENT
162 /*	for clients and TLS_ROLE_SERVER for servers. Any errors are fatal.
163 /*
164 /*	tls_proto_mask_lims() returns a bitmask of excluded protocols, and
165 /*	and the protocol version floor/ceiling, given a list (plist) of
166 /*	protocols to include or (preceded by a '!') exclude, or constraints
167 /*	of the form '>=name', '<=name', '>=hexvalue', '<=hexvalue'. If "plist"
168 /*	contains invalid protocol names, TLS_PROTOCOL_INVALID is returned and
169 /*	no warning is logged.
170 /*
171 /*	tls_cipher_grade() converts a case-insensitive cipher grade
172 /*	name (high, medium, low, export, null) to the corresponding
173 /*	TLS_CIPHER_ constant.  When the input specifies an unrecognized
174 /*	grade, tls_cipher_grade() logs no warning, and returns
175 /*	TLS_CIPHER_NONE.
176 /*
177 /*	str_tls_cipher_grade() converts a cipher grade to a name.
178 /*	When the input specifies an undefined grade, str_tls_cipher_grade()
179 /*	logs no warning, returns a null pointer.
180 /*
181 /*	tls_set_ciphers() applies the requested cipher grade and exclusions
182 /*	to the provided TLS session context, returning the resulting cipher
183 /*	list string.  The return value is the cipherlist used and is
184 /*	overwritten upon each call.  When the input is invalid,
185 /*	tls_set_ciphers() logs a warning, and returns a null result.
186 /*
187 /*	tls_get_signature_params() updates the "TLScontext" with handshake
188 /*	signature parameters pertaining to TLS 1.3, where the ciphersuite
189 /*	no longer describes the asymmetric algorithms employed in the
190 /*	handshake, which are negotiated separately.  This function
191 /*	has no effect for TLS 1.2 and earlier.
192 /*
193 /*	tls_print_errors() queries the OpenSSL error stack,
194 /*	logs the error messages, and clears the error stack.
195 /*
196 /*	tls_info_callback() is a call-back routine for the
197 /*	SSL_CTX_set_info_callback() routine. It logs SSL events
198 /*	to the Postfix logfile.
199 /*
200 /*	tls_bio_dump_cb() is a call-back routine for the
201 /*	BIO_set_callback() routine. It logs SSL content to the
202 /*	Postfix logfile.
203 /*
204 /*	tls_log_mask() converts a TLS log_level value from string
205 /*	to mask.  The main.cf parameter name is passed along for
206 /*	diagnostics.
207 /*
208 /*	tls_update_app_logmask() changes the log mask of the
209 /*	application TLS context to the new setting.
210 /*
211 /*	tls_validate_digest() returns a static handle for the named
212 /*	digest algorithm, or NULL on error.
213 /* LICENSE
214 /* .ad
215 /* .fi
216 /*	This software is free. You can do with it whatever you want.
217 /*	The original author kindly requests that you acknowledge
218 /*	the use of his software.
219 /* AUTHOR(S)
220 /*	Originally written by:
221 /*	Lutz Jaenicke
222 /*	BTU Cottbus
223 /*	Allgemeine Elektrotechnik
224 /*	Universitaetsplatz 3-4
225 /*	D-03044 Cottbus, Germany
226 /*
227 /*	Updated by:
228 /*	Wietse Venema
229 /*	IBM T.J. Watson Research
230 /*	P.O. Box 704
231 /*	Yorktown Heights, NY 10598, USA
232 /*
233 /*	Victor Duchovni
234 /*	Morgan Stanley
235 /*
236 /*	Wietse Venema
237 /*	Google, Inc.
238 /*	111 8th Avenue
239 /*	New York, NY 10011, USA
240 /*--*/
241 
242 /* System library. */
243 
244 #include <sys_defs.h>
245 #include <ctype.h>
246 #include <string.h>
247 
248 /* Utility library. */
249 
250 #include <vstream.h>
251 #include <msg.h>
252 #include <mymalloc.h>
253 #include <vstring.h>
254 #include <stringops.h>
255 #include <argv.h>
256 #include <name_mask.h>
257 #include <name_code.h>
258 #include <dict.h>
259 #include <valid_hostname.h>
260 
261  /*
262   * Global library.
263   */
264 #include <mail_params.h>
265 #include <mail_conf.h>
266 #include <maps.h>
267 
268  /*
269   * TLS library.
270   */
271 #define TLS_INTERNAL
272 #include <tls.h>
273 
274  /* Application-specific. */
275 
276  /*
277   * Tunable parameters.
278   */
279 char   *var_tls_high_clist;
280 char   *var_tls_medium_clist;
281 char   *var_tls_low_clist;
282 char   *var_tls_export_clist;
283 char   *var_tls_null_clist;
284 int     var_tls_daemon_rand_bytes;
285 char   *var_tls_eecdh_auto;
286 char   *var_tls_eecdh_strong;
287 char   *var_tls_eecdh_ultra;
288 char   *var_tls_dane_digests;
289 bool    var_tls_append_def_CA;
290 char   *var_tls_bug_tweaks;
291 char   *var_tls_ssl_options;
292 bool    var_tls_bc_pkey_fprint;
293 bool    var_tls_multi_wildcard;
294 char   *var_tls_mgr_service;
295 char   *var_tls_tkt_cipher;
296 char   *var_openssl_path;
297 char   *var_tls_server_sni_maps;
298 bool    var_tls_fast_shutdown;
299 bool    var_tls_preempt_clist;
300 
301 #ifdef USE_TLS
302 
303 static MAPS *tls_server_sni_maps;
304 
305  /*
306   * Index to attach TLScontext pointers to SSL objects, so that they can be
307   * accessed by call-back routines.
308   */
309 int     TLScontext_index = -1;
310 
311  /*
312   * Protocol name <=> mask conversion.
313   */
314 static const NAME_CODE protocol_table[] = {
315     SSL_TXT_SSLV2, TLS_PROTOCOL_SSLv2,
316     SSL_TXT_SSLV3, TLS_PROTOCOL_SSLv3,
317     SSL_TXT_TLSV1, TLS_PROTOCOL_TLSv1,
318     SSL_TXT_TLSV1_1, TLS_PROTOCOL_TLSv1_1,
319     SSL_TXT_TLSV1_2, TLS_PROTOCOL_TLSv1_2,
320     TLS_PROTOCOL_TXT_TLSV1_3, TLS_PROTOCOL_TLSv1_3,
321     0, TLS_PROTOCOL_INVALID,
322 };
323 
324 /*
325  * Protocol name => numeric version, for MinProtocol and MaxProtocol
326  */
327 static const NAME_CODE tls_version_table[] = {
328     "None", 0,
329     SSL_TXT_SSLV3, SSL3_VERSION,
330     SSL_TXT_TLSV1, TLS1_VERSION,
331     SSL_TXT_TLSV1_1, TLS1_1_VERSION,
332     SSL_TXT_TLSV1_2, TLS1_2_VERSION,
333     TLS_PROTOCOL_TXT_TLSV1_3, TLS1_3_VERSION,
334     0, -1,
335 };
336 
337  /*
338   * SSL_OP_MUMBLE bug work-around name <=> mask conversion.
339   */
340 #define NAMEBUG(x)	#x, SSL_OP_##x
341 static const LONG_NAME_MASK ssl_bug_tweaks[] = {
342 
343 #ifndef SSL_OP_MICROSOFT_SESS_ID_BUG
344 #define SSL_OP_MICROSOFT_SESS_ID_BUG		0
345 #endif
346     NAMEBUG(MICROSOFT_SESS_ID_BUG),
347 
348 #ifndef SSL_OP_NETSCAPE_CHALLENGE_BUG
349 #define SSL_OP_NETSCAPE_CHALLENGE_BUG		0
350 #endif
351     NAMEBUG(NETSCAPE_CHALLENGE_BUG),
352 
353 #ifndef SSL_OP_LEGACY_SERVER_CONNECT
354 #define SSL_OP_LEGACY_SERVER_CONNECT		0
355 #endif
356     NAMEBUG(LEGACY_SERVER_CONNECT),
357 
358 #ifndef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
359 #define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 0
360 #endif
361     NAMEBUG(NETSCAPE_REUSE_CIPHER_CHANGE_BUG),
362     "CVE-2010-4180", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG,
363 
364 #ifndef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
365 #define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG	0
366 #endif
367     NAMEBUG(SSLREF2_REUSE_CERT_TYPE_BUG),
368 
369 #ifndef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
370 #define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER	0
371 #endif
372     NAMEBUG(MICROSOFT_BIG_SSLV3_BUFFER),
373 
374 #ifndef SSL_OP_MSIE_SSLV2_RSA_PADDING
375 #define SSL_OP_MSIE_SSLV2_RSA_PADDING		0
376 #endif
377     NAMEBUG(MSIE_SSLV2_RSA_PADDING),
378     "CVE-2005-2969", SSL_OP_MSIE_SSLV2_RSA_PADDING,
379 
380 #ifndef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
381 #define SSL_OP_SSLEAY_080_CLIENT_DH_BUG		0
382 #endif
383     NAMEBUG(SSLEAY_080_CLIENT_DH_BUG),
384 
385 #ifndef SSL_OP_TLS_D5_BUG
386 #define SSL_OP_TLS_D5_BUG			0
387 #endif
388     NAMEBUG(TLS_D5_BUG),
389 
390 #ifndef SSL_OP_TLS_BLOCK_PADDING_BUG
391 #define SSL_OP_TLS_BLOCK_PADDING_BUG		0
392 #endif
393     NAMEBUG(TLS_BLOCK_PADDING_BUG),
394 
395 #ifndef SSL_OP_TLS_ROLLBACK_BUG
396 #define SSL_OP_TLS_ROLLBACK_BUG			0
397 #endif
398     NAMEBUG(TLS_ROLLBACK_BUG),
399 
400 #ifndef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
401 #define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS	0
402 #endif
403     NAMEBUG(DONT_INSERT_EMPTY_FRAGMENTS),
404 
405 #ifndef SSL_OP_CRYPTOPRO_TLSEXT_BUG
406 #define SSL_OP_CRYPTOPRO_TLSEXT_BUG		0
407 #endif
408     NAMEBUG(CRYPTOPRO_TLSEXT_BUG),
409 
410 #ifndef SSL_OP_TLSEXT_PADDING
411 #define SSL_OP_TLSEXT_PADDING	0
412 #endif
413     NAMEBUG(TLSEXT_PADDING),
414 
415 #if 0
416 
417     /*
418      * XXX: New with OpenSSL 1.1.1, this is turned on implicitly in
419      * SSL_CTX_new() and is not included in SSL_OP_ALL.  Allowing users to
420      * disable this would thus be a code change that would require clearing
421      * bug work-around bits in SSL_CTX, after setting SSL_OP_ALL.  Since this
422      * is presumably required for TLS 1.3 on today's Internet, the code
423      * change will be done separately later. For now this implicit bug
424      * work-around cannot be disabled via supported Postfix mechanisms.
425      */
426 #ifndef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
427 #define SSL_OP_ENABLE_MIDDLEBOX_COMPAT	0
428 #endif
429     NAMEBUG(ENABLE_MIDDLEBOX_COMPAT),
430 #endif
431 
432     0, 0,
433 };
434 
435  /*
436   * SSL_OP_MUMBLE option name <=> mask conversion for options that are not
437   * (or may in the future not be) in SSL_OP_ALL.  These enable optional
438   * behavior, rather than bug interoperability work-arounds.
439   */
440 #define NAME_SSL_OP(x)	#x, SSL_OP_##x
441 static const LONG_NAME_MASK ssl_op_tweaks[] = {
442 
443 #ifndef SSL_OP_LEGACY_SERVER_CONNECT
444 #define SSL_OP_LEGACY_SERVER_CONNECT	0
445 #endif
446     NAME_SSL_OP(LEGACY_SERVER_CONNECT),
447 
448 #ifndef SSL_OP_NO_TICKET
449 #define SSL_OP_NO_TICKET		0
450 #endif
451     NAME_SSL_OP(NO_TICKET),
452 
453 #ifndef SSL_OP_NO_COMPRESSION
454 #define SSL_OP_NO_COMPRESSION		0
455 #endif
456     NAME_SSL_OP(NO_COMPRESSION),
457 
458 #ifndef SSL_OP_NO_RENEGOTIATION
459 #define SSL_OP_NO_RENEGOTIATION		0
460 #endif
461     NAME_SSL_OP(NO_RENEGOTIATION),
462 
463 #ifndef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
464 #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION	0
465 #endif
466     NAME_SSL_OP(NO_SESSION_RESUMPTION_ON_RENEGOTIATION),
467 
468 #ifndef SSL_OP_PRIORITIZE_CHACHA
469 #define SSL_OP_PRIORITIZE_CHACHA	0
470 #endif
471     NAME_SSL_OP(PRIORITIZE_CHACHA),
472 
473 #ifndef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
474 #define SSL_OP_ENABLE_MIDDLEBOX_COMPAT	0
475 #endif
476     NAME_SSL_OP(ENABLE_MIDDLEBOX_COMPAT),
477 
478     0, 0,
479 };
480 
481  /*
482   * Once these have been a NOOP long enough, they might some day be removed
483   * from OpenSSL.  The defines below will avoid bitrot issues if/when that
484   * happens.
485   */
486 #ifndef SSL_OP_SINGLE_DH_USE
487 #define SSL_OP_SINGLE_DH_USE 0
488 #endif
489 #ifndef SSL_OP_SINGLE_ECDH_USE
490 #define SSL_OP_SINGLE_ECDH_USE 0
491 #endif
492 
493  /*
494   * Ciphersuite name <=> code conversion.
495   */
496 const NAME_CODE tls_cipher_grade_table[] = {
497     "high", TLS_CIPHER_HIGH,
498     "medium", TLS_CIPHER_MEDIUM,
499     "low", TLS_CIPHER_LOW,
500     "export", TLS_CIPHER_EXPORT,
501     "null", TLS_CIPHER_NULL,
502     "invalid", TLS_CIPHER_NONE,
503     0, TLS_CIPHER_NONE,
504 };
505 
506  /*
507   * Log keyword <=> mask conversion.
508   */
509 #define TLS_LOG_0 TLS_LOG_NONE
510 #define TLS_LOG_1 TLS_LOG_SUMMARY
511 #define TLS_LOG_2 (TLS_LOG_1 | TLS_LOG_VERBOSE | TLS_LOG_CACHE | TLS_LOG_DEBUG)
512 #define TLS_LOG_3 (TLS_LOG_2 | TLS_LOG_TLSPKTS)
513 #define TLS_LOG_4 (TLS_LOG_3 | TLS_LOG_ALLPKTS)
514 
515 static const NAME_MASK tls_log_table[] = {
516     "0", TLS_LOG_0,
517     "none", TLS_LOG_NONE,
518     "1", TLS_LOG_1,
519     "routine", TLS_LOG_1,
520     "2", TLS_LOG_2,
521     "debug", TLS_LOG_2,
522     "3", TLS_LOG_3,
523     "ssl-expert", TLS_LOG_3,
524     "4", TLS_LOG_4,
525     "ssl-developer", TLS_LOG_4,
526     "5", TLS_LOG_4,			/* for good measure */
527     "6", TLS_LOG_4,			/* for good measure */
528     "7", TLS_LOG_4,			/* for good measure */
529     "8", TLS_LOG_4,			/* for good measure */
530     "9", TLS_LOG_4,			/* for good measure */
531     "summary", TLS_LOG_SUMMARY,
532     "untrusted", TLS_LOG_UNTRUSTED,
533     "peercert", TLS_LOG_PEERCERT,
534     "certmatch", TLS_LOG_CERTMATCH,
535     "verbose", TLS_LOG_VERBOSE,		/* Postfix TLS library verbose */
536     "cache", TLS_LOG_CACHE,
537     "dane", TLS_LOG_DANE,		/* DANE policy construction */
538     "ssl-debug", TLS_LOG_DEBUG,		/* SSL library debug/verbose */
539     "ssl-handshake-packet-dump", TLS_LOG_TLSPKTS,
540     "ssl-session-packet-dump", TLS_LOG_TLSPKTS | TLS_LOG_ALLPKTS,
541     0, 0,
542 };
543 
544  /*
545   * Parsed OpenSSL version number.
546   */
547 typedef struct {
548     int     major;
549     int     minor;
550     int     micro;
551     int     patch;
552     int     status;
553 } TLS_VINFO;
554 
555 /* tls_log_mask - Convert user TLS loglevel to internal log feature mask */
556 
tls_log_mask(const char * log_param,const char * log_level)557 int     tls_log_mask(const char *log_param, const char *log_level)
558 {
559     int     mask;
560 
561     mask = name_mask_opt(log_param, tls_log_table, log_level,
562 			 NAME_MASK_ANY_CASE | NAME_MASK_RETURN);
563     return (mask);
564 }
565 
566 /* tls_update_app_logmask - update log level after init */
567 
tls_update_app_logmask(TLS_APPL_STATE * app_ctx,int log_mask)568 void    tls_update_app_logmask(TLS_APPL_STATE *app_ctx, int log_mask)
569 {
570     app_ctx->log_mask = log_mask;
571 }
572 
573 /* parse_version - parse TLS protocol version name or hex number */
574 
parse_tls_version(const char * tok,int * version)575 static int parse_tls_version(const char *tok, int *version)
576 {
577     int     code = name_code(tls_version_table, NAME_CODE_FLAG_NONE, tok);
578     char   *_end;
579     unsigned long ulval;
580 
581     if (code != -1) {
582 	*version = code;
583 	return (0);
584     }
585     errno = 0;
586     ulval = strtoul(tok, &_end, 16);
587     if (*_end != 0
588 	|| (ulval == ULONG_MAX && errno == ERANGE)
589 	|| ulval > INT_MAX)
590 	return TLS_PROTOCOL_INVALID;
591 
592     *version = (int) ulval;
593     return (0);
594 }
595 
596 /* tls_proto_mask_lims - protocols to exclude and floor/ceiling */
597 
tls_proto_mask_lims(const char * plist,int * floor,int * ceiling)598 int     tls_proto_mask_lims(const char *plist, int *floor, int *ceiling)
599 {
600     char   *save;
601     char   *tok;
602     char   *cp;
603     int     code;
604     int     exclude = 0;
605     int     include = 0;
606 
607 #define FREE_AND_RETURN(ptr, res) do { \
608 	myfree(ptr); \
609 	return (res); \
610     } while (0)
611 
612     *floor = *ceiling = 0;
613 
614     save = cp = mystrdup(plist);
615     while ((tok = mystrtok(&cp, CHARS_COMMA_SP ":")) != 0) {
616 	if (strncmp(tok, ">=", 2) == 0)
617 	    code = parse_tls_version(tok + 2, floor);
618 	else if (strncmp(tok, "<=", 2) == 0)
619 	    code = parse_tls_version(tok + 2, ceiling);
620 	else if (*tok == '!')
621 	    exclude |= code =
622 		name_code(protocol_table, NAME_CODE_FLAG_NONE, ++tok);
623 	else
624 	    include |= code =
625 		name_code(protocol_table, NAME_CODE_FLAG_NONE, tok);
626 	if (code == TLS_PROTOCOL_INVALID)
627 	    FREE_AND_RETURN(save, TLS_PROTOCOL_INVALID);
628     }
629 
630     /*
631      * When the include list is empty, use only the explicit exclusions.
632      * Otherwise, also exclude the complement of the include list from the
633      * built-in list of known protocols. There is no way to exclude protocols
634      * we don't know about at compile time, and this is unavoidable because
635      * the OpenSSL API works with compile-time *exclusion* bit-masks.
636      */
637     FREE_AND_RETURN(save,
638 	(include ? (exclude | (TLS_KNOWN_PROTOCOLS & ~include)) : exclude));
639 }
640 
641 /* tls_param_init - Load TLS related config parameters */
642 
tls_param_init(void)643 void    tls_param_init(void)
644 {
645     /* If this changes, update TLS_CLIENT_PARAMS in tls_proxy.h. */
646     static const CONFIG_STR_TABLE str_table[] = {
647 	VAR_TLS_HIGH_CLIST, DEF_TLS_HIGH_CLIST, &var_tls_high_clist, 1, 0,
648 	VAR_TLS_MEDIUM_CLIST, DEF_TLS_MEDIUM_CLIST, &var_tls_medium_clist, 1, 0,
649 	VAR_TLS_LOW_CLIST, DEF_TLS_LOW_CLIST, &var_tls_low_clist, 1, 0,
650 	VAR_TLS_EXPORT_CLIST, DEF_TLS_EXPORT_CLIST, &var_tls_export_clist, 1, 0,
651 	VAR_TLS_NULL_CLIST, DEF_TLS_NULL_CLIST, &var_tls_null_clist, 1, 0,
652 	VAR_TLS_EECDH_AUTO, DEF_TLS_EECDH_AUTO, &var_tls_eecdh_auto, 1, 0,
653 	VAR_TLS_EECDH_STRONG, DEF_TLS_EECDH_STRONG, &var_tls_eecdh_strong, 1, 0,
654 	VAR_TLS_EECDH_ULTRA, DEF_TLS_EECDH_ULTRA, &var_tls_eecdh_ultra, 1, 0,
655 	VAR_TLS_BUG_TWEAKS, DEF_TLS_BUG_TWEAKS, &var_tls_bug_tweaks, 0, 0,
656 	VAR_TLS_SSL_OPTIONS, DEF_TLS_SSL_OPTIONS, &var_tls_ssl_options, 0, 0,
657 	VAR_TLS_DANE_DIGESTS, DEF_TLS_DANE_DIGESTS, &var_tls_dane_digests, 1, 0,
658 	VAR_TLS_MGR_SERVICE, DEF_TLS_MGR_SERVICE, &var_tls_mgr_service, 1, 0,
659 	VAR_TLS_TKT_CIPHER, DEF_TLS_TKT_CIPHER, &var_tls_tkt_cipher, 0, 0,
660 	VAR_OPENSSL_PATH, DEF_OPENSSL_PATH, &var_openssl_path, 1, 0,
661 	0,
662     };
663 
664     /* If this changes, update TLS_CLIENT_PARAMS in tls_proxy.h. */
665     static const CONFIG_INT_TABLE int_table[] = {
666 	VAR_TLS_DAEMON_RAND_BYTES, DEF_TLS_DAEMON_RAND_BYTES, &var_tls_daemon_rand_bytes, 1, 0,
667 	0,
668     };
669 
670     /* If this changes, update TLS_CLIENT_PARAMS in tls_proxy.h. */
671     static const CONFIG_BOOL_TABLE bool_table[] = {
672 	VAR_TLS_APPEND_DEF_CA, DEF_TLS_APPEND_DEF_CA, &var_tls_append_def_CA,
673 	VAR_TLS_BC_PKEY_FPRINT, DEF_TLS_BC_PKEY_FPRINT, &var_tls_bc_pkey_fprint,
674 	VAR_TLS_PREEMPT_CLIST, DEF_TLS_PREEMPT_CLIST, &var_tls_preempt_clist,
675 	VAR_TLS_MULTI_WILDCARD, DEF_TLS_MULTI_WILDCARD, &var_tls_multi_wildcard,
676 	VAR_TLS_FAST_SHUTDOWN, DEF_TLS_FAST_SHUTDOWN, &var_tls_fast_shutdown,
677 	0,
678     };
679     static int init_done;
680 
681     if (init_done)
682 	return;
683     init_done = 1;
684 
685     get_mail_conf_str_table(str_table);
686     get_mail_conf_int_table(int_table);
687     get_mail_conf_bool_table(bool_table);
688 }
689 
690 /* tls_pre_jail_init - Load TLS related pre-jail tables */
691 
tls_pre_jail_init(TLS_ROLE role)692 void    tls_pre_jail_init(TLS_ROLE role)
693 {
694     static const CONFIG_STR_TABLE str_table[] = {
695 	VAR_TLS_SERVER_SNI_MAPS, DEF_TLS_SERVER_SNI_MAPS, &var_tls_server_sni_maps, 0, 0,
696 	0,
697     };
698     int     flags;
699 
700     tls_param_init();
701 
702     /* Nothing for clients at this time */
703     if (role != TLS_ROLE_SERVER)
704 	return;
705 
706     get_mail_conf_str_table(str_table);
707     if (*var_tls_server_sni_maps == 0)
708 	return;
709 
710     flags = DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX | DICT_FLAG_SRC_RHS_IS_FILE;
711     tls_server_sni_maps =
712 	maps_create(VAR_TLS_SERVER_SNI_MAPS, var_tls_server_sni_maps, flags);
713 }
714 
715 /* server_sni_callback - process client's SNI extension */
716 
server_sni_callback(SSL * ssl,int * alert,void * arg)717 static int server_sni_callback(SSL *ssl, int *alert, void *arg)
718 {
719     SSL_CTX *sni_ctx = (SSL_CTX *) arg;
720     TLS_SESS_STATE *TLScontext = SSL_get_ex_data(ssl, TLScontext_index);
721     const char *sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
722     const char *cp = sni;
723     const char *pem;
724 
725     /* SNI is silently ignored when we don't care or is NULL or empty */
726     if (!sni_ctx || !tls_server_sni_maps || !sni || !*sni)
727 	return SSL_TLSEXT_ERR_NOACK;
728 
729     if (!valid_hostname(sni, DONT_GRIPE)) {
730 	msg_warn("TLS SNI from %s is invalid: %s",
731 		 TLScontext->namaddr, sni);
732 	return SSL_TLSEXT_ERR_NOACK;
733     }
734 
735     /*
736      * With TLS 1.3, when the client's proposed key share is not supported by
737      * the server, the server may issue a HelloRetryRequest (HRR), and the
738      * client will then retry with a new key share on a curve supported by
739      * the server.  This results in the SNI callback running twice for the
740      * same connection.
741      *
742      * When that happens, The client MUST send the essentially the same hello
743      * message, including the SNI name, and since we've already loaded our
744      * certificate chain, we don't need to do it again!  Therefore, if we've
745      * already recorded the peer SNI name, just check that it has not
746      * changed, and return success.
747      */
748     if (TLScontext->peer_sni) {
749 	if (strcmp(sni, TLScontext->peer_sni) == 0)
750 	    return SSL_TLSEXT_ERR_OK;
751 	msg_warn("TLS SNI changed from %s initially %s, %s after hello retry",
752 		 TLScontext->namaddr, TLScontext->peer_sni, sni);
753 	return SSL_TLSEXT_ERR_NOACK;
754     }
755     do {
756 	/* Don't silently skip maps opened with the wrong flags. */
757 	pem = maps_file_find(tls_server_sni_maps, cp, 0);
758     } while (!pem
759 	     && !tls_server_sni_maps->error
760 	     && (cp = strchr(cp + 1, '.')) != 0);
761 
762     if (!pem) {
763 	if (tls_server_sni_maps->error) {
764 	    msg_warn("%s: %s map lookup problem",
765 		     tls_server_sni_maps->title, sni);
766 	    *alert = SSL_AD_INTERNAL_ERROR;
767 	    return SSL_TLSEXT_ERR_ALERT_FATAL;
768 	}
769 	msg_info("TLS SNI %s from %s not matched, using default chain",
770 		 sni, TLScontext->namaddr);
771 
772 	/*
773 	 * XXX: We could lie and pretend to accept the name, but since we've
774 	 * previously not implemented the callback (with OpenSSL then
775 	 * declining the extension), and nothing bad happened, declining it
776 	 * explicitly should be safe.
777 	 */
778 	return SSL_TLSEXT_ERR_NOACK;
779     }
780     SSL_set_SSL_CTX(ssl, sni_ctx);
781     if (tls_load_pem_chain(ssl, pem, sni) != 0) {
782 	/* errors already logged */
783 	*alert = SSL_AD_INTERNAL_ERROR;
784 	return SSL_TLSEXT_ERR_ALERT_FATAL;
785     }
786     TLScontext->peer_sni = mystrdup(sni);
787     return SSL_TLSEXT_ERR_OK;
788 }
789 
790 /* tls_set_ciphers - Set SSL context cipher list */
791 
tls_set_ciphers(TLS_SESS_STATE * TLScontext,const char * grade,const char * exclusions)792 const char *tls_set_ciphers(TLS_SESS_STATE *TLScontext, const char *grade,
793 			            const char *exclusions)
794 {
795     const char *myname = "tls_set_ciphers";
796     static VSTRING *buf;
797     char   *save;
798     char   *cp;
799     char   *tok;
800 
801     if (buf == 0)
802 	buf = vstring_alloc(10);
803     VSTRING_RESET(buf);
804 
805     switch (tls_cipher_grade(grade)) {
806     case TLS_CIPHER_NONE:
807 	msg_warn("%s: invalid cipher grade: \"%s\"",
808 		 TLScontext->namaddr, grade);
809 	return (0);
810     case TLS_CIPHER_HIGH:
811 	vstring_strcpy(buf, var_tls_high_clist);
812 	break;
813     case TLS_CIPHER_MEDIUM:
814 	vstring_strcpy(buf, var_tls_medium_clist);
815 	break;
816     case TLS_CIPHER_LOW:
817 	vstring_strcpy(buf, var_tls_low_clist);
818 	break;
819     case TLS_CIPHER_EXPORT:
820 	vstring_strcpy(buf, var_tls_export_clist);
821 	break;
822     case TLS_CIPHER_NULL:
823 	vstring_strcpy(buf, var_tls_null_clist);
824 	break;
825     default:
826 	/* Internal error, valid grade, but missing case label. */
827 	msg_panic("%s: unexpected cipher grade: %s", myname, grade);
828     }
829 
830     /*
831      * The base lists for each grade can't be empty.
832      */
833     if (VSTRING_LEN(buf) == 0)
834 	msg_panic("%s: empty \"%s\" cipherlist", myname, grade);
835 
836     /*
837      * Apply locally-specified exclusions.
838      */
839 #define CIPHER_SEP CHARS_COMMA_SP ":"
840     if (exclusions != 0) {
841 	cp = save = mystrdup(exclusions);
842 	while ((tok = mystrtok(&cp, CIPHER_SEP)) != 0) {
843 
844 	    /*
845 	     * Can't exclude ciphers that start with modifiers.
846 	     */
847 	    if (strchr("!+-@", *tok)) {
848 		msg_warn("%s: invalid unary '!+-@' in cipher exclusion: %s",
849 			 TLScontext->namaddr, tok);
850 		return (0);
851 	    }
852 	    vstring_sprintf_append(buf, ":!%s", tok);
853 	}
854 	myfree(save);
855     }
856     ERR_clear_error();
857     if (SSL_set_cipher_list(TLScontext->con, vstring_str(buf)) == 0) {
858 	msg_warn("%s: error setting cipher grade: \"%s\"",
859 		 TLScontext->namaddr, grade);
860 	tls_print_errors();
861 	return (0);
862     }
863     return (vstring_str(buf));
864 }
865 
866 /* ec_curve_name - copy EC key curve group name */
867 
868 #ifndef OPENSSL_NO_EC
ec_curve_name(EVP_PKEY * pkey)869 static char *ec_curve_name(EVP_PKEY *pkey)
870 {
871     char   *curve = 0;
872 
873 #if OPENSSL_VERSION_PREREQ(3,0)
874     size_t  namelen;
875 
876     if (EVP_PKEY_get_group_name(pkey, 0, 0, &namelen)) {
877 	curve = mymalloc(++namelen);
878 	if (!EVP_PKEY_get_group_name(pkey, curve, namelen, 0)) {
879 	    myfree(curve);
880 	    curve = 0;
881 	}
882     }
883 #else
884     EC_KEY *eckey = EVP_PKEY_get0_EC_KEY(pkey);
885     int     nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(eckey));
886     const char *tmp = EC_curve_nid2nist(nid);
887 
888     if (!tmp)
889 	tmp = OBJ_nid2sn(nid);
890     if (tmp)
891 	curve = mystrdup(tmp);
892 #endif
893     return (curve);
894 }
895 
896 #endif
897 
898 /* tls_get_signature_params - TLS 1.3 signature details */
899 
tls_get_signature_params(TLS_SESS_STATE * TLScontext)900 void    tls_get_signature_params(TLS_SESS_STATE *TLScontext)
901 {
902     const char *kex_name = 0;
903     const char *locl_sig_name = 0;
904     const char *locl_sig_dgst = 0;
905     const char *peer_sig_name = 0;
906     const char *peer_sig_dgst = 0;
907     char   *kex_curve = 0;
908     char   *locl_sig_curve = 0;
909     char   *peer_sig_curve = 0;
910     int     nid;
911     SSL    *ssl = TLScontext->con;
912     int     srvr = SSL_is_server(ssl);
913     EVP_PKEY *dh_pkey = 0;
914     X509   *local_cert;
915     EVP_PKEY *local_pkey = 0;
916     X509   *peer_cert;
917     EVP_PKEY *peer_pkey = 0;
918 
919 #define SIG_PROP(c, s, p) (*((s) ? &c->srvr_sig_##p : &c->clnt_sig_##p))
920 
921     if (SSL_version(ssl) < TLS1_3_VERSION)
922 	return;
923 
924     if (tls_get_peer_dh_pubkey(ssl, &dh_pkey)) {
925 	switch (nid = EVP_PKEY_id(dh_pkey)) {
926 	default:
927 	    kex_name = OBJ_nid2sn(EVP_PKEY_type(nid));
928 	    break;
929 
930 	case EVP_PKEY_DH:
931 	    kex_name = "DHE";
932 	    TLScontext->kex_bits = EVP_PKEY_bits(dh_pkey);
933 	    break;
934 
935 #ifndef OPENSSL_NO_EC
936 	case EVP_PKEY_EC:
937 	    kex_name = "ECDHE";
938 	    kex_curve = ec_curve_name(dh_pkey);
939 	    break;
940 #endif
941 	}
942 	EVP_PKEY_free(dh_pkey);
943     }
944 
945     /*
946      * On the client end, the certificate may be preset, but not used, so we
947      * check via SSL_get_signature_nid().  This means that local signature
948      * data on clients requires at least 1.1.1a.
949      */
950     if (srvr || SSL_get_signature_nid(ssl, &nid))
951 	local_cert = SSL_get_certificate(ssl);
952     else
953 	local_cert = 0;
954 
955     /* Signature algorithms for the local end of the connection */
956     if (local_cert) {
957 	local_pkey = X509_get0_pubkey(local_cert);
958 
959 	/*
960 	 * Override the built-in name for the "ECDSA" algorithms OID, with
961 	 * the more familiar name.  For "RSA" keys report "RSA-PSS", which
962 	 * must be used with TLS 1.3.
963 	 */
964 	if ((nid = EVP_PKEY_type(EVP_PKEY_id(local_pkey))) != NID_undef) {
965 	    switch (nid) {
966 	    default:
967 		locl_sig_name = OBJ_nid2sn(nid);
968 		break;
969 
970 	    case EVP_PKEY_RSA:
971 		/* For RSA, TLS 1.3 mandates PSS signatures */
972 		locl_sig_name = "RSA-PSS";
973 		SIG_PROP(TLScontext, srvr, bits) = EVP_PKEY_bits(local_pkey);
974 		break;
975 
976 #ifndef OPENSSL_NO_EC
977 	    case EVP_PKEY_EC:
978 		locl_sig_name = "ECDSA";
979 		locl_sig_curve = ec_curve_name(local_pkey);
980 		break;
981 #endif
982 	    }
983 	    /* No X509_free(local_cert) */
984 	}
985 
986 	/*
987 	 * With Ed25519 and Ed448 there is no pre-signature digest, but the
988 	 * accessor does not fail, rather we get NID_undef.
989 	 */
990 	if (SSL_get_signature_nid(ssl, &nid) && nid != NID_undef)
991 	    locl_sig_dgst = OBJ_nid2sn(nid);
992     }
993     /* Signature algorithms for the peer end of the connection */
994     if ((peer_cert = TLS_PEEK_PEER_CERT(ssl)) != 0) {
995 	peer_pkey = X509_get0_pubkey(peer_cert);
996 
997 	/*
998 	 * Override the built-in name for the "ECDSA" algorithms OID, with
999 	 * the more familiar name.  For "RSA" keys report "RSA-PSS", which
1000 	 * must be used with TLS 1.3.
1001 	 */
1002 	if ((nid = EVP_PKEY_type(EVP_PKEY_id(peer_pkey))) != NID_undef) {
1003 	    switch (nid) {
1004 	    default:
1005 		peer_sig_name = OBJ_nid2sn(nid);
1006 		break;
1007 
1008 	    case EVP_PKEY_RSA:
1009 		/* For RSA, TLS 1.3 mandates PSS signatures */
1010 		peer_sig_name = "RSA-PSS";
1011 		SIG_PROP(TLScontext, !srvr, bits) = EVP_PKEY_bits(peer_pkey);
1012 		break;
1013 
1014 #ifndef OPENSSL_NO_EC
1015 	    case EVP_PKEY_EC:
1016 		peer_sig_name = "ECDSA";
1017 		peer_sig_curve = ec_curve_name(peer_pkey);
1018 		break;
1019 #endif
1020 	    }
1021 	}
1022 
1023 	/*
1024 	 * With Ed25519 and Ed448 there is no pre-signature digest, but the
1025 	 * accessor does not fail, rather we get NID_undef.
1026 	 */
1027 	if (SSL_get_peer_signature_nid(ssl, &nid) && nid != NID_undef)
1028 	    peer_sig_dgst = OBJ_nid2sn(nid);
1029 
1030 	TLS_FREE_PEER_CERT(peer_cert);
1031     }
1032     if (kex_name) {
1033 	TLScontext->kex_name = mystrdup(kex_name);
1034 	TLScontext->kex_curve = kex_curve;
1035     }
1036     if (locl_sig_name) {
1037 	SIG_PROP(TLScontext, srvr, name) = mystrdup(locl_sig_name);
1038 	SIG_PROP(TLScontext, srvr, curve) = locl_sig_curve;
1039 	if (locl_sig_dgst)
1040 	    SIG_PROP(TLScontext, srvr, dgst) = mystrdup(locl_sig_dgst);
1041     }
1042     if (peer_sig_name) {
1043 	SIG_PROP(TLScontext, !srvr, name) = mystrdup(peer_sig_name);
1044 	SIG_PROP(TLScontext, !srvr, curve) = peer_sig_curve;
1045 	if (peer_sig_dgst)
1046 	    SIG_PROP(TLScontext, !srvr, dgst) = mystrdup(peer_sig_dgst);
1047     }
1048 }
1049 
1050 /* tls_log_summary - TLS loglevel 1 one-liner, embellished with TLS 1.3 details */
1051 
tls_log_summary(TLS_ROLE role,TLS_USAGE usage,TLS_SESS_STATE * ctx)1052 void    tls_log_summary(TLS_ROLE role, TLS_USAGE usage, TLS_SESS_STATE *ctx)
1053 {
1054     VSTRING *msg = vstring_alloc(100);
1055     const char *direction = (role == TLS_ROLE_CLIENT) ? "to" : "from";
1056     const char *sni = (role == TLS_ROLE_CLIENT) ? 0 : ctx->peer_sni;
1057 
1058     /*
1059      * When SNI was sent and accepted, the server-side log message now
1060      * includes a "to <sni-name>" detail after the "from <namaddr>" detail
1061      * identifying the remote client.  We don't presently log (purportedly)
1062      * accepted SNI on the client side.
1063      */
1064     vstring_sprintf(msg, "%s TLS connection %s %s %s%s%s: %s"
1065 		    " with cipher %s (%d/%d bits)",
1066 		    !TLS_CERT_IS_PRESENT(ctx) ? "Anonymous" :
1067 		    TLS_CERT_IS_SECURED(ctx) ? "Verified" :
1068 		    TLS_CERT_IS_TRUSTED(ctx) ? "Trusted" : "Untrusted",
1069 		    usage == TLS_USAGE_NEW ? "established" : "reused",
1070 		 direction, ctx->namaddr, sni ? " to " : "", sni ? sni : "",
1071 		    ctx->protocol, ctx->cipher_name, ctx->cipher_usebits,
1072 		    ctx->cipher_algbits);
1073 
1074     if (ctx->kex_name && *ctx->kex_name) {
1075 	vstring_sprintf_append(msg, " key-exchange %s", ctx->kex_name);
1076 	if (ctx->kex_curve && *ctx->kex_curve)
1077 	    vstring_sprintf_append(msg, " (%s)", ctx->kex_curve);
1078 	else if (ctx->kex_bits > 0)
1079 	    vstring_sprintf_append(msg, " (%d bits)", ctx->kex_bits);
1080     }
1081     if (ctx->srvr_sig_name && *ctx->srvr_sig_name) {
1082 	vstring_sprintf_append(msg, " server-signature %s",
1083 			       ctx->srvr_sig_name);
1084 	if (ctx->srvr_sig_curve && *ctx->srvr_sig_curve)
1085 	    vstring_sprintf_append(msg, " (%s)", ctx->srvr_sig_curve);
1086 	else if (ctx->srvr_sig_bits > 0)
1087 	    vstring_sprintf_append(msg, " (%d bits)", ctx->srvr_sig_bits);
1088 	if (ctx->srvr_sig_dgst && *ctx->srvr_sig_dgst)
1089 	    vstring_sprintf_append(msg, " server-digest %s",
1090 				   ctx->srvr_sig_dgst);
1091     }
1092     if (ctx->clnt_sig_name && *ctx->clnt_sig_name) {
1093 	vstring_sprintf_append(msg, " client-signature %s",
1094 			       ctx->clnt_sig_name);
1095 	if (ctx->clnt_sig_curve && *ctx->clnt_sig_curve)
1096 	    vstring_sprintf_append(msg, " (%s)", ctx->clnt_sig_curve);
1097 	else if (ctx->clnt_sig_bits > 0)
1098 	    vstring_sprintf_append(msg, " (%d bits)", ctx->clnt_sig_bits);
1099 	if (ctx->clnt_sig_dgst && *ctx->clnt_sig_dgst)
1100 	    vstring_sprintf_append(msg, " client-digest %s",
1101 				   ctx->clnt_sig_dgst);
1102     }
1103     msg_info("%s", vstring_str(msg));
1104     vstring_free(msg);
1105 }
1106 
1107 /* tls_alloc_app_context - allocate TLS application context */
1108 
tls_alloc_app_context(SSL_CTX * ssl_ctx,SSL_CTX * sni_ctx,int log_mask)1109 TLS_APPL_STATE *tls_alloc_app_context(SSL_CTX *ssl_ctx, SSL_CTX *sni_ctx,
1110 				              int log_mask)
1111 {
1112     TLS_APPL_STATE *app_ctx;
1113 
1114     app_ctx = (TLS_APPL_STATE *) mymalloc(sizeof(*app_ctx));
1115 
1116     /* See portability note below with other memset() call. */
1117     memset((void *) app_ctx, 0, sizeof(*app_ctx));
1118     app_ctx->ssl_ctx = ssl_ctx;
1119     app_ctx->sni_ctx = sni_ctx;
1120     app_ctx->log_mask = log_mask;
1121 
1122     /* See also: cache purging code in tls_set_ciphers(). */
1123     app_ctx->cache_type = 0;
1124 
1125     if (tls_server_sni_maps) {
1126 	SSL_CTX_set_tlsext_servername_callback(ssl_ctx, server_sni_callback);
1127 	SSL_CTX_set_tlsext_servername_arg(ssl_ctx, (void *) sni_ctx);
1128     }
1129     return (app_ctx);
1130 }
1131 
1132 /* tls_free_app_context - Free TLS application context */
1133 
tls_free_app_context(TLS_APPL_STATE * app_ctx)1134 void    tls_free_app_context(TLS_APPL_STATE *app_ctx)
1135 {
1136     if (app_ctx->ssl_ctx)
1137 	SSL_CTX_free(app_ctx->ssl_ctx);
1138     if (app_ctx->sni_ctx)
1139 	SSL_CTX_free(app_ctx->sni_ctx);
1140     if (app_ctx->cache_type)
1141 	myfree(app_ctx->cache_type);
1142     myfree((void *) app_ctx);
1143 }
1144 
1145 /* tls_alloc_sess_context - allocate TLS session context */
1146 
tls_alloc_sess_context(int log_mask,const char * namaddr)1147 TLS_SESS_STATE *tls_alloc_sess_context(int log_mask, const char *namaddr)
1148 {
1149     TLS_SESS_STATE *TLScontext;
1150 
1151     /*
1152      * PORTABILITY: Do not assume that null pointers are all-zero bits. Use
1153      * explicit assignments to initialize pointers.
1154      *
1155      * See the C language FAQ item 5.17, or if you have time to burn,
1156      * http://www.google.com/search?q=zero+bit+null+pointer
1157      *
1158      * However, it's OK to use memset() to zero integer values.
1159      */
1160     TLScontext = (TLS_SESS_STATE *) mymalloc(sizeof(TLS_SESS_STATE));
1161     memset((void *) TLScontext, 0, sizeof(*TLScontext));
1162     TLScontext->con = 0;
1163     TLScontext->cache_type = 0;
1164     TLScontext->serverid = 0;
1165     TLScontext->peer_CN = 0;
1166     TLScontext->issuer_CN = 0;
1167     TLScontext->peer_sni = 0;
1168     TLScontext->peer_cert_fprint = 0;
1169     TLScontext->peer_pkey_fprint = 0;
1170     TLScontext->protocol = 0;
1171     TLScontext->cipher_name = 0;
1172     TLScontext->kex_name = 0;
1173     TLScontext->kex_curve = 0;
1174     TLScontext->clnt_sig_name = 0;
1175     TLScontext->clnt_sig_curve = 0;
1176     TLScontext->clnt_sig_dgst = 0;
1177     TLScontext->srvr_sig_name = 0;
1178     TLScontext->srvr_sig_curve = 0;
1179     TLScontext->srvr_sig_dgst = 0;
1180     TLScontext->log_mask = log_mask;
1181     TLScontext->namaddr = lowercase(mystrdup(namaddr));
1182     TLScontext->mdalg = 0;			/* Alias for props->mdalg */
1183     TLScontext->dane = 0;			/* Alias for props->dane */
1184     TLScontext->errordepth = -1;
1185     TLScontext->errorcode = X509_V_OK;
1186     TLScontext->errorcert = 0;
1187 
1188     return (TLScontext);
1189 }
1190 
1191 /* tls_free_context - deallocate TLScontext and members */
1192 
tls_free_context(TLS_SESS_STATE * TLScontext)1193 void    tls_free_context(TLS_SESS_STATE *TLScontext)
1194 {
1195 
1196     /*
1197      * Free the SSL structure and the BIOs. Warning: the internal_bio is
1198      * connected to the SSL structure and is automatically freed with it. Do
1199      * not free it again (core dump)!! Only free the network_bio.
1200      */
1201     if (TLScontext->con != 0)
1202 	SSL_free(TLScontext->con);
1203 
1204     if (TLScontext->namaddr)
1205 	myfree(TLScontext->namaddr);
1206     if (TLScontext->serverid)
1207 	myfree(TLScontext->serverid);
1208 
1209     if (TLScontext->peer_CN)
1210 	myfree(TLScontext->peer_CN);
1211     if (TLScontext->issuer_CN)
1212 	myfree(TLScontext->issuer_CN);
1213     if (TLScontext->peer_sni)
1214 	myfree(TLScontext->peer_sni);
1215     if (TLScontext->peer_cert_fprint)
1216 	myfree(TLScontext->peer_cert_fprint);
1217     if (TLScontext->peer_pkey_fprint)
1218 	myfree(TLScontext->peer_pkey_fprint);
1219     if (TLScontext->kex_name)
1220 	myfree((void *) TLScontext->kex_name);
1221     if (TLScontext->kex_curve)
1222 	myfree((void *) TLScontext->kex_curve);
1223     if (TLScontext->clnt_sig_name)
1224 	myfree((void *) TLScontext->clnt_sig_name);
1225     if (TLScontext->clnt_sig_curve)
1226 	myfree((void *) TLScontext->clnt_sig_curve);
1227     if (TLScontext->clnt_sig_dgst)
1228 	myfree((void *) TLScontext->clnt_sig_dgst);
1229     if (TLScontext->srvr_sig_name)
1230 	myfree((void *) TLScontext->srvr_sig_name);
1231     if (TLScontext->srvr_sig_curve)
1232 	myfree((void *) TLScontext->srvr_sig_curve);
1233     if (TLScontext->srvr_sig_dgst)
1234 	myfree((void *) TLScontext->srvr_sig_dgst);
1235     if (TLScontext->errorcert)
1236 	X509_free(TLScontext->errorcert);
1237 
1238     myfree((void *) TLScontext);
1239 }
1240 
1241 /* tls_version_split - Split OpenSSL version number into major, minor, ... */
1242 
tls_version_split(unsigned long version,TLS_VINFO * info)1243 static void tls_version_split(unsigned long version, TLS_VINFO *info)
1244 {
1245 
1246     /*
1247      * OPENSSL_VERSION_NUMBER(3):
1248      *
1249      * OPENSSL_VERSION_NUMBER is a numeric release version identifier:
1250      *
1251      * MMNNFFPPS: major minor fix patch status
1252      *
1253      * The status nibble has one of the values 0 for development, 1 to e for
1254      * betas 1 to 14, and f for release. Parsed OpenSSL version number. for
1255      * example: 0x1010103f == 1.1.1c.
1256      */
1257     info->status = version & 0xf;
1258     version >>= 4;
1259     info->patch = version & 0xff;
1260     version >>= 8;
1261     info->micro = version & 0xff;
1262     version >>= 8;
1263     info->minor = version & 0xff;
1264     version >>= 8;
1265     info->major = version & 0xff;
1266 }
1267 
1268 /* tls_check_version - Detect mismatch between headers and library. */
1269 
tls_check_version(void)1270 void    tls_check_version(void)
1271 {
1272     TLS_VINFO hdr_info;
1273     TLS_VINFO lib_info;
1274 
1275     tls_version_split(OPENSSL_VERSION_NUMBER, &hdr_info);
1276     tls_version_split(OpenSSL_version_num(), &lib_info);
1277 
1278     /*
1279      * Warn if run-time library is different from compile-time library,
1280      * allowing later run-time "micro" versions starting with 1.1.0.
1281      */
1282     if (lib_info.major != hdr_info.major
1283 	|| lib_info.minor != hdr_info.minor
1284 	|| (lib_info.micro != hdr_info.micro
1285 	    && (lib_info.micro < hdr_info.micro
1286 		|| hdr_info.major == 0
1287 		|| (hdr_info.major == 1 && hdr_info.minor == 0))))
1288 	msg_warn("run-time library vs. compile-time header version mismatch: "
1289 	     "OpenSSL %d.%d.%d may not be compatible with OpenSSL %d.%d.%d",
1290 		 lib_info.major, lib_info.minor, lib_info.micro,
1291 		 hdr_info.major, hdr_info.minor, hdr_info.micro);
1292 }
1293 
1294 /* tls_compile_version - compile-time OpenSSL version */
1295 
tls_compile_version(void)1296 const char *tls_compile_version(void)
1297 {
1298     return (OPENSSL_VERSION_TEXT);
1299 }
1300 
1301 /* tls_run_version - run-time version "major.minor.micro" */
1302 
tls_run_version(void)1303 const char *tls_run_version(void)
1304 {
1305     return (OpenSSL_version(OPENSSL_VERSION));
1306 }
1307 
tls_pkey_algorithms(void)1308 const char **tls_pkey_algorithms(void)
1309 {
1310 
1311     /*
1312      * Return an array, not string, so that the result can be inspected
1313      * without parsing. Sort the result alphabetically, not chronologically.
1314      */
1315     static const char *algs[] = {
1316 #ifndef OPENSSL_NO_DSA
1317 	"dsa",
1318 #endif
1319 #ifndef OPENSSL_NO_ECDSA
1320 	"ecdsa",
1321 #endif
1322 #ifndef OPENSSL_NO_RSA
1323 	"rsa",
1324 #endif
1325 	0,
1326     };
1327 
1328     return (algs);
1329 }
1330 
1331 /* tls_bug_bits - SSL bug compatibility bits for this OpenSSL version */
1332 
tls_bug_bits(void)1333 long    tls_bug_bits(void)
1334 {
1335     long    bits = SSL_OP_ALL;		/* Work around all known bugs */
1336 
1337     /*
1338      * Silently ignore any strings that don't appear in the tweaks table, or
1339      * hex bits that are not in SSL_OP_ALL.
1340      */
1341     if (*var_tls_bug_tweaks) {
1342 	bits &= ~long_name_mask_opt(VAR_TLS_BUG_TWEAKS, ssl_bug_tweaks,
1343 				    var_tls_bug_tweaks, NAME_MASK_ANY_CASE |
1344 				    NAME_MASK_NUMBER | NAME_MASK_WARN);
1345 #ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
1346 	/* Not relevant to SMTP */
1347 	bits &= ~SSL_OP_SAFARI_ECDHE_ECDSA_BUG;
1348 #endif
1349     }
1350 
1351     /*
1352      * Allow users to set options not in SSL_OP_ALL, and not already managed
1353      * via other Postfix parameters.
1354      */
1355     if (*var_tls_ssl_options) {
1356 	long    enable;
1357 
1358 	enable = long_name_mask_opt(VAR_TLS_SSL_OPTIONS, ssl_op_tweaks,
1359 				    var_tls_ssl_options, NAME_MASK_ANY_CASE |
1360 				    NAME_MASK_NUMBER | NAME_MASK_WARN);
1361 	enable &= ~(SSL_OP_ALL | TLS_SSL_OP_MANAGED_BITS);
1362 	bits |= enable;
1363     }
1364 
1365     /*
1366      * We unconditionally avoid re-use of ephemeral keys, note that we set DH
1367      * keys via a callback, so reuse was never possible, but the ECDH key is
1368      * set statically, so that is potentially subject to reuse.  Set both
1369      * options just in case.
1370      */
1371     bits |= SSL_OP_SINGLE_ECDH_USE | SSL_OP_SINGLE_DH_USE;
1372     return (bits);
1373 }
1374 
1375 /* tls_print_errors - print and clear the error stack */
1376 
tls_print_errors(void)1377 void    tls_print_errors(void)
1378 {
1379     unsigned long err;
1380     char    buffer[1024];		/* XXX */
1381     const char *file;
1382     const char *data;
1383     int     line;
1384     int     flags;
1385 
1386 #if OPENSSL_VERSION_PREREQ(3,0)
1387 /* XXX: We're ignoring the function name, do we want to log it? */
1388 #define ERRGET(fi, l, d, fl) ERR_get_error_all(fi, l, 0, d, fl)
1389 #else
1390 #define ERRGET(fi, l, d, fl) ERR_get_error_line_data(fi, l, d, fl)
1391 #endif
1392 
1393     while ((err = ERRGET(&file, &line, &data, &flags)) != 0) {
1394 	ERR_error_string_n(err, buffer, sizeof(buffer));
1395 	if (flags & ERR_TXT_STRING)
1396 	    msg_warn("TLS library problem: %s:%s:%d:%s:",
1397 		     buffer, file, line, data);
1398 	else
1399 	    msg_warn("TLS library problem: %s:%s:%d:", buffer, file, line);
1400     }
1401 }
1402 
1403 /* tls_info_callback - callback for logging SSL events via Postfix */
1404 
tls_info_callback(const SSL * s,int where,int ret)1405 void    tls_info_callback(const SSL *s, int where, int ret)
1406 {
1407     char   *str;
1408     int     w;
1409 
1410     /* Adapted from OpenSSL apps/s_cb.c. */
1411 
1412     w = where & ~SSL_ST_MASK;
1413 
1414     if (w & SSL_ST_CONNECT)
1415 	str = "SSL_connect";
1416     else if (w & SSL_ST_ACCEPT)
1417 	str = "SSL_accept";
1418     else
1419 	str = "unknown";
1420 
1421     if (where & SSL_CB_LOOP) {
1422 	msg_info("%s:%s", str, SSL_state_string_long((SSL *) s));
1423     } else if (where & SSL_CB_ALERT) {
1424 	str = (where & SSL_CB_READ) ? "read" : "write";
1425 	if ((ret & 0xff) != SSL3_AD_CLOSE_NOTIFY)
1426 	    msg_info("SSL3 alert %s:%s:%s", str,
1427 		     SSL_alert_type_string_long(ret),
1428 		     SSL_alert_desc_string_long(ret));
1429     } else if (where & SSL_CB_EXIT) {
1430 	if (ret == 0)
1431 	    msg_info("%s:failed in %s",
1432 		     str, SSL_state_string_long((SSL *) s));
1433 	else if (ret < 0) {
1434 #ifndef LOG_NON_ERROR_STATES
1435 	    switch (SSL_get_error((SSL *) s, ret)) {
1436 	    case SSL_ERROR_WANT_READ:
1437 	    case SSL_ERROR_WANT_WRITE:
1438 		/* Don't log non-error states. */
1439 		break;
1440 	    default:
1441 #endif
1442 		msg_info("%s:error in %s",
1443 			 str, SSL_state_string_long((SSL *) s));
1444 #ifndef LOG_NON_ERROR_STATES
1445 	    }
1446 #endif
1447 	}
1448     }
1449 }
1450 
1451  /*
1452   * taken from OpenSSL crypto/bio/b_dump.c.
1453   *
1454   * Modified to save a lot of strcpy and strcat by Matti Aarnio.
1455   *
1456   * Rewritten by Wietse to elimate fixed-size stack buffer, array index
1457   * multiplication and division, sprintf() and strcpy(), and lots of strlen()
1458   * calls. We could make it a little faster by using a fixed-size stack-based
1459   * buffer.
1460   *
1461   * 200412 - use %lx to print pointers, after casting them to unsigned long.
1462   */
1463 
1464 #define TRUNCATE_SPACE_NULL
1465 #define DUMP_WIDTH	16
1466 #define VERT_SPLIT	7
1467 
tls_dump_buffer(const unsigned char * start,int len)1468 static void tls_dump_buffer(const unsigned char *start, int len)
1469 {
1470     VSTRING *buf = vstring_alloc(100);
1471     const unsigned char *last = start + len - 1;
1472     const unsigned char *row;
1473     const unsigned char *col;
1474     int     ch;
1475 
1476 #ifdef TRUNCATE_SPACE_NULL
1477     while (last >= start && (*last == ' ' || *last == 0))
1478 	last--;
1479 #endif
1480 
1481     for (row = start; row <= last; row += DUMP_WIDTH) {
1482 	VSTRING_RESET(buf);
1483 	vstring_sprintf(buf, "%04lx ", (unsigned long) (row - start));
1484 	for (col = row; col < row + DUMP_WIDTH; col++) {
1485 	    if (col > last) {
1486 		vstring_strcat(buf, "   ");
1487 	    } else {
1488 		ch = *col;
1489 		vstring_sprintf_append(buf, "%02x%c",
1490 				   ch, col - row == VERT_SPLIT ? '|' : ' ');
1491 	    }
1492 	}
1493 	VSTRING_ADDCH(buf, ' ');
1494 	for (col = row; col < row + DUMP_WIDTH; col++) {
1495 	    if (col > last)
1496 		break;
1497 	    ch = *col;
1498 	    if (!ISPRINT(ch))
1499 		ch = '.';
1500 	    VSTRING_ADDCH(buf, ch);
1501 	    if (col - row == VERT_SPLIT)
1502 		VSTRING_ADDCH(buf, ' ');
1503 	}
1504 	VSTRING_TERMINATE(buf);
1505 	msg_info("%s", vstring_str(buf));
1506     }
1507 #ifdef TRUNCATE_SPACE_NULL
1508     if ((last + 1) - start < len)
1509 	msg_info("%04lx - <SPACES/NULLS>",
1510 		 (unsigned long) ((last + 1) - start));
1511 #endif
1512     vstring_free(buf);
1513 }
1514 
1515 /* taken from OpenSSL apps/s_cb.c */
1516 
1517 #if !OPENSSL_VERSION_PREREQ(3,0)
tls_bio_dump_cb(BIO * bio,int cmd,const char * argp,int argi,long unused_argl,long ret)1518 long    tls_bio_dump_cb(BIO *bio, int cmd, const char *argp, int argi,
1519 			        long unused_argl, long ret)
1520 {
1521     if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
1522 	msg_info("read from %08lX [%08lX] (%d bytes => %ld (0x%lX))",
1523 		 (unsigned long) bio, (unsigned long) argp, argi,
1524 		 ret, (unsigned long) ret);
1525 	tls_dump_buffer((unsigned char *) argp, (int) ret);
1526     } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
1527 	msg_info("write to %08lX [%08lX] (%d bytes => %ld (0x%lX))",
1528 		 (unsigned long) bio, (unsigned long) argp, argi,
1529 		 ret, (unsigned long) ret);
1530 	tls_dump_buffer((unsigned char *) argp, (int) ret);
1531     }
1532     return (ret);
1533 }
1534 
1535 #else
tls_bio_dump_cb(BIO * bio,int cmd,const char * argp,size_t len,int argi,long unused_argl,int ret,size_t * processed)1536 long    tls_bio_dump_cb(BIO *bio, int cmd, const char *argp, size_t len,
1537 	             int argi, long unused_argl, int ret, size_t *processed)
1538 {
1539     size_t  bytes = (ret > 0 && processed != NULL) ? *processed : len;
1540 
1541     if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
1542 	if (ret > 0) {
1543 	    msg_info("read from %08lX [%08lX] (%ld bytes => %ld (0x%lX))",
1544 		     (unsigned long) bio, (unsigned long) argp, (long) len,
1545 		     (long) bytes, (long) bytes);
1546 	    tls_dump_buffer((unsigned char *) argp, (int) bytes);
1547 	} else {
1548 	    msg_info("read from %08lX [%08lX] (%ld bytes => %d)",
1549 		     (unsigned long) bio, (unsigned long) argp,
1550 		     (long) len, ret);
1551 	}
1552     } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
1553 	if (ret > 0) {
1554 	    msg_info("write to %08lX [%08lX] (%ld bytes => %ld (0x%lX))",
1555 		     (unsigned long) bio, (unsigned long) argp, (long) len,
1556 		     (long) bytes, (long) bytes);
1557 	    tls_dump_buffer((unsigned char *) argp, (int) bytes);
1558 	} else {
1559 	    msg_info("write to %08lX [%08lX] (%ld bytes => %d)",
1560 		     (unsigned long) bio, (unsigned long) argp,
1561 		     (long) len, ret);
1562 	}
1563     }
1564     return ret;
1565 }
1566 
1567 #endif
1568 
tls_validate_digest(const char * dgst)1569 const EVP_MD *tls_validate_digest(const char *dgst)
1570 {
1571     const EVP_MD *md_alg;
1572     unsigned int md_len;
1573 
1574     /*
1575      * If the administrator specifies an unsupported digest algorithm, fail
1576      * now, rather than in the middle of a TLS handshake.
1577      */
1578     if ((md_alg = EVP_get_digestbyname(dgst)) == 0) {
1579 	msg_warn("Digest algorithm \"%s\" not found", dgst);
1580 	return (0);
1581     }
1582 
1583     /*
1584      * Sanity check: Newer shared libraries may use larger digests.
1585      */
1586     if ((md_len = EVP_MD_size(md_alg)) > EVP_MAX_MD_SIZE) {
1587 	msg_warn("Digest algorithm \"%s\" output size %u too large",
1588 		 dgst, md_len);
1589 	return (0);
1590     }
1591     return md_alg;
1592 }
1593 
1594 #else
1595 
1596  /*
1597   * Broken linker workaround.
1598   */
1599 int     tls_dummy_for_broken_linkers;
1600 
1601 #endif
1602