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