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