xref: /netbsd-src/external/ibm-public/postfix/dist/src/tls/tls_server.c (revision 46f5119e40af2e51998f686b2fdcc76b5488f7f3)
1 /*	$NetBSD: tls_server.c,v 1.4 2011/03/02 19:56:39 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   */
167 static const char server_session_id_context[] = "Postfix/TLS";
168 
169 /* get_server_session_cb - callback to retrieve session from server cache */
170 
171 static 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) + 1 + strlen(service) + 3); \
187 	hex_encode(buf, (char *) (id), (len)); \
188     	vstring_sprintf_append(buf, "&s=%s", (service)); \
189     } while (0)
190 
191 
192     GEN_CACHE_ID(cache_id, session_id, session_id_length, TLScontext->serverid);
193 
194     if (TLScontext->log_level >= 2)
195 	msg_info("%s: looking up session %s in %s cache", TLScontext->namaddr,
196 		 STR(cache_id), TLScontext->cache_type);
197 
198     /*
199      * Load the session from cache and decode it.
200      */
201     if (tls_mgr_lookup(TLScontext->cache_type, STR(cache_id),
202 		       session_data) == TLS_MGR_STAT_OK) {
203 	session = tls_session_activate(STR(session_data), LEN(session_data));
204 	if (session && (TLScontext->log_level >= 2))
205 	    msg_info("%s: reloaded session %s from %s cache",
206 		     TLScontext->namaddr, STR(cache_id),
207 		     TLScontext->cache_type);
208     }
209 
210     /*
211      * Clean up.
212      */
213     vstring_free(cache_id);
214     vstring_free(session_data);
215 
216     return (session);
217 }
218 
219 /* uncache_session - remove session from internal & external cache */
220 
221 static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext)
222 {
223     VSTRING *cache_id;
224     SSL_SESSION *session = SSL_get_session(TLScontext->con);
225 
226     SSL_CTX_remove_session(ctx, session);
227 
228     if (TLScontext->cache_type == 0)
229 	return;
230 
231     GEN_CACHE_ID(cache_id, session->session_id, session->session_id_length,
232 		 TLScontext->serverid);
233 
234     if (TLScontext->log_level >= 2)
235 	msg_info("%s: remove session %s from %s cache", TLScontext->namaddr,
236 		 STR(cache_id), TLScontext->cache_type);
237 
238     tls_mgr_delete(TLScontext->cache_type, STR(cache_id));
239     vstring_free(cache_id);
240 }
241 
242 /* new_server_session_cb - callback to save session to server cache */
243 
244 static int new_server_session_cb(SSL *ssl, SSL_SESSION *session)
245 {
246     const char *myname = "new_server_session_cb";
247     VSTRING *cache_id;
248     TLS_SESS_STATE *TLScontext;
249     VSTRING *session_data;
250 
251     if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
252 	msg_panic("%s: null TLScontext in new session callback", myname);
253 
254     GEN_CACHE_ID(cache_id, session->session_id, session->session_id_length,
255 		 TLScontext->serverid);
256 
257     if (TLScontext->log_level >= 2)
258 	msg_info("%s: save session %s to %s cache", TLScontext->namaddr,
259 		 STR(cache_id), TLScontext->cache_type);
260 
261     /*
262      * Passivate and save the session state.
263      */
264     session_data = tls_session_passivate(session);
265     if (session_data)
266 	tls_mgr_update(TLScontext->cache_type, STR(cache_id),
267 		       STR(session_data), LEN(session_data));
268 
269     /*
270      * Clean up.
271      */
272     if (session_data)
273 	vstring_free(session_data);
274     vstring_free(cache_id);
275     SSL_SESSION_free(session);			/* 200502 */
276 
277     return (1);
278 }
279 
280 /* tls_server_init - initialize the server-side TLS engine */
281 
282 TLS_APPL_STATE *tls_server_init(const TLS_SERVER_INIT_PROPS *props)
283 {
284     SSL_CTX *server_ctx;
285     long    off = 0;
286     int     verify_flags = SSL_VERIFY_NONE;
287     int     cachable;
288     int     protomask;
289     TLS_APPL_STATE *app_ctx;
290     const EVP_MD *md_alg;
291     unsigned int md_len;
292 
293     if (props->log_level >= 2)
294 	msg_info("initializing the server-side TLS engine");
295 
296     /*
297      * Load (mostly cipher related) TLS-library internal main.cf parameters.
298      */
299     tls_param_init();
300 
301     /*
302      * Detect mismatch between compile-time headers and run-time library.
303      */
304     tls_check_version();
305 
306     /*
307      * Initialize the OpenSSL library by the book! To start with, we must
308      * initialize the algorithms. We want cleartext error messages instead of
309      * just error codes, so we load the error_strings.
310      */
311     SSL_load_error_strings();
312     OpenSSL_add_ssl_algorithms();
313 
314     /*
315      * First validate the protocols. If these are invalid, we can't continue.
316      */
317     protomask = tls_protocol_mask(props->protocols);
318     if (protomask == TLS_PROTOCOL_INVALID) {
319 	/* tls_protocol_mask() logs no warning. */
320 	msg_warn("Invalid TLS protocol list \"%s\": disabling TLS support",
321 		 props->protocols);
322 	return (0);
323     }
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. Netscape communicator can still
372      * communicate with SSLv2 servers, so it sends out a SSLv2 client hello.
373      * To deal with it, our server must be SSLv2 aware (even if we don't like
374      * SSLv2), so we need to have the SSLv23 server here. If we want to limit
375      * the protocol level, we can add an option to not use SSLv2/v3/TLSv1
376      * later.
377      */
378     ERR_clear_error();
379     if ((server_ctx = SSL_CTX_new(SSLv23_server_method())) == 0) {
380 	msg_warn("cannot allocate server SSL_CTX: disabling TLS support");
381 	tls_print_errors();
382 	return (0);
383     }
384 
385     /*
386      * See the verify callback in tls_verify.c
387      */
388     SSL_CTX_set_verify_depth(server_ctx, props->verifydepth + 1);
389 
390     /*
391      * Protocol work-arounds, OpenSSL version dependent.
392      */
393     off |= tls_bug_bits();
394     SSL_CTX_set_options(server_ctx, off);
395 
396     /*
397      * Global protocol selection.
398      */
399     if (protomask != 0)
400 	SSL_CTX_set_options(server_ctx,
401 		   ((protomask & TLS_PROTOCOL_TLSv1) ? SSL_OP_NO_TLSv1 : 0L)
402 		 | ((protomask & TLS_PROTOCOL_SSLv3) ? SSL_OP_NO_SSLv3 : 0L)
403 	       | ((protomask & TLS_PROTOCOL_SSLv2) ? SSL_OP_NO_SSLv2 : 0L));
404 
405 #if OPENSSL_VERSION_NUMBER >= 0x0090700fL
406 
407     /*
408      * Some sites may want to give the client less rope. On the other hand,
409      * this could trigger inter-operability issues, the client should not
410      * offer ciphers it implements poorly, but this hasn't stopped some
411      * vendors from getting it wrong.
412      *
413      * XXX: Given OpenSSL's security history, nobody should still be using
414      * 0.9.7, let alone 0.9.6 or earlier. Warning added to TLS_README.html.
415      */
416     if (var_tls_preempt_clist)
417 	SSL_CTX_set_options(server_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
418 #endif
419 
420     /*
421      * Set the call-back routine to debug handshake progress.
422      */
423     if (props->log_level >= 2)
424 	SSL_CTX_set_info_callback(server_ctx, tls_info_callback);
425 
426     /*
427      * Load the CA public key certificates for both the server cert and for
428      * the verification of client certificates. As provided by OpenSSL we
429      * support two types of CA certificate handling: One possibility is to
430      * add all CA certificates to one large CAfile, the other possibility is
431      * a directory pointed to by CApath, containing separate files for each
432      * CA with softlinks named after the hash values of the certificate. The
433      * first alternative has the advantage that the file is opened and read
434      * at startup time, so that you don't have the hassle to maintain another
435      * copy of the CApath directory for chroot-jail.
436      */
437     if (tls_set_ca_certificate_info(server_ctx,
438 				    props->CAfile, props->CApath) < 0) {
439 	/* tls_set_ca_certificate_info() already logs a warning. */
440 	SSL_CTX_free(server_ctx);		/* 200411 */
441 	return (0);
442     }
443 
444     /*
445      * Load the server public key certificate and private key from file and
446      * check whether the cert matches the key. We can use RSA certificates
447      * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
448      * All three can be made available at the same time. The CA certificates
449      * for all three are handled in the same setup already finished. Which
450      * one is used depends on the cipher negotiated (that is: the first
451      * cipher listed by the client which does match the server). A client
452      * with RSA only (e.g. Netscape) will use the RSA certificate only. A
453      * client with openssl-library will use RSA first if not especially
454      * changed in the cipher setup.
455      */
456     if (tls_set_my_certificate_key_info(server_ctx,
457 					props->cert_file,
458 					props->key_file,
459 					props->dcert_file,
460 					props->dkey_file,
461 					props->eccert_file,
462 					props->eckey_file) < 0) {
463 	/* tls_set_my_certificate_key_info() already logs a warning. */
464 	SSL_CTX_free(server_ctx);		/* 200411 */
465 	return (0);
466     }
467 
468     /*
469      * According to the OpenSSL documentation, temporary RSA key is needed
470      * export ciphers are in use. We have to provide one, so well, we just do
471      * it.
472      */
473     SSL_CTX_set_tmp_rsa_callback(server_ctx, tls_tmp_rsa_cb);
474 
475     /*
476      * Diffie-Hellman key generation parameters can either be loaded from
477      * files (preferred) or taken from compiled in values. First, set the
478      * callback that will select the values when requested, then load the
479      * (possibly) available DH parameters from files. We are generous with
480      * the error handling, since we do have default values compiled in, so we
481      * will not abort but just log the error message.
482      */
483     SSL_CTX_set_tmp_dh_callback(server_ctx, tls_tmp_dh_cb);
484     if (*props->dh1024_param_file != 0)
485 	tls_set_dh_from_file(props->dh1024_param_file, 1024);
486     if (*props->dh512_param_file != 0)
487 	tls_set_dh_from_file(props->dh512_param_file, 512);
488 
489     /*
490      * Enable EECDH if available, errors are not fatal, we just keep going
491      * with any remaining key-exchange algorithms.
492      */
493     (void) tls_set_eecdh_curve(server_ctx, props->eecdh_grade);
494 
495     /*
496      * If we want to check client certificates, we have to indicate it in
497      * advance. By now we only allow to decide on a global basis. If we want
498      * to allow certificate based relaying, we must ask the client to provide
499      * one with SSL_VERIFY_PEER. The client now can decide, whether it
500      * provides one or not. We can enforce a failure of the negotiation with
501      * SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we do not allow a connection
502      * without one. In the "server hello" following the initialization by the
503      * "client hello" the server must provide a list of CAs it is willing to
504      * accept. Some clever clients will then select one from the list of
505      * available certificates matching these CAs. Netscape Communicator will
506      * present the list of certificates for selecting the one to be sent, or
507      * it will issue a warning, if there is no certificate matching the
508      * available CAs.
509      *
510      * With regard to the purpose of the certificate for relaying, we might like
511      * a later negotiation, maybe relaying would already be allowed for other
512      * reasons, but this would involve severe changes in the internal postfix
513      * logic, so we have to live with it the way it is.
514      */
515     if (props->ask_ccert)
516 	verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
517     SSL_CTX_set_verify(server_ctx, verify_flags,
518 		       tls_verify_certificate_callback);
519     if (*props->CAfile)
520 	SSL_CTX_set_client_CA_list(server_ctx,
521 				   SSL_load_client_CA_file(props->CAfile));
522 
523     /*
524      * Initialize our own TLS server handle, before diving into the details
525      * of TLS session cache management.
526      */
527     app_ctx = tls_alloc_app_context(server_ctx);
528 
529     /*
530      * The session cache is implemented by the tlsmgr(8) server.
531      *
532      * XXX 200502 Surprise: when OpenSSL purges an entry from the in-memory
533      * cache, it also attempts to purge the entry from the on-disk cache.
534      * This is undesirable, especially when we set the in-memory cache size
535      * to 1. For this reason we don't allow OpenSSL to purge on-disk cache
536      * entries, and leave it up to the tlsmgr process instead. Found by
537      * Victor Duchovni.
538      */
539 
540     if (tls_mgr_policy(props->cache_type, &cachable) != TLS_MGR_STAT_OK)
541 	cachable = 0;
542 
543     if (cachable || props->set_sessid) {
544 
545 	/*
546 	 * Initialize the session cache.
547 	 *
548 	 * With a large number of concurrent smtpd(8) processes, it is not a
549 	 * good idea to cache multiple large session objects in each process.
550 	 * We set the internal cache size to 1, and don't register a
551 	 * "remove_cb" so as to avoid deleting good sessions from the
552 	 * external cache prematurely (when the internal cache is full,
553 	 * OpenSSL removes sessions from the external cache also)!
554 	 *
555 	 * This makes SSL_CTX_remove_session() not useful for flushing broken
556 	 * sessions from the external cache, so we must delete them directly
557 	 * (not via a callback).
558 	 *
559 	 * Set a session id context to identify to what type of server process
560 	 * created a session. In our case, the context is simply the name of
561 	 * the mail system: "Postfix/TLS".
562 	 */
563 	SSL_CTX_sess_set_cache_size(server_ctx, 1);
564 	SSL_CTX_set_session_id_context(server_ctx,
565 				       (void *) &server_session_id_context,
566 				       sizeof(server_session_id_context));
567 	SSL_CTX_set_session_cache_mode(server_ctx,
568 				       SSL_SESS_CACHE_SERVER |
569 				       SSL_SESS_CACHE_NO_AUTO_CLEAR);
570 	if (cachable) {
571 	    app_ctx->cache_type = mystrdup(props->cache_type);
572 
573 	    SSL_CTX_sess_set_get_cb(server_ctx, get_server_session_cb);
574 	    SSL_CTX_sess_set_new_cb(server_ctx, new_server_session_cb);
575 	}
576 
577 	/*
578 	 * OpenSSL ignores timed-out sessions. We need to set the internal
579 	 * cache timeout at least as high as the external cache timeout. This
580 	 * applies even if no internal cache is used.
581 	 */
582 	SSL_CTX_set_timeout(server_ctx, props->scache_timeout);
583     } else {
584 
585 	/*
586 	 * If we have no external cache, disable all caching. No use wasting
587 	 * server memory resources with sessions they are unlikely to be able
588 	 * to reuse.
589 	 */
590 	SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF);
591     }
592 
593     return (app_ctx);
594 }
595 
596  /*
597   * This is the actual startup routine for a new connection. We expect that
598   * the SMTP buffers are flushed and the "220 Ready to start TLS" was sent to
599   * the client, so that we can immediately start the TLS handshake process.
600   */
601 TLS_SESS_STATE *tls_server_start(const TLS_SERVER_START_PROPS *props)
602 {
603     int     sts;
604     TLS_SESS_STATE *TLScontext;
605     const char *cipher_list;
606     TLS_APPL_STATE *app_ctx = props->ctx;
607 
608     if (props->log_level >= 1)
609 	msg_info("setting up TLS connection from %s", props->namaddr);
610 
611     cipher_list = tls_set_ciphers(app_ctx, "TLS", props->cipher_grade,
612 				  props->cipher_exclusions);
613     if (cipher_list == 0) {
614 	msg_warn("%s: %s: aborting TLS session", props->namaddr,
615 		 vstring_str(app_ctx->why));
616 	return (0);
617     }
618     if (props->log_level >= 2)
619 	msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
620 
621     /*
622      * Allocate a new TLScontext for the new connection and get an SSL
623      * structure. Add the location of TLScontext to the SSL to later retrieve
624      * the information inside the tls_verify_certificate_callback().
625      */
626     TLScontext = tls_alloc_sess_context(props->log_level, props->namaddr);
627     TLScontext->cache_type = app_ctx->cache_type;
628 
629     TLScontext->serverid = mystrdup(props->serverid);
630     TLScontext->am_server = 1;
631 
632     TLScontext->fpt_dgst = mystrdup(props->fpt_dgst);
633     TLScontext->stream = props->stream;
634 
635     ERR_clear_error();
636     if ((TLScontext->con = (SSL *) SSL_new(app_ctx->ssl_ctx)) == 0) {
637 	msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
638 	tls_print_errors();
639 	tls_free_context(TLScontext);
640 	return (0);
641     }
642     if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
643 	msg_warn("Could not set application data for 'TLScontext->con'");
644 	tls_print_errors();
645 	tls_free_context(TLScontext);
646 	return (0);
647     }
648 
649     /*
650      * Before really starting anything, try to seed the PRNG a little bit
651      * more.
652      */
653     tls_int_seed();
654     (void) tls_ext_seed(var_tls_daemon_rand_bytes);
655 
656     /*
657      * Initialize the SSL connection to accept state. This should not be
658      * necessary anymore since 0.9.3, but the call is still in the library
659      * and maintaining compatibility never hurts.
660      */
661     SSL_set_accept_state(TLScontext->con);
662 
663     /*
664      * Connect the SSL connection with the network socket.
665      */
666     if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd :
667 		   vstream_fileno(props->stream)) != 1) {
668 	msg_info("SSL_set_fd error to %s", props->namaddr);
669 	tls_print_errors();
670 	uncache_session(app_ctx->ssl_ctx, TLScontext);
671 	tls_free_context(TLScontext);
672 	return (0);
673     }
674 
675     /*
676      * If the debug level selected is high enough, all of the data is dumped:
677      * 3 will dump the SSL negotiation, 4 will dump everything.
678      *
679      * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
680      * Well there is a BIO below the SSL routines that is automatically
681      * created for us, so we can use it for debugging purposes.
682      */
683     if (props->log_level >= 3)
684 	BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
685 
686     /*
687      * If we don't trigger the handshake in the library, leave control over
688      * SSL_accept/read/write/etc with the application.
689      */
690     if (props->stream == 0)
691 	return (TLScontext);
692 
693     /*
694      * Turn on non-blocking I/O so that we can enforce timeouts on network
695      * I/O.
696      */
697     non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
698 
699     /*
700      * Start TLS negotiations. This process is a black box that invokes our
701      * call-backs for session caching and certificate verification.
702      *
703      * Error handling: If the SSL handhake fails, we print out an error message
704      * and remove all TLS state concerning this session.
705      */
706     sts = tls_bio_accept(vstream_fileno(props->stream), props->timeout,
707 			 TLScontext);
708     if (sts <= 0) {
709 	msg_info("SSL_accept error from %s: %d", props->namaddr, sts);
710 	tls_print_errors();
711 	tls_free_context(TLScontext);
712 	return (0);
713     }
714     return (tls_server_post_accept(TLScontext));
715 }
716 
717 /* tls_server_post_accept - post-handshake processing */
718 
719 TLS_SESS_STATE *tls_server_post_accept(TLS_SESS_STATE *TLScontext)
720 {
721     const SSL_CIPHER *cipher;
722     X509   *peer;
723     char    buf[CCERT_BUFSIZ];
724 
725     /* Only loglevel==4 dumps everything */
726     if (TLScontext->log_level < 4)
727 	BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
728 
729     /*
730      * The caller may want to know if this session was reused or if a new
731      * session was negotiated.
732      */
733     TLScontext->session_reused = SSL_session_reused(TLScontext->con);
734     if (TLScontext->log_level >= 2 && TLScontext->session_reused)
735 	msg_info("%s: Reusing old session", TLScontext->namaddr);
736 
737     /*
738      * Let's see whether a peer certificate is available and what is the
739      * actual information. We want to save it for later use.
740      */
741     peer = SSL_get_peer_certificate(TLScontext->con);
742     if (peer != NULL) {
743 	TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT;
744 	if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
745 	    TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
746 
747 	if (TLScontext->log_level >= 2) {
748 	    X509_NAME_oneline(X509_get_subject_name(peer),
749 			      buf, sizeof(buf));
750 	    msg_info("subject=%s", buf);
751 	    X509_NAME_oneline(X509_get_issuer_name(peer),
752 			      buf, sizeof(buf));
753 	    msg_info("issuer=%s", buf);
754 	}
755 	TLScontext->peer_CN = tls_peer_CN(peer, TLScontext);
756 	TLScontext->issuer_CN = tls_issuer_CN(peer, TLScontext);
757 	TLScontext->peer_fingerprint =
758 	    tls_fingerprint(peer, TLScontext->fpt_dgst);
759 
760 	if (TLScontext->log_level >= 1) {
761 	    msg_info("%s: %s: subject_CN=%s, issuer=%s, fingerprint=%s",
762 		     TLScontext->namaddr,
763 		  TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
764 		     TLScontext->peer_CN, TLScontext->issuer_CN,
765 		     TLScontext->peer_fingerprint);
766 	}
767 	X509_free(peer);
768     } else {
769 	TLScontext->peer_CN = mystrdup("");
770 	TLScontext->issuer_CN = mystrdup("");
771 	TLScontext->peer_fingerprint = mystrdup("");
772     }
773 
774     /*
775      * Finally, collect information about protocol and cipher for logging
776      */
777     TLScontext->protocol = SSL_get_version(TLScontext->con);
778     cipher = SSL_get_current_cipher(TLScontext->con);
779     TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
780     TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
781 					     &(TLScontext->cipher_algbits));
782 
783     /*
784      * If the library triggered the SSL handshake, switch to the
785      * tls_timed_read/write() functions and make the TLScontext available to
786      * those functions. Otherwise, leave control over SSL_read/write/etc.
787      * with the application.
788      */
789     if (TLScontext->stream != 0)
790 	tls_stream_start(TLScontext->stream, TLScontext);
791 
792     /*
793      * All the key facts in a single log entry.
794      */
795     if (TLScontext->log_level >= 1)
796 	msg_info("%s TLS connection established from %s: %s with cipher %s "
797 	      "(%d/%d bits)", !TLS_CERT_IS_PRESENT(TLScontext) ? "Anonymous"
798 		 : TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
799 	 TLScontext->namaddr, TLScontext->protocol, TLScontext->cipher_name,
800 		 TLScontext->cipher_usebits, TLScontext->cipher_algbits);
801 
802     tls_int_seed();
803 
804     return (TLScontext);
805 }
806 
807 #endif					/* USE_TLS */
808