xref: /netbsd-src/external/ibm-public/postfix/dist/src/tls/tls_server.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*	$NetBSD: tls_server.c,v 1.10 2020/03/18 19:05:21 christos 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 #define GET_SID(s, v, lptr)	((v) = SSL_SESSION_get_id((s), (lptr)))
170 
171  /* OpenSSL 1.1.0 bitrot */
172 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
173 typedef const unsigned char *session_id_t;
174 
175 #else
176 typedef unsigned char *session_id_t;
177 
178 #endif
179 
180 /* get_server_session_cb - callback to retrieve session from server cache */
181 
182 static SSL_SESSION *get_server_session_cb(SSL *ssl, session_id_t session_id,
183 					          int session_id_length,
184 					          int *unused_copy)
185 {
186     const char *myname = "get_server_session_cb";
187     TLS_SESS_STATE *TLScontext;
188     VSTRING *cache_id;
189     VSTRING *session_data = vstring_alloc(2048);
190     SSL_SESSION *session = 0;
191 
192     if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
193 	msg_panic("%s: null TLScontext in session lookup callback", myname);
194 
195 #define GEN_CACHE_ID(buf, id, len, service) \
196     do { \
197 	buf = vstring_alloc(2 * (len + strlen(service))); \
198 	hex_encode(buf, (char *) (id), (len)); \
199 	vstring_sprintf_append(buf, "&s=%s", (service)); \
200 	vstring_sprintf_append(buf, "&l=%ld", (long) OpenSSL_version_num()); \
201     } while (0)
202 
203 
204     GEN_CACHE_ID(cache_id, session_id, session_id_length, TLScontext->serverid);
205 
206     if (TLScontext->log_mask & TLS_LOG_CACHE)
207 	msg_info("%s: looking up session %s in %s cache", TLScontext->namaddr,
208 		 STR(cache_id), TLScontext->cache_type);
209 
210     /*
211      * Load the session from cache and decode it.
212      */
213     if (tls_mgr_lookup(TLScontext->cache_type, STR(cache_id),
214 		       session_data) == TLS_MGR_STAT_OK) {
215 	session = tls_session_activate(STR(session_data), LEN(session_data));
216 	if (session && (TLScontext->log_mask & TLS_LOG_CACHE))
217 	    msg_info("%s: reloaded session %s from %s cache",
218 		     TLScontext->namaddr, STR(cache_id),
219 		     TLScontext->cache_type);
220     }
221 
222     /*
223      * Clean up.
224      */
225     vstring_free(cache_id);
226     vstring_free(session_data);
227 
228     return (session);
229 }
230 
231 /* uncache_session - remove session from internal & external cache */
232 
233 static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext)
234 {
235     VSTRING *cache_id;
236     SSL_SESSION *session = SSL_get_session(TLScontext->con);
237     const unsigned char *sid;
238     unsigned int sid_length;
239 
240     SSL_CTX_remove_session(ctx, session);
241 
242     if (TLScontext->cache_type == 0)
243 	return;
244 
245     GET_SID(session, sid, &sid_length);
246     GEN_CACHE_ID(cache_id, sid, sid_length, TLScontext->serverid);
247 
248     if (TLScontext->log_mask & TLS_LOG_CACHE)
249 	msg_info("%s: remove session %s from %s cache", TLScontext->namaddr,
250 		 STR(cache_id), TLScontext->cache_type);
251 
252     tls_mgr_delete(TLScontext->cache_type, STR(cache_id));
253     vstring_free(cache_id);
254 }
255 
256 /* new_server_session_cb - callback to save session to server cache */
257 
258 static int new_server_session_cb(SSL *ssl, SSL_SESSION *session)
259 {
260     const char *myname = "new_server_session_cb";
261     VSTRING *cache_id;
262     TLS_SESS_STATE *TLScontext;
263     VSTRING *session_data;
264     const unsigned char *sid;
265     unsigned int sid_length;
266 
267     if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
268 	msg_panic("%s: null TLScontext in new session callback", myname);
269 
270     GET_SID(session, sid, &sid_length);
271     GEN_CACHE_ID(cache_id, sid, sid_length, TLScontext->serverid);
272 
273     if (TLScontext->log_mask & TLS_LOG_CACHE)
274 	msg_info("%s: save session %s to %s cache", TLScontext->namaddr,
275 		 STR(cache_id), TLScontext->cache_type);
276 
277     /*
278      * Passivate and save the session state.
279      */
280     session_data = tls_session_passivate(session);
281     if (session_data)
282 	tls_mgr_update(TLScontext->cache_type, STR(cache_id),
283 		       STR(session_data), LEN(session_data));
284 
285     /*
286      * Clean up.
287      */
288     if (session_data)
289 	vstring_free(session_data);
290     vstring_free(cache_id);
291     SSL_SESSION_free(session);			/* 200502 */
292 
293     return (1);
294 }
295 
296 #define NOENGINE	((ENGINE *) 0)
297 #define TLS_TKT_NOKEYS -1		/* No keys for encryption */
298 #define TLS_TKT_STALE	0		/* No matching keys for decryption */
299 #define TLS_TKT_ACCEPT	1		/* Ticket decryptable and re-usable */
300 #define TLS_TKT_REISSUE	2		/* Ticket decryptable, not re-usable */
301 
302 /* ticket_cb - configure tls session ticket encrypt/decrypt context */
303 
304 #if defined(SSL_OP_NO_TICKET) && !defined(OPENSSL_NO_TLSEXT)
305 
306 static int ticket_cb(SSL *con, unsigned char name[], unsigned char iv[],
307 		          EVP_CIPHER_CTX * ctx, HMAC_CTX * hctx, int create)
308 {
309     static const EVP_MD *sha256;
310     static const EVP_CIPHER *ciph;
311     TLS_TICKET_KEY *key;
312     TLS_SESS_STATE *TLScontext = SSL_get_ex_data(con, TLScontext_index);
313     int     timeout = ((int) SSL_CTX_get_timeout(SSL_get_SSL_CTX(con))) / 2;
314 
315     if ((!sha256 && (sha256 = EVP_sha256()) == 0)
316 	|| (!ciph && (ciph = EVP_get_cipherbyname(var_tls_tkt_cipher)) == 0)
317 	|| (key = tls_mgr_key(create ? 0 : name, timeout)) == 0
318 	|| (create && RAND_bytes(iv, TLS_TICKET_IVLEN) <= 0))
319 	return (create ? TLS_TKT_NOKEYS : TLS_TKT_STALE);
320 
321     HMAC_Init_ex(hctx, key->hmac, TLS_TICKET_MACLEN, sha256, NOENGINE);
322 
323     if (create) {
324 	EVP_EncryptInit_ex(ctx, ciph, NOENGINE, key->bits, iv);
325 	memcpy((void *) name, (void *) key->name, TLS_TICKET_NAMELEN);
326 	if (TLScontext->log_mask & TLS_LOG_CACHE)
327 	    msg_info("%s: Issuing session ticket, key expiration: %ld",
328 		     TLScontext->namaddr, (long) key->tout);
329     } else {
330 	EVP_DecryptInit_ex(ctx, ciph, NOENGINE, key->bits, iv);
331 	if (TLScontext->log_mask & TLS_LOG_CACHE)
332 	    msg_info("%s: Decrypting session ticket, key expiration: %ld",
333 		     TLScontext->namaddr, (long) key->tout);
334     }
335     TLScontext->ticketed = 1;
336     return (TLS_TKT_ACCEPT);
337 }
338 
339 #endif
340 
341 /* tls_server_init - initialize the server-side TLS engine */
342 
343 TLS_APPL_STATE *tls_server_init(const TLS_SERVER_INIT_PROPS *props)
344 {
345     SSL_CTX *server_ctx;
346     SSL_CTX *sni_ctx;
347     X509_STORE *cert_store;
348     long    off = 0;
349     int     verify_flags = SSL_VERIFY_NONE;
350     int     cachable;
351     int     scache_timeout;
352     int     ticketable = 0;
353     int     protomask;
354     TLS_APPL_STATE *app_ctx;
355     int     log_mask;
356 
357     /*
358      * Convert user loglevel to internal logmask.
359      */
360     log_mask = tls_log_mask(props->log_param, props->log_level);
361 
362     if (log_mask & TLS_LOG_VERBOSE)
363 	msg_info("initializing the server-side TLS engine");
364 
365     /*
366      * Load (mostly cipher related) TLS-library internal main.cf parameters.
367      */
368     tls_param_init();
369 
370     /*
371      * Detect mismatch between compile-time headers and run-time library.
372      */
373     tls_check_version();
374 
375 #if OPENSSL_VERSION_NUMBER < 0x10100000L
376 
377     /*
378      * Initialize the OpenSSL library by the book! To start with, we must
379      * initialize the algorithms. We want cleartext error messages instead of
380      * just error codes, so we load the error_strings.
381      */
382     SSL_load_error_strings();
383     OpenSSL_add_ssl_algorithms();
384 #endif
385 
386     /*
387      * First validate the protocols. If these are invalid, we can't continue.
388      */
389     protomask = tls_protocol_mask(props->protocols);
390     if (protomask == TLS_PROTOCOL_INVALID) {
391 	/* tls_protocol_mask() logs no warning. */
392 	msg_warn("Invalid TLS protocol list \"%s\": disabling TLS support",
393 		 props->protocols);
394 	return (0);
395     }
396 
397     /*
398      * Create an application data index for SSL objects, so that we can
399      * attach TLScontext information; this information is needed inside
400      * tls_verify_certificate_callback().
401      */
402     if (TLScontext_index < 0) {
403 	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) {
404 	    msg_warn("Cannot allocate SSL application data index: "
405 		     "disabling TLS support");
406 	    return (0);
407 	}
408     }
409 
410     /*
411      * If the administrator specifies an unsupported digest algorithm, fail
412      * now, rather than in the middle of a TLS handshake.
413      */
414     if (!tls_validate_digest(props->mdalg)) {
415 	msg_warn("disabling TLS support");
416 	return (0);
417     }
418 
419     /*
420      * Initialize the PRNG (Pseudo Random Number Generator) with some seed
421      * from external and internal sources. Don't enable TLS without some real
422      * entropy.
423      */
424     if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
425 	msg_warn("no entropy for TLS key generation: disabling TLS support");
426 	return (0);
427     }
428     tls_int_seed();
429 
430     /*
431      * The SSL/TLS specifications require the client to send a message in the
432      * oldest specification it understands with the highest level it
433      * understands in the message. Netscape communicator can still
434      * communicate with SSLv2 servers, so it sends out a SSLv2 client hello.
435      * To deal with it, our server must be SSLv2 aware (even if we don't like
436      * SSLv2), so we need to have the SSLv23 server here. If we want to limit
437      * the protocol level, we can add an option to not use SSLv2/v3/TLSv1
438      * later.
439      */
440     ERR_clear_error();
441     server_ctx = SSL_CTX_new(TLS_server_method());
442     if (server_ctx == 0) {
443 	msg_warn("cannot allocate server SSL_CTX: disabling TLS support");
444 	tls_print_errors();
445 	return (0);
446     }
447     sni_ctx = SSL_CTX_new(TLS_server_method());
448     if (sni_ctx == 0) {
449 	SSL_CTX_free(server_ctx);
450 	msg_warn("cannot allocate server SNI SSL_CTX: disabling TLS support");
451 	tls_print_errors();
452 	return (0);
453     }
454 #ifdef SSL_SECOP_PEER
455     /* Backwards compatible security as a base for opportunistic TLS. */
456     SSL_CTX_set_security_level(server_ctx, 0);
457     SSL_CTX_set_security_level(sni_ctx, 0);
458 #endif
459 
460     /*
461      * See the verify callback in tls_verify.c
462      */
463     SSL_CTX_set_verify_depth(server_ctx, props->verifydepth + 1);
464     SSL_CTX_set_verify_depth(sni_ctx, props->verifydepth + 1);
465 
466     /*
467      * The session cache is implemented by the tlsmgr(8) server.
468      *
469      * XXX 200502 Surprise: when OpenSSL purges an entry from the in-memory
470      * cache, it also attempts to purge the entry from the on-disk cache.
471      * This is undesirable, especially when we set the in-memory cache size
472      * to 1. For this reason we don't allow OpenSSL to purge on-disk cache
473      * entries, and leave it up to the tlsmgr process instead. Found by
474      * Victor Duchovni.
475      */
476     if (tls_mgr_policy(props->cache_type, &cachable,
477 		       &scache_timeout) != TLS_MGR_STAT_OK)
478 	scache_timeout = 0;
479     if (scache_timeout <= 0)
480 	cachable = 0;
481 
482     /*
483      * Protocol work-arounds, OpenSSL version dependent.
484      */
485     off |= tls_bug_bits();
486 
487     /*
488      * Add SSL_OP_NO_TICKET when the timeout is zero or library support is
489      * incomplete.
490      */
491 #ifdef SSL_OP_NO_TICKET
492 #ifndef OPENSSL_NO_TLSEXT
493     ticketable = (*var_tls_tkt_cipher && scache_timeout > 0
494 		  && !(off & SSL_OP_NO_TICKET));
495     if (ticketable) {
496 	const EVP_CIPHER *ciph;
497 
498 	if ((ciph = EVP_get_cipherbyname(var_tls_tkt_cipher)) == 0
499 	    || EVP_CIPHER_mode(ciph) != EVP_CIPH_CBC_MODE
500 	    || EVP_CIPHER_iv_length(ciph) != TLS_TICKET_IVLEN
501 	    || EVP_CIPHER_key_length(ciph) < TLS_TICKET_IVLEN
502 	    || EVP_CIPHER_key_length(ciph) > TLS_TICKET_KEYLEN) {
503 	    msg_warn("%s: invalid value: %s; session tickets disabled",
504 		     VAR_TLS_TKT_CIPHER, var_tls_tkt_cipher);
505 	    ticketable = 0;
506 	}
507     }
508     if (ticketable) {
509 	SSL_CTX_set_tlsext_ticket_key_cb(server_ctx, ticket_cb);
510 
511 	/*
512 	 * OpenSSL 1.1.1 introduces support for TLS 1.3, which can issue more
513 	 * than one ticket per handshake.  While this may be appropriate for
514 	 * communication between browsers and webservers, it is not terribly
515 	 * useful for MTAs, many of which other than Postfix don't do TLS
516 	 * session caching at all, and Postfix has no mechanism for storing
517 	 * multiple session tickets, if more than one sent, the second
518 	 * clobbers the first.  OpenSSL 1.1.1 servers default to issuing two
519 	 * tickets for non-resumption handshakes, we reduce this to one.  Our
520 	 * ticket decryption callback already (since 2.11) asks OpenSSL to
521 	 * avoid issuing new tickets when the presented ticket is re-usable.
522 	 */
523 	SSL_CTX_set_num_tickets(server_ctx, 1);
524     }
525 #endif
526     if (!ticketable)
527 	off |= SSL_OP_NO_TICKET;
528 #endif
529 
530     SSL_CTX_set_options(server_ctx, off);
531 
532     /*
533      * Global protocol selection.
534      */
535     if (protomask != 0)
536 	SSL_CTX_set_options(server_ctx, TLS_SSL_OP_PROTOMASK(protomask));
537 
538     /*
539      * Some sites may want to give the client less rope. On the other hand,
540      * this could trigger inter-operability issues, the client should not
541      * offer ciphers it implements poorly, but this hasn't stopped some
542      * vendors from getting it wrong.
543      */
544     if (var_tls_preempt_clist)
545 	SSL_CTX_set_options(server_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
546 
547     /* Done with server_ctx options, clone to sni_ctx */
548     SSL_CTX_clear_options(sni_ctx, ~0);
549     SSL_CTX_set_options(sni_ctx, SSL_CTX_get_options(server_ctx));
550 
551     /*
552      * Set the call-back routine to debug handshake progress.
553      */
554     if (log_mask & TLS_LOG_DEBUG) {
555 	SSL_CTX_set_info_callback(server_ctx, tls_info_callback);
556 	SSL_CTX_set_info_callback(sni_ctx, tls_info_callback);
557     }
558 
559     /*
560      * Load the CA public key certificates for both the server cert and for
561      * the verification of client certificates. As provided by OpenSSL we
562      * support two types of CA certificate handling: One possibility is to
563      * add all CA certificates to one large CAfile, the other possibility is
564      * a directory pointed to by CApath, containing separate files for each
565      * CA with softlinks named after the hash values of the certificate. The
566      * first alternative has the advantage that the file is opened and read
567      * at startup time, so that you don't have the hassle to maintain another
568      * copy of the CApath directory for chroot-jail.
569      */
570     if (tls_set_ca_certificate_info(server_ctx,
571 				    props->CAfile, props->CApath) < 0) {
572 	/* tls_set_ca_certificate_info() already logs a warning. */
573 	SSL_CTX_free(server_ctx);		/* 200411 */
574 	SSL_CTX_free(sni_ctx);
575 	return (0);
576     }
577 
578     /*
579      * Upref and share the cert store.  Sadly we can't yet use
580      * SSL_CTX_set1_cert_store(3) which was added in OpenSSL 1.1.0.
581      */
582     cert_store = SSL_CTX_get_cert_store(server_ctx);
583     X509_STORE_up_ref(cert_store);
584     SSL_CTX_set_cert_store(sni_ctx, cert_store);
585 
586     /*
587      * Load the server public key certificate and private key from file and
588      * check whether the cert matches the key. We can use RSA certificates
589      * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
590      * All three can be made available at the same time. The CA certificates
591      * for all three are handled in the same setup already finished. Which
592      * one is used depends on the cipher negotiated (that is: the first
593      * cipher listed by the client which does match the server). A client
594      * with RSA only (e.g. Netscape) will use the RSA certificate only. A
595      * client with openssl-library will use RSA first if not especially
596      * changed in the cipher setup.
597      */
598     if (tls_set_my_certificate_key_info(server_ctx,
599 					props->chain_files,
600 					props->cert_file,
601 					props->key_file,
602 					props->dcert_file,
603 					props->dkey_file,
604 					props->eccert_file,
605 					props->eckey_file) < 0) {
606 	/* tls_set_my_certificate_key_info() already logs a warning. */
607 	SSL_CTX_free(server_ctx);		/* 200411 */
608 	SSL_CTX_free(sni_ctx);
609 	return (0);
610     }
611 
612     /*
613      * 2015-12-05: Ephemeral RSA removed from OpenSSL 1.1.0-dev
614      */
615 #if OPENSSL_VERSION_NUMBER < 0x10100000L
616 
617     /*
618      * According to OpenSSL documentation, a temporary RSA key is needed when
619      * export ciphers are in use, because the certified key cannot be
620      * directly used.
621      */
622     SSL_CTX_set_tmp_rsa_callback(server_ctx, tls_tmp_rsa_cb);
623     SSL_CTX_set_tmp_rsa_callback(sni_ctx, tls_tmp_rsa_cb);
624 #endif
625 
626     /*
627      * Diffie-Hellman key generation parameters can either be loaded from
628      * files (preferred) or taken from compiled in values. First, set the
629      * callback that will select the values when requested, then load the
630      * (possibly) available DH parameters from files. We are generous with
631      * the error handling, since we do have default values compiled in, so we
632      * will not abort but just log the error message.
633      */
634     SSL_CTX_set_tmp_dh_callback(server_ctx, tls_tmp_dh_cb);
635     SSL_CTX_set_tmp_dh_callback(sni_ctx, tls_tmp_dh_cb);
636     if (*props->dh1024_param_file != 0)
637 	tls_set_dh_from_file(props->dh1024_param_file, 1024);
638     if (*props->dh512_param_file != 0)
639 	tls_set_dh_from_file(props->dh512_param_file, 512);
640 
641     /*
642      * Enable EECDH if available, errors are not fatal, we just keep going
643      * with any remaining key-exchange algorithms.
644      */
645     tls_set_eecdh_curve(server_ctx, props->eecdh_grade);
646     tls_set_eecdh_curve(sni_ctx, props->eecdh_grade);
647 
648     /*
649      * If we want to check client certificates, we have to indicate it in
650      * advance. By now we only allow to decide on a global basis. If we want
651      * to allow certificate based relaying, we must ask the client to provide
652      * one with SSL_VERIFY_PEER. The client now can decide, whether it
653      * provides one or not. We can enforce a failure of the negotiation with
654      * SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we do not allow a connection
655      * without one. In the "server hello" following the initialization by the
656      * "client hello" the server must provide a list of CAs it is willing to
657      * accept. Some clever clients will then select one from the list of
658      * available certificates matching these CAs. Netscape Communicator will
659      * present the list of certificates for selecting the one to be sent, or
660      * it will issue a warning, if there is no certificate matching the
661      * available CAs.
662      *
663      * With regard to the purpose of the certificate for relaying, we might like
664      * a later negotiation, maybe relaying would already be allowed for other
665      * reasons, but this would involve severe changes in the internal postfix
666      * logic, so we have to live with it the way it is.
667      */
668     if (props->ask_ccert)
669 	verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
670     SSL_CTX_set_verify(server_ctx, verify_flags,
671 		       tls_verify_certificate_callback);
672     SSL_CTX_set_verify(sni_ctx, verify_flags,
673 		       tls_verify_certificate_callback);
674     if (props->ask_ccert && *props->CAfile) {
675 	STACK_OF(X509_NAME) *calist = SSL_load_client_CA_file(props->CAfile);
676 
677 	if (calist == 0) {
678 	    /* Not generally critical */
679 	    msg_warn("error loading client CA names from: %s",
680 		     props->CAfile);
681 	    tls_print_errors();
682 	}
683 	SSL_CTX_set_client_CA_list(server_ctx, calist);
684 
685 	if (calist != 0 && sk_X509_NAME_num(calist) > 0) {
686 	    calist = SSL_dup_CA_list(calist);
687 
688 	    if (calist == 0) {
689 		msg_warn("error duplicating client CA names for SNI");
690 		tls_print_errors();
691 	    } else {
692 		SSL_CTX_set_client_CA_list(sni_ctx, calist);
693 	    }
694 	}
695     }
696 
697     /*
698      * Initialize our own TLS server handle, before diving into the details
699      * of TLS session cache management.
700      */
701     app_ctx = tls_alloc_app_context(server_ctx, sni_ctx, log_mask);
702 
703     if (cachable || ticketable || props->set_sessid) {
704 
705 	/*
706 	 * Initialize the session cache.
707 	 *
708 	 * With a large number of concurrent smtpd(8) processes, it is not a
709 	 * good idea to cache multiple large session objects in each process.
710 	 * We set the internal cache size to 1, and don't register a
711 	 * "remove_cb" so as to avoid deleting good sessions from the
712 	 * external cache prematurely (when the internal cache is full,
713 	 * OpenSSL removes sessions from the external cache also)!
714 	 *
715 	 * This makes SSL_CTX_remove_session() not useful for flushing broken
716 	 * sessions from the external cache, so we must delete them directly
717 	 * (not via a callback).
718 	 *
719 	 * Set a session id context to identify to what type of server process
720 	 * created a session. In our case, the context is simply the name of
721 	 * the mail system: "Postfix/TLS".
722 	 */
723 	SSL_CTX_sess_set_cache_size(server_ctx, 1);
724 	SSL_CTX_set_session_id_context(server_ctx,
725 				       (void *) &server_session_id_context,
726 				       sizeof(server_session_id_context));
727 	SSL_CTX_set_session_cache_mode(server_ctx,
728 				       SSL_SESS_CACHE_SERVER |
729 				       SSL_SESS_CACHE_NO_AUTO_CLEAR);
730 	if (cachable) {
731 	    app_ctx->cache_type = mystrdup(props->cache_type);
732 
733 	    SSL_CTX_sess_set_get_cb(server_ctx, get_server_session_cb);
734 	    SSL_CTX_sess_set_new_cb(server_ctx, new_server_session_cb);
735 	}
736 
737 	/*
738 	 * OpenSSL ignores timed-out sessions. We need to set the internal
739 	 * cache timeout at least as high as the external cache timeout. This
740 	 * applies even if no internal cache is used.  We set the session
741 	 * lifetime to twice the cache lifetime, which is also the issuing
742 	 * and retired key validation lifetime of session tickets keys. This
743 	 * way a session always lasts longer than the server's ability to
744 	 * decrypt its session ticket.  Otherwise, a bug in OpenSSL may fail
745 	 * to re-issue tickets when sessions decrypt, but are expired.
746 	 */
747 	SSL_CTX_set_timeout(server_ctx, 2 * scache_timeout);
748     } else {
749 
750 	/*
751 	 * If we have no external cache, disable all caching. No use wasting
752 	 * server memory resources with sessions they are unlikely to be able
753 	 * to reuse.
754 	 */
755 	SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF);
756     }
757 
758     return (app_ctx);
759 }
760 
761  /*
762   * This is the actual startup routine for a new connection. We expect that
763   * the SMTP buffers are flushed and the "220 Ready to start TLS" was sent to
764   * the client, so that we can immediately start the TLS handshake process.
765   */
766 TLS_SESS_STATE *tls_server_start(const TLS_SERVER_START_PROPS *props)
767 {
768     int     sts;
769     TLS_SESS_STATE *TLScontext;
770     const char *cipher_list;
771     TLS_APPL_STATE *app_ctx = props->ctx;
772     int     log_mask = app_ctx->log_mask;
773 
774     /*
775      * Implicitly enable logging of trust chain errors when verified certs
776      * are required.
777      */
778     if (props->requirecert)
779 	log_mask |= TLS_LOG_UNTRUSTED;
780 
781     if (log_mask & TLS_LOG_VERBOSE)
782 	msg_info("setting up TLS connection from %s", props->namaddr);
783 
784     /*
785      * Allocate a new TLScontext for the new connection and get an SSL
786      * structure. Add the location of TLScontext to the SSL to later retrieve
787      * the information inside the tls_verify_certificate_callback().
788      */
789     TLScontext = tls_alloc_sess_context(log_mask, props->namaddr);
790     TLScontext->cache_type = app_ctx->cache_type;
791 
792     ERR_clear_error();
793     if ((TLScontext->con = (SSL *) SSL_new(app_ctx->ssl_ctx)) == 0) {
794 	msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
795 	tls_print_errors();
796 	tls_free_context(TLScontext);
797 	return (0);
798     }
799     cipher_list = tls_set_ciphers(TLScontext, props->cipher_grade,
800 				  props->cipher_exclusions);
801     if (cipher_list == 0) {
802 	/* already warned */
803 	tls_free_context(TLScontext);
804 	return (0);
805     }
806     if (log_mask & TLS_LOG_VERBOSE)
807 	msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
808 
809     TLScontext->serverid = mystrdup(props->serverid);
810     TLScontext->am_server = 1;
811     TLScontext->stream = props->stream;
812     TLScontext->mdalg = props->mdalg;
813 
814     if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
815 	msg_warn("Could not set application data for 'TLScontext->con'");
816 	tls_print_errors();
817 	tls_free_context(TLScontext);
818 	return (0);
819     }
820 #ifdef SSL_SECOP_PEER
821     /* When authenticating the peer, use 80-bit plus OpenSSL security level */
822     if (props->requirecert)
823 	SSL_set_security_level(TLScontext->con, 1);
824 #endif
825 
826     /*
827      * Before really starting anything, try to seed the PRNG a little bit
828      * more.
829      */
830     tls_int_seed();
831     (void) tls_ext_seed(var_tls_daemon_rand_bytes);
832 
833     /*
834      * Connect the SSL connection with the network socket.
835      */
836     if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd :
837 		   vstream_fileno(props->stream)) != 1) {
838 	msg_info("SSL_set_fd error to %s", props->namaddr);
839 	tls_print_errors();
840 	uncache_session(app_ctx->ssl_ctx, TLScontext);
841 	tls_free_context(TLScontext);
842 	return (0);
843     }
844 
845     /*
846      * If the debug level selected is high enough, all of the data is dumped:
847      * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will
848      * dump everything.
849      *
850      * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
851      * Well there is a BIO below the SSL routines that is automatically
852      * created for us, so we can use it for debugging purposes.
853      */
854     if (log_mask & TLS_LOG_TLSPKTS)
855 	BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
856 
857     /*
858      * If we don't trigger the handshake in the library, leave control over
859      * SSL_accept/read/write/etc with the application.
860      */
861     if (props->stream == 0)
862 	return (TLScontext);
863 
864     /*
865      * Turn on non-blocking I/O so that we can enforce timeouts on network
866      * I/O.
867      */
868     non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
869 
870     /*
871      * Start TLS negotiations. This process is a black box that invokes our
872      * call-backs for session caching and certificate verification.
873      *
874      * Error handling: If the SSL handshake fails, we print out an error message
875      * and remove all TLS state concerning this session.
876      */
877     sts = tls_bio_accept(vstream_fileno(props->stream), props->timeout,
878 			 TLScontext);
879     if (sts <= 0) {
880 	if (ERR_peek_error() != 0) {
881 	    msg_info("SSL_accept error from %s: %d", props->namaddr, sts);
882 	    tls_print_errors();
883 	} else if (errno != 0) {
884 	    msg_info("SSL_accept error from %s: %m", props->namaddr);
885 	} else {
886 	    msg_info("SSL_accept error from %s: lost connection",
887 		     props->namaddr);
888 	}
889 	tls_free_context(TLScontext);
890 	return (0);
891     }
892     return (tls_server_post_accept(TLScontext));
893 }
894 
895 /* tls_server_post_accept - post-handshake processing */
896 
897 TLS_SESS_STATE *tls_server_post_accept(TLS_SESS_STATE *TLScontext)
898 {
899     const SSL_CIPHER *cipher;
900     X509   *peer;
901     char    buf[CCERT_BUFSIZ];
902 
903     /* Turn off packet dump if only dumping the handshake */
904     if ((TLScontext->log_mask & TLS_LOG_ALLPKTS) == 0)
905 	BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
906 
907     /*
908      * The caller may want to know if this session was reused or if a new
909      * session was negotiated.
910      */
911     TLScontext->session_reused = SSL_session_reused(TLScontext->con);
912     if ((TLScontext->log_mask & TLS_LOG_CACHE) && TLScontext->session_reused)
913 	msg_info("%s: Reusing old session%s", TLScontext->namaddr,
914 		 TLScontext->ticketed ? " (RFC 5077 session ticket)" : "");
915 
916     /*
917      * Let's see whether a peer certificate is available and what is the
918      * actual information. We want to save it for later use.
919      */
920     peer = SSL_get_peer_certificate(TLScontext->con);
921     if (peer != NULL) {
922 	TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT;
923 	if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
924 	    TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
925 
926 	if (TLScontext->log_mask & TLS_LOG_VERBOSE) {
927 	    X509_NAME_oneline(X509_get_subject_name(peer),
928 			      buf, sizeof(buf));
929 	    msg_info("subject=%s", printable(buf, '?'));
930 	    X509_NAME_oneline(X509_get_issuer_name(peer),
931 			      buf, sizeof(buf));
932 	    msg_info("issuer=%s", printable(buf, '?'));
933 	}
934 	TLScontext->peer_CN = tls_peer_CN(peer, TLScontext);
935 	TLScontext->issuer_CN = tls_issuer_CN(peer, TLScontext);
936 	TLScontext->peer_cert_fprint = tls_cert_fprint(peer, TLScontext->mdalg);
937 	TLScontext->peer_pkey_fprint = tls_pkey_fprint(peer, TLScontext->mdalg);
938 
939 	if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_PEERCERT)) {
940 	    msg_info("%s: subject_CN=%s, issuer=%s, fingerprint=%s"
941 		     ", pkey_fingerprint=%s",
942 		     TLScontext->namaddr,
943 		     TLScontext->peer_CN, TLScontext->issuer_CN,
944 		     TLScontext->peer_cert_fprint,
945 		     TLScontext->peer_pkey_fprint);
946 	}
947 	X509_free(peer);
948 
949 	/*
950 	 * Give them a clue. Problems with trust chain verification are
951 	 * logged when the session is first negotiated, before the session is
952 	 * stored into the cache. We don't want mystery failures, so log the
953 	 * fact the real problem is to be found in the past.
954 	 */
955 	if (!TLS_CERT_IS_TRUSTED(TLScontext)
956 	    && (TLScontext->log_mask & TLS_LOG_UNTRUSTED)) {
957 	    if (TLScontext->session_reused == 0)
958 		tls_log_verify_error(TLScontext);
959 	    else
960 		msg_info("%s: re-using session with untrusted certificate, "
961 			 "look for details earlier in the log",
962 			 TLScontext->namaddr);
963 	}
964     } else {
965 	TLScontext->peer_CN = mystrdup("");
966 	TLScontext->issuer_CN = mystrdup("");
967 	TLScontext->peer_cert_fprint = mystrdup("");
968 	TLScontext->peer_pkey_fprint = mystrdup("");
969     }
970 
971     /*
972      * Finally, collect information about protocol and cipher for logging
973      */
974     TLScontext->protocol = SSL_get_version(TLScontext->con);
975     cipher = SSL_get_current_cipher(TLScontext->con);
976     TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
977     TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
978 					     &(TLScontext->cipher_algbits));
979 
980     /*
981      * If the library triggered the SSL handshake, switch to the
982      * tls_timed_read/write() functions and make the TLScontext available to
983      * those functions. Otherwise, leave control over SSL_read/write/etc.
984      * with the application.
985      */
986     if (TLScontext->stream != 0)
987 	tls_stream_start(TLScontext->stream, TLScontext);
988 
989     /*
990      * With the handshake done, extract TLS 1.3 signature metadata.
991      */
992     tls_get_signature_params(TLScontext);
993 
994     /*
995      * All the key facts in a single log entry.
996      */
997     if (TLScontext->log_mask & TLS_LOG_SUMMARY)
998 	tls_log_summary(TLS_ROLE_SERVER, TLS_USAGE_NEW, TLScontext);
999 
1000     tls_int_seed();
1001 
1002     return (TLScontext);
1003 }
1004 
1005 #endif					/* USE_TLS */
1006