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