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