xref: /netbsd-src/external/ibm-public/postfix/dist/src/tls/tls_server.c (revision 7788a0781fe6ff2cce37368b4578a7ade0850cb1)
1 /*	$NetBSD: tls_server.c,v 1.6 2013/01/02 19:18:36 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 + 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_mask & TLS_LOG_CACHE)
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_mask & TLS_LOG_CACHE))
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 
222 static 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_mask & TLS_LOG_CACHE)
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 
245 static 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_mask & TLS_LOG_CACHE)
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 
283 TLS_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     int     log_mask;
294 
295     /*
296      * Convert user loglevel to internal logmask.
297      */
298     log_mask = tls_log_mask(props->log_param, props->log_level);
299 
300     if (log_mask & TLS_LOG_VERBOSE)
301 	msg_info("initializing the server-side TLS engine");
302 
303     /*
304      * Load (mostly cipher related) TLS-library internal main.cf parameters.
305      */
306     tls_param_init();
307 
308     /*
309      * Detect mismatch between compile-time headers and run-time library.
310      */
311     tls_check_version();
312 
313     /*
314      * Initialize the OpenSSL library by the book! To start with, we must
315      * initialize the algorithms. We want cleartext error messages instead of
316      * just error codes, so we load the error_strings.
317      */
318     SSL_load_error_strings();
319     OpenSSL_add_ssl_algorithms();
320 
321     /*
322      * First validate the protocols. If these are invalid, we can't continue.
323      */
324     protomask = tls_protocol_mask(props->protocols);
325     if (protomask == TLS_PROTOCOL_INVALID) {
326 	/* tls_protocol_mask() logs no warning. */
327 	msg_warn("Invalid TLS protocol list \"%s\": disabling TLS support",
328 		 props->protocols);
329 	return (0);
330     }
331 
332     /*
333      * Create an application data index for SSL objects, so that we can
334      * attach TLScontext information; this information is needed inside
335      * tls_verify_certificate_callback().
336      */
337     if (TLScontext_index < 0) {
338 	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) {
339 	    msg_warn("Cannot allocate SSL application data index: "
340 		     "disabling TLS support");
341 	    return (0);
342 	}
343     }
344 
345     /*
346      * If the administrator specifies an unsupported digest algorithm, fail
347      * now, rather than in the middle of a TLS handshake.
348      */
349     if ((md_alg = EVP_get_digestbyname(props->fpt_dgst)) == 0) {
350 	msg_warn("Digest algorithm \"%s\" not found: disabling TLS support",
351 		 props->fpt_dgst);
352 	return (0);
353     }
354 
355     /*
356      * Sanity check: Newer shared libraries may use larger digests.
357      */
358     if ((md_len = EVP_MD_size(md_alg)) > EVP_MAX_MD_SIZE) {
359 	msg_warn("Digest algorithm \"%s\" output size %u too large:"
360 		 " disabling TLS support", props->fpt_dgst, md_len);
361 	return (0);
362     }
363 
364     /*
365      * Initialize the PRNG (Pseudo Random Number Generator) with some seed
366      * from external and internal sources. Don't enable TLS without some real
367      * entropy.
368      */
369     if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
370 	msg_warn("no entropy for TLS key generation: disabling TLS support");
371 	return (0);
372     }
373     tls_int_seed();
374 
375     /*
376      * The SSL/TLS specifications require the client to send a message in the
377      * oldest specification it understands with the highest level it
378      * understands in the message. Netscape communicator can still
379      * communicate with SSLv2 servers, so it sends out a SSLv2 client hello.
380      * To deal with it, our server must be SSLv2 aware (even if we don't like
381      * SSLv2), so we need to have the SSLv23 server here. If we want to limit
382      * the protocol level, we can add an option to not use SSLv2/v3/TLSv1
383      * later.
384      */
385     ERR_clear_error();
386     if ((server_ctx = SSL_CTX_new(SSLv23_server_method())) == 0) {
387 	msg_warn("cannot allocate server SSL_CTX: disabling TLS support");
388 	tls_print_errors();
389 	return (0);
390     }
391 
392     /*
393      * See the verify callback in tls_verify.c
394      */
395     SSL_CTX_set_verify_depth(server_ctx, props->verifydepth + 1);
396 
397     /*
398      * Protocol work-arounds, OpenSSL version dependent.
399      */
400     off |= tls_bug_bits();
401     SSL_CTX_set_options(server_ctx, off);
402 
403     /*
404      * Global protocol selection.
405      */
406     if (protomask != 0)
407 	SSL_CTX_set_options(server_ctx,
408 		   ((protomask & TLS_PROTOCOL_TLSv1) ? SSL_OP_NO_TLSv1 : 0L)
409 	     | ((protomask & TLS_PROTOCOL_TLSv1_1) ? SSL_OP_NO_TLSv1_1 : 0L)
410 	     | ((protomask & TLS_PROTOCOL_TLSv1_2) ? SSL_OP_NO_TLSv1_2 : 0L)
411 		 | ((protomask & TLS_PROTOCOL_SSLv3) ? SSL_OP_NO_SSLv3 : 0L)
412 	       | ((protomask & TLS_PROTOCOL_SSLv2) ? SSL_OP_NO_SSLv2 : 0L));
413 
414 #if OPENSSL_VERSION_NUMBER >= 0x0090700fL
415 
416     /*
417      * Some sites may want to give the client less rope. On the other hand,
418      * this could trigger inter-operability issues, the client should not
419      * offer ciphers it implements poorly, but this hasn't stopped some
420      * vendors from getting it wrong.
421      *
422      * XXX: Given OpenSSL's security history, nobody should still be using
423      * 0.9.7, let alone 0.9.6 or earlier. Warning added to TLS_README.html.
424      */
425     if (var_tls_preempt_clist)
426 	SSL_CTX_set_options(server_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
427 #endif
428 
429     /*
430      * Set the call-back routine to debug handshake progress.
431      */
432     if (log_mask & TLS_LOG_DEBUG)
433 	SSL_CTX_set_info_callback(server_ctx, tls_info_callback);
434 
435     /*
436      * Load the CA public key certificates for both the server cert and for
437      * the verification of client certificates. As provided by OpenSSL we
438      * support two types of CA certificate handling: One possibility is to
439      * add all CA certificates to one large CAfile, the other possibility is
440      * a directory pointed to by CApath, containing separate files for each
441      * CA with softlinks named after the hash values of the certificate. The
442      * first alternative has the advantage that the file is opened and read
443      * at startup time, so that you don't have the hassle to maintain another
444      * copy of the CApath directory for chroot-jail.
445      */
446     if (tls_set_ca_certificate_info(server_ctx,
447 				    props->CAfile, props->CApath) < 0) {
448 	/* tls_set_ca_certificate_info() already logs a warning. */
449 	SSL_CTX_free(server_ctx);		/* 200411 */
450 	return (0);
451     }
452 
453     /*
454      * Load the server public key certificate and private key from file and
455      * check whether the cert matches the key. We can use RSA certificates
456      * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
457      * All three can be made available at the same time. The CA certificates
458      * for all three are handled in the same setup already finished. Which
459      * one is used depends on the cipher negotiated (that is: the first
460      * cipher listed by the client which does match the server). A client
461      * with RSA only (e.g. Netscape) will use the RSA certificate only. A
462      * client with openssl-library will use RSA first if not especially
463      * changed in the cipher setup.
464      */
465     if (tls_set_my_certificate_key_info(server_ctx,
466 					props->cert_file,
467 					props->key_file,
468 					props->dcert_file,
469 					props->dkey_file,
470 					props->eccert_file,
471 					props->eckey_file) < 0) {
472 	/* tls_set_my_certificate_key_info() already logs a warning. */
473 	SSL_CTX_free(server_ctx);		/* 200411 */
474 	return (0);
475     }
476 
477     /*
478      * According to OpenSSL documentation, a temporary RSA key is needed when
479      * export ciphers are in use, because the certified key cannot be
480      * directly used.
481      */
482     SSL_CTX_set_tmp_rsa_callback(server_ctx, tls_tmp_rsa_cb);
483 
484     /*
485      * Diffie-Hellman key generation parameters can either be loaded from
486      * files (preferred) or taken from compiled in values. First, set the
487      * callback that will select the values when requested, then load the
488      * (possibly) available DH parameters from files. We are generous with
489      * the error handling, since we do have default values compiled in, so we
490      * will not abort but just log the error message.
491      */
492     SSL_CTX_set_tmp_dh_callback(server_ctx, tls_tmp_dh_cb);
493     if (*props->dh1024_param_file != 0)
494 	tls_set_dh_from_file(props->dh1024_param_file, 1024);
495     if (*props->dh512_param_file != 0)
496 	tls_set_dh_from_file(props->dh512_param_file, 512);
497 
498     /*
499      * Enable EECDH if available, errors are not fatal, we just keep going
500      * with any remaining key-exchange algorithms.
501      */
502     (void) tls_set_eecdh_curve(server_ctx, props->eecdh_grade);
503 
504     /*
505      * If we want to check client certificates, we have to indicate it in
506      * advance. By now we only allow to decide on a global basis. If we want
507      * to allow certificate based relaying, we must ask the client to provide
508      * one with SSL_VERIFY_PEER. The client now can decide, whether it
509      * provides one or not. We can enforce a failure of the negotiation with
510      * SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we do not allow a connection
511      * without one. In the "server hello" following the initialization by the
512      * "client hello" the server must provide a list of CAs it is willing to
513      * accept. Some clever clients will then select one from the list of
514      * available certificates matching these CAs. Netscape Communicator will
515      * present the list of certificates for selecting the one to be sent, or
516      * it will issue a warning, if there is no certificate matching the
517      * available CAs.
518      *
519      * With regard to the purpose of the certificate for relaying, we might like
520      * a later negotiation, maybe relaying would already be allowed for other
521      * reasons, but this would involve severe changes in the internal postfix
522      * logic, so we have to live with it the way it is.
523      */
524     if (props->ask_ccert)
525 	verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
526     SSL_CTX_set_verify(server_ctx, verify_flags,
527 		       tls_verify_certificate_callback);
528     if (*props->CAfile)
529 	SSL_CTX_set_client_CA_list(server_ctx,
530 				   SSL_load_client_CA_file(props->CAfile));
531 
532     /*
533      * Initialize our own TLS server handle, before diving into the details
534      * of TLS session cache management.
535      */
536     app_ctx = tls_alloc_app_context(server_ctx, log_mask);
537 
538     /*
539      * The session cache is implemented by the tlsmgr(8) server.
540      *
541      * XXX 200502 Surprise: when OpenSSL purges an entry from the in-memory
542      * cache, it also attempts to purge the entry from the on-disk cache.
543      * This is undesirable, especially when we set the in-memory cache size
544      * to 1. For this reason we don't allow OpenSSL to purge on-disk cache
545      * entries, and leave it up to the tlsmgr process instead. Found by
546      * Victor Duchovni.
547      */
548 
549     if (tls_mgr_policy(props->cache_type, &cachable) != TLS_MGR_STAT_OK)
550 	cachable = 0;
551 
552     if (cachable || props->set_sessid) {
553 
554 	/*
555 	 * Initialize the session cache.
556 	 *
557 	 * With a large number of concurrent smtpd(8) processes, it is not a
558 	 * good idea to cache multiple large session objects in each process.
559 	 * We set the internal cache size to 1, and don't register a
560 	 * "remove_cb" so as to avoid deleting good sessions from the
561 	 * external cache prematurely (when the internal cache is full,
562 	 * OpenSSL removes sessions from the external cache also)!
563 	 *
564 	 * This makes SSL_CTX_remove_session() not useful for flushing broken
565 	 * sessions from the external cache, so we must delete them directly
566 	 * (not via a callback).
567 	 *
568 	 * Set a session id context to identify to what type of server process
569 	 * created a session. In our case, the context is simply the name of
570 	 * the mail system: "Postfix/TLS".
571 	 */
572 	SSL_CTX_sess_set_cache_size(server_ctx, 1);
573 	SSL_CTX_set_session_id_context(server_ctx,
574 				       (void *) &server_session_id_context,
575 				       sizeof(server_session_id_context));
576 	SSL_CTX_set_session_cache_mode(server_ctx,
577 				       SSL_SESS_CACHE_SERVER |
578 				       SSL_SESS_CACHE_NO_AUTO_CLEAR);
579 	if (cachable) {
580 	    app_ctx->cache_type = mystrdup(props->cache_type);
581 
582 	    SSL_CTX_sess_set_get_cb(server_ctx, get_server_session_cb);
583 	    SSL_CTX_sess_set_new_cb(server_ctx, new_server_session_cb);
584 	}
585 
586 	/*
587 	 * OpenSSL ignores timed-out sessions. We need to set the internal
588 	 * cache timeout at least as high as the external cache timeout. This
589 	 * applies even if no internal cache is used.
590 	 */
591 	SSL_CTX_set_timeout(server_ctx, props->scache_timeout);
592     } else {
593 
594 	/*
595 	 * If we have no external cache, disable all caching. No use wasting
596 	 * server memory resources with sessions they are unlikely to be able
597 	 * to reuse.
598 	 */
599 	SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF);
600     }
601 
602     return (app_ctx);
603 }
604 
605  /*
606   * This is the actual startup routine for a new connection. We expect that
607   * the SMTP buffers are flushed and the "220 Ready to start TLS" was sent to
608   * the client, so that we can immediately start the TLS handshake process.
609   */
610 TLS_SESS_STATE *tls_server_start(const TLS_SERVER_START_PROPS *props)
611 {
612     int     sts;
613     TLS_SESS_STATE *TLScontext;
614     const char *cipher_list;
615     TLS_APPL_STATE *app_ctx = props->ctx;
616     int     log_mask = app_ctx->log_mask;
617 
618     /*
619      * Implicitly enable logging of trust chain errors when verified certs
620      * are required.
621      */
622     if (props->requirecert)
623 	log_mask |= TLS_LOG_UNTRUSTED;
624 
625     if (log_mask & TLS_LOG_VERBOSE)
626 	msg_info("setting up TLS connection from %s", props->namaddr);
627 
628     cipher_list = tls_set_ciphers(app_ctx, "TLS", props->cipher_grade,
629 				  props->cipher_exclusions);
630     if (cipher_list == 0) {
631 	msg_warn("%s: %s: aborting TLS session", props->namaddr,
632 		 vstring_str(app_ctx->why));
633 	return (0);
634     }
635     if (log_mask & TLS_LOG_VERBOSE)
636 	msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
637 
638     /*
639      * Allocate a new TLScontext for the new connection and get an SSL
640      * structure. Add the location of TLScontext to the SSL to later retrieve
641      * the information inside the tls_verify_certificate_callback().
642      */
643     TLScontext = tls_alloc_sess_context(log_mask, props->namaddr);
644     TLScontext->cache_type = app_ctx->cache_type;
645 
646     TLScontext->serverid = mystrdup(props->serverid);
647     TLScontext->am_server = 1;
648 
649     TLScontext->fpt_dgst = mystrdup(props->fpt_dgst);
650     TLScontext->stream = props->stream;
651 
652     ERR_clear_error();
653     if ((TLScontext->con = (SSL *) SSL_new(app_ctx->ssl_ctx)) == 0) {
654 	msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
655 	tls_print_errors();
656 	tls_free_context(TLScontext);
657 	return (0);
658     }
659     if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
660 	msg_warn("Could not set application data for 'TLScontext->con'");
661 	tls_print_errors();
662 	tls_free_context(TLScontext);
663 	return (0);
664     }
665 
666     /*
667      * Before really starting anything, try to seed the PRNG a little bit
668      * more.
669      */
670     tls_int_seed();
671     (void) tls_ext_seed(var_tls_daemon_rand_bytes);
672 
673     /*
674      * Initialize the SSL connection to accept state. This should not be
675      * necessary anymore since 0.9.3, but the call is still in the library
676      * and maintaining compatibility never hurts.
677      */
678     SSL_set_accept_state(TLScontext->con);
679 
680     /*
681      * Connect the SSL connection with the network socket.
682      */
683     if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd :
684 		   vstream_fileno(props->stream)) != 1) {
685 	msg_info("SSL_set_fd error to %s", props->namaddr);
686 	tls_print_errors();
687 	uncache_session(app_ctx->ssl_ctx, TLScontext);
688 	tls_free_context(TLScontext);
689 	return (0);
690     }
691 
692     /*
693      * If the debug level selected is high enough, all of the data is dumped:
694      * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will
695      * dump everything.
696      *
697      * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
698      * Well there is a BIO below the SSL routines that is automatically
699      * created for us, so we can use it for debugging purposes.
700      */
701     if (log_mask & TLS_LOG_TLSPKTS)
702 	BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
703 
704     /*
705      * If we don't trigger the handshake in the library, leave control over
706      * SSL_accept/read/write/etc with the application.
707      */
708     if (props->stream == 0)
709 	return (TLScontext);
710 
711     /*
712      * Turn on non-blocking I/O so that we can enforce timeouts on network
713      * I/O.
714      */
715     non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
716 
717     /*
718      * Start TLS negotiations. This process is a black box that invokes our
719      * call-backs for session caching and certificate verification.
720      *
721      * Error handling: If the SSL handhake fails, we print out an error message
722      * and remove all TLS state concerning this session.
723      */
724     sts = tls_bio_accept(vstream_fileno(props->stream), props->timeout,
725 			 TLScontext);
726     if (sts <= 0) {
727 	if (ERR_peek_error() != 0) {
728 	    msg_info("SSL_accept error from %s: %d", props->namaddr, sts);
729 	    tls_print_errors();
730 	} else if (errno != 0) {
731 	    msg_info("SSL_accept error from %s: %m", props->namaddr);
732 	} else {
733 	    msg_info("SSL_accept error from %s: lost connection",
734 		     props->namaddr);
735 	}
736 	tls_free_context(TLScontext);
737 	return (0);
738     }
739     return (tls_server_post_accept(TLScontext));
740 }
741 
742 /* tls_server_post_accept - post-handshake processing */
743 
744 TLS_SESS_STATE *tls_server_post_accept(TLS_SESS_STATE *TLScontext)
745 {
746     const SSL_CIPHER *cipher;
747     X509   *peer;
748     char    buf[CCERT_BUFSIZ];
749 
750     /* Turn off packet dump if only dumping the handshake */
751     if ((TLScontext->log_mask & TLS_LOG_ALLPKTS) == 0)
752 	BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
753 
754     /*
755      * The caller may want to know if this session was reused or if a new
756      * session was negotiated.
757      */
758     TLScontext->session_reused = SSL_session_reused(TLScontext->con);
759     if ((TLScontext->log_mask & TLS_LOG_CACHE) && TLScontext->session_reused)
760 	msg_info("%s: Reusing old session", TLScontext->namaddr);
761 
762     /*
763      * Let's see whether a peer certificate is available and what is the
764      * actual information. We want to save it for later use.
765      */
766     peer = SSL_get_peer_certificate(TLScontext->con);
767     if (peer != NULL) {
768 	TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT;
769 	if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
770 	    TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
771 
772 	if (TLScontext->log_mask & TLS_LOG_VERBOSE) {
773 	    X509_NAME_oneline(X509_get_subject_name(peer),
774 			      buf, sizeof(buf));
775 	    msg_info("subject=%s", buf);
776 	    X509_NAME_oneline(X509_get_issuer_name(peer),
777 			      buf, sizeof(buf));
778 	    msg_info("issuer=%s", buf);
779 	}
780 	TLScontext->peer_CN = tls_peer_CN(peer, TLScontext);
781 	TLScontext->issuer_CN = tls_issuer_CN(peer, TLScontext);
782 	TLScontext->peer_fingerprint =
783 	    tls_fingerprint(peer, TLScontext->fpt_dgst);
784 	TLScontext->peer_pkey_fprint =
785 	    tls_pkey_fprint(peer, TLScontext->fpt_dgst);
786 
787 	if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_PEERCERT)) {
788 	    msg_info("%s: subject_CN=%s, issuer=%s, fingerprint=%s"
789 		     ", pkey_fingerprint=%s",
790 		     TLScontext->namaddr,
791 		     TLScontext->peer_CN, TLScontext->issuer_CN,
792 		     TLScontext->peer_fingerprint,
793 		     TLScontext->peer_pkey_fprint);
794 	}
795 	X509_free(peer);
796     } else {
797 	TLScontext->peer_CN = mystrdup("");
798 	TLScontext->issuer_CN = mystrdup("");
799 	TLScontext->peer_fingerprint = mystrdup("");
800     }
801 
802     /*
803      * Finally, collect information about protocol and cipher for logging
804      */
805     TLScontext->protocol = SSL_get_version(TLScontext->con);
806     cipher = SSL_get_current_cipher(TLScontext->con);
807     TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
808     TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
809 					     &(TLScontext->cipher_algbits));
810 
811     /*
812      * If the library triggered the SSL handshake, switch to the
813      * tls_timed_read/write() functions and make the TLScontext available to
814      * those functions. Otherwise, leave control over SSL_read/write/etc.
815      * with the application.
816      */
817     if (TLScontext->stream != 0)
818 	tls_stream_start(TLScontext->stream, TLScontext);
819 
820     /*
821      * All the key facts in a single log entry.
822      */
823     if (TLScontext->log_mask & TLS_LOG_SUMMARY)
824 	msg_info("%s TLS connection established from %s: %s with cipher %s "
825 	      "(%d/%d bits)", !TLS_CERT_IS_PRESENT(TLScontext) ? "Anonymous"
826 		 : TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
827 	 TLScontext->namaddr, TLScontext->protocol, TLScontext->cipher_name,
828 		 TLScontext->cipher_usebits, TLScontext->cipher_algbits);
829 
830     tls_int_seed();
831 
832     return (TLScontext);
833 }
834 
835 #endif					/* USE_TLS */
836