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