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