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