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