Home | History | Annotate | Line # | Download | only in tls
      1 /*	$NetBSD: tls_client.c,v 1.15 2026/05/09 18:49:21 christos Exp $	*/
      2 
      3 /*++
      4 /* NAME
      5 /*	tls_client
      6 /* SUMMARY
      7 /*	client-side TLS engine
      8 /* SYNOPSIS
      9 /*	#include <tls.h>
     10 /*
     11 /*	TLS_APPL_STATE *tls_client_init(init_props)
     12 /*	const TLS_CLIENT_INIT_PROPS *init_props;
     13 /*
     14 /*	TLS_SESS_STATE *tls_client_start(start_props)
     15 /*	const TLS_CLIENT_START_PROPS *start_props;
     16 /*
     17 /*	TLS_SESS_STATE *tls_client_post_connect(TLScontext, start_props)
     18 /*	TLS_SESS_STATE *TLScontext;
     19 /*	const TLS_CLIENT_START_PROPS *start_props;
     20 /*
     21 /*	void	tls_client_stop(app_ctx, stream, failure, TLScontext)
     22 /*	TLS_APPL_STATE *app_ctx;
     23 /*	VSTREAM	*stream;
     24 /*	int	failure;
     25 /*	TLS_SESS_STATE *TLScontext;
     26 /* DESCRIPTION
     27 /*	This module is the interface between Postfix TLS clients,
     28 /*	the OpenSSL library and the TLS entropy and cache manager.
     29 /*
     30 /*	The SMTP client will attempt to verify the server hostname
     31 /*	against the names listed in the server certificate. When
     32 /*	a hostname match is required, the verification fails
     33 /*	on certificate verification or hostname mis-match errors.
     34 /*	When no hostname match is required, hostname verification
     35 /*	failures are logged but they do not affect the TLS handshake
     36 /*	or the SMTP session.
     37 /*
     38 /*	The rules for peer name wild-card matching differ between
     39 /*	RFC 2818 (HTTP over TLS) and RFC 2830 (LDAP over TLS), while
     40 /*	RFC RFC3207 (SMTP over TLS) does not specify a rule at all.
     41 /*	Postfix uses a restrictive match algorithm. One asterisk
     42 /*	('*') is allowed as the left-most component of a wild-card
     43 /*	certificate name; it matches the left-most component of
     44 /*	the peer hostname.
     45 /*
     46 /*	Another area where RFCs aren't always explicit is the
     47 /*	handling of dNSNames in peer certificates. RFC 3207 (SMTP
     48 /*	over TLS) does not mention dNSNames. Postfix follows the
     49 /*	strict rules in RFC 2818 (HTTP over TLS), section 3.1: The
     50 /*	Subject Alternative Name/dNSName has precedence over
     51 /*	CommonName.  If at least one dNSName is provided, Postfix
     52 /*	verifies those against the peer hostname and ignores the
     53 /*	CommonName, otherwise Postfix verifies the CommonName
     54 /*	against the peer hostname.
     55 /*
     56 /*	tls_client_init() is called once when the SMTP client
     57 /*	initializes.
     58 /*	Certificate details are also decided during this phase,
     59 /*	so peer-specific certificate selection is not possible.
     60 /*
     61 /*	tls_client_start() activates the TLS session over an established
     62 /*	stream. We expect that network buffers are flushed and
     63 /*	the TLS handshake can begin immediately.
     64 /*
     65 /*	tls_client_stop() sends the "close notify" alert via
     66 /*	SSL_shutdown() to the peer and resets all connection specific
     67 /*	TLS data. As RFC2487 does not specify a separate shutdown, it
     68 /*	is assumed that the underlying TCP connection is shut down
     69 /*	immediately afterwards. Any further writes to the channel will
     70 /*	be discarded, and any further reads will report end-of-file.
     71 /*	If the failure flag is set, no SSL_shutdown() handshake is performed.
     72 /*
     73 /*	Once the TLS connection is initiated, information about the TLS
     74 /*	state is available via the TLScontext structure:
     75 /* .IP TLScontext->protocol
     76 /*	the protocol name (SSLv2, SSLv3, TLSv1),
     77 /* .IP TLScontext->cipher_name
     78 /*	the cipher name (e.g. RC4/MD5),
     79 /* .IP TLScontext->cipher_usebits
     80 /*	the number of bits actually used (e.g. 40),
     81 /* .IP TLScontext->cipher_algbits
     82 /*	the number of bits the algorithm is based on (e.g. 128).
     83 /* .PP
     84 /*	The last two values may differ from each other when export-strength
     85 /*	encryption is used.
     86 /*
     87 /*	If the peer offered a certificate, part of the certificate data are
     88 /*	available as:
     89 /* .IP TLScontext->peer_status
     90 /*	A bitmask field that records the status of the peer certificate
     91 /*	verification. This consists of one or more of TLS_CRED_FLAG_CERT,
     92 /*	TLS_CRED_FLAG_RPK, TLS_CERT_FLAG_TRUSTED, TLS_CERT_FLAG_MATCHED and
     93 /*	TLS_CERT_FLAG_SECURED.
     94 /* .IP TLScontext->peer_CN
     95 /*	Extracted CommonName of the peer, or zero-length string if the
     96 /*	information could not be extracted.
     97 /* .IP TLScontext->issuer_CN
     98 /*	Extracted CommonName of the issuer, or zero-length string if the
     99 /*	information could not be extracted.
    100 /* .IP TLScontext->peer_cert_fprint
    101 /*	At the fingerprint security level, if the peer presented a certificate
    102 /*	the fingerprint of the certificate.
    103 /* .PP
    104 /*	If no peer certificate is presented the peer_status is set to 0.
    105 /* EVENT_DRIVEN APPLICATIONS
    106 /* .ad
    107 /* .fi
    108 /*	Event-driven programs manage multiple I/O channels.  Such
    109 /*	programs cannot use the synchronous VSTREAM-over-TLS
    110 /*	implementation that the TLS library historically provides,
    111 /*	including tls_client_stop() and the underlying tls_stream(3)
    112 /*	and tls_bio_ops(3) routines.
    113 /*
    114 /*	With the current TLS library implementation, this means
    115 /*	that an event-driven application is responsible for calling
    116 /*	and retrying SSL_connect(), SSL_read(), SSL_write() and
    117 /*	SSL_shutdown().
    118 /*
    119 /*	To maintain control over TLS I/O, an event-driven client
    120 /*	invokes tls_client_start() with a null VSTREAM argument and
    121 /*	with an fd argument that specifies the I/O file descriptor.
    122 /*	Then, tls_client_start() performs all the necessary
    123 /*	preparations before the TLS handshake and returns a partially
    124 /*	populated TLS context. The event-driven application is then
    125 /*	responsible for invoking SSL_connect(), and if successful,
    126 /*	for invoking tls_client_post_connect() to finish the work
    127 /*	that was started by tls_client_start(). In case of unrecoverable
    128 /*	failure, tls_client_post_connect() destroys the TLS context
    129 /*	and returns a null pointer value.
    130 /* LICENSE
    131 /* .ad
    132 /* .fi
    133 /*	This software is free. You can do with it whatever you want.
    134 /*	The original author kindly requests that you acknowledge
    135 /*	the use of his software.
    136 /* AUTHOR(S)
    137 /*	Originally written by:
    138 /*	Lutz Jaenicke
    139 /*	BTU Cottbus
    140 /*	Allgemeine Elektrotechnik
    141 /*	Universitaetsplatz 3-4
    142 /*	D-03044 Cottbus, Germany
    143 /*
    144 /*	Updated by:
    145 /*	Wietse Venema
    146 /*	IBM T.J. Watson Research
    147 /*	P.O. Box 704
    148 /*	Yorktown Heights, NY 10598, USA
    149 /*
    150 /*	Wietse Venema
    151 /*	Google, Inc.
    152 /*	111 8th Avenue
    153 /*	New York, NY 10011, USA
    154 /*
    155 /*	Victor Duchovni
    156 /*	Morgan Stanley
    157 /*
    158 /*	Wietse Venema
    159 /*	porcupine.org
    160 /*--*/
    161 
    162 /* System library. */
    163 
    164 #include <sys_defs.h>
    165 
    166 #ifdef USE_TLS
    167 #include <string.h>
    168 #include <tlsrpt_wrapper.h>
    169 
    170 #ifdef STRCASECMP_IN_STRINGS_H
    171 #include <strings.h>
    172 #endif
    173 
    174 /* Utility library. */
    175 
    176 #include <argv.h>
    177 #include <mymalloc.h>
    178 #include <vstring.h>
    179 #include <vstream.h>
    180 #include <stringops.h>
    181 #include <msg.h>
    182 #include <iostuff.h>			/* non-blocking */
    183 #include <midna_domain.h>
    184 
    185 /* Global library. */
    186 
    187 #include <mail_params.h>
    188 
    189 /* TLS library. */
    190 
    191 #include <tls_mgr.h>
    192 #define TLS_INTERNAL
    193 #include <tls.h>
    194 
    195 /* Application-specific. */
    196 
    197 #define STR	vstring_str
    198 #define LEN	VSTRING_LEN
    199 
    200 /* load_clnt_session - load session from client cache (non-callback) */
    201 
    202 static SSL_SESSION *load_clnt_session(TLS_SESS_STATE *TLScontext)
    203 {
    204     const char *myname = "load_clnt_session";
    205     SSL_SESSION *session = 0;
    206     VSTRING *session_data = vstring_alloc(2048);
    207 
    208     /*
    209      * Prepare the query.
    210      */
    211     if (TLScontext->log_mask & TLS_LOG_CACHE)
    212 	/* serverid contains transport:addr:port information */
    213 	msg_info("looking for session %s in %s cache",
    214 		 TLScontext->serverid, TLScontext->cache_type);
    215 
    216     /*
    217      * We only get here if the cache_type is not empty. This code is not
    218      * called unless caching is enabled and the cache_type is stored in the
    219      * server SSL context.
    220      */
    221     if (TLScontext->cache_type == 0)
    222 	msg_panic("%s: null client session cache type in session lookup",
    223 		  myname);
    224 
    225     /*
    226      * Look up and activate the SSL_SESSION object. Errors are non-fatal,
    227      * since caching is only an optimization.
    228      */
    229     if (tls_mgr_lookup(TLScontext->cache_type, TLScontext->serverid,
    230 		       session_data) == TLS_MGR_STAT_OK) {
    231 	session = tls_session_activate(STR(session_data), LEN(session_data));
    232 	if (session) {
    233 	    if (TLScontext->log_mask & TLS_LOG_CACHE)
    234 		/* serverid contains transport:addr:port information */
    235 		msg_info("reloaded session %s from %s cache",
    236 			 TLScontext->serverid, TLScontext->cache_type);
    237 	}
    238     }
    239 
    240     /*
    241      * Clean up.
    242      */
    243     vstring_free(session_data);
    244 
    245     return (session);
    246 }
    247 
    248 /* new_client_session_cb - name new session and save it to client cache */
    249 
    250 static int new_client_session_cb(SSL *ssl, SSL_SESSION *session)
    251 {
    252     const char *myname = "new_client_session_cb";
    253     TLS_SESS_STATE *TLScontext;
    254     VSTRING *session_data;
    255 
    256     /*
    257      * The cache name (if caching is enabled in tlsmgr(8)) and the cache ID
    258      * string for this session are stored in the TLScontext. It cannot be
    259      * null at this point.
    260      */
    261     if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
    262 	msg_panic("%s: null TLScontext in new session callback", myname);
    263 
    264     /*
    265      * We only get here if the cache_type is not empty. This callback is not
    266      * set unless caching is enabled and the cache_type is stored in the
    267      * server SSL context.
    268      */
    269     if (TLScontext->cache_type == 0)
    270 	msg_panic("%s: null session cache type in new session callback",
    271 		  myname);
    272 
    273     /*-
    274      * Store only the first ticket for a given connection.
    275      * - Even if the server offers multiple tickets, we have no mechanism to
    276      *   store or use multiple concurrent tickets for the same nexthop.
    277      *
    278      * Passivate and save the session object. Errors are non-fatal, since
    279      * caching is only an optimization.
    280      */
    281     if (TLScontext->ticketed == 0 &&
    282 	(session_data = tls_session_passivate(session)) != 0) {
    283 	TLScontext->ticketed = 1;
    284 	if (TLScontext->log_mask & TLS_LOG_CACHE)
    285 	    /* serverid contains transport:addr:port information */
    286 	    msg_info("save session %s to %s cache",
    287 		     TLScontext->serverid, TLScontext->cache_type);
    288 
    289 	tls_mgr_update(TLScontext->cache_type, TLScontext->serverid,
    290 		       STR(session_data), LEN(session_data));
    291 	vstring_free(session_data);
    292     }
    293 
    294     /*
    295      * Clean up.
    296      */
    297     SSL_SESSION_free(session);			/* 200502 */
    298 
    299     return (1);
    300 }
    301 
    302 /* uncache_session - remove session from the external cache */
    303 
    304 static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext)
    305 {
    306     SSL_SESSION *session = SSL_get_session(TLScontext->con);
    307 
    308     SSL_CTX_remove_session(ctx, session);
    309     if (TLScontext->cache_type == 0 || TLScontext->serverid == 0)
    310 	return;
    311 
    312     if (TLScontext->log_mask & TLS_LOG_CACHE)
    313 	/* serverid contains transport:addr:port information */
    314 	msg_info("remove session %s from client cache", TLScontext->serverid);
    315 
    316     tls_mgr_delete(TLScontext->cache_type, TLScontext->serverid);
    317 }
    318 
    319 /* verify_x509 - process X.509 certificate verification status */
    320 
    321 static void verify_x509(TLS_SESS_STATE *TLScontext, X509 *peercert,
    322 			        const TLS_CLIENT_START_PROPS *props)
    323 {
    324     int     x509_err = SSL_get_verify_result(TLScontext->con);
    325 
    326     /*
    327      * On exit both peer_CN and issuer_CN should be set.
    328      */
    329     TLScontext->issuer_CN = tls_issuer_CN(peercert, TLScontext);
    330     TLScontext->peer_CN = tls_peer_CN(peercert, TLScontext);
    331 
    332     /*
    333      * Is the certificate trust chain trusted and matched?  Any required name
    334      * checks are now performed internally in OpenSSL.
    335      */
    336     if (x509_err == X509_V_OK) {
    337 	TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
    338 	if (TLScontext->must_fail) {
    339 	    msg_panic("%s: cert valid despite trust init failure",
    340 		      TLScontext->namaddr);
    341 	} else if (TLS_MUST_MATCH(TLScontext->level)) {
    342 
    343 	    /*
    344 	     * Fully secured only if not insecure like half-dane.  We use
    345 	     * TLS_CERT_FLAG_MATCHED to satisfy policy, but
    346 	     * TLS_CERT_FLAG_SECURED to log the effective security.
    347 	     *
    348 	     * Would ideally also exclude "verify" (as opposed to "secure")
    349 	     * here, because that can be subject to insecure MX indirection,
    350 	     * but that's rather incompatible (and not even the case with
    351 	     * explicitly chosen non-default match patterns).  Users have
    352 	     * been warned.
    353 	     */
    354 	    if (!TLS_NEVER_SECURED(TLScontext->level))
    355 		TLScontext->peer_status |= TLS_CERT_FLAG_SECURED;
    356 	    TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED;
    357 
    358 	    if (TLScontext->log_mask &
    359 		(TLS_LOG_CERTMATCH | TLS_LOG_VERBOSE | TLS_LOG_PEERCERT)) {
    360 		const char *peername = SSL_get0_peername(TLScontext->con);
    361 
    362 		if (peername)
    363 		    msg_info("%s: matched peername: %s",
    364 			     TLScontext->namaddr, peername);
    365 		tls_dane_log(TLScontext);
    366 	    }
    367 	}
    368     } else if (TLS_MUST_MATCH(TLScontext->level) &&
    369 	       x509_err == X509_V_ERR_HOSTNAME_MISMATCH) {
    370 
    371 	/*
    372 	 * If the only error is a hostname mismatch, the certificate must
    373 	 * have been trusted.
    374 	 */
    375 	TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
    376     }
    377 
    378     /*
    379      * Give them a clue. Problems with trust chain verification are logged
    380      * when the session is first negotiated, before the session is stored
    381      * into the cache. We don't want mystery failures, so log the fact the
    382      * real problem is to be found in the past.
    383      */
    384     if (!TLS_CERT_IS_MATCHED(TLScontext)
    385 	&& (TLScontext->log_mask & TLS_LOG_UNTRUSTED)) {
    386 	if (TLScontext->session_reused == 0)
    387 	    tls_log_verify_error(TLScontext, props->tlsrpt);
    388 	else
    389 	    msg_info("%s: re-using session with untrusted peer credential, "
    390 		     "look for details earlier in the log", props->namaddr);
    391     }
    392 }
    393 
    394 /* verify_rpk - process RFC7250 raw public key verification status */
    395 
    396 static void verify_rpk(TLS_SESS_STATE *TLScontext, EVP_PKEY *peerpkey,
    397 		               const TLS_CLIENT_START_PROPS *props)
    398 {
    399     /* Was the raw public key (type of cert) matched? */
    400     if (SSL_get_verify_result(TLScontext->con) == X509_V_OK) {
    401 	TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
    402 	if (TLScontext->must_fail) {
    403 	    msg_panic("%s: raw public key valid despite trust init failure",
    404 		      TLScontext->namaddr);
    405 	} else if (TLS_MUST_MATCH(TLScontext->level)) {
    406 
    407 	    /*
    408 	     * Fully secured only if not insecure like half-dane.  We use
    409 	     * TLS_CERT_FLAG_MATCHED to satisfy policy, but
    410 	     * TLS_CERT_FLAG_SECURED to log the effective security.
    411 	     */
    412 	    if (!TLS_NEVER_SECURED(TLScontext->level))
    413 		TLScontext->peer_status |= TLS_CERT_FLAG_SECURED;
    414 	    TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED;
    415 
    416 	    if (TLScontext->log_mask &
    417 		(TLS_LOG_CERTMATCH | TLS_LOG_VERBOSE | TLS_LOG_PEERCERT))
    418 		tls_dane_log(TLScontext);
    419 	}
    420     }
    421 
    422     /*
    423      * Give them a clue. Problems with trust chain verification are logged
    424      * when the session is first negotiated, before the session is stored
    425      * into the cache. We don't want mystery failures, so log the fact the
    426      * real problem is to be found in the past.
    427      */
    428     if (!TLS_CERT_IS_MATCHED(TLScontext)
    429 	&& (TLScontext->log_mask & TLS_LOG_UNTRUSTED)) {
    430 	if (TLScontext->session_reused == 0)
    431 	    tls_log_verify_error(TLScontext, props->tlsrpt);
    432 	else
    433 	    msg_info("%s: re-using session with untrusted certificate, "
    434 		     "look for details earlier in the log", props->namaddr);
    435     }
    436 }
    437 
    438 /* add_namechecks - tell OpenSSL what names to check */
    439 
    440 static void add_namechecks(TLS_SESS_STATE *TLScontext,
    441 			           const TLS_CLIENT_START_PROPS *props)
    442 {
    443     SSL    *ssl = TLScontext->con;
    444     int     namechecks_count = 0;
    445     int     i;
    446 
    447     /* RFC6125: No part-label 'foo*bar.example.com' wildcards for SMTP */
    448     SSL_set_hostflags(ssl, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
    449 
    450     for (i = 0; i < props->matchargv->argc; ++i) {
    451 	const char *name = props->matchargv->argv[i];
    452 	const char *aname;
    453 	int     match_subdomain = 0;
    454 
    455 	if (strcasecmp(name, "nexthop") == 0) {
    456 	    name = props->nexthop;
    457 	} else if (strcasecmp(name, "dot-nexthop") == 0) {
    458 	    name = props->nexthop;
    459 	    match_subdomain = 1;
    460 	} else if (strcasecmp(name, "hostname") == 0) {
    461 	    name = props->host;
    462 	} else {
    463 	    if (*name == '.') {
    464 		if (*++name == 0) {
    465 		    msg_warn("%s: ignoring invalid match name: \".\"",
    466 			     TLScontext->namaddr);
    467 		    continue;
    468 		}
    469 		match_subdomain = 1;
    470 	    }
    471 #ifndef NO_EAI
    472 	    else {
    473 
    474 		/*
    475 		 * Besides U+002E (full stop) IDNA2003 allows labels to be
    476 		 * separated by any of the Unicode variants U+3002
    477 		 * (ideographic full stop), U+FF0E (fullwidth full stop), and
    478 		 * U+FF61 (halfwidth ideographic full stop). Their respective
    479 		 * UTF-8 encodings are: E38082, EFBC8E and EFBDA1.
    480 		 *
    481 		 * IDNA2008 does not permit (upper) case and other variant
    482 		 * differences in U-labels. The midna_domain_to_ascii()
    483 		 * function, based on UTS46, normalizes such differences
    484 		 * away.
    485 		 *
    486 		 * The IDNA to_ASCII conversion does not allow empty leading
    487 		 * labels, so we handle these explicitly here.
    488 		 */
    489 		unsigned char *cp = (unsigned char *) name;
    490 
    491 		if ((cp[0] == 0xe3 && cp[1] == 0x80 && cp[2] == 0x82)
    492 		    || (cp[0] == 0xef && cp[1] == 0xbc && cp[2] == 0x8e)
    493 		    || (cp[0] == 0xef && cp[1] == 0xbd && cp[2] == 0xa1)) {
    494 		    if (name[3]) {
    495 			name = name + 3;
    496 			match_subdomain = 1;
    497 		    }
    498 		}
    499 	    }
    500 #endif
    501 	}
    502 
    503 	/*
    504 	 * DNS subjectAltNames are required to be ASCII.
    505 	 *
    506 	 * Per RFC 6125 Section 6.4.4 Matching the CN-ID, follows the same rules
    507 	 * (6.4.1, 6.4.2 and 6.4.3) that apply to subjectAltNames.  In
    508 	 * particular, 6.4.2 says that the reference identifier is coerced to
    509 	 * ASCII, but no conversion is stated or implied for the CN-ID, so it
    510 	 * seems it only matches if it is all ASCII.  Otherwise, it is some
    511 	 * other sort of name.
    512 	 */
    513 #ifndef NO_EAI
    514 	if (!allascii(name) && (aname = midna_domain_to_ascii(name)) != 0) {
    515 	    if (msg_verbose)
    516 		msg_info("%s asciified to %s", name, aname);
    517 	    name = aname;
    518 	}
    519 #endif
    520 
    521 	if (!match_subdomain) {
    522 	    if (TLS_ADD1_HOST(ssl, name))
    523 		++namechecks_count;
    524 	    else
    525 		msg_warn("%s: error loading match name: \"%s\"",
    526 			 TLScontext->namaddr, name);
    527 	} else {
    528 	    char   *dot_name = concatenate(".", name, (char *) 0);
    529 
    530 	    if (TLS_ADD1_HOST(ssl, dot_name))
    531 		++namechecks_count;
    532 	    else
    533 		msg_warn("%s: error loading match name: \"%s\"",
    534 			 TLScontext->namaddr, dot_name);
    535 	    myfree(dot_name);
    536 	}
    537     }
    538 
    539     /*
    540      * If we failed to add any names, OpenSSL will perform no namechecks, so
    541      * we set the "must_fail" bit to avoid verification false-positives.
    542      */
    543     if (namechecks_count == 0) {
    544 	msg_warn("%s: could not configure peer name checks",
    545 		 TLScontext->namaddr);
    546 	TLScontext->must_fail = 1;
    547     }
    548 }
    549 
    550 /* tls_auth_enable - set up TLS authentication */
    551 
    552 static int tls_auth_enable(TLS_SESS_STATE *TLScontext,
    553 			           const TLS_CLIENT_START_PROPS *props)
    554 {
    555     const char *sni = 0;
    556 
    557     if (props->sni && *props->sni) {
    558 #ifndef NO_EAI
    559 	const char *aname;
    560 
    561 #endif
    562 
    563 	/*
    564 	 * MTA-STS policy plugin compatibility: with servername=hostname,
    565 	 * Postfix must send the MX hostname (not CNAME expanded).
    566 	 */
    567 	if (strcmp(props->sni, "hostname") == 0)
    568 	    sni = props->host;
    569 	else if (strcmp(props->sni, "nexthop") == 0)
    570 	    sni = props->nexthop;
    571 	else
    572 	    sni = props->sni;
    573 
    574 	/*
    575 	 * The SSL_set_tlsext_host_name() documentation does not promise that
    576 	 * every implementation will convert U-label form to A-label form.
    577 	 */
    578 #ifndef NO_EAI
    579 	if (!allascii(sni) && (aname = midna_domain_to_ascii(sni)) != 0) {
    580 	    if (msg_verbose)
    581 		msg_info("%s asciified to %s", sni, aname);
    582 	    sni = aname;
    583 	}
    584 #endif
    585     }
    586     switch (TLScontext->level) {
    587     case TLS_LEV_HALF_DANE:
    588     case TLS_LEV_DANE:
    589     case TLS_LEV_DANE_ONLY:
    590 
    591 	/*
    592 	 * With DANE sessions, send an SNI hint.  We don't care whether the
    593 	 * server reports finding a matching certificate or not, so no
    594 	 * callback is required to process the server response.  Our use of
    595 	 * SNI is limited to giving servers that make use of SNI the best
    596 	 * opportunity to find the certificate they promised via the
    597 	 * associated TLSA RRs.
    598 	 *
    599 	 * Since the hostname is DNSSEC-validated, it must be a DNS FQDN and
    600 	 * therefore valid for use with SNI.
    601 	 */
    602 	if (SSL_dane_enable(TLScontext->con, 0) <= 0) {
    603 	    /* TLSRPT: Local resource error, don't report. */
    604 	    msg_warn("%s: error enabling DANE-based certificate validation",
    605 		     TLScontext->namaddr);
    606 	    tls_print_errors();
    607 	    return (0);
    608 	}
    609 	/* RFC7672 Section 3.1.1 specifies no name checks for DANE-EE(3) */
    610 	SSL_dane_set_flags(TLScontext->con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
    611 
    612 	/* Per RFC7672 the SNI name is the TLSA base domain */
    613 	sni = props->dane->base_domain;
    614 	add_namechecks(TLScontext, props);
    615 	break;
    616 
    617     case TLS_LEV_FPRINT:
    618 	/* Synthetic DANE for fingerprint security */
    619 	if (SSL_dane_enable(TLScontext->con, 0) <= 0) {
    620 	    /* TLSRPT: Local resource error, don't report. */
    621 	    msg_warn("%s: error enabling fingerprint certificate validation",
    622 		     props->namaddr);
    623 	    tls_print_errors();
    624 	    return (0);
    625 	}
    626 	SSL_dane_set_flags(TLScontext->con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
    627 	break;
    628 
    629     case TLS_LEV_SECURE:
    630     case TLS_LEV_VERIFY:
    631 	if (TLScontext->dane != 0 && TLScontext->dane->tlsa != 0) {
    632 	    /* Synthetic DANE for per-destination trust-anchors */
    633 	    if (SSL_dane_enable(TLScontext->con, NULL) <= 0) {
    634 		/* TLSRPT: Local resource error, don't report. */
    635 		msg_warn("%s: error configuring local trust anchors",
    636 			 props->namaddr);
    637 		tls_print_errors();
    638 		return (0);
    639 	    }
    640 	}
    641 	add_namechecks(TLScontext, props);
    642 	break;
    643     default:
    644 	break;
    645     }
    646 
    647     if (sni) {
    648 	if (strlen(sni) > TLSEXT_MAXLEN_host_name) {
    649 	    /* TLSRPT: Local configuration error, don't report. */
    650 	    msg_warn("%s: ignoring too long SNI hostname: %.100s",
    651 		     props->namaddr, sni);
    652 	    return (0);
    653 	}
    654 
    655 	/*
    656 	 * Failure to set a valid SNI hostname is a memory allocation error,
    657 	 * and thus transient.  Since we must not cache the session if we
    658 	 * failed to send the SNI name, we have little choice but to abort.
    659 	 */
    660 	if (!SSL_set_tlsext_host_name(TLScontext->con, sni)) {
    661 	    /* TLSRPT: Local resource or configuration error, don't report. */
    662 	    msg_warn("%s: error setting SNI hostname to: %s", props->namaddr,
    663 		     sni);
    664 	    return (0);
    665 	}
    666 
    667 	/*
    668 	 * The saved value is not presently used client-side, but could later
    669 	 * be logged if acked by the server (requires new client-side
    670 	 * callback to detect the ack).  For now this just maintains symmetry
    671 	 * with the server code, where do record the received SNI for
    672 	 * logging.
    673 	 */
    674 	TLScontext->peer_sni = mystrdup(sni);
    675 	if (TLScontext->log_mask & TLS_LOG_DEBUG)
    676 	    msg_info("%s: SNI hostname: %s", props->namaddr, sni);
    677     }
    678     return (1);
    679 }
    680 
    681 /* tls_client_init - initialize client-side TLS engine */
    682 
    683 TLS_APPL_STATE *tls_client_init(const TLS_CLIENT_INIT_PROPS *props)
    684 {
    685     SSL_CTX *client_ctx;
    686     TLS_APPL_STATE *app_ctx;
    687     const EVP_MD *fpt_alg;
    688     long    off = 0;
    689     int     cachable;
    690     int     scache_timeout;
    691     int     log_mask;
    692 
    693     /*
    694      * Convert user loglevel to internal logmask.
    695      */
    696     log_mask = tls_log_mask(props->log_param, props->log_level);
    697 
    698     if (log_mask & TLS_LOG_VERBOSE)
    699 	msg_info("initializing the client-side TLS engine");
    700 
    701     /*
    702      * Load (mostly cipher related) TLS-library internal main.cf parameters.
    703      */
    704     tls_param_init();
    705 
    706     /*
    707      * Detect mismatch between compile-time headers and run-time library.
    708      */
    709     tls_check_version();
    710 
    711     /*
    712      * Initialize the OpenSSL library, possibly loading its configuration
    713      * file.
    714      */
    715     if (tls_library_init() == 0)
    716 	return (0);
    717 
    718     /*
    719      * Create an application data index for SSL objects, so that we can
    720      * attach TLScontext information; this information is needed inside
    721      * tls_verify_certificate_callback().
    722      */
    723     if (TLScontext_index < 0) {
    724 	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) {
    725 	    msg_warn("Cannot allocate SSL application data index: "
    726 		     "disabling TLS support");
    727 	    return (0);
    728 	}
    729     }
    730 
    731     /*
    732      * If the administrator specifies an unsupported digest algorithm, fail
    733      * now, rather than in the middle of a TLS handshake.
    734      */
    735     if ((fpt_alg = tls_validate_digest(props->mdalg)) == 0) {
    736 	msg_warn("disabling TLS support");
    737 	return (0);
    738     }
    739 
    740     /*
    741      * Initialize the PRNG (Pseudo Random Number Generator) with some seed
    742      * from external and internal sources. Don't enable TLS without some real
    743      * entropy.
    744      */
    745     if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
    746 	msg_warn("no entropy for TLS key generation: disabling TLS support");
    747 	return (0);
    748     }
    749     tls_int_seed();
    750 
    751     /*
    752      * The SSL/TLS specifications require the client to send a message in the
    753      * oldest specification it understands with the highest level it
    754      * understands in the message. RFC2487 is only specified for TLSv1, but
    755      * we want to be as compatible as possible, so we will start off with a
    756      * SSLv2 greeting allowing the best we can offer: TLSv1. We can restrict
    757      * this with the options setting later, anyhow.
    758      */
    759     ERR_clear_error();
    760     client_ctx = SSL_CTX_new(TLS_client_method());
    761     if (client_ctx == 0) {
    762 	msg_warn("cannot allocate client SSL_CTX: disabling TLS support");
    763 	tls_print_errors();
    764 	return (0);
    765     }
    766 #ifdef SSL_SECOP_PEER
    767     /* Backwards compatible security as a base for opportunistic TLS. */
    768     SSL_CTX_set_security_level(client_ctx, 0);
    769 #endif
    770 
    771     /*
    772      * See the verify callback in tls_verify.c
    773      */
    774     SSL_CTX_set_verify_depth(client_ctx, props->verifydepth + 1);
    775 
    776     /*
    777      * This is a prerequisite for enabling DANE support in OpenSSL, but not a
    778      * commitment to use DANE, thus suitable for both DANE and non-DANE TLS
    779      * connections.  Indeed we need this not just for DANE, but aslo for
    780      * fingerprint and "tafile" support.  Since it just allocates memory, it
    781      * should never fail except when we're likely to fail anyway.  Rather
    782      * than try to run with crippled TLS support, just give up using TLS.
    783      */
    784     if (SSL_CTX_dane_enable(client_ctx) <= 0) {
    785 	msg_warn("OpenSSL DANE initialization failed: disabling TLS support");
    786 	tls_print_errors();
    787 	return (0);
    788     }
    789     tls_dane_digest_init(client_ctx, fpt_alg);
    790 
    791     /*
    792      * Presently we use TLS only with SMTP where truncation attacks are not
    793      * possible as a result of application framing.  If we ever use TLS in
    794      * some other application protocol where truncation could be relevant,
    795      * we'd need to disable truncation detection conditionally, or explicitly
    796      * clear the option in that code path.
    797      */
    798     off |= SSL_OP_IGNORE_UNEXPECTED_EOF;
    799 
    800     /*
    801      * Protocol selection is destination dependent, so we delay the protocol
    802      * selection options to the per-session SSL object.
    803      */
    804     off |= tls_bug_bits();
    805     SSL_CTX_set_options(client_ctx, off);
    806 
    807     /*
    808      * Set the call-back routine for verbose logging.
    809      */
    810     if (log_mask & TLS_LOG_DEBUG)
    811 	SSL_CTX_set_info_callback(client_ctx, tls_info_callback);
    812 
    813     /*
    814      * Load the CA public key certificates for both the client cert and for
    815      * the verification of server certificates. As provided by OpenSSL we
    816      * support two types of CA certificate handling: One possibility is to
    817      * add all CA certificates to one large CAfile, the other possibility is
    818      * a directory pointed to by CApath, containing separate files for each
    819      * CA with softlinks named after the hash values of the certificate. The
    820      * first alternative has the advantage that the file is opened and read
    821      * at startup time, so that you don't have the hassle to maintain another
    822      * copy of the CApath directory for chroot-jail.
    823      */
    824     if (tls_set_ca_certificate_info(client_ctx,
    825 				    props->CAfile, props->CApath) < 0) {
    826 	/* tls_set_ca_certificate_info() already logs a warning. */
    827 	SSL_CTX_free(client_ctx);		/* 200411 */
    828 	return (0);
    829     }
    830 
    831     /*
    832      * We do not need a client certificate, so the certificates are only
    833      * loaded (and checked) if supplied. A clever client would handle
    834      * multiple client certificates and decide based on the list of
    835      * acceptable CAs, sent by the server, which certificate to submit.
    836      * OpenSSL does however not do this and also has no call-back hooks to
    837      * easily implement it.
    838      *
    839      * Load the client public key certificate and private key from file and
    840      * check whether the cert matches the key. We can use RSA certificates
    841      * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
    842      * All three can be made available at the same time. The CA certificates
    843      * for all three are handled in the same setup already finished. Which
    844      * one is used depends on the cipher negotiated (that is: the first
    845      * cipher listed by the client which does match the server). The client
    846      * certificate is presented after the server chooses the session cipher,
    847      * so we will just present the right cert for the chosen cipher (if it
    848      * uses certificates).
    849      */
    850     if (tls_set_my_certificate_key_info(client_ctx,
    851 					props->chain_files,
    852 					props->cert_file,
    853 					props->key_file,
    854 					props->dcert_file,
    855 					props->dkey_file,
    856 					props->eccert_file,
    857 					props->eckey_file) < 0) {
    858 	/* tls_set_my_certificate_key_info() already logs a warning. */
    859 	SSL_CTX_free(client_ctx);		/* 200411 */
    860 	return (0);
    861     }
    862 
    863     /*
    864      * Enable support for client->server raw public keys, provided we
    865      * actually have keys to send.  They'll only be used if the server also
    866      * enables client RPKs.
    867      *
    868      * XXX: When the server requests client auth, the TLS 1.2 protocol does not
    869      * provide an unambiguous mechanism for the client to not send an RPK (as
    870      * it can with client X.509 certs or TLS 1.3).  This is why we don't just
    871      * enable client RPK also with no keys in hand.
    872      *
    873      * A very unlikely scenario is that the server allows clients to not send
    874      * keys, but only accepts keys for a set of algorithms we don't have.
    875      * Then we still can't send a key, but have agreed to RPK.  OpenSSL will
    876      * attempt to send an empty RPK even with TLS 1.2 (and will accept such a
    877      * message), but other implementations may be more strict.
    878      *
    879      * We could limit client RPK support to connections that support only TLS
    880      * 1.3 and up, but that's practical only decades in the future, and the
    881      * risk scenario is contrived and very unlikely.
    882      */
    883     if (SSL_CTX_get0_certificate(client_ctx) != NULL &&
    884 	SSL_CTX_get0_privatekey(client_ctx) != NULL)
    885 	tls_enable_client_rpk(client_ctx, NULL);
    886 
    887     /*
    888      * With OpenSSL 1.0.2 and later the client EECDH curve list becomes
    889      * configurable with the preferred curve negotiated via the supported
    890      * curves extension.  With OpenSSL 3.0 and TLS 1.3, the same applies to
    891      * the FFDHE groups which become part of a unified "groups" list.
    892      */
    893     tls_auto_groups(client_ctx, var_tls_eecdh_auto, var_tls_ffdhe_auto);
    894 
    895     /*
    896      * Finally, the setup for the server certificate checking, done "by the
    897      * book".
    898      */
    899     SSL_CTX_set_verify(client_ctx, SSL_VERIFY_NONE,
    900 		       tls_verify_certificate_callback);
    901 
    902     /*
    903      * Initialize the session cache.
    904      *
    905      * Since the client does not search an internal cache, we simply disable it.
    906      * It is only useful for expiring old sessions, but we do that in the
    907      * tlsmgr(8).
    908      *
    909      * This makes SSL_CTX_remove_session() not useful for flushing broken
    910      * sessions from the external cache, so we must delete them directly (not
    911      * via a callback).
    912      */
    913     if (tls_mgr_policy(props->cache_type, &cachable,
    914 		       &scache_timeout) != TLS_MGR_STAT_OK)
    915 	scache_timeout = 0;
    916     if (scache_timeout <= 0)
    917 	cachable = 0;
    918 
    919     /*
    920      * Allocate an application context, and populate with mandatory protocol
    921      * and cipher data.
    922      */
    923     app_ctx = tls_alloc_app_context(client_ctx, 0, log_mask);
    924 
    925     /*
    926      * The external session cache is implemented by the tlsmgr(8) process.
    927      */
    928     if (cachable) {
    929 
    930 	app_ctx->cache_type = mystrdup(props->cache_type);
    931 
    932 	/*
    933 	 * OpenSSL does not use callbacks to load sessions from a client
    934 	 * cache, so we must invoke that function directly. Apparently,
    935 	 * OpenSSL does not provide a way to pass session names from here to
    936 	 * call-back routines that do session lookup.
    937 	 *
    938 	 * OpenSSL can, however, automatically save newly created sessions for
    939 	 * us by callback (we create the session name in the call-back
    940 	 * function).
    941 	 *
    942 	 * XXX gcc 2.95 can't compile #ifdef .. #endif in the expansion of
    943 	 * SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE |
    944 	 * SSL_SESS_CACHE_NO_AUTO_CLEAR.
    945 	 */
    946 #ifndef SSL_SESS_CACHE_NO_INTERNAL_STORE
    947 #define SSL_SESS_CACHE_NO_INTERNAL_STORE 0
    948 #endif
    949 
    950 	SSL_CTX_set_session_cache_mode(client_ctx,
    951 				       SSL_SESS_CACHE_CLIENT |
    952 				       SSL_SESS_CACHE_NO_INTERNAL_STORE |
    953 				       SSL_SESS_CACHE_NO_AUTO_CLEAR);
    954 	SSL_CTX_sess_set_new_cb(client_ctx, new_client_session_cb);
    955 
    956 	/*
    957 	 * OpenSSL ignores timed-out sessions. We need to set the internal
    958 	 * cache timeout at least as high as the external cache timeout. This
    959 	 * applies even if no internal cache is used.  We set the session to
    960 	 * twice the cache lifetime.  This way a session always lasts longer
    961 	 * than its lifetime in the cache.
    962 	 */
    963 	SSL_CTX_set_timeout(client_ctx, 2 * scache_timeout);
    964     }
    965     return (app_ctx);
    966 }
    967 
    968  /*
    969   * This is the actual startup routine for the connection. We expect that the
    970   * buffers are flushed and the "220 Ready to start TLS" was received by us,
    971   * so that we can immediately start the TLS handshake process.
    972   */
    973 TLS_SESS_STATE *tls_client_start(const TLS_CLIENT_START_PROPS *props)
    974 {
    975     int     sts;
    976     int     protomask;
    977     int     min_proto;
    978     int     max_proto;
    979     const char *cipher_list;
    980     SSL_SESSION *session = 0;
    981     TLS_SESS_STATE *TLScontext;
    982     TLS_APPL_STATE *app_ctx = props->ctx;
    983     int     log_mask = app_ctx->log_mask;
    984 
    985     /*
    986      * When certificate verification is required, log trust chain validation
    987      * errors even when disabled by default for opportunistic sessions. For
    988      * DANE this only applies when using trust-anchor associations.
    989      */
    990     if (TLS_MUST_MATCH(props->tls_level))
    991 	log_mask |= TLS_LOG_UNTRUSTED;
    992 
    993     if (log_mask & TLS_LOG_VERBOSE)
    994 	msg_info("setting up TLS connection to %s", props->namaddr);
    995 
    996     /*
    997      * First make sure we have valid protocol and cipher parameters
    998      *
    999      * Per-session protocol restrictions must be applied to the SSL connection,
   1000      * as restrictions in the global context cannot be cleared.
   1001      */
   1002     protomask = tls_proto_mask_lims(props->protocols, &min_proto, &max_proto);
   1003     if (protomask == TLS_PROTOCOL_INVALID) {
   1004 	/* TLSRPT: Local configuration error, don't report. */
   1005 	/* tls_protocol_mask() logs no warning. */
   1006 	msg_warn("%s: Invalid TLS protocol list \"%s\": aborting TLS session",
   1007 		 props->namaddr, props->protocols);
   1008 	return (0);
   1009     }
   1010 
   1011     /*
   1012      * Though RFC7672 set the floor at SSLv3, we really can and should
   1013      * require TLS 1.0, since e.g. we send SNI, which is a TLS 1.0 extension.
   1014      * No DANE domains have been observed to support only SSLv3.
   1015      *
   1016      * XXX: Would be nice to make that TLS 1.2 at some point.  Users can choose
   1017      * to exclude TLS 1.0 and TLS 1.1 if they find they don't run into any
   1018      * problems doing that.
   1019      */
   1020     if (TLS_DANE_BASED(props->tls_level))
   1021 	protomask |= TLS_PROTOCOL_SSLv2 | TLS_PROTOCOL_SSLv3;
   1022 
   1023     /*
   1024      * Allocate a new TLScontext for the new connection and get an SSL
   1025      * structure. Add the location of TLScontext to the SSL to later retrieve
   1026      * the information inside the tls_verify_certificate_callback().
   1027      *
   1028      * If session caching was enabled when TLS was initialized, the cache type
   1029      * is stored in the client SSL context.
   1030      */
   1031     TLScontext = tls_alloc_sess_context(log_mask, props->namaddr);
   1032     TLScontext->cache_type = app_ctx->cache_type;
   1033     TLScontext->level = props->tls_level;
   1034 
   1035     if ((TLScontext->con = SSL_new(app_ctx->ssl_ctx)) == NULL) {
   1036 	/* TLSRPT: Local resource error, don't report. */
   1037 	msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
   1038 	tls_print_errors();
   1039 	tls_free_context(TLScontext);
   1040 	return (0);
   1041     }
   1042 
   1043     /*
   1044      * Per session cipher selection for sessions with mandatory encryption
   1045      *
   1046      * The cipherlist is applied to the global SSL context, since it is likely
   1047      * to stay the same between connections, so we make use of a 1-element
   1048      * cache to return the same result for identical inputs.
   1049      */
   1050     cipher_list = tls_set_ciphers(TLScontext, props->cipher_grade,
   1051 				  props->cipher_exclusions);
   1052     if (cipher_list == 0) {
   1053 	/* TLSRPT: Local configuration error, don't report. */
   1054 	/* already warned */
   1055 	tls_free_context(TLScontext);
   1056 	return (0);
   1057     }
   1058     if (log_mask & TLS_LOG_VERBOSE)
   1059 	msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
   1060 
   1061     TLScontext->stream = props->stream;
   1062     TLScontext->mdalg = props->mdalg;
   1063 
   1064     /* Alias DANE digest info from props */
   1065     TLScontext->dane = props->dane;
   1066 
   1067     if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
   1068 	/* TLSRPT: Local resource error, don't report. */
   1069 	msg_warn("Could not set application data for 'TLScontext->con'");
   1070 	tls_print_errors();
   1071 	tls_free_context(TLScontext);
   1072 	return (0);
   1073     }
   1074 #define CARP_VERSION(which) do { \
   1075         if (which##_proto != 0) \
   1076             msg_warn("%s: error setting %simum TLS version to: 0x%04x", \
   1077                      TLScontext->namaddr, #which, which##_proto); \
   1078         else \
   1079             msg_warn("%s: error clearing %simum TLS version", \
   1080                      TLScontext->namaddr, #which); \
   1081     } while (0)
   1082 
   1083     /*
   1084      * Apply session protocol restrictions.
   1085      */
   1086     if (protomask != 0)
   1087 	SSL_set_options(TLScontext->con, TLS_SSL_OP_PROTOMASK(protomask));
   1088     if (!SSL_set_min_proto_version(TLScontext->con, min_proto))
   1089 	CARP_VERSION(min);
   1090     if (!SSL_set_max_proto_version(TLScontext->con, max_proto))
   1091 	CARP_VERSION(max);
   1092 
   1093     /*
   1094      * When applicable, configure DNS-based or synthetic (fingerprint or
   1095      * local trust anchor) DANE authentication, enable an appropriate SNI
   1096      * name and peer name matching.
   1097      *
   1098      * NOTE, this can change the effective security level, and needs to happen
   1099      * early.
   1100      */
   1101     if (!tls_auth_enable(TLScontext, props)) {
   1102 	/* Already warned and reported TLSRPT result. */
   1103 	tls_free_context(TLScontext);
   1104 	return (0);
   1105     }
   1106 
   1107     /*
   1108      * Possibly enable RFC7250 raw public keys in non-DANE/non-PKI levels
   1109      * when the fingerprint mask includes only public keys.  For "may" and
   1110      * "encrypt" this is a heuristic, since we don't use the fingerprints
   1111      * beyond reporting them in verbose logging.  If you always want certs
   1112      * with "may" and "encrypt" you'll have to tolerate them with
   1113      * "fingerprint", or use a separate transport.
   1114      */
   1115     switch (props->tls_level) {
   1116     case TLS_LEV_MAY:
   1117     case TLS_LEV_ENCRYPT:
   1118     case TLS_LEV_FPRINT:
   1119 	if (props->enable_rpk)
   1120 	    tls_enable_server_rpk(NULL, TLScontext->con);
   1121     default:
   1122 	break;
   1123     }
   1124 
   1125     /*
   1126      * Try to convey the configured TLSA records for this connection to the
   1127      * OpenSSL library.  If none are "usable", we'll fall back to "encrypt"
   1128      * when authentication is not mandatory, otherwise we must arrange to
   1129      * ensure authentication failure.
   1130      */
   1131     if (TLScontext->dane && TLScontext->dane->tlsa) {
   1132 	int     usable = tls_dane_enable(TLScontext);
   1133 	int     must_fail = usable <= 0;
   1134 
   1135 	if (usable == 0) {
   1136 	    switch (TLScontext->level) {
   1137 	    case TLS_LEV_HALF_DANE:
   1138 	    case TLS_LEV_DANE:
   1139 #ifdef USE_TLSRPT
   1140 		if (props->tlsrpt) {
   1141 		    trw_report_failure(props->tlsrpt, TLSRPT_TLSA_INVALID,
   1142 				        /* additional_info= */ (char *) 0,
   1143 				       "all-TLSA-records-unusable");
   1144 		}
   1145 #endif
   1146 		msg_warn("%s: all TLSA records unusable, fallback to "
   1147 			 "unauthenticated TLS", TLScontext->namaddr);
   1148 		must_fail = 0;
   1149 		TLScontext->level = TLS_LEV_ENCRYPT;
   1150 		break;
   1151 
   1152 	    case TLS_LEV_FPRINT:
   1153 #ifdef USE_TLSRPT
   1154 		if (props->tlsrpt) {
   1155 		    trw_report_failure(props->tlsrpt, TLSRPT_VALIDATION_FAILURE,
   1156 				        /* additional_info= */ (char *) 0,
   1157 				       "all-fingerprints-unusable");
   1158 		}
   1159 #endif
   1160 		msg_warn("%s: all fingerprints unusable", TLScontext->namaddr);
   1161 		break;
   1162 	    case TLS_LEV_DANE_ONLY:
   1163 #ifdef USE_TLSRPT
   1164 		if (props->tlsrpt) {
   1165 		    trw_report_failure(props->tlsrpt, TLSRPT_TLSA_INVALID,
   1166 				        /* additional_info= */ (char *) 0,
   1167 				       "all-TLSA-records-unusable");
   1168 		}
   1169 #endif
   1170 		msg_warn("%s: all TLSA records unusable", TLScontext->namaddr);
   1171 		break;
   1172 	    case TLS_LEV_SECURE:
   1173 	    case TLS_LEV_VERIFY:
   1174 #ifdef USE_TLSRPT
   1175 		if (props->tlsrpt) {
   1176 		    trw_report_failure(props->tlsrpt, TLSRPT_VALIDATION_FAILURE,
   1177 				        /* additional_info= */ (char *) 0,
   1178 				       "all-trust-anchors-unusable");
   1179 		}
   1180 #endif
   1181 		msg_warn("%s: all trust anchors unusable", TLScontext->namaddr);
   1182 		break;
   1183 	    }
   1184 	}
   1185 	TLScontext->must_fail |= must_fail;
   1186     }
   1187 
   1188     /*
   1189      * We compute the policy digest after we compute the SNI name in
   1190      * tls_auth_enable() and possibly update the TLScontext security level.
   1191      *
   1192      * OpenSSL will ignore cached sessions that use the wrong protocol. So we do
   1193      * not need to filter out cached sessions with the "wrong" protocol,
   1194      * rather OpenSSL will simply negotiate a new session.
   1195      *
   1196      * We salt the session lookup key with the protocol list, so that sessions
   1197      * found in the cache are plausibly acceptable.
   1198      *
   1199      * By the time a TLS client is negotiating ciphers it has already offered to
   1200      * re-use a session, it is too late to renege on the offer. So we must
   1201      * not attempt to re-use sessions whose ciphers are too weak. We salt the
   1202      * session lookup key with the cipher list, so that sessions found in the
   1203      * cache are always acceptable.
   1204      *
   1205      * With DANE, (more generally any TLScontext where we specified explicit
   1206      * trust-anchor or end-entity certificates) the verification status of
   1207      * the SSL session depends on the specified list.  Since we verify the
   1208      * certificate only during the initial handshake, we must segregate
   1209      * sessions with different TA lists.  Note, that TA re-verification is
   1210      * not possible with cached sessions, since these don't hold the complete
   1211      * peer trust chain.  Therefore, we compute a digest of the sorted TA
   1212      * parameters and append it to the serverid.
   1213      */
   1214     TLScontext->serverid =
   1215 	tls_serverid_digest(TLScontext, props, cipher_list);
   1216 
   1217     /*
   1218      * When authenticating the peer, use 80-bit plus OpenSSL security level
   1219      *
   1220      * XXX: We should perhaps use security level 1 also for mandatory
   1221      * encryption, with only "may" tolerating weaker algorithms.  But that
   1222      * could mean no TLS 1.0 with OpenSSL >= 3.0 and encrypt, unless I get my
   1223      * patch in on time to conditionally re-enable SHA1 at security level 1,
   1224      * and we add code to make it so.
   1225      *
   1226      * That said, with "encrypt", we could reasonably require TLS 1.2?
   1227      */
   1228     if (TLS_MUST_MATCH(TLScontext->level))
   1229 	SSL_set_security_level(TLScontext->con, 1);
   1230 
   1231     /*
   1232      * XXX To avoid memory leaks we must always call SSL_SESSION_free() after
   1233      * calling SSL_set_session(), regardless of whether or not the session
   1234      * will be reused.
   1235      */
   1236     if (TLScontext->cache_type) {
   1237 	session = load_clnt_session(TLScontext);
   1238 	if (session) {
   1239 	    SSL_set_session(TLScontext->con, session);
   1240 	    SSL_SESSION_free(session);		/* 200411 */
   1241 	}
   1242     }
   1243 
   1244     /*
   1245      * Before really starting anything, try to seed the PRNG a little bit
   1246      * more.
   1247      */
   1248     tls_int_seed();
   1249     (void) tls_ext_seed(var_tls_daemon_rand_bytes);
   1250 
   1251     /*
   1252      * Connect the SSL connection with the network socket.
   1253      */
   1254     if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd :
   1255 		   vstream_fileno(props->stream)) != 1) {
   1256 	/* TLSRPT: Local resource error, don't report. */
   1257 	msg_info("SSL_set_fd error to %s", props->namaddr);
   1258 	tls_print_errors();
   1259 	uncache_session(app_ctx->ssl_ctx, TLScontext);
   1260 	tls_free_context(TLScontext);
   1261 	return (0);
   1262     }
   1263 
   1264     /*
   1265      * If the debug level selected is high enough, all of the data is dumped:
   1266      * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will
   1267      * dump everything.
   1268      *
   1269      * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
   1270      * Well there is a BIO below the SSL routines that is automatically
   1271      * created for us, so we can use it for debugging purposes.
   1272      */
   1273     if (log_mask & TLS_LOG_TLSPKTS)
   1274 	tls_set_bio_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
   1275 
   1276     /*
   1277      * An external (STS) policy signaled a failure. Prevent false (PKI)
   1278      * certificate matches in tls_verify.c. TODO(wietse) how was this handled
   1279      * historically?
   1280      */
   1281     if (props->ffail_type) {
   1282 	TLScontext->ffail_type = mystrdup(props->ffail_type);
   1283 	TLScontext->must_fail = 1;
   1284     }
   1285 
   1286     /*
   1287      * If we don't trigger the handshake in the library, leave control over
   1288      * SSL_connect/read/write/etc with the application.
   1289      */
   1290     if (props->stream == 0)
   1291 	return (TLScontext);
   1292 
   1293     /*
   1294      * Turn on non-blocking I/O so that we can enforce timeouts on network
   1295      * I/O.
   1296      */
   1297     non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
   1298 
   1299     /*
   1300      * Start TLS negotiations. This process is a black box that invokes our
   1301      * call-backs for certificate verification.
   1302      *
   1303      * Error handling: If the SSL handshake fails, we print out an error message
   1304      * and remove all TLS state concerning this session.
   1305      */
   1306     sts = tls_bio_connect(vstream_fileno(props->stream), props->timeout,
   1307 			  TLScontext);
   1308     if (sts <= 0) {
   1309 	if (ERR_peek_error() != 0) {
   1310 	    msg_info("SSL_connect error to %s: %d", props->namaddr, sts);
   1311 	    tls_print_errors();
   1312 	} else if (errno != 0) {
   1313 	    msg_info("SSL_connect error to %s: %m", props->namaddr);
   1314 	} else {
   1315 	    msg_info("SSL_connect error to %s: lost connection",
   1316 		     props->namaddr);
   1317 	}
   1318 #ifdef USE_TLSRPT
   1319 	if (props->tlsrpt)
   1320 	    trw_report_failure(props->tlsrpt, TLSRPT_VALIDATION_FAILURE,
   1321 			        /* additional_info= */ (char *) 0,
   1322 			       "tls-handshake-failure");
   1323 #endif
   1324 	uncache_session(app_ctx->ssl_ctx, TLScontext);
   1325 	tls_free_context(TLScontext);
   1326 	return (0);
   1327     }
   1328     return (tls_client_post_connect(TLScontext, props));
   1329 }
   1330 
   1331 /* tls_client_post_connect - post-handshake processing */
   1332 
   1333 TLS_SESS_STATE *tls_client_post_connect(TLS_SESS_STATE *TLScontext,
   1334 				        const TLS_CLIENT_START_PROPS *props)
   1335 {
   1336     const SSL_CIPHER *cipher;
   1337     X509   *peercert;
   1338     EVP_PKEY *peerpkey = 0;
   1339 
   1340     /* Turn off packet dump if only dumping the handshake */
   1341     if ((TLScontext->log_mask & TLS_LOG_ALLPKTS) == 0)
   1342 	tls_set_bio_callback(SSL_get_rbio(TLScontext->con), 0);
   1343 
   1344     /*
   1345      * The caller may want to know if this session was reused or if a new
   1346      * session was negotiated.
   1347      */
   1348     TLScontext->session_reused = SSL_session_reused(TLScontext->con);
   1349     if ((TLScontext->log_mask & TLS_LOG_CACHE) && TLScontext->session_reused)
   1350 	msg_info("%s: Reusing old session", TLScontext->namaddr);
   1351 
   1352     /*
   1353      * Do peername verification if requested and extract useful information
   1354      * from the certificate for later use.
   1355      */
   1356     peercert = TLS_PEEK_PEER_CERT(TLScontext->con);
   1357     if (peercert != 0) {
   1358 	peerpkey = X509_get0_pubkey(peercert);
   1359     }
   1360 #if OPENSSL_VERSION_PREREQ(3,2)
   1361     else {
   1362 	peerpkey = SSL_get0_peer_rpk(TLScontext->con);
   1363     }
   1364 #endif
   1365 
   1366     if (peercert != 0) {
   1367 	TLScontext->peer_status |= TLS_CRED_FLAG_CERT;
   1368 
   1369 	/*
   1370 	 * Peer name or fingerprint verification as requested.
   1371 	 * Unconditionally set peer_CN, issuer_CN and peer_cert_fprint. Check
   1372 	 * fingerprint first, and avoid logging verified as untrusted in the
   1373 	 * call to verify_x509().
   1374 	 */
   1375 	TLScontext->peer_cert_fprint =
   1376 	    tls_cert_fprint(peercert, props->mdalg);
   1377 	TLScontext->peer_pkey_fprint =
   1378 	    tls_pkey_fprint(peerpkey, props->mdalg);
   1379 	verify_x509(TLScontext, peercert, props);
   1380 
   1381 	if (TLScontext->log_mask &
   1382 	    (TLS_LOG_CERTMATCH | TLS_LOG_VERBOSE | TLS_LOG_PEERCERT))
   1383 	    msg_info("%s: subject_CN=%s, issuer=%s%s%s%s%s",
   1384 		     TLScontext->namaddr,
   1385 		     TLScontext->peer_CN, TLScontext->issuer_CN,
   1386 		     *TLScontext->peer_cert_fprint ?
   1387 		     ", cert fingerprint=" : "",
   1388 		     *TLScontext->peer_cert_fprint ?
   1389 		     TLScontext->peer_cert_fprint : "",
   1390 		     *TLScontext->peer_pkey_fprint ?
   1391 		     ", pkey fingerprint=" : "",
   1392 		     *TLScontext->peer_pkey_fprint ?
   1393 		     TLScontext->peer_pkey_fprint : "");
   1394     } else {
   1395 	TLScontext->issuer_CN = mystrdup("");
   1396 	TLScontext->peer_CN = mystrdup("");
   1397 	TLScontext->peer_cert_fprint = mystrdup("");
   1398 
   1399 	if (!peerpkey) {
   1400 	    TLScontext->peer_pkey_fprint = mystrdup("");
   1401 	} else {
   1402 	    TLScontext->peer_status |= TLS_CRED_FLAG_RPK;
   1403 	    TLScontext->peer_pkey_fprint =
   1404 		tls_pkey_fprint(peerpkey, props->mdalg);
   1405 	    if (TLScontext->log_mask &
   1406 		(TLS_LOG_CERTMATCH | TLS_LOG_VERBOSE | TLS_LOG_PEERCERT))
   1407 		msg_info("%s: raw public key fingerprint=%s", props->namaddr,
   1408 			 TLScontext->peer_pkey_fprint);
   1409 	    verify_rpk(TLScontext, peerpkey, props);
   1410 	}
   1411     }
   1412 
   1413     /*
   1414      * Finally, collect information about protocol and cipher for logging
   1415      */
   1416     TLScontext->protocol = SSL_get_version(TLScontext->con);
   1417     cipher = SSL_get_current_cipher(TLScontext->con);
   1418     TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
   1419     TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
   1420 					     &(TLScontext->cipher_algbits));
   1421 
   1422     /*
   1423      * The TLS engine is active. Switch to the tls_timed_read/write()
   1424      * functions and make the TLScontext available to those functions.
   1425      */
   1426     if (TLScontext->stream != 0)
   1427 	tls_stream_start(props->stream, TLScontext);
   1428 
   1429     /*
   1430      * With the handshake done, extract TLS 1.3 signature metadata.
   1431      */
   1432     tls_get_signature_params(TLScontext);
   1433 
   1434     if (TLScontext->log_mask & TLS_LOG_SUMMARY)
   1435 	tls_log_summary(TLS_ROLE_CLIENT, TLS_USAGE_NEW, TLScontext);
   1436 
   1437     tls_int_seed();
   1438 
   1439     /*
   1440      * Precondition: tls_client_start() is called only for a new TCP
   1441      * connection. It is never called for a reused TCP connection.
   1442      *
   1443      * Inform the caller that they should not generate a TLSRPT 'success' or
   1444      * 'failure' event: either this TLS protocol engine has already generated
   1445      * a TLSRPT 'failure' event for this session, or this is a reused TLS
   1446      * session.
   1447      */
   1448 #ifdef USE_TLSRPT
   1449     TLScontext->rpt_reported = props->tlsrpt != 0
   1450 	&& (trw_is_reported(props->tlsrpt)
   1451 	    || (TLScontext->session_reused
   1452 		&& trw_is_skip_reused_hs(props->tlsrpt)));
   1453 #endif
   1454 
   1455     return (TLScontext);
   1456 }
   1457 
   1458 #endif					/* USE_TLS */
   1459