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