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