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