1 /*	$NetBSD: tls_client.c,v 1.7 2013/08/21 20:12:31 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_fingerprint
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 already contains namaddrport 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 already contains namaddrport 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 already contains namaddrport information */
236 	msg_info("save session %s to %s cache",
237 		 TLScontext->serverid, TLScontext->cache_type);
238 
239 #if (OPENSSL_VERSION_NUMBER < 0x00906011L) || (OPENSSL_VERSION_NUMBER == 0x00907000L)
240 
241     /*
242      * Ugly Hack: OpenSSL before 0.9.6a does not store the verify result in
243      * sessions for the client side. We modify the session directly which is
244      * version specific, but this bug is version specific, too.
245      *
246      * READ: 0-09-06-01-1 = 0-9-6-a-beta1: all versions before beta1 have this
247      * bug, it has been fixed during development of 0.9.6a. The development
248      * version of 0.9.7 can have this bug, too. It has been fixed on
249      * 2000/11/29.
250      */
251     session->verify_result = SSL_get_verify_result(TLScontext->con);
252 #endif
253 
254     /*
255      * Passivate and save the session object. Errors are non-fatal, since
256      * caching is only an optimization.
257      */
258     if ((session_data = tls_session_passivate(session)) != 0) {
259 	tls_mgr_update(TLScontext->cache_type, TLScontext->serverid,
260 		       STR(session_data), LEN(session_data));
261 	vstring_free(session_data);
262     }
263 
264     /*
265      * Clean up.
266      */
267     SSL_SESSION_free(session);			/* 200502 */
268 
269     return (1);
270 }
271 
272 /* uncache_session - remove session from the external cache */
273 
274 static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext)
275 {
276     SSL_SESSION *session = SSL_get_session(TLScontext->con);
277 
278     SSL_CTX_remove_session(ctx, session);
279     if (TLScontext->cache_type == 0 || TLScontext->serverid == 0)
280 	return;
281 
282     if (TLScontext->log_mask & TLS_LOG_CACHE)
283 	/* serverid already contains namaddrport information */
284 	msg_info("remove session %s from client cache", TLScontext->serverid);
285 
286     tls_mgr_delete(TLScontext->cache_type, TLScontext->serverid);
287 }
288 
289 /* tls_client_init - initialize client-side TLS engine */
290 
291 TLS_APPL_STATE *tls_client_init(const TLS_CLIENT_INIT_PROPS *props)
292 {
293     long    off = 0;
294     int     cachable;
295     SSL_CTX *client_ctx;
296     TLS_APPL_STATE *app_ctx;
297     const EVP_MD *md_alg;
298     unsigned int md_len;
299     int     log_mask;
300 
301     /*
302      * Convert user loglevel to internal logmask.
303      */
304     log_mask = tls_log_mask(props->log_param, props->log_level);
305 
306     if (log_mask & TLS_LOG_VERBOSE)
307 	msg_info("initializing the client-side TLS engine");
308 
309     /*
310      * Load (mostly cipher related) TLS-library internal main.cf parameters.
311      */
312     tls_param_init();
313 
314     /*
315      * Detect mismatch between compile-time headers and run-time library.
316      */
317     tls_check_version();
318 
319     /*
320      * Initialize the OpenSSL library by the book! To start with, we must
321      * initialize the algorithms. We want cleartext error messages instead of
322      * just error codes, so we load the error_strings.
323      */
324     SSL_load_error_strings();
325     OpenSSL_add_ssl_algorithms();
326 
327     /*
328      * Create an application data index for SSL objects, so that we can
329      * attach TLScontext information; this information is needed inside
330      * tls_verify_certificate_callback().
331      */
332     if (TLScontext_index < 0) {
333 	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) {
334 	    msg_warn("Cannot allocate SSL application data index: "
335 		     "disabling TLS support");
336 	    return (0);
337 	}
338     }
339 
340     /*
341      * If the administrator specifies an unsupported digest algorithm, fail
342      * now, rather than in the middle of a TLS handshake.
343      */
344     if ((md_alg = EVP_get_digestbyname(props->fpt_dgst)) == 0) {
345 	msg_warn("Digest algorithm \"%s\" not found: disabling TLS support",
346 		 props->fpt_dgst);
347 	return (0);
348     }
349 
350     /*
351      * Sanity check: Newer shared libraries may use larger digests.
352      */
353     if ((md_len = EVP_MD_size(md_alg)) > EVP_MAX_MD_SIZE) {
354 	msg_warn("Digest algorithm \"%s\" output size %u too large:"
355 		 " disabling TLS support", props->fpt_dgst, md_len);
356 	return (0);
357     }
358 
359     /*
360      * Initialize the PRNG (Pseudo Random Number Generator) with some seed
361      * from external and internal sources. Don't enable TLS without some real
362      * entropy.
363      */
364     if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
365 	msg_warn("no entropy for TLS key generation: disabling TLS support");
366 	return (0);
367     }
368     tls_int_seed();
369 
370     /*
371      * The SSL/TLS specifications require the client to send a message in the
372      * oldest specification it understands with the highest level it
373      * understands in the message. RFC2487 is only specified for TLSv1, but
374      * we want to be as compatible as possible, so we will start off with a
375      * SSLv2 greeting allowing the best we can offer: TLSv1. We can restrict
376      * this with the options setting later, anyhow.
377      */
378     ERR_clear_error();
379     if ((client_ctx = SSL_CTX_new(SSLv23_client_method())) == 0) {
380 	msg_warn("cannot allocate client SSL_CTX: disabling TLS support");
381 	tls_print_errors();
382 	return (0);
383     }
384 
385     /*
386      * See the verify callback in tls_verify.c
387      */
388     SSL_CTX_set_verify_depth(client_ctx, props->verifydepth + 1);
389 
390     /*
391      * Protocol selection is destination dependent, so we delay the protocol
392      * selection options to the per-session SSL object.
393      */
394     off |= tls_bug_bits();
395     SSL_CTX_set_options(client_ctx, off);
396 
397     /*
398      * Set the call-back routine for verbose logging.
399      */
400     if (log_mask & TLS_LOG_DEBUG)
401 	SSL_CTX_set_info_callback(client_ctx, tls_info_callback);
402 
403     /*
404      * Load the CA public key certificates for both the client cert and for
405      * the verification of server certificates. As provided by OpenSSL we
406      * support two types of CA certificate handling: One possibility is to
407      * add all CA certificates to one large CAfile, the other possibility is
408      * a directory pointed to by CApath, containing separate files for each
409      * CA with softlinks named after the hash values of the certificate. The
410      * first alternative has the advantage that the file is opened and read
411      * at startup time, so that you don't have the hassle to maintain another
412      * copy of the CApath directory for chroot-jail.
413      */
414     if (tls_set_ca_certificate_info(client_ctx,
415 				    props->CAfile, props->CApath) < 0) {
416 	/* tls_set_ca_certificate_info() already logs a warning. */
417 	SSL_CTX_free(client_ctx);		/* 200411 */
418 	return (0);
419     }
420 
421     /*
422      * We do not need a client certificate, so the certificates are only
423      * loaded (and checked) if supplied. A clever client would handle
424      * multiple client certificates and decide based on the list of
425      * acceptable CAs, sent by the server, which certificate to submit.
426      * OpenSSL does however not do this and also has no call-back hooks to
427      * easily implement it.
428      *
429      * Load the client public key certificate and private key from file and
430      * check whether the cert matches the key. We can use RSA certificates
431      * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
432      * All three can be made available at the same time. The CA certificates
433      * for all three are handled in the same setup already finished. Which
434      * one is used depends on the cipher negotiated (that is: the first
435      * cipher listed by the client which does match the server). The client
436      * certificate is presented after the server chooses the session cipher,
437      * so we will just present the right cert for the chosen cipher (if it
438      * uses certificates).
439      */
440     if (tls_set_my_certificate_key_info(client_ctx,
441 					props->cert_file,
442 					props->key_file,
443 					props->dcert_file,
444 					props->dkey_file,
445 					props->eccert_file,
446 					props->eckey_file) < 0) {
447 	/* tls_set_my_certificate_key_info() already logs a warning. */
448 	SSL_CTX_free(client_ctx);		/* 200411 */
449 	return (0);
450     }
451 
452     /*
453      * According to the OpenSSL documentation, temporary RSA key is needed
454      * export ciphers are in use. We have to provide one, so well, we just do
455      * it.
456      */
457     SSL_CTX_set_tmp_rsa_callback(client_ctx, tls_tmp_rsa_cb);
458 
459     /*
460      * Finally, the setup for the server certificate checking, done "by the
461      * book".
462      */
463     SSL_CTX_set_verify(client_ctx, SSL_VERIFY_NONE,
464 		       tls_verify_certificate_callback);
465 
466     /*
467      * Initialize the session cache.
468      *
469      * Since the client does not search an internal cache, we simply disable it.
470      * It is only useful for expiring old sessions, but we do that in the
471      * tlsmgr(8).
472      *
473      * This makes SSL_CTX_remove_session() not useful for flushing broken
474      * sessions from the external cache, so we must delete them directly (not
475      * via a callback).
476      */
477     if (tls_mgr_policy(props->cache_type, &cachable) != TLS_MGR_STAT_OK)
478 	cachable = 0;
479 
480     /*
481      * Allocate an application context, and populate with mandatory protocol
482      * and cipher data.
483      */
484     app_ctx = tls_alloc_app_context(client_ctx, log_mask);
485 
486     /*
487      * The external session cache is implemented by the tlsmgr(8) process.
488      */
489     if (cachable) {
490 
491 	app_ctx->cache_type = mystrdup(props->cache_type);
492 
493 	/*
494 	 * OpenSSL does not use callbacks to load sessions from a client
495 	 * cache, so we must invoke that function directly. Apparently,
496 	 * OpenSSL does not provide a way to pass session names from here to
497 	 * call-back routines that do session lookup.
498 	 *
499 	 * OpenSSL can, however, automatically save newly created sessions for
500 	 * us by callback (we create the session name in the call-back
501 	 * function).
502 	 *
503 	 * XXX gcc 2.95 can't compile #ifdef .. #endif in the expansion of
504 	 * SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE |
505 	 * SSL_SESS_CACHE_NO_AUTO_CLEAR.
506 	 */
507 #ifndef SSL_SESS_CACHE_NO_INTERNAL_STORE
508 #define SSL_SESS_CACHE_NO_INTERNAL_STORE 0
509 #endif
510 
511 	SSL_CTX_set_session_cache_mode(client_ctx,
512 				       SSL_SESS_CACHE_CLIENT |
513 				       SSL_SESS_CACHE_NO_INTERNAL_STORE |
514 				       SSL_SESS_CACHE_NO_AUTO_CLEAR);
515 	SSL_CTX_sess_set_new_cb(client_ctx, new_client_session_cb);
516     }
517     return (app_ctx);
518 }
519 
520 /* match_hostname -  match hostname against pattern */
521 
522 static int match_hostname(const char *peerid,
523 			          const TLS_CLIENT_START_PROPS *props)
524 {
525     const ARGV *cmatch_argv;
526     const char *nexthop = props->nexthop;
527     const char *hname = props->host;
528     const char *pattern;
529     const char *pattern_left;
530     int     sub;
531     int     i;
532     int     idlen;
533     int     patlen;
534 
535     if ((cmatch_argv = props->matchargv) == 0)
536 	return 0;
537 
538     /*
539      * Match the peerid against each pattern until we find a match.
540      */
541     for (i = 0; i < cmatch_argv->argc; ++i) {
542 	sub = 0;
543 	if (!strcasecmp(cmatch_argv->argv[i], "nexthop"))
544 	    pattern = nexthop;
545 	else if (!strcasecmp(cmatch_argv->argv[i], "hostname"))
546 	    pattern = hname;
547 	else if (!strcasecmp(cmatch_argv->argv[i], "dot-nexthop")) {
548 	    pattern = nexthop;
549 	    sub = 1;
550 	} else {
551 	    pattern = cmatch_argv->argv[i];
552 	    if (*pattern == '.' && pattern[1] != '\0') {
553 		++pattern;
554 		sub = 1;
555 	    }
556 	}
557 
558 	/*
559 	 * Sub-domain match: peerid is any sub-domain of pattern.
560 	 */
561 	if (sub) {
562 	    if ((idlen = strlen(peerid)) > (patlen = strlen(pattern)) + 1
563 		&& peerid[idlen - patlen - 1] == '.'
564 		&& !strcasecmp(peerid + (idlen - patlen), pattern))
565 		return (1);
566 	    else
567 		continue;
568 	}
569 
570 	/*
571 	 * Exact match and initial "*" match. The initial "*" in a peerid
572 	 * matches exactly one hostname component, under the condition that
573 	 * the peerid contains multiple hostname components.
574 	 */
575 	if (!strcasecmp(peerid, pattern)
576 	    || (peerid[0] == '*' && peerid[1] == '.' && peerid[2] != 0
577 		&& (pattern_left = strchr(pattern, '.')) != 0
578 		&& strcasecmp(pattern_left + 1, peerid + 2) == 0))
579 	    return (1);
580     }
581     return (0);
582 }
583 
584 /* verify_extract_name - verify peer name and extract peer information */
585 
586 static void verify_extract_name(TLS_SESS_STATE *TLScontext, X509 *peercert,
587 				        const TLS_CLIENT_START_PROPS *props)
588 {
589     int     i;
590     int     r;
591     int     matched = 0;
592     int     dnsname_match;
593     int     verify_peername = 0;
594     int     log_certmatch;
595     int     verbose;
596     const char *dnsname;
597     const GENERAL_NAME *gn;
598 
599     STACK_OF(GENERAL_NAME) * gens;
600 
601     /*
602      * On exit both peer_CN and issuer_CN should be set.
603      */
604     TLScontext->issuer_CN = tls_issuer_CN(peercert, TLScontext);
605 
606     /*
607      * Is the certificate trust chain valid and trusted?
608      */
609     if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
610 	TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
611 
612     if (TLS_CERT_IS_TRUSTED(TLScontext) && props->tls_level >= TLS_LEV_VERIFY)
613 	verify_peername = 1;
614 
615     /* Force cert processing so we can log the data? */
616     log_certmatch = TLScontext->log_mask & TLS_LOG_CERTMATCH;
617 
618     /* Log cert details when processing? */
619     verbose = log_certmatch || (TLScontext->log_mask & TLS_LOG_VERBOSE);
620 
621     if (verify_peername || log_certmatch) {
622 
623 	/*
624 	 * Verify the dNSName(s) in the peer certificate against the nexthop
625 	 * and hostname.
626 	 *
627 	 * If DNS names are present, we use the first matching (or else simply
628 	 * the first) DNS name as the subject CN. The CommonName in the
629 	 * issuer DN is obsolete when SubjectAltName is available. This
630 	 * yields much less surprising logs, because we log the name we
631 	 * verified or a name we checked and failed to match.
632 	 *
633 	 * XXX: The nexthop and host name may both be the same network address
634 	 * rather than a DNS name. In this case we really should be looking
635 	 * for GEN_IPADD entries, not GEN_DNS entries.
636 	 *
637 	 * XXX: In ideal world the caller who used the address to build the
638 	 * connection would tell us that the nexthop is the connection
639 	 * address, but if that is not practical, we can parse the nexthop
640 	 * again here.
641 	 */
642 	gens = X509_get_ext_d2i(peercert, NID_subject_alt_name, 0, 0);
643 	if (gens) {
644 	    r = sk_GENERAL_NAME_num(gens);
645 	    for (i = 0; i < r; ++i) {
646 		gn = sk_GENERAL_NAME_value(gens, i);
647 		if (gn->type != GEN_DNS)
648 		    continue;
649 
650 		/*
651 		 * Even if we have an invalid DNS name, we still ultimately
652 		 * ignore the CommonName, because subjectAltName:DNS is
653 		 * present (though malformed). Replace any previous peer_CN
654 		 * if empty or we get a match.
655 		 *
656 		 * We always set at least an empty peer_CN if the ALTNAME cert
657 		 * flag is set. If not, we set peer_CN from the cert
658 		 * CommonName below, so peer_CN is always non-null on return.
659 		 */
660 		TLScontext->peer_status |= TLS_CERT_FLAG_ALTNAME;
661 		dnsname = tls_dns_name(gn, TLScontext);
662 		if (dnsname && *dnsname) {
663 		    if ((dnsname_match = match_hostname(dnsname, props)) != 0)
664 			matched++;
665 		    /* Keep the first matched name. */
666 		    if (TLScontext->peer_CN
667 			&& ((dnsname_match && matched == 1)
668 			    || *TLScontext->peer_CN == 0)) {
669 			myfree(TLScontext->peer_CN);
670 			TLScontext->peer_CN = 0;
671 		    }
672 		    if (verbose)
673 			msg_info("%s: %ssubjectAltName: %s", props->namaddr,
674 				 dnsname_match ? "Matched " : "", dnsname);
675 		}
676 		if (TLScontext->peer_CN == 0)
677 		    TLScontext->peer_CN = mystrdup(dnsname ? dnsname : "");
678 		if (matched && !log_certmatch)
679 		    break;
680 	    }
681 	    if (verify_peername && matched)
682 		TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED;
683 
684 	    /*
685 	     * (Sam Rushing, Ironport) Free stack *and* member GENERAL_NAME
686 	     * objects
687 	     */
688 	    sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
689 	}
690 
691 	/*
692 	 * No subjectAltNames, peer_CN is taken from CommonName.
693 	 */
694 	if (TLScontext->peer_CN == 0) {
695 	    TLScontext->peer_CN = tls_peer_CN(peercert, TLScontext);
696 	    if (*TLScontext->peer_CN)
697 		matched = match_hostname(TLScontext->peer_CN, props);
698 	    if (verify_peername && matched)
699 		TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED;
700 	    if (verbose)
701 		msg_info("%s %sCommonName %s", props->namaddr,
702 			 matched ? "Matched " : "", TLScontext->peer_CN);
703 	} else if (verbose) {
704 	    char   *tmpcn = tls_peer_CN(peercert, TLScontext);
705 
706 	    /*
707 	     * Though the CommonName was superceded by a subjectAltName, log
708 	     * it when certificate match debugging was requested.
709 	     */
710 	    msg_info("%s CommonName %s", TLScontext->namaddr, tmpcn);
711 	    myfree(tmpcn);
712 	}
713     } else
714 	TLScontext->peer_CN = tls_peer_CN(peercert, TLScontext);
715 
716     /*
717      * Give them a clue. Problems with trust chain verification were logged
718      * when the session was first negotiated, before the session was stored
719      * into the cache. We don't want mystery failures, so log the fact the
720      * real problem is to be found in the past.
721      */
722     if (TLScontext->session_reused
723 	&& !TLS_CERT_IS_TRUSTED(TLScontext)
724 	&& (TLScontext->log_mask & TLS_LOG_UNTRUSTED))
725 	msg_info("%s: re-using session with untrusted certificate, "
726 		 "look for details earlier in the log", props->namaddr);
727 }
728 
729 /* verify_extract_print - extract and verify peer fingerprint */
730 
731 static void verify_extract_print(TLS_SESS_STATE *TLScontext, X509 *peercert,
732 				         const TLS_CLIENT_START_PROPS *props)
733 {
734     char  **cpp;
735 
736     /* Non-null by contract */
737     TLScontext->peer_fingerprint = tls_fingerprint(peercert, props->fpt_dgst);
738     TLScontext->peer_pkey_fprint = tls_pkey_fprint(peercert, props->fpt_dgst);
739 
740     /*
741      * Compare the fingerprint against each acceptable value, ignoring
742      * upper/lower case differences.
743      */
744     if (props->tls_level == TLS_LEV_FPRINT) {
745 	for (cpp = props->matchargv->argv; *cpp; ++cpp) {
746 	    if (strcasecmp(TLScontext->peer_fingerprint, *cpp) == 0
747 		|| strcasecmp(TLScontext->peer_pkey_fprint, *cpp) == 0) {
748 		TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED;
749 		break;
750 	    }
751 	}
752     }
753 }
754 
755  /*
756   * This is the actual startup routine for the connection. We expect that the
757   * buffers are flushed and the "220 Ready to start TLS" was received by us,
758   * so that we can immediately start the TLS handshake process.
759   */
760 TLS_SESS_STATE *tls_client_start(const TLS_CLIENT_START_PROPS *props)
761 {
762     int     sts;
763     int     protomask;
764     const char *cipher_list;
765     SSL_SESSION *session;
766     const SSL_CIPHER *cipher;
767     X509   *peercert;
768     TLS_SESS_STATE *TLScontext;
769     TLS_APPL_STATE *app_ctx = props->ctx;
770     VSTRING *myserverid;
771     int     log_mask = app_ctx->log_mask;
772 
773     /*
774      * When certificate verification is required, log trust chain validation
775      * errors even when disabled by default for opportunistic sessions.
776      */
777     if (props->tls_level >= TLS_LEV_VERIFY)
778 	log_mask |= TLS_LOG_UNTRUSTED;
779 
780     if (log_mask & TLS_LOG_VERBOSE)
781 	msg_info("setting up TLS connection to %s", props->namaddr);
782 
783     /*
784      * First make sure we have valid protocol and cipher parameters
785      *
786      * The cipherlist will be applied to the global SSL context, where it can be
787      * repeatedly reset if necessary, but the protocol restrictions will be
788      * is applied to the SSL connection, because protocol restrictions in the
789      * global context cannot be cleared.
790      */
791 
792     /*
793      * OpenSSL will ignore cached sessions that use the wrong protocol. So we
794      * do not need to filter out cached sessions with the "wrong" protocol,
795      * rather OpenSSL will simply negotiate a new session.
796      *
797      * Still, we salt the session lookup key with the protocol list, so that
798      * sessions found in the cache are always acceptable.
799      */
800     protomask = tls_protocol_mask(props->protocols);
801     if (protomask == TLS_PROTOCOL_INVALID) {
802 	/* tls_protocol_mask() logs no warning. */
803 	msg_warn("%s: Invalid TLS protocol list \"%s\": aborting TLS session",
804 		 props->namaddr, props->protocols);
805 	return (0);
806     }
807     myserverid = vstring_alloc(100);
808     vstring_sprintf_append(myserverid, "%s&p=%d", props->serverid, protomask);
809 
810     /*
811      * Per session cipher selection for sessions with mandatory encryption
812      *
813      * By the time a TLS client is negotiating ciphers it has already offered to
814      * re-use a session, it is too late to renege on the offer. So we must
815      * not attempt to re-use sessions whose ciphers are too weak. We salt the
816      * session lookup key with the cipher list, so that sessions found in the
817      * cache are always acceptable.
818      */
819     cipher_list = tls_set_ciphers(app_ctx, "TLS", props->cipher_grade,
820 				  props->cipher_exclusions);
821     if (cipher_list == 0) {
822 	msg_warn("%s: %s: aborting TLS session",
823 		 props->namaddr, vstring_str(app_ctx->why));
824 	vstring_free(myserverid);
825 	return (0);
826     }
827     if (log_mask & TLS_LOG_VERBOSE)
828 	msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
829     vstring_sprintf_append(myserverid, "&c=%s", cipher_list);
830 
831     /*
832      * Finally, salt the session key with the OpenSSL library version,
833      * (run-time, rather than compile-time, just in case that matters).
834      */
835     vstring_sprintf_append(myserverid, "&l=%ld", (long) SSLeay());
836 
837     /*
838      * Allocate a new TLScontext for the new connection and get an SSL
839      * structure. Add the location of TLScontext to the SSL to later retrieve
840      * the information inside the tls_verify_certificate_callback().
841      *
842      * If session caching was enabled when TLS was initialized, the cache type
843      * is stored in the client SSL context.
844      */
845     TLScontext = tls_alloc_sess_context(log_mask, props->namaddr);
846     TLScontext->cache_type = app_ctx->cache_type;
847 
848     TLScontext->serverid = vstring_export(myserverid);
849     TLScontext->stream = props->stream;
850 
851     if ((TLScontext->con = SSL_new(app_ctx->ssl_ctx)) == NULL) {
852 	msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
853 	tls_print_errors();
854 	tls_free_context(TLScontext);
855 	return (0);
856     }
857     if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
858 	msg_warn("Could not set application data for 'TLScontext->con'");
859 	tls_print_errors();
860 	tls_free_context(TLScontext);
861 	return (0);
862     }
863 
864     /*
865      * Apply session protocol restrictions.
866      */
867     if (protomask != 0)
868 	SSL_set_options(TLScontext->con,
869 		   ((protomask & TLS_PROTOCOL_TLSv1) ? SSL_OP_NO_TLSv1 : 0L)
870 	     | ((protomask & TLS_PROTOCOL_TLSv1_1) ? SSL_OP_NO_TLSv1_1 : 0L)
871 	     | ((protomask & TLS_PROTOCOL_TLSv1_2) ? SSL_OP_NO_TLSv1_2 : 0L)
872 		 | ((protomask & TLS_PROTOCOL_SSLv3) ? SSL_OP_NO_SSLv3 : 0L)
873 	       | ((protomask & TLS_PROTOCOL_SSLv2) ? SSL_OP_NO_SSLv2 : 0L));
874 
875     /*
876      * XXX To avoid memory leaks we must always call SSL_SESSION_free() after
877      * calling SSL_set_session(), regardless of whether or not the session
878      * will be reused.
879      */
880     if (TLScontext->cache_type) {
881 	session = load_clnt_session(TLScontext);
882 	if (session) {
883 	    SSL_set_session(TLScontext->con, session);
884 	    SSL_SESSION_free(session);		/* 200411 */
885 #if (OPENSSL_VERSION_NUMBER < 0x00906011L) || (OPENSSL_VERSION_NUMBER == 0x00907000L)
886 
887 	    /*
888 	     * Ugly Hack: OpenSSL before 0.9.6a does not store the verify
889 	     * result in sessions for the client side. We modify the session
890 	     * directly which is version specific, but this bug is version
891 	     * specific, too.
892 	     *
893 	     * READ: 0-09-06-01-1 = 0-9-6-a-beta1: all versions before beta1
894 	     * have this bug, it has been fixed during development of 0.9.6a.
895 	     * The development version of 0.9.7 can have this bug, too. It
896 	     * has been fixed on 2000/11/29.
897 	     */
898 	    SSL_set_verify_result(TLScontext->con, session->verify_result);
899 #endif
900 
901 	}
902     }
903 
904     /*
905      * Before really starting anything, try to seed the PRNG a little bit
906      * more.
907      */
908     tls_int_seed();
909     (void) tls_ext_seed(var_tls_daemon_rand_bytes);
910 
911     /*
912      * Initialize the SSL connection to connect state. This should not be
913      * necessary anymore since 0.9.3, but the call is still in the library
914      * and maintaining compatibility never hurts.
915      */
916     SSL_set_connect_state(TLScontext->con);
917 
918     /*
919      * Connect the SSL connection with the network socket.
920      */
921     if (SSL_set_fd(TLScontext->con, vstream_fileno(props->stream)) != 1) {
922 	msg_info("SSL_set_fd error to %s", props->namaddr);
923 	tls_print_errors();
924 	uncache_session(app_ctx->ssl_ctx, TLScontext);
925 	tls_free_context(TLScontext);
926 	return (0);
927     }
928 
929     /*
930      * Turn on non-blocking I/O so that we can enforce timeouts on network
931      * I/O.
932      */
933     non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
934 
935     /*
936      * If the debug level selected is high enough, all of the data is dumped:
937      * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will
938      * dump everything.
939      *
940      * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
941      * Well there is a BIO below the SSL routines that is automatically
942      * created for us, so we can use it for debugging purposes.
943      */
944     if (log_mask & TLS_LOG_TLSPKTS)
945 	BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
946 
947     /*
948      * Start TLS negotiations. This process is a black box that invokes our
949      * call-backs for certificate verification.
950      *
951      * Error handling: If the SSL handhake fails, we print out an error message
952      * and remove all TLS state concerning this session.
953      */
954     sts = tls_bio_connect(vstream_fileno(props->stream), props->timeout,
955 			  TLScontext);
956     if (sts <= 0) {
957 	if (ERR_peek_error() != 0) {
958 	    msg_info("SSL_connect error to %s: %d", props->namaddr, sts);
959 	    tls_print_errors();
960 	} else if (errno != 0) {
961 	    msg_info("SSL_connect error to %s: %m", props->namaddr);
962 	} else {
963 	    msg_info("SSL_connect error to %s: lost connection",
964 		     props->namaddr);
965 	}
966 	uncache_session(app_ctx->ssl_ctx, TLScontext);
967 	tls_free_context(TLScontext);
968 	return (0);
969     }
970     /* Turn off packet dump if only dumping the handshake */
971     if ((log_mask & TLS_LOG_ALLPKTS) == 0)
972 	BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
973 
974     /*
975      * The caller may want to know if this session was reused or if a new
976      * session was negotiated.
977      */
978     TLScontext->session_reused = SSL_session_reused(TLScontext->con);
979     if ((log_mask & TLS_LOG_CACHE) && TLScontext->session_reused)
980 	msg_info("%s: Reusing old session", TLScontext->namaddr);
981 
982     /*
983      * Do peername verification if requested and extract useful information
984      * from the certificate for later use.
985      */
986     if ((peercert = SSL_get_peer_certificate(TLScontext->con)) != 0) {
987 	TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT;
988 
989 	/*
990 	 * Peer name or fingerprint verification as requested.
991 	 * Unconditionally set peer_CN, issuer_CN and peer_fingerprint.
992 	 */
993 	verify_extract_name(TLScontext, peercert, props);
994 	verify_extract_print(TLScontext, peercert, props);
995 
996 	if (TLScontext->log_mask &
997 	    (TLS_LOG_CERTMATCH | TLS_LOG_VERBOSE | TLS_LOG_PEERCERT))
998 	    msg_info("%s: subject_CN=%s, issuer_CN=%s, "
999 		     "fingerprint=%s, pkey_fingerprint=%s", props->namaddr,
1000 		     TLScontext->peer_CN, TLScontext->issuer_CN,
1001 		     TLScontext->peer_fingerprint,
1002 		     TLScontext->peer_pkey_fprint);
1003 	X509_free(peercert);
1004     } else {
1005 	TLScontext->issuer_CN = mystrdup("");
1006 	TLScontext->peer_CN = mystrdup("");
1007 	TLScontext->peer_fingerprint = mystrdup("");
1008 	TLScontext->peer_pkey_fprint = mystrdup("");
1009     }
1010 
1011     /*
1012      * Finally, collect information about protocol and cipher for logging
1013      */
1014     TLScontext->protocol = SSL_get_version(TLScontext->con);
1015     cipher = SSL_get_current_cipher(TLScontext->con);
1016     TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
1017     TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
1018 					     &(TLScontext->cipher_algbits));
1019 
1020     /*
1021      * The TLS engine is active. Switch to the tls_timed_read/write()
1022      * functions and make the TLScontext available to those functions.
1023      */
1024     tls_stream_start(props->stream, TLScontext);
1025 
1026     /*
1027      * All the key facts in a single log entry.
1028      */
1029     if (log_mask & TLS_LOG_SUMMARY)
1030 	msg_info("%s TLS connection established to %s: %s with cipher %s "
1031 	      "(%d/%d bits)", TLS_CERT_IS_MATCHED(TLScontext) ? "Verified" :
1032 		 TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
1033 	      props->namaddr, TLScontext->protocol, TLScontext->cipher_name,
1034 		 TLScontext->cipher_usebits, TLScontext->cipher_algbits);
1035 
1036     tls_int_seed();
1037 
1038     return (TLScontext);
1039 }
1040 
1041 #endif					/* USE_TLS */
1042