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