1/*	$NetBSD: tls_server.c,v 1.5 2012/06/09 11:32:20 tron Exp $	*/
2
3/*++
4/* NAME
5/*	tls_server 3
6/* SUMMARY
7/*	server-side TLS engine
8/* SYNOPSIS
9/*	#include <tls.h>
10/*
11/*	TLS_APPL_STATE *tls_server_init(props)
12/*	const TLS_SERVER_INIT_PROPS *props;
13/*
14/*	TLS_SESS_STATE *tls_server_start(props)
15/*	const TLS_SERVER_START_PROPS *props;
16/*
17/*	TLS_SESS_STATE *tls_server_post_accept(TLScontext)
18/*	TLS_SESS_STATE *TLScontext;
19/*
20/*	void	tls_server_stop(app_ctx, stream, failure, TLScontext)
21/*	TLS_APPL_STATE *app_ctx;
22/*	VSTREAM	*stream;
23/*	int	failure;
24/*	TLS_SESS_STATE *TLScontext;
25/* DESCRIPTION
26/*	This module is the interface between Postfix TLS servers,
27/*	the OpenSSL library, and the TLS entropy and cache manager.
28/*
29/*	See "EVENT_DRIVEN APPLICATIONS" below for using this code
30/*	in event-driven programs.
31/*
32/*	tls_server_init() is called once when the SMTP server
33/*	initializes.
34/*	Certificate details are also decided during this phase,
35/*	so that peer-specific behavior is not possible.
36/*
37/*	tls_server_start() activates the TLS feature for the VSTREAM
38/*	passed as argument. We assume that network buffers are flushed
39/*	and the TLS handshake can begin	immediately.
40/*
41/*	tls_server_stop() sends the "close notify" alert via
42/*	SSL_shutdown() to the peer and resets all connection specific
43/*	TLS data. As RFC2487 does not specify a separate shutdown, it
44/*	is assumed that the underlying TCP connection is shut down
45/*	immediately afterwards. Any further writes to the channel will
46/*	be discarded, and any further reads will report end-of-file.
47/*	If the failure flag is set, no SSL_shutdown() handshake is performed.
48/*
49/*	Once the TLS connection is initiated, information about the TLS
50/*	state is available via the TLScontext structure:
51/* .IP TLScontext->protocol
52/*	the protocol name (SSLv2, SSLv3, TLSv1),
53/* .IP TLScontext->cipher_name
54/*	the cipher name (e.g. RC4/MD5),
55/* .IP TLScontext->cipher_usebits
56/*	the number of bits actually used (e.g. 40),
57/* .IP TLScontext->cipher_algbits
58/*	the number of bits the algorithm is based on (e.g. 128).
59/* .PP
60/*	The last two values may differ from each other when export-strength
61/*	encryption is used.
62/*
63/*	If the peer offered a certificate, part of the certificate data are
64/*	available as:
65/* .IP TLScontext->peer_status
66/*	A bitmask field that records the status of the peer certificate
67/*	verification. One or more of TLS_CERT_FLAG_PRESENT and
68/*	TLS_CERT_FLAG_TRUSTED.
69/* .IP TLScontext->peer_CN
70/*	Extracted CommonName of the peer, or zero-length string
71/*	when information could not be extracted.
72/* .IP TLScontext->issuer_CN
73/*	Extracted CommonName of the issuer, or zero-length string
74/*	when information could not be extracted.
75/* .IP TLScontext->peer_fingerprint
76/*	Fingerprint of the certificate, or zero-length string when no peer
77/*	certificate is available.
78/* .PP
79/*	If no peer certificate is presented the peer_status is set to 0.
80/* EVENT_DRIVEN APPLICATIONS
81/* .ad
82/* .fi
83/*	Event-driven programs manage multiple I/O channels.  Such
84/*	programs cannot use the synchronous VSTREAM-over-TLS
85/*	implementation that the current TLS library provides,
86/*	including tls_server_stop() and the underlying tls_stream(3)
87/*	and tls_bio_ops(3) routines.
88/*
89/*	With the current TLS library implementation, this means
90/*	that the application is responsible for calling and retrying
91/*	SSL_accept(), SSL_read(), SSL_write() and SSL_shutdown().
92/*
93/*	To maintain control over TLS I/O, an event-driven server
94/*	invokes tls_server_start() with a null VSTREAM argument and
95/*	with an fd argument that specifies the I/O file descriptor.
96/*	Then, tls_server_start() performs all the necessary
97/*	preparations before the TLS handshake and returns a partially
98/*	populated TLS context. The event-driven application is then
99/*	responsible for invoking SSL_accept(), and if successful,
100/*	for invoking tls_server_post_accept() to finish the work
101/*	that was started by tls_server_start(). In case of unrecoverable
102/*	failure, tls_server_post_accept() destroys the TLS context
103/*	and returns a null pointer value.
104/* LICENSE
105/* .ad
106/* .fi
107/*	This software is free. You can do with it whatever you want.
108/*	The original author kindly requests that you acknowledge
109/*	the use of his software.
110/* AUTHOR(S)
111/*	Originally written by:
112/*	Lutz Jaenicke
113/*	BTU Cottbus
114/*	Allgemeine Elektrotechnik
115/*	Universitaetsplatz 3-4
116/*	D-03044 Cottbus, Germany
117/*
118/*	Updated by:
119/*	Wietse Venema
120/*	IBM T.J. Watson Research
121/*	P.O. Box 704
122/*	Yorktown Heights, NY 10598, USA
123/*
124/*	Victor Duchovni
125/*	Morgan Stanley
126/*--*/
127
128/* System library. */
129
130#include <sys_defs.h>
131
132#ifdef USE_TLS
133#include <unistd.h>
134#include <string.h>
135
136/* Utility library. */
137
138#include <mymalloc.h>
139#include <vstring.h>
140#include <vstream.h>
141#include <dict.h>
142#include <stringops.h>
143#include <msg.h>
144#include <hex_code.h>
145#include <iostuff.h>			/* non-blocking */
146
147/* Global library. */
148
149#include <mail_params.h>
150
151/* TLS library. */
152
153#include <tls_mgr.h>
154#define TLS_INTERNAL
155#include <tls.h>
156
157#define STR(x)	vstring_str(x)
158#define LEN(x)	VSTRING_LEN(x)
159
160/* Application-specific. */
161
162 /*
163  * The session_id_context indentifies the service that created a session.
164  * This information is used to distinguish between multiple TLS-based
165  * servers running on the same server. We use the name of the mail system.
166  */
167static const char server_session_id_context[] = "Postfix/TLS";
168
169/* get_server_session_cb - callback to retrieve session from server cache */
170
171static SSL_SESSION *get_server_session_cb(SSL *ssl, unsigned char *session_id,
172					          int session_id_length,
173					          int *unused_copy)
174{
175    const char *myname = "get_server_session_cb";
176    TLS_SESS_STATE *TLScontext;
177    VSTRING *cache_id;
178    VSTRING *session_data = vstring_alloc(2048);
179    SSL_SESSION *session = 0;
180
181    if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
182	msg_panic("%s: null TLScontext in session lookup callback", myname);
183
184#define GEN_CACHE_ID(buf, id, len, service) \
185    do { \
186	buf = vstring_alloc(2 * (len + strlen(service))); \
187	hex_encode(buf, (char *) (id), (len)); \
188    	vstring_sprintf_append(buf, "&s=%s", (service)); \
189    	vstring_sprintf_append(buf, "&l=%ld", (long) SSLeay()); \
190    } while (0)
191
192
193    GEN_CACHE_ID(cache_id, session_id, session_id_length, TLScontext->serverid);
194
195    if (TLScontext->log_level >= 2)
196	msg_info("%s: looking up session %s in %s cache", TLScontext->namaddr,
197		 STR(cache_id), TLScontext->cache_type);
198
199    /*
200     * Load the session from cache and decode it.
201     */
202    if (tls_mgr_lookup(TLScontext->cache_type, STR(cache_id),
203		       session_data) == TLS_MGR_STAT_OK) {
204	session = tls_session_activate(STR(session_data), LEN(session_data));
205	if (session && (TLScontext->log_level >= 2))
206	    msg_info("%s: reloaded session %s from %s cache",
207		     TLScontext->namaddr, STR(cache_id),
208		     TLScontext->cache_type);
209    }
210
211    /*
212     * Clean up.
213     */
214    vstring_free(cache_id);
215    vstring_free(session_data);
216
217    return (session);
218}
219
220/* uncache_session - remove session from internal & external cache */
221
222static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext)
223{
224    VSTRING *cache_id;
225    SSL_SESSION *session = SSL_get_session(TLScontext->con);
226
227    SSL_CTX_remove_session(ctx, session);
228
229    if (TLScontext->cache_type == 0)
230	return;
231
232    GEN_CACHE_ID(cache_id, session->session_id, session->session_id_length,
233		 TLScontext->serverid);
234
235    if (TLScontext->log_level >= 2)
236	msg_info("%s: remove session %s from %s cache", TLScontext->namaddr,
237		 STR(cache_id), TLScontext->cache_type);
238
239    tls_mgr_delete(TLScontext->cache_type, STR(cache_id));
240    vstring_free(cache_id);
241}
242
243/* new_server_session_cb - callback to save session to server cache */
244
245static int new_server_session_cb(SSL *ssl, SSL_SESSION *session)
246{
247    const char *myname = "new_server_session_cb";
248    VSTRING *cache_id;
249    TLS_SESS_STATE *TLScontext;
250    VSTRING *session_data;
251
252    if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
253	msg_panic("%s: null TLScontext in new session callback", myname);
254
255    GEN_CACHE_ID(cache_id, session->session_id, session->session_id_length,
256		 TLScontext->serverid);
257
258    if (TLScontext->log_level >= 2)
259	msg_info("%s: save session %s to %s cache", TLScontext->namaddr,
260		 STR(cache_id), TLScontext->cache_type);
261
262    /*
263     * Passivate and save the session state.
264     */
265    session_data = tls_session_passivate(session);
266    if (session_data)
267	tls_mgr_update(TLScontext->cache_type, STR(cache_id),
268		       STR(session_data), LEN(session_data));
269
270    /*
271     * Clean up.
272     */
273    if (session_data)
274	vstring_free(session_data);
275    vstring_free(cache_id);
276    SSL_SESSION_free(session);			/* 200502 */
277
278    return (1);
279}
280
281/* tls_server_init - initialize the server-side TLS engine */
282
283TLS_APPL_STATE *tls_server_init(const TLS_SERVER_INIT_PROPS *props)
284{
285    SSL_CTX *server_ctx;
286    long    off = 0;
287    int     verify_flags = SSL_VERIFY_NONE;
288    int     cachable;
289    int     protomask;
290    TLS_APPL_STATE *app_ctx;
291    const EVP_MD *md_alg;
292    unsigned int md_len;
293
294    if (props->log_level >= 2)
295	msg_info("initializing the server-side TLS engine");
296
297    /*
298     * Load (mostly cipher related) TLS-library internal main.cf parameters.
299     */
300    tls_param_init();
301
302    /*
303     * Detect mismatch between compile-time headers and run-time library.
304     */
305    tls_check_version();
306
307    /*
308     * Initialize the OpenSSL library by the book! To start with, we must
309     * initialize the algorithms. We want cleartext error messages instead of
310     * just error codes, so we load the error_strings.
311     */
312    SSL_load_error_strings();
313    OpenSSL_add_ssl_algorithms();
314
315    /*
316     * First validate the protocols. If these are invalid, we can't continue.
317     */
318    protomask = tls_protocol_mask(props->protocols);
319    if (protomask == TLS_PROTOCOL_INVALID) {
320	/* tls_protocol_mask() logs no warning. */
321	msg_warn("Invalid TLS protocol list \"%s\": disabling TLS support",
322		 props->protocols);
323	return (0);
324    }
325
326    /*
327     * Create an application data index for SSL objects, so that we can
328     * attach TLScontext information; this information is needed inside
329     * tls_verify_certificate_callback().
330     */
331    if (TLScontext_index < 0) {
332	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) {
333	    msg_warn("Cannot allocate SSL application data index: "
334		     "disabling TLS support");
335	    return (0);
336	}
337    }
338
339    /*
340     * If the administrator specifies an unsupported digest algorithm, fail
341     * now, rather than in the middle of a TLS handshake.
342     */
343    if ((md_alg = EVP_get_digestbyname(props->fpt_dgst)) == 0) {
344	msg_warn("Digest algorithm \"%s\" not found: disabling TLS support",
345		 props->fpt_dgst);
346	return (0);
347    }
348
349    /*
350     * Sanity check: Newer shared libraries may use larger digests.
351     */
352    if ((md_len = EVP_MD_size(md_alg)) > EVP_MAX_MD_SIZE) {
353	msg_warn("Digest algorithm \"%s\" output size %u too large:"
354		 " disabling TLS support", props->fpt_dgst, md_len);
355	return (0);
356    }
357
358    /*
359     * Initialize the PRNG (Pseudo Random Number Generator) with some seed
360     * from external and internal sources. Don't enable TLS without some real
361     * entropy.
362     */
363    if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
364	msg_warn("no entropy for TLS key generation: disabling TLS support");
365	return (0);
366    }
367    tls_int_seed();
368
369    /*
370     * The SSL/TLS specifications require the client to send a message in the
371     * oldest specification it understands with the highest level it
372     * understands in the message. Netscape communicator can still
373     * communicate with SSLv2 servers, so it sends out a SSLv2 client hello.
374     * To deal with it, our server must be SSLv2 aware (even if we don't like
375     * SSLv2), so we need to have the SSLv23 server here. If we want to limit
376     * the protocol level, we can add an option to not use SSLv2/v3/TLSv1
377     * later.
378     */
379    ERR_clear_error();
380    if ((server_ctx = SSL_CTX_new(SSLv23_server_method())) == 0) {
381	msg_warn("cannot allocate server SSL_CTX: disabling TLS support");
382	tls_print_errors();
383	return (0);
384    }
385
386    /*
387     * See the verify callback in tls_verify.c
388     */
389    SSL_CTX_set_verify_depth(server_ctx, props->verifydepth + 1);
390
391    /*
392     * Protocol work-arounds, OpenSSL version dependent.
393     */
394    off |= tls_bug_bits();
395    SSL_CTX_set_options(server_ctx, off);
396
397    /*
398     * Global protocol selection.
399     */
400    if (protomask != 0)
401	SSL_CTX_set_options(server_ctx,
402		   ((protomask & TLS_PROTOCOL_TLSv1) ? SSL_OP_NO_TLSv1 : 0L)
403	     | ((protomask & TLS_PROTOCOL_TLSv1_1) ? SSL_OP_NO_TLSv1_1 : 0L)
404	     | ((protomask & TLS_PROTOCOL_TLSv1_2) ? SSL_OP_NO_TLSv1_2 : 0L)
405		 | ((protomask & TLS_PROTOCOL_SSLv3) ? SSL_OP_NO_SSLv3 : 0L)
406	       | ((protomask & TLS_PROTOCOL_SSLv2) ? SSL_OP_NO_SSLv2 : 0L));
407
408#if OPENSSL_VERSION_NUMBER >= 0x0090700fL
409
410    /*
411     * Some sites may want to give the client less rope. On the other hand,
412     * this could trigger inter-operability issues, the client should not
413     * offer ciphers it implements poorly, but this hasn't stopped some
414     * vendors from getting it wrong.
415     *
416     * XXX: Given OpenSSL's security history, nobody should still be using
417     * 0.9.7, let alone 0.9.6 or earlier. Warning added to TLS_README.html.
418     */
419    if (var_tls_preempt_clist)
420	SSL_CTX_set_options(server_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
421#endif
422
423    /*
424     * Set the call-back routine to debug handshake progress.
425     */
426    if (props->log_level >= 2)
427	SSL_CTX_set_info_callback(server_ctx, tls_info_callback);
428
429    /*
430     * Load the CA public key certificates for both the server cert and for
431     * the verification of client certificates. As provided by OpenSSL we
432     * support two types of CA certificate handling: One possibility is to
433     * add all CA certificates to one large CAfile, the other possibility is
434     * a directory pointed to by CApath, containing separate files for each
435     * CA with softlinks named after the hash values of the certificate. The
436     * first alternative has the advantage that the file is opened and read
437     * at startup time, so that you don't have the hassle to maintain another
438     * copy of the CApath directory for chroot-jail.
439     */
440    if (tls_set_ca_certificate_info(server_ctx,
441				    props->CAfile, props->CApath) < 0) {
442	/* tls_set_ca_certificate_info() already logs a warning. */
443	SSL_CTX_free(server_ctx);		/* 200411 */
444	return (0);
445    }
446
447    /*
448     * Load the server public key certificate and private key from file and
449     * check whether the cert matches the key. We can use RSA certificates
450     * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
451     * All three can be made available at the same time. The CA certificates
452     * for all three are handled in the same setup already finished. Which
453     * one is used depends on the cipher negotiated (that is: the first
454     * cipher listed by the client which does match the server). A client
455     * with RSA only (e.g. Netscape) will use the RSA certificate only. A
456     * client with openssl-library will use RSA first if not especially
457     * changed in the cipher setup.
458     */
459    if (tls_set_my_certificate_key_info(server_ctx,
460					props->cert_file,
461					props->key_file,
462					props->dcert_file,
463					props->dkey_file,
464					props->eccert_file,
465					props->eckey_file) < 0) {
466	/* tls_set_my_certificate_key_info() already logs a warning. */
467	SSL_CTX_free(server_ctx);		/* 200411 */
468	return (0);
469    }
470
471    /*
472     * According to the OpenSSL documentation, temporary RSA key is needed
473     * export ciphers are in use. We have to provide one, so well, we just do
474     * it.
475     */
476    SSL_CTX_set_tmp_rsa_callback(server_ctx, tls_tmp_rsa_cb);
477
478    /*
479     * Diffie-Hellman key generation parameters can either be loaded from
480     * files (preferred) or taken from compiled in values. First, set the
481     * callback that will select the values when requested, then load the
482     * (possibly) available DH parameters from files. We are generous with
483     * the error handling, since we do have default values compiled in, so we
484     * will not abort but just log the error message.
485     */
486    SSL_CTX_set_tmp_dh_callback(server_ctx, tls_tmp_dh_cb);
487    if (*props->dh1024_param_file != 0)
488	tls_set_dh_from_file(props->dh1024_param_file, 1024);
489    if (*props->dh512_param_file != 0)
490	tls_set_dh_from_file(props->dh512_param_file, 512);
491
492    /*
493     * Enable EECDH if available, errors are not fatal, we just keep going
494     * with any remaining key-exchange algorithms.
495     */
496    (void) tls_set_eecdh_curve(server_ctx, props->eecdh_grade);
497
498    /*
499     * If we want to check client certificates, we have to indicate it in
500     * advance. By now we only allow to decide on a global basis. If we want
501     * to allow certificate based relaying, we must ask the client to provide
502     * one with SSL_VERIFY_PEER. The client now can decide, whether it
503     * provides one or not. We can enforce a failure of the negotiation with
504     * SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we do not allow a connection
505     * without one. In the "server hello" following the initialization by the
506     * "client hello" the server must provide a list of CAs it is willing to
507     * accept. Some clever clients will then select one from the list of
508     * available certificates matching these CAs. Netscape Communicator will
509     * present the list of certificates for selecting the one to be sent, or
510     * it will issue a warning, if there is no certificate matching the
511     * available CAs.
512     *
513     * With regard to the purpose of the certificate for relaying, we might like
514     * a later negotiation, maybe relaying would already be allowed for other
515     * reasons, but this would involve severe changes in the internal postfix
516     * logic, so we have to live with it the way it is.
517     */
518    if (props->ask_ccert)
519	verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
520    SSL_CTX_set_verify(server_ctx, verify_flags,
521		       tls_verify_certificate_callback);
522    if (*props->CAfile)
523	SSL_CTX_set_client_CA_list(server_ctx,
524				   SSL_load_client_CA_file(props->CAfile));
525
526    /*
527     * Initialize our own TLS server handle, before diving into the details
528     * of TLS session cache management.
529     */
530    app_ctx = tls_alloc_app_context(server_ctx);
531
532    /*
533     * The session cache is implemented by the tlsmgr(8) server.
534     *
535     * XXX 200502 Surprise: when OpenSSL purges an entry from the in-memory
536     * cache, it also attempts to purge the entry from the on-disk cache.
537     * This is undesirable, especially when we set the in-memory cache size
538     * to 1. For this reason we don't allow OpenSSL to purge on-disk cache
539     * entries, and leave it up to the tlsmgr process instead. Found by
540     * Victor Duchovni.
541     */
542
543    if (tls_mgr_policy(props->cache_type, &cachable) != TLS_MGR_STAT_OK)
544	cachable = 0;
545
546    if (cachable || props->set_sessid) {
547
548	/*
549	 * Initialize the session cache.
550	 *
551	 * With a large number of concurrent smtpd(8) processes, it is not a
552	 * good idea to cache multiple large session objects in each process.
553	 * We set the internal cache size to 1, and don't register a
554	 * "remove_cb" so as to avoid deleting good sessions from the
555	 * external cache prematurely (when the internal cache is full,
556	 * OpenSSL removes sessions from the external cache also)!
557	 *
558	 * This makes SSL_CTX_remove_session() not useful for flushing broken
559	 * sessions from the external cache, so we must delete them directly
560	 * (not via a callback).
561	 *
562	 * Set a session id context to identify to what type of server process
563	 * created a session. In our case, the context is simply the name of
564	 * the mail system: "Postfix/TLS".
565	 */
566	SSL_CTX_sess_set_cache_size(server_ctx, 1);
567	SSL_CTX_set_session_id_context(server_ctx,
568				       (void *) &server_session_id_context,
569				       sizeof(server_session_id_context));
570	SSL_CTX_set_session_cache_mode(server_ctx,
571				       SSL_SESS_CACHE_SERVER |
572				       SSL_SESS_CACHE_NO_AUTO_CLEAR);
573	if (cachable) {
574	    app_ctx->cache_type = mystrdup(props->cache_type);
575
576	    SSL_CTX_sess_set_get_cb(server_ctx, get_server_session_cb);
577	    SSL_CTX_sess_set_new_cb(server_ctx, new_server_session_cb);
578	}
579
580	/*
581	 * OpenSSL ignores timed-out sessions. We need to set the internal
582	 * cache timeout at least as high as the external cache timeout. This
583	 * applies even if no internal cache is used.
584	 */
585	SSL_CTX_set_timeout(server_ctx, props->scache_timeout);
586    } else {
587
588	/*
589	 * If we have no external cache, disable all caching. No use wasting
590	 * server memory resources with sessions they are unlikely to be able
591	 * to reuse.
592	 */
593	SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF);
594    }
595
596    return (app_ctx);
597}
598
599 /*
600  * This is the actual startup routine for a new connection. We expect that
601  * the SMTP buffers are flushed and the "220 Ready to start TLS" was sent to
602  * the client, so that we can immediately start the TLS handshake process.
603  */
604TLS_SESS_STATE *tls_server_start(const TLS_SERVER_START_PROPS *props)
605{
606    int     sts;
607    TLS_SESS_STATE *TLScontext;
608    const char *cipher_list;
609    TLS_APPL_STATE *app_ctx = props->ctx;
610
611    if (props->log_level >= 1)
612	msg_info("setting up TLS connection from %s", props->namaddr);
613
614    cipher_list = tls_set_ciphers(app_ctx, "TLS", props->cipher_grade,
615				  props->cipher_exclusions);
616    if (cipher_list == 0) {
617	msg_warn("%s: %s: aborting TLS session", props->namaddr,
618		 vstring_str(app_ctx->why));
619	return (0);
620    }
621    if (props->log_level >= 2)
622	msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
623
624    /*
625     * Allocate a new TLScontext for the new connection and get an SSL
626     * structure. Add the location of TLScontext to the SSL to later retrieve
627     * the information inside the tls_verify_certificate_callback().
628     */
629    TLScontext = tls_alloc_sess_context(props->log_level, props->namaddr);
630    TLScontext->cache_type = app_ctx->cache_type;
631
632    TLScontext->serverid = mystrdup(props->serverid);
633    TLScontext->am_server = 1;
634
635    TLScontext->fpt_dgst = mystrdup(props->fpt_dgst);
636    TLScontext->stream = props->stream;
637
638    ERR_clear_error();
639    if ((TLScontext->con = (SSL *) SSL_new(app_ctx->ssl_ctx)) == 0) {
640	msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
641	tls_print_errors();
642	tls_free_context(TLScontext);
643	return (0);
644    }
645    if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
646	msg_warn("Could not set application data for 'TLScontext->con'");
647	tls_print_errors();
648	tls_free_context(TLScontext);
649	return (0);
650    }
651
652    /*
653     * Before really starting anything, try to seed the PRNG a little bit
654     * more.
655     */
656    tls_int_seed();
657    (void) tls_ext_seed(var_tls_daemon_rand_bytes);
658
659    /*
660     * Initialize the SSL connection to accept state. This should not be
661     * necessary anymore since 0.9.3, but the call is still in the library
662     * and maintaining compatibility never hurts.
663     */
664    SSL_set_accept_state(TLScontext->con);
665
666    /*
667     * Connect the SSL connection with the network socket.
668     */
669    if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd :
670		   vstream_fileno(props->stream)) != 1) {
671	msg_info("SSL_set_fd error to %s", props->namaddr);
672	tls_print_errors();
673	uncache_session(app_ctx->ssl_ctx, TLScontext);
674	tls_free_context(TLScontext);
675	return (0);
676    }
677
678    /*
679     * If the debug level selected is high enough, all of the data is dumped:
680     * 3 will dump the SSL negotiation, 4 will dump everything.
681     *
682     * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
683     * Well there is a BIO below the SSL routines that is automatically
684     * created for us, so we can use it for debugging purposes.
685     */
686    if (props->log_level >= 3)
687	BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
688
689    /*
690     * If we don't trigger the handshake in the library, leave control over
691     * SSL_accept/read/write/etc with the application.
692     */
693    if (props->stream == 0)
694	return (TLScontext);
695
696    /*
697     * Turn on non-blocking I/O so that we can enforce timeouts on network
698     * I/O.
699     */
700    non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
701
702    /*
703     * Start TLS negotiations. This process is a black box that invokes our
704     * call-backs for session caching and certificate verification.
705     *
706     * Error handling: If the SSL handhake fails, we print out an error message
707     * and remove all TLS state concerning this session.
708     */
709    sts = tls_bio_accept(vstream_fileno(props->stream), props->timeout,
710			 TLScontext);
711    if (sts <= 0) {
712	msg_info("SSL_accept error from %s: %d", props->namaddr, sts);
713	tls_print_errors();
714	tls_free_context(TLScontext);
715	return (0);
716    }
717    return (tls_server_post_accept(TLScontext));
718}
719
720/* tls_server_post_accept - post-handshake processing */
721
722TLS_SESS_STATE *tls_server_post_accept(TLS_SESS_STATE *TLScontext)
723{
724    const SSL_CIPHER *cipher;
725    X509   *peer;
726    char    buf[CCERT_BUFSIZ];
727
728    /* Only loglevel==4 dumps everything */
729    if (TLScontext->log_level < 4)
730	BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
731
732    /*
733     * The caller may want to know if this session was reused or if a new
734     * session was negotiated.
735     */
736    TLScontext->session_reused = SSL_session_reused(TLScontext->con);
737    if (TLScontext->log_level >= 2 && TLScontext->session_reused)
738	msg_info("%s: Reusing old session", TLScontext->namaddr);
739
740    /*
741     * Let's see whether a peer certificate is available and what is the
742     * actual information. We want to save it for later use.
743     */
744    peer = SSL_get_peer_certificate(TLScontext->con);
745    if (peer != NULL) {
746	TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT;
747	if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
748	    TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
749
750	if (TLScontext->log_level >= 2) {
751	    X509_NAME_oneline(X509_get_subject_name(peer),
752			      buf, sizeof(buf));
753	    msg_info("subject=%s", buf);
754	    X509_NAME_oneline(X509_get_issuer_name(peer),
755			      buf, sizeof(buf));
756	    msg_info("issuer=%s", buf);
757	}
758	TLScontext->peer_CN = tls_peer_CN(peer, TLScontext);
759	TLScontext->issuer_CN = tls_issuer_CN(peer, TLScontext);
760	TLScontext->peer_fingerprint =
761	    tls_fingerprint(peer, TLScontext->fpt_dgst);
762
763	if (TLScontext->log_level >= 1) {
764	    msg_info("%s: %s: subject_CN=%s, issuer=%s, fingerprint=%s",
765		     TLScontext->namaddr,
766		  TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
767		     TLScontext->peer_CN, TLScontext->issuer_CN,
768		     TLScontext->peer_fingerprint);
769	}
770	X509_free(peer);
771    } else {
772	TLScontext->peer_CN = mystrdup("");
773	TLScontext->issuer_CN = mystrdup("");
774	TLScontext->peer_fingerprint = mystrdup("");
775    }
776
777    /*
778     * Finally, collect information about protocol and cipher for logging
779     */
780    TLScontext->protocol = SSL_get_version(TLScontext->con);
781    cipher = SSL_get_current_cipher(TLScontext->con);
782    TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
783    TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
784					     &(TLScontext->cipher_algbits));
785
786    /*
787     * If the library triggered the SSL handshake, switch to the
788     * tls_timed_read/write() functions and make the TLScontext available to
789     * those functions. Otherwise, leave control over SSL_read/write/etc.
790     * with the application.
791     */
792    if (TLScontext->stream != 0)
793	tls_stream_start(TLScontext->stream, TLScontext);
794
795    /*
796     * All the key facts in a single log entry.
797     */
798    if (TLScontext->log_level >= 1)
799	msg_info("%s TLS connection established from %s: %s with cipher %s "
800	      "(%d/%d bits)", !TLS_CERT_IS_PRESENT(TLScontext) ? "Anonymous"
801		 : TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
802	 TLScontext->namaddr, TLScontext->protocol, TLScontext->cipher_name,
803		 TLScontext->cipher_usebits, TLScontext->cipher_algbits);
804
805    tls_int_seed();
806
807    return (TLScontext);
808}
809
810#endif					/* USE_TLS */
811