xref: /netbsd-src/external/ibm-public/postfix/dist/src/tls/tls_client.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: tls_client.c,v 1.9 2014/07/06 19:45:50 tron 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 /*	void	tls_client_stop(app_ctx, stream, failure, TLScontext)
18 /*	TLS_APPL_STATE *app_ctx;
19 /*	VSTREAM	*stream;
20 /*	int	failure;
21 /*	TLS_SESS_STATE *TLScontext;
22 /* DESCRIPTION
23 /*	This module is the interface between Postfix TLS clients,
24 /*	the OpenSSL library and the TLS entropy and cache manager.
25 /*
26 /*	The SMTP client will attempt to verify the server hostname
27 /*	against the names listed in the server certificate. When
28 /*	a hostname match is required, the verification fails
29 /*	on certificate verification or hostname mis-match errors.
30 /*	When no hostname match is required, hostname verification
31 /*	failures are logged but they do not affect the TLS handshake
32 /*	or the SMTP session.
33 /*
34 /*	The rules for peer name wild-card matching differ between
35 /*	RFC 2818 (HTTP over TLS) and RFC 2830 (LDAP over TLS), while
36 /*	RFC RFC3207 (SMTP over TLS) does not specify a rule at all.
37 /*	Postfix uses a restrictive match algorithm. One asterisk
38 /*	('*') is allowed as the left-most component of a wild-card
39 /*	certificate name; it matches the left-most component of
40 /*	the peer hostname.
41 /*
42 /*	Another area where RFCs aren't always explicit is the
43 /*	handling of dNSNames in peer certificates. RFC 3207 (SMTP
44 /*	over TLS) does not mention dNSNames. Postfix follows the
45 /*	strict rules in RFC 2818 (HTTP over TLS), section 3.1: The
46 /*	Subject Alternative Name/dNSName has precedence over
47 /*	CommonName.  If at least one dNSName is provided, Postfix
48 /*	verifies those against the peer hostname and ignores the
49 /*	CommonName, otherwise Postfix verifies the CommonName
50 /*	against the peer hostname.
51 /*
52 /*	tls_client_init() is called once when the SMTP client
53 /*	initializes.
54 /*	Certificate details are also decided during this phase,
55 /*	so peer-specific certificate selection is not possible.
56 /*
57 /*	tls_client_start() activates the TLS session over an established
58 /*	stream. We expect that network buffers are flushed and
59 /*	the TLS handshake can begin immediately.
60 /*
61 /*	tls_client_stop() sends the "close notify" alert via
62 /*	SSL_shutdown() to the peer and resets all connection specific
63 /*	TLS data. As RFC2487 does not specify a separate shutdown, it
64 /*	is assumed that the underlying TCP connection is shut down
65 /*	immediately afterwards. Any further writes to the channel will
66 /*	be discarded, and any further reads will report end-of-file.
67 /*	If the failure flag is set, no SSL_shutdown() handshake is performed.
68 /*
69 /*	Once the TLS connection is initiated, information about the TLS
70 /*	state is available via the TLScontext structure:
71 /* .IP TLScontext->protocol
72 /*	the protocol name (SSLv2, SSLv3, TLSv1),
73 /* .IP TLScontext->cipher_name
74 /*	the cipher name (e.g. RC4/MD5),
75 /* .IP TLScontext->cipher_usebits
76 /*	the number of bits actually used (e.g. 40),
77 /* .IP TLScontext->cipher_algbits
78 /*	the number of bits the algorithm is based on (e.g. 128).
79 /* .PP
80 /*	The last two values may differ from each other when export-strength
81 /*	encryption is used.
82 /*
83 /*	If the peer offered a certificate, part of the certificate data are
84 /*	available as:
85 /* .IP TLScontext->peer_status
86 /*	A bitmask field that records the status of the peer certificate
87 /*	verification. This consists of one or more of
88 /*	TLS_CERT_FLAG_PRESENT, TLS_CERT_FLAG_ALTNAME, TLS_CERT_FLAG_TRUSTED
89 /*	and TLS_CERT_FLAG_MATCHED.
90 /* .IP TLScontext->peer_CN
91 /*	Extracted CommonName of the peer, or zero-length string if the
92 /*	information could not be extracted.
93 /* .IP TLScontext->issuer_CN
94 /*	Extracted CommonName of the issuer, or zero-length string if the
95 /*	information could not be extracted.
96 /* .IP TLScontext->peer_cert_fprint
97 /*	At the fingerprint security level, if the peer presented a certificate
98 /*	the fingerprint of the certificate.
99 /* .PP
100 /*	If no peer certificate is presented the peer_status is set to 0.
101 /* LICENSE
102 /* .ad
103 /* .fi
104 /*	This software is free. You can do with it whatever you want.
105 /*	The original author kindly requests that you acknowledge
106 /*	the use of his software.
107 /* AUTHOR(S)
108 /*	Originally written by:
109 /*	Lutz Jaenicke
110 /*	BTU Cottbus
111 /*	Allgemeine Elektrotechnik
112 /*	Universitaetsplatz 3-4
113 /*	D-03044 Cottbus, Germany
114 /*
115 /*	Updated by:
116 /*	Wietse Venema
117 /*	IBM T.J. Watson Research
118 /*	P.O. Box 704
119 /*	Yorktown Heights, NY 10598, USA
120 /*
121 /*	Victor Duchovni
122 /*	Morgan Stanley
123 /*--*/
124 
125 /* System library. */
126 
127 #include <sys_defs.h>
128 
129 #ifdef USE_TLS
130 #include <string.h>
131 
132 #ifdef STRCASECMP_IN_STRINGS_H
133 #include <strings.h>
134 #endif
135 
136 /* Utility library. */
137 
138 #include <argv.h>
139 #include <mymalloc.h>
140 #include <vstring.h>
141 #include <vstream.h>
142 #include <stringops.h>
143 #include <msg.h>
144 #include <iostuff.h>			/* non-blocking */
145 
146 /* Global library. */
147 
148 #include <mail_params.h>
149 
150 /* TLS library. */
151 
152 #include <tls_mgr.h>
153 #define TLS_INTERNAL
154 #include <tls.h>
155 
156 /* Application-specific. */
157 
158 #define STR	vstring_str
159 #define LEN	VSTRING_LEN
160 
161 /* load_clnt_session - load session from client cache (non-callback) */
162 
163 static SSL_SESSION *load_clnt_session(TLS_SESS_STATE *TLScontext)
164 {
165     const char *myname = "load_clnt_session";
166     SSL_SESSION *session = 0;
167     VSTRING *session_data = vstring_alloc(2048);
168 
169     /*
170      * Prepare the query.
171      */
172     if (TLScontext->log_mask & TLS_LOG_CACHE)
173 	/* serverid contains transport:addr:port information */
174 	msg_info("looking for session %s in %s cache",
175 		 TLScontext->serverid, TLScontext->cache_type);
176 
177     /*
178      * We only get here if the cache_type is not empty. This code is not
179      * called unless caching is enabled and the cache_type is stored in the
180      * server SSL context.
181      */
182     if (TLScontext->cache_type == 0)
183 	msg_panic("%s: null client session cache type in session lookup",
184 		  myname);
185 
186     /*
187      * Look up and activate the SSL_SESSION object. Errors are non-fatal,
188      * since caching is only an optimization.
189      */
190     if (tls_mgr_lookup(TLScontext->cache_type, TLScontext->serverid,
191 		       session_data) == TLS_MGR_STAT_OK) {
192 	session = tls_session_activate(STR(session_data), LEN(session_data));
193 	if (session) {
194 	    if (TLScontext->log_mask & TLS_LOG_CACHE)
195 		/* serverid contains transport:addr:port information */
196 		msg_info("reloaded session %s from %s cache",
197 			 TLScontext->serverid, TLScontext->cache_type);
198 	}
199     }
200 
201     /*
202      * Clean up.
203      */
204     vstring_free(session_data);
205 
206     return (session);
207 }
208 
209 /* new_client_session_cb - name new session and save it to client cache */
210 
211 static int new_client_session_cb(SSL *ssl, SSL_SESSION *session)
212 {
213     const char *myname = "new_client_session_cb";
214     TLS_SESS_STATE *TLScontext;
215     VSTRING *session_data;
216 
217     /*
218      * The cache name (if caching is enabled in tlsmgr(8)) and the cache ID
219      * string for this session are stored in the TLScontext. It cannot be
220      * null at this point.
221      */
222     if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
223 	msg_panic("%s: null TLScontext in new session callback", myname);
224 
225     /*
226      * We only get here if the cache_type is not empty. This callback is not
227      * set unless caching is enabled and the cache_type is stored in the
228      * server SSL context.
229      */
230     if (TLScontext->cache_type == 0)
231 	msg_panic("%s: null session cache type in new session callback",
232 		  myname);
233 
234     if (TLScontext->log_mask & TLS_LOG_CACHE)
235 	/* serverid contains transport:addr:port information */
236 	msg_info("save session %s to %s cache",
237 		 TLScontext->serverid, TLScontext->cache_type);
238 
239     /*
240      * Passivate and save the session object. Errors are non-fatal, since
241      * caching is only an optimization.
242      */
243     if ((session_data = tls_session_passivate(session)) != 0) {
244 	tls_mgr_update(TLScontext->cache_type, TLScontext->serverid,
245 		       STR(session_data), LEN(session_data));
246 	vstring_free(session_data);
247     }
248 
249     /*
250      * Clean up.
251      */
252     SSL_SESSION_free(session);			/* 200502 */
253 
254     return (1);
255 }
256 
257 /* uncache_session - remove session from the external cache */
258 
259 static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext)
260 {
261     SSL_SESSION *session = SSL_get_session(TLScontext->con);
262 
263     SSL_CTX_remove_session(ctx, session);
264     if (TLScontext->cache_type == 0 || TLScontext->serverid == 0)
265 	return;
266 
267     if (TLScontext->log_mask & TLS_LOG_CACHE)
268 	/* serverid contains transport:addr:port information */
269 	msg_info("remove session %s from client cache", TLScontext->serverid);
270 
271     tls_mgr_delete(TLScontext->cache_type, TLScontext->serverid);
272 }
273 
274 /* tls_client_init - initialize client-side TLS engine */
275 
276 TLS_APPL_STATE *tls_client_init(const TLS_CLIENT_INIT_PROPS *props)
277 {
278     long    off = 0;
279     int     cachable;
280     int     scache_timeout;
281     SSL_CTX *client_ctx;
282     TLS_APPL_STATE *app_ctx;
283     int     log_mask;
284 
285     /*
286      * Convert user loglevel to internal logmask.
287      */
288     log_mask = tls_log_mask(props->log_param, props->log_level);
289 
290     if (log_mask & TLS_LOG_VERBOSE)
291 	msg_info("initializing the client-side TLS engine");
292 
293     /*
294      * Load (mostly cipher related) TLS-library internal main.cf parameters.
295      */
296     tls_param_init();
297 
298     /*
299      * Detect mismatch between compile-time headers and run-time library.
300      */
301     tls_check_version();
302 
303     /*
304      * Initialize the OpenSSL library by the book! To start with, we must
305      * initialize the algorithms. We want cleartext error messages instead of
306      * just error codes, so we load the error_strings.
307      */
308     SSL_load_error_strings();
309     OpenSSL_add_ssl_algorithms();
310 
311     /*
312      * Create an application data index for SSL objects, so that we can
313      * attach TLScontext information; this information is needed inside
314      * tls_verify_certificate_callback().
315      */
316     if (TLScontext_index < 0) {
317 	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) {
318 	    msg_warn("Cannot allocate SSL application data index: "
319 		     "disabling TLS support");
320 	    return (0);
321 	}
322     }
323 
324     /*
325      * If the administrator specifies an unsupported digest algorithm, fail
326      * now, rather than in the middle of a TLS handshake.
327      */
328     if (!tls_validate_digest(props->mdalg)) {
329 	msg_warn("disabling TLS support");
330 	return (0);
331     }
332 
333     /*
334      * Initialize the PRNG (Pseudo Random Number Generator) with some seed
335      * from external and internal sources. Don't enable TLS without some real
336      * entropy.
337      */
338     if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
339 	msg_warn("no entropy for TLS key generation: disabling TLS support");
340 	return (0);
341     }
342     tls_int_seed();
343 
344     /*
345      * The SSL/TLS specifications require the client to send a message in the
346      * oldest specification it understands with the highest level it
347      * understands in the message. RFC2487 is only specified for TLSv1, but
348      * we want to be as compatible as possible, so we will start off with a
349      * SSLv2 greeting allowing the best we can offer: TLSv1. We can restrict
350      * this with the options setting later, anyhow.
351      */
352     ERR_clear_error();
353     if ((client_ctx = SSL_CTX_new(SSLv23_client_method())) == 0) {
354 	msg_warn("cannot allocate client SSL_CTX: disabling TLS support");
355 	tls_print_errors();
356 	return (0);
357     }
358 
359     /*
360      * See the verify callback in tls_verify.c
361      */
362     SSL_CTX_set_verify_depth(client_ctx, props->verifydepth + 1);
363 
364     /*
365      * Protocol selection is destination dependent, so we delay the protocol
366      * selection options to the per-session SSL object.
367      */
368     off |= tls_bug_bits();
369     SSL_CTX_set_options(client_ctx, off);
370 
371     /*
372      * Set the call-back routine for verbose logging.
373      */
374     if (log_mask & TLS_LOG_DEBUG)
375 	SSL_CTX_set_info_callback(client_ctx, tls_info_callback);
376 
377     /*
378      * Load the CA public key certificates for both the client cert and for
379      * the verification of server certificates. As provided by OpenSSL we
380      * support two types of CA certificate handling: One possibility is to
381      * add all CA certificates to one large CAfile, the other possibility is
382      * a directory pointed to by CApath, containing separate files for each
383      * CA with softlinks named after the hash values of the certificate. The
384      * first alternative has the advantage that the file is opened and read
385      * at startup time, so that you don't have the hassle to maintain another
386      * copy of the CApath directory for chroot-jail.
387      */
388     if (tls_set_ca_certificate_info(client_ctx,
389 				    props->CAfile, props->CApath) < 0) {
390 	/* tls_set_ca_certificate_info() already logs a warning. */
391 	SSL_CTX_free(client_ctx);		/* 200411 */
392 	return (0);
393     }
394 
395     /*
396      * We do not need a client certificate, so the certificates are only
397      * loaded (and checked) if supplied. A clever client would handle
398      * multiple client certificates and decide based on the list of
399      * acceptable CAs, sent by the server, which certificate to submit.
400      * OpenSSL does however not do this and also has no call-back hooks to
401      * easily implement it.
402      *
403      * Load the client public key certificate and private key from file and
404      * check whether the cert matches the key. We can use RSA certificates
405      * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
406      * All three can be made available at the same time. The CA certificates
407      * for all three are handled in the same setup already finished. Which
408      * one is used depends on the cipher negotiated (that is: the first
409      * cipher listed by the client which does match the server). The client
410      * certificate is presented after the server chooses the session cipher,
411      * so we will just present the right cert for the chosen cipher (if it
412      * uses certificates).
413      */
414     if (tls_set_my_certificate_key_info(client_ctx,
415 					props->cert_file,
416 					props->key_file,
417 					props->dcert_file,
418 					props->dkey_file,
419 					props->eccert_file,
420 					props->eckey_file) < 0) {
421 	/* tls_set_my_certificate_key_info() already logs a warning. */
422 	SSL_CTX_free(client_ctx);		/* 200411 */
423 	return (0);
424     }
425 
426     /*
427      * According to the OpenSSL documentation, temporary RSA key is needed
428      * export ciphers are in use. We have to provide one, so well, we just do
429      * it.
430      */
431     SSL_CTX_set_tmp_rsa_callback(client_ctx, tls_tmp_rsa_cb);
432 
433     /*
434      * Finally, the setup for the server certificate checking, done "by the
435      * book".
436      */
437     SSL_CTX_set_verify(client_ctx, SSL_VERIFY_NONE,
438 		       tls_verify_certificate_callback);
439 
440     /*
441      * Initialize the session cache.
442      *
443      * Since the client does not search an internal cache, we simply disable it.
444      * It is only useful for expiring old sessions, but we do that in the
445      * tlsmgr(8).
446      *
447      * This makes SSL_CTX_remove_session() not useful for flushing broken
448      * sessions from the external cache, so we must delete them directly (not
449      * via a callback).
450      */
451     if (tls_mgr_policy(props->cache_type, &cachable,
452 		       &scache_timeout) != TLS_MGR_STAT_OK)
453 	scache_timeout = 0;
454     if (scache_timeout <= 0)
455 	cachable = 0;
456 
457     /*
458      * Allocate an application context, and populate with mandatory protocol
459      * and cipher data.
460      */
461     app_ctx = tls_alloc_app_context(client_ctx, log_mask);
462 
463     /*
464      * The external session cache is implemented by the tlsmgr(8) process.
465      */
466     if (cachable) {
467 
468 	app_ctx->cache_type = mystrdup(props->cache_type);
469 
470 	/*
471 	 * OpenSSL does not use callbacks to load sessions from a client
472 	 * cache, so we must invoke that function directly. Apparently,
473 	 * OpenSSL does not provide a way to pass session names from here to
474 	 * call-back routines that do session lookup.
475 	 *
476 	 * OpenSSL can, however, automatically save newly created sessions for
477 	 * us by callback (we create the session name in the call-back
478 	 * function).
479 	 *
480 	 * XXX gcc 2.95 can't compile #ifdef .. #endif in the expansion of
481 	 * SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE |
482 	 * SSL_SESS_CACHE_NO_AUTO_CLEAR.
483 	 */
484 #ifndef SSL_SESS_CACHE_NO_INTERNAL_STORE
485 #define SSL_SESS_CACHE_NO_INTERNAL_STORE 0
486 #endif
487 
488 	SSL_CTX_set_session_cache_mode(client_ctx,
489 				       SSL_SESS_CACHE_CLIENT |
490 				       SSL_SESS_CACHE_NO_INTERNAL_STORE |
491 				       SSL_SESS_CACHE_NO_AUTO_CLEAR);
492 	SSL_CTX_sess_set_new_cb(client_ctx, new_client_session_cb);
493 
494 	/*
495 	 * OpenSSL ignores timed-out sessions. We need to set the internal
496 	 * cache timeout at least as high as the external cache timeout. This
497 	 * applies even if no internal cache is used.  We set the session to
498 	 * twice the cache lifetime.  This way a session always lasts longer
499 	 * than its lifetime in the cache.
500 	 */
501 	SSL_CTX_set_timeout(client_ctx, 2 * scache_timeout);
502     }
503     return (app_ctx);
504 }
505 
506 /* match_servername -  match servername against pattern */
507 
508 static int match_servername(const char *certid,
509 			            const TLS_CLIENT_START_PROPS *props)
510 {
511     const ARGV *cmatch_argv;
512     const char *nexthop = props->nexthop;
513     const char *hname = props->host;
514     const char *domain;
515     const char *parent;
516     int     match_subdomain;
517     int     i;
518     int     idlen;
519     int     domlen;
520 
521     if ((cmatch_argv = props->matchargv) == 0)
522 	return 0;
523 
524     /*
525      * Match the certid against each pattern until we find a match.
526      */
527     for (i = 0; i < cmatch_argv->argc; ++i) {
528 	match_subdomain = 0;
529 	if (!strcasecmp(cmatch_argv->argv[i], "nexthop"))
530 	    domain = nexthop;
531 	else if (!strcasecmp(cmatch_argv->argv[i], "hostname"))
532 	    domain = hname;
533 	else if (!strcasecmp(cmatch_argv->argv[i], "dot-nexthop")) {
534 	    domain = nexthop;
535 	    match_subdomain = 1;
536 	} else {
537 	    domain = cmatch_argv->argv[i];
538 	    if (*domain == '.' && domain[1] != '\0') {
539 		++domain;
540 		match_subdomain = 1;
541 	    }
542 	}
543 
544 	/*
545 	 * Sub-domain match: certid is any sub-domain of hostname.
546 	 */
547 	if (match_subdomain) {
548 	    if ((idlen = strlen(certid)) > (domlen = strlen(domain)) + 1
549 		&& certid[idlen - domlen - 1] == '.'
550 		&& !strcasecmp(certid + (idlen - domlen), domain))
551 		return (1);
552 	    else
553 		continue;
554 	}
555 
556 	/*
557 	 * Exact match and initial "*" match. The initial "*" in a certid
558 	 * matches one (if var_tls_multi_label is false) or more hostname
559 	 * components under the condition that the certid contains multiple
560 	 * hostname components.
561 	 */
562 	if (!strcasecmp(certid, domain)
563 	    || (certid[0] == '*' && certid[1] == '.' && certid[2] != 0
564 		&& (parent = strchr(domain, '.')) != 0
565 		&& (idlen = strlen(certid + 1)) <= (domlen = strlen(parent))
566 		&& strcasecmp(var_tls_multi_wildcard == 0 ? parent :
567 			      parent + domlen - idlen,
568 			      certid + 1) == 0))
569 	    return (1);
570     }
571     return (0);
572 }
573 
574 /* verify_extract_name - verify peer name and extract peer information */
575 
576 static void verify_extract_name(TLS_SESS_STATE *TLScontext, X509 *peercert,
577 				        const TLS_CLIENT_START_PROPS *props)
578 {
579     int     i;
580     int     r;
581     int     matched = 0;
582     int     dnsname_match;
583     int     verify_peername = 0;
584     int     log_certmatch;
585     int     verbose;
586     const char *dnsname;
587     const GENERAL_NAME *gn;
588     general_name_stack_t *gens;
589 
590     /*
591      * On exit both peer_CN and issuer_CN should be set.
592      */
593     TLScontext->issuer_CN = tls_issuer_CN(peercert, TLScontext);
594 
595     /*
596      * Is the certificate trust chain valid and trusted?
597      */
598     if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
599 	TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
600 
601     /*
602      * With fingerprint or dane we may already be done. Otherwise, verify the
603      * peername if using traditional PKI or DANE with trust-anchors.
604      */
605     if (!TLS_CERT_IS_MATCHED(TLScontext)
606 	&& TLS_CERT_IS_TRUSTED(TLScontext)
607 	&& TLS_MUST_TRUST(props->tls_level))
608 	verify_peername = 1;
609 
610     /* Force cert processing so we can log the data? */
611     log_certmatch = TLScontext->log_mask & TLS_LOG_CERTMATCH;
612 
613     /* Log cert details when processing? */
614     verbose = log_certmatch || (TLScontext->log_mask & TLS_LOG_VERBOSE);
615 
616     if (verify_peername || log_certmatch) {
617 
618 	/*
619 	 * Verify the dNSName(s) in the peer certificate against the nexthop
620 	 * and hostname.
621 	 *
622 	 * If DNS names are present, we use the first matching (or else simply
623 	 * the first) DNS name as the subject CN. The CommonName in the
624 	 * issuer DN is obsolete when SubjectAltName is available. This
625 	 * yields much less surprising logs, because we log the name we
626 	 * verified or a name we checked and failed to match.
627 	 *
628 	 * XXX: The nexthop and host name may both be the same network address
629 	 * rather than a DNS name. In this case we really should be looking
630 	 * for GEN_IPADD entries, not GEN_DNS entries.
631 	 *
632 	 * XXX: In ideal world the caller who used the address to build the
633 	 * connection would tell us that the nexthop is the connection
634 	 * address, but if that is not practical, we can parse the nexthop
635 	 * again here.
636 	 */
637 	gens = X509_get_ext_d2i(peercert, NID_subject_alt_name, 0, 0);
638 	if (gens) {
639 	    r = sk_GENERAL_NAME_num(gens);
640 	    for (i = 0; i < r; ++i) {
641 		gn = sk_GENERAL_NAME_value(gens, i);
642 		if (gn->type != GEN_DNS)
643 		    continue;
644 
645 		/*
646 		 * Even if we have an invalid DNS name, we still ultimately
647 		 * ignore the CommonName, because subjectAltName:DNS is
648 		 * present (though malformed). Replace any previous peer_CN
649 		 * if empty or we get a match.
650 		 *
651 		 * We always set at least an empty peer_CN if the ALTNAME cert
652 		 * flag is set. If not, we set peer_CN from the cert
653 		 * CommonName below, so peer_CN is always non-null on return.
654 		 */
655 		TLScontext->peer_status |= TLS_CERT_FLAG_ALTNAME;
656 		dnsname = tls_dns_name(gn, TLScontext);
657 		if (dnsname && *dnsname) {
658 		    if ((dnsname_match = match_servername(dnsname, props)) != 0)
659 			matched++;
660 		    /* Keep the first matched name. */
661 		    if (TLScontext->peer_CN
662 			&& ((dnsname_match && matched == 1)
663 			    || *TLScontext->peer_CN == 0)) {
664 			myfree(TLScontext->peer_CN);
665 			TLScontext->peer_CN = 0;
666 		    }
667 		    if (verbose)
668 			msg_info("%s: %ssubjectAltName: %s", props->namaddr,
669 				 dnsname_match ? "Matched " : "", dnsname);
670 		}
671 		if (TLScontext->peer_CN == 0)
672 		    TLScontext->peer_CN = mystrdup(dnsname ? dnsname : "");
673 		if (matched && !log_certmatch)
674 		    break;
675 	    }
676 	    if (verify_peername && matched)
677 		TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED;
678 
679 	    /*
680 	     * (Sam Rushing, Ironport) Free stack *and* member GENERAL_NAME
681 	     * objects
682 	     */
683 	    sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
684 	}
685 
686 	/*
687 	 * No subjectAltNames, peer_CN is taken from CommonName.
688 	 */
689 	if (TLScontext->peer_CN == 0) {
690 	    TLScontext->peer_CN = tls_peer_CN(peercert, TLScontext);
691 	    if (*TLScontext->peer_CN)
692 		matched = match_servername(TLScontext->peer_CN, props);
693 	    if (verify_peername && matched)
694 		TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED;
695 	    if (verbose)
696 		msg_info("%s %sCommonName %s", props->namaddr,
697 			 matched ? "Matched " : "", TLScontext->peer_CN);
698 	} else if (verbose) {
699 	    char   *tmpcn = tls_peer_CN(peercert, TLScontext);
700 
701 	    /*
702 	     * Though the CommonName was superceded by a subjectAltName, log
703 	     * it when certificate match debugging was requested.
704 	     */
705 	    msg_info("%s CommonName %s", TLScontext->namaddr, tmpcn);
706 	    myfree(tmpcn);
707 	}
708     } else
709 	TLScontext->peer_CN = tls_peer_CN(peercert, TLScontext);
710 
711     /*
712      * Give them a clue. Problems with trust chain verification are logged
713      * when the session is first negotiated, before the session is stored
714      * into the cache. We don't want mystery failures, so log the fact the
715      * real problem is to be found in the past.
716      */
717     if (!TLS_CERT_IS_TRUSTED(TLScontext)
718 	&& (TLScontext->log_mask & TLS_LOG_UNTRUSTED)) {
719 	if (TLScontext->session_reused == 0)
720 	    tls_log_verify_error(TLScontext);
721 	else
722 	    msg_info("%s: re-using session with untrusted certificate, "
723 		     "look for details earlier in the log", props->namaddr);
724     }
725 }
726 
727 /* verify_extract_print - extract and verify peer fingerprint */
728 
729 static void verify_extract_print(TLS_SESS_STATE *TLScontext, X509 *peercert,
730 				         const TLS_CLIENT_START_PROPS *props)
731 {
732     TLScontext->peer_cert_fprint = tls_cert_fprint(peercert, props->mdalg);
733     TLScontext->peer_pkey_fprint = tls_pkey_fprint(peercert, props->mdalg);
734 
735     /*
736      * Whether the level is "dane" or "fingerprint" when the peer certificate
737      * is matched without resorting to a separate CA, we set both the trusted
738      * and matched bits.  This simplifies logic in smtp_proto.c where "dane"
739      * must be trusted and matched, since some "dane" TLSA RRsets do use CAs.
740      *
741      * This also suppresses spurious logging of the peer certificate as
742      * untrusted in verify_extract_name().
743      */
744     if (TLS_DANE_HASEE(props->dane)
745 	&& tls_dane_match(TLScontext, TLS_DANE_EE, peercert, 0))
746 	TLScontext->peer_status |=
747 	    TLS_CERT_FLAG_TRUSTED | TLS_CERT_FLAG_MATCHED;
748 }
749 
750  /*
751   * This is the actual startup routine for the connection. We expect that the
752   * buffers are flushed and the "220 Ready to start TLS" was received by us,
753   * so that we can immediately start the TLS handshake process.
754   */
755 TLS_SESS_STATE *tls_client_start(const TLS_CLIENT_START_PROPS *props)
756 {
757     int     sts;
758     int     protomask;
759     const char *cipher_list;
760     SSL_SESSION *session = 0;
761     SSL_CIPHER_const SSL_CIPHER *cipher;
762     X509   *peercert;
763     TLS_SESS_STATE *TLScontext;
764     TLS_APPL_STATE *app_ctx = props->ctx;
765     char   *myserverid;
766     int     log_mask = app_ctx->log_mask;
767 
768     /*
769      * When certificate verification is required, log trust chain validation
770      * errors even when disabled by default for opportunistic sessions. For
771      * "dane" this only applies when using trust-anchor associations.
772      */
773     if (TLS_MUST_TRUST(props->tls_level)
774 	&& (props->tls_level != TLS_LEV_DANE || TLS_DANE_HASTA(props->dane)))
775 	log_mask |= TLS_LOG_UNTRUSTED;
776 
777     if (log_mask & TLS_LOG_VERBOSE)
778 	msg_info("setting up TLS connection to %s", props->namaddr);
779 
780     /*
781      * First make sure we have valid protocol and cipher parameters
782      *
783      * Per-session protocol restrictions must be applied to the SSL connection,
784      * as restrictions in the global context cannot be cleared.
785      */
786     protomask = tls_protocol_mask(props->protocols);
787     if (protomask == TLS_PROTOCOL_INVALID) {
788 	/* tls_protocol_mask() logs no warning. */
789 	msg_warn("%s: Invalid TLS protocol list \"%s\": aborting TLS session",
790 		 props->namaddr, props->protocols);
791 	return (0);
792     }
793     /* The DANE level requires SSLv3 or later, not SSLv2. */
794     if (props->tls_level == TLS_LEV_DANE)
795 	protomask |= TLS_PROTOCOL_SSLv2;
796 
797     /*
798      * Per session cipher selection for sessions with mandatory encryption
799      *
800      * The cipherlist is applied to the global SSL context, since it is likely
801      * to stay the same between connections, so we make use of a 1-element
802      * cache to return the same result for identical inputs.
803      */
804     cipher_list = tls_set_ciphers(app_ctx, "TLS", props->cipher_grade,
805 				  props->cipher_exclusions);
806     if (cipher_list == 0) {
807 	msg_warn("%s: %s: aborting TLS session",
808 		 props->namaddr, vstring_str(app_ctx->why));
809 	return (0);
810     }
811     if (log_mask & TLS_LOG_VERBOSE)
812 	msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
813 
814     /*
815      * OpenSSL will ignore cached sessions that use the wrong protocol. So we
816      * do not need to filter out cached sessions with the "wrong" protocol,
817      * rather OpenSSL will simply negotiate a new session.
818      *
819      * We salt the session lookup key with the protocol list, so that sessions
820      * found in the cache are plausibly acceptable.
821      *
822      * By the time a TLS client is negotiating ciphers it has already offered to
823      * re-use a session, it is too late to renege on the offer. So we must
824      * not attempt to re-use sessions whose ciphers are too weak. We salt the
825      * session lookup key with the cipher list, so that sessions found in the
826      * cache are always acceptable.
827      *
828      * With DANE, (more generally any TLScontext where we specified explicit
829      * trust-anchor or end-entity certificates) the verification status of
830      * the SSL session depends on the specified list.  Since we verify the
831      * certificate only during the initial handshake, we must segregate
832      * sessions with different TA lists.  Note, that TA re-verification is
833      * not possible with cached sessions, since these don't hold the complete
834      * peer trust chain.  Therefore, we compute a digest of the sorted TA
835      * parameters and append it to the serverid.
836      */
837     myserverid = tls_serverid_digest(props, protomask, cipher_list);
838 
839     /*
840      * Allocate a new TLScontext for the new connection and get an SSL
841      * structure. Add the location of TLScontext to the SSL to later retrieve
842      * the information inside the tls_verify_certificate_callback().
843      *
844      * If session caching was enabled when TLS was initialized, the cache type
845      * is stored in the client SSL context.
846      */
847     TLScontext = tls_alloc_sess_context(log_mask, props->namaddr);
848     TLScontext->cache_type = app_ctx->cache_type;
849 
850     TLScontext->serverid = myserverid;
851     TLScontext->stream = props->stream;
852     TLScontext->mdalg = props->mdalg;
853 
854     /* Alias DANE digest info from props */
855     TLScontext->dane = props->dane;
856 
857     if ((TLScontext->con = SSL_new(app_ctx->ssl_ctx)) == NULL) {
858 	msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
859 	tls_print_errors();
860 	tls_free_context(TLScontext);
861 	return (0);
862     }
863     if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
864 	msg_warn("Could not set application data for 'TLScontext->con'");
865 	tls_print_errors();
866 	tls_free_context(TLScontext);
867 	return (0);
868     }
869 
870     /*
871      * Apply session protocol restrictions.
872      */
873     if (protomask != 0)
874 	SSL_set_options(TLScontext->con, TLS_SSL_OP_PROTOMASK(protomask));
875 
876     /*
877      * XXX To avoid memory leaks we must always call SSL_SESSION_free() after
878      * calling SSL_set_session(), regardless of whether or not the session
879      * will be reused.
880      */
881     if (TLScontext->cache_type) {
882 	session = load_clnt_session(TLScontext);
883 	if (session) {
884 	    SSL_set_session(TLScontext->con, session);
885 	    SSL_SESSION_free(session);		/* 200411 */
886 	}
887     }
888 #ifdef TLSEXT_MAXLEN_host_name
889     if (props->tls_level == TLS_LEV_DANE
890 	&& strlen(props->host) <= TLSEXT_MAXLEN_host_name) {
891 
892 	/*
893 	 * With DANE sessions, send an SNI hint.  We don't care whether the
894 	 * server reports finding a matching certificate or not, so no
895 	 * callback is required to process the server response.  Our use of
896 	 * SNI is limited to giving servers that are (mis)configured to use
897 	 * SNI the best opportunity to find the certificate they promised via
898 	 * the associated TLSA RRs.  (Generally, server administrators should
899 	 * avoid SNI, and there are no plans to support SNI in the Postfix
900 	 * SMTP server).
901 	 *
902 	 * Since the hostname is DNSSEC-validated, it must be a DNS FQDN and
903 	 * thererefore valid for use with SNI.  Failure to set a valid SNI
904 	 * hostname is a memory allocation error, and thus transient.  Since
905 	 * we must not cache the session if we failed to send the SNI name,
906 	 * we have little choice but to abort.
907 	 */
908 	if (!SSL_set_tlsext_host_name(TLScontext->con, props->host)) {
909 	    msg_warn("%s: error setting SNI hostname to: %s", props->namaddr,
910 		     props->host);
911 	    tls_free_context(TLScontext);
912 	    return (0);
913 	}
914 	if (log_mask & TLS_LOG_DEBUG)
915 	    msg_info("%s: SNI hostname: %s", props->namaddr, props->host);
916     }
917 #endif
918 
919     /*
920      * Before really starting anything, try to seed the PRNG a little bit
921      * more.
922      */
923     tls_int_seed();
924     (void) tls_ext_seed(var_tls_daemon_rand_bytes);
925 
926     /*
927      * Initialize the SSL connection to connect state. This should not be
928      * necessary anymore since 0.9.3, but the call is still in the library
929      * and maintaining compatibility never hurts.
930      */
931     SSL_set_connect_state(TLScontext->con);
932 
933     /*
934      * Connect the SSL connection with the network socket.
935      */
936     if (SSL_set_fd(TLScontext->con, vstream_fileno(props->stream)) != 1) {
937 	msg_info("SSL_set_fd error to %s", props->namaddr);
938 	tls_print_errors();
939 	uncache_session(app_ctx->ssl_ctx, TLScontext);
940 	tls_free_context(TLScontext);
941 	return (0);
942     }
943 
944     /*
945      * Turn on non-blocking I/O so that we can enforce timeouts on network
946      * I/O.
947      */
948     non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
949 
950     /*
951      * If the debug level selected is high enough, all of the data is dumped:
952      * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will
953      * dump everything.
954      *
955      * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
956      * Well there is a BIO below the SSL routines that is automatically
957      * created for us, so we can use it for debugging purposes.
958      */
959     if (log_mask & TLS_LOG_TLSPKTS)
960 	BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
961 
962     tls_dane_set_callback(app_ctx->ssl_ctx, TLScontext);
963 
964     /*
965      * Start TLS negotiations. This process is a black box that invokes our
966      * call-backs for certificate verification.
967      *
968      * Error handling: If the SSL handhake fails, we print out an error message
969      * and remove all TLS state concerning this session.
970      */
971     sts = tls_bio_connect(vstream_fileno(props->stream), props->timeout,
972 			  TLScontext);
973     if (sts <= 0) {
974 	if (ERR_peek_error() != 0) {
975 	    msg_info("SSL_connect error to %s: %d", props->namaddr, sts);
976 	    tls_print_errors();
977 	} else if (errno != 0) {
978 	    msg_info("SSL_connect error to %s: %m", props->namaddr);
979 	} else {
980 	    msg_info("SSL_connect error to %s: lost connection",
981 		     props->namaddr);
982 	}
983 	uncache_session(app_ctx->ssl_ctx, TLScontext);
984 	tls_free_context(TLScontext);
985 	return (0);
986     }
987     /* Turn off packet dump if only dumping the handshake */
988     if ((log_mask & TLS_LOG_ALLPKTS) == 0)
989 	BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
990 
991     /*
992      * The caller may want to know if this session was reused or if a new
993      * session was negotiated.
994      */
995     TLScontext->session_reused = SSL_session_reused(TLScontext->con);
996     if ((log_mask & TLS_LOG_CACHE) && TLScontext->session_reused)
997 	msg_info("%s: Reusing old session", TLScontext->namaddr);
998 
999     /*
1000      * Do peername verification if requested and extract useful information
1001      * from the certificate for later use.
1002      */
1003     if ((peercert = SSL_get_peer_certificate(TLScontext->con)) != 0) {
1004 	TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT;
1005 
1006 	/*
1007 	 * Peer name or fingerprint verification as requested.
1008 	 * Unconditionally set peer_CN, issuer_CN and peer_cert_fprint. Check
1009 	 * fingerprint first, and avoid logging verified as untrusted in the
1010 	 * call to verify_extract_name().
1011 	 */
1012 	verify_extract_print(TLScontext, peercert, props);
1013 	verify_extract_name(TLScontext, peercert, props);
1014 
1015 	if (TLScontext->log_mask &
1016 	    (TLS_LOG_CERTMATCH | TLS_LOG_VERBOSE | TLS_LOG_PEERCERT))
1017 	    msg_info("%s: subject_CN=%s, issuer_CN=%s, "
1018 		     "fingerprint=%s, pkey_fingerprint=%s", props->namaddr,
1019 		     TLScontext->peer_CN, TLScontext->issuer_CN,
1020 		     TLScontext->peer_cert_fprint,
1021 		     TLScontext->peer_pkey_fprint);
1022 	X509_free(peercert);
1023     } else {
1024 	TLScontext->issuer_CN = mystrdup("");
1025 	TLScontext->peer_CN = mystrdup("");
1026 	TLScontext->peer_cert_fprint = mystrdup("");
1027 	TLScontext->peer_pkey_fprint = mystrdup("");
1028     }
1029 
1030     /*
1031      * Finally, collect information about protocol and cipher for logging
1032      */
1033     TLScontext->protocol = SSL_get_version(TLScontext->con);
1034     cipher = SSL_get_current_cipher(TLScontext->con);
1035     TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
1036     TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
1037 					     &(TLScontext->cipher_algbits));
1038 
1039     /*
1040      * The TLS engine is active. Switch to the tls_timed_read/write()
1041      * functions and make the TLScontext available to those functions.
1042      */
1043     tls_stream_start(props->stream, TLScontext);
1044 
1045     /*
1046      * All the key facts in a single log entry.
1047      */
1048     if (log_mask & TLS_LOG_SUMMARY)
1049 	msg_info("%s TLS connection established to %s: %s with cipher %s "
1050 		 "(%d/%d bits)",
1051 		 !TLS_CERT_IS_PRESENT(TLScontext) ? "Anonymous" :
1052 		 TLS_CERT_IS_MATCHED(TLScontext) ? "Verified" :
1053 		 TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
1054 	      props->namaddr, TLScontext->protocol, TLScontext->cipher_name,
1055 		 TLScontext->cipher_usebits, TLScontext->cipher_algbits);
1056 
1057     tls_int_seed();
1058 
1059     return (TLScontext);
1060 }
1061 
1062 #endif					/* USE_TLS */
1063