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