1/*++
2/* NAME
3/*	tls_server 3
4/* SUMMARY
5/*	server-side TLS engine
6/* SYNOPSIS
7/*	#include <tls.h>
8/*
9/*	TLS_APPL_STATE *tls_server_init(props)
10/*	const TLS_SERVER_INIT_PROPS *props;
11/*
12/*	TLS_SESS_STATE *tls_server_start(props)
13/*	const TLS_SERVER_START_PROPS *props;
14/*
15/*	TLS_SESS_STATE *tls_server_post_accept(TLScontext)
16/*	TLS_SESS_STATE *TLScontext;
17/*
18/*	void	tls_server_stop(app_ctx, stream, failure, TLScontext)
19/*	TLS_APPL_STATE *app_ctx;
20/*	VSTREAM	*stream;
21/*	int	failure;
22/*	TLS_SESS_STATE *TLScontext;
23/* DESCRIPTION
24/*	This module is the interface between Postfix TLS servers,
25/*	the OpenSSL library, and the TLS entropy and cache manager.
26/*
27/*	See "EVENT_DRIVEN APPLICATIONS" below for using this code
28/*	in event-driven programs.
29/*
30/*	tls_server_init() is called once when the SMTP server
31/*	initializes.
32/*	Certificate details are also decided during this phase,
33/*	so that peer-specific behavior is not possible.
34/*
35/*	tls_server_start() activates the TLS feature for the VSTREAM
36/*	passed as argument. We assume that network buffers are flushed
37/*	and the TLS handshake can begin	immediately.
38/*
39/*	tls_server_stop() sends the "close notify" alert via
40/*	SSL_shutdown() to the peer and resets all connection specific
41/*	TLS data. As RFC2487 does not specify a separate shutdown, it
42/*	is assumed that the underlying TCP connection is shut down
43/*	immediately afterwards. Any further writes to the channel will
44/*	be discarded, and any further reads will report end-of-file.
45/*	If the failure flag is set, no SSL_shutdown() handshake is performed.
46/*
47/*	Once the TLS connection is initiated, information about the TLS
48/*	state is available via the TLScontext structure:
49/* .IP TLScontext->protocol
50/*	the protocol name (SSLv2, SSLv3, TLSv1),
51/* .IP TLScontext->cipher_name
52/*	the cipher name (e.g. RC4/MD5),
53/* .IP TLScontext->cipher_usebits
54/*	the number of bits actually used (e.g. 40),
55/* .IP TLScontext->cipher_algbits
56/*	the number of bits the algorithm is based on (e.g. 128).
57/* .PP
58/*	The last two values may differ from each other when export-strength
59/*	encryption is used.
60/*
61/*	If the peer offered a certificate, part of the certificate data are
62/*	available as:
63/* .IP TLScontext->peer_status
64/*	A bitmask field that records the status of the peer certificate
65/*	verification. One or more of TLS_CERT_FLAG_PRESENT and
66/*	TLS_CERT_FLAG_TRUSTED.
67/* .IP TLScontext->peer_CN
68/*	Extracted CommonName of the peer, or zero-length string
69/*	when information could not be extracted.
70/* .IP TLScontext->issuer_CN
71/*	Extracted CommonName of the issuer, or zero-length string
72/*	when information could not be extracted.
73/* .IP TLScontext->peer_cert_fprint
74/*	Fingerprint of the certificate, or zero-length string when no peer
75/*	certificate is available.
76/* .PP
77/*	If no peer certificate is presented the peer_status is set to 0.
78/* EVENT_DRIVEN APPLICATIONS
79/* .ad
80/* .fi
81/*	Event-driven programs manage multiple I/O channels.  Such
82/*	programs cannot use the synchronous VSTREAM-over-TLS
83/*	implementation that the current TLS library provides,
84/*	including tls_server_stop() and the underlying tls_stream(3)
85/*	and tls_bio_ops(3) routines.
86/*
87/*	With the current TLS library implementation, this means
88/*	that the application is responsible for calling and retrying
89/*	SSL_accept(), SSL_read(), SSL_write() and SSL_shutdown().
90/*
91/*	To maintain control over TLS I/O, an event-driven server
92/*	invokes tls_server_start() with a null VSTREAM argument and
93/*	with an fd argument that specifies the I/O file descriptor.
94/*	Then, tls_server_start() performs all the necessary
95/*	preparations before the TLS handshake and returns a partially
96/*	populated TLS context. The event-driven application is then
97/*	responsible for invoking SSL_accept(), and if successful,
98/*	for invoking tls_server_post_accept() to finish the work
99/*	that was started by tls_server_start(). In case of unrecoverable
100/*	failure, tls_server_post_accept() destroys the TLS context
101/*	and returns a null pointer value.
102/* LICENSE
103/* .ad
104/* .fi
105/*	This software is free. You can do with it whatever you want.
106/*	The original author kindly requests that you acknowledge
107/*	the use of his software.
108/* AUTHOR(S)
109/*	Originally written by:
110/*	Lutz Jaenicke
111/*	BTU Cottbus
112/*	Allgemeine Elektrotechnik
113/*	Universitaetsplatz 3-4
114/*	D-03044 Cottbus, Germany
115/*
116/*	Updated by:
117/*	Wietse Venema
118/*	IBM T.J. Watson Research
119/*	P.O. Box 704
120/*	Yorktown Heights, NY 10598, USA
121/*
122/*	Victor Duchovni
123/*	Morgan Stanley
124/*--*/
125
126/* System library. */
127
128#include <sys_defs.h>
129
130#ifdef USE_TLS
131#include <unistd.h>
132#include <string.h>
133
134/* Utility library. */
135
136#include <mymalloc.h>
137#include <vstring.h>
138#include <vstream.h>
139#include <dict.h>
140#include <stringops.h>
141#include <msg.h>
142#include <hex_code.h>
143#include <iostuff.h>			/* non-blocking */
144
145/* Global library. */
146
147#include <mail_params.h>
148
149/* TLS library. */
150
151#include <tls_mgr.h>
152#define TLS_INTERNAL
153#include <tls.h>
154
155#define STR(x)	vstring_str(x)
156#define LEN(x)	VSTRING_LEN(x)
157
158/* Application-specific. */
159
160 /*
161  * The session_id_context indentifies the service that created a session.
162  * This information is used to distinguish between multiple TLS-based
163  * servers running on the same server. We use the name of the mail system.
164  */
165static const char server_session_id_context[] = "Postfix/TLS";
166
167/* get_server_session_cb - callback to retrieve session from server cache */
168
169static SSL_SESSION *get_server_session_cb(SSL *ssl, unsigned char *session_id,
170					          int session_id_length,
171					          int *unused_copy)
172{
173    const char *myname = "get_server_session_cb";
174    TLS_SESS_STATE *TLScontext;
175    VSTRING *cache_id;
176    VSTRING *session_data = vstring_alloc(2048);
177    SSL_SESSION *session = 0;
178
179    if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
180	msg_panic("%s: null TLScontext in session lookup callback", myname);
181
182#define GEN_CACHE_ID(buf, id, len, service) \
183    do { \
184	buf = vstring_alloc(2 * (len + strlen(service))); \
185	hex_encode(buf, (char *) (id), (len)); \
186	vstring_sprintf_append(buf, "&s=%s", (service)); \
187	vstring_sprintf_append(buf, "&l=%ld", (long) SSLeay()); \
188    } while (0)
189
190
191    GEN_CACHE_ID(cache_id, session_id, session_id_length, TLScontext->serverid);
192
193    if (TLScontext->log_mask & TLS_LOG_CACHE)
194	msg_info("%s: looking up session %s in %s cache", TLScontext->namaddr,
195		 STR(cache_id), TLScontext->cache_type);
196
197    /*
198     * Load the session from cache and decode it.
199     */
200    if (tls_mgr_lookup(TLScontext->cache_type, STR(cache_id),
201		       session_data) == TLS_MGR_STAT_OK) {
202	session = tls_session_activate(STR(session_data), LEN(session_data));
203	if (session && (TLScontext->log_mask & TLS_LOG_CACHE))
204	    msg_info("%s: reloaded session %s from %s cache",
205		     TLScontext->namaddr, STR(cache_id),
206		     TLScontext->cache_type);
207    }
208
209    /*
210     * Clean up.
211     */
212    vstring_free(cache_id);
213    vstring_free(session_data);
214
215    return (session);
216}
217
218/* uncache_session - remove session from internal & external cache */
219
220static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext)
221{
222    VSTRING *cache_id;
223    SSL_SESSION *session = SSL_get_session(TLScontext->con);
224
225    SSL_CTX_remove_session(ctx, session);
226
227    if (TLScontext->cache_type == 0)
228	return;
229
230    GEN_CACHE_ID(cache_id, session->session_id, session->session_id_length,
231		 TLScontext->serverid);
232
233    if (TLScontext->log_mask & TLS_LOG_CACHE)
234	msg_info("%s: remove session %s from %s cache", TLScontext->namaddr,
235		 STR(cache_id), TLScontext->cache_type);
236
237    tls_mgr_delete(TLScontext->cache_type, STR(cache_id));
238    vstring_free(cache_id);
239}
240
241/* new_server_session_cb - callback to save session to server cache */
242
243static int new_server_session_cb(SSL *ssl, SSL_SESSION *session)
244{
245    const char *myname = "new_server_session_cb";
246    VSTRING *cache_id;
247    TLS_SESS_STATE *TLScontext;
248    VSTRING *session_data;
249
250    if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0)
251	msg_panic("%s: null TLScontext in new session callback", myname);
252
253    GEN_CACHE_ID(cache_id, session->session_id, session->session_id_length,
254		 TLScontext->serverid);
255
256    if (TLScontext->log_mask & TLS_LOG_CACHE)
257	msg_info("%s: save session %s to %s cache", TLScontext->namaddr,
258		 STR(cache_id), TLScontext->cache_type);
259
260    /*
261     * Passivate and save the session state.
262     */
263    session_data = tls_session_passivate(session);
264    if (session_data)
265	tls_mgr_update(TLScontext->cache_type, STR(cache_id),
266		       STR(session_data), LEN(session_data));
267
268    /*
269     * Clean up.
270     */
271    if (session_data)
272	vstring_free(session_data);
273    vstring_free(cache_id);
274    SSL_SESSION_free(session);			/* 200502 */
275
276    return (1);
277}
278
279#define NOENGINE	((ENGINE *) 0)
280#define TLS_TKT_NOKEYS -1		/* No keys for encryption */
281#define TLS_TKT_STALE	0		/* No matching keys for decryption */
282#define TLS_TKT_ACCEPT	1		/* Ticket decryptable and re-usable */
283#define TLS_TKT_REISSUE	2		/* Ticket decryptable, not re-usable */
284
285/* ticket_cb - configure tls session ticket encrypt/decrypt context */
286
287#if defined(SSL_OP_NO_TICKET) \
288    && !defined(OPENSSL_NO_TLSEXT) \
289    && OPENSSL_VERSION_NUMBER >= 0x0090808fL
290
291static int ticket_cb(SSL *con, unsigned char name[], unsigned char iv[],
292		          EVP_CIPHER_CTX * ctx, HMAC_CTX * hctx, int create)
293{
294    static const EVP_MD *sha256;
295    static const EVP_CIPHER *aes128;
296    TLS_TICKET_KEY *key;
297    TLS_SESS_STATE *TLScontext = SSL_get_ex_data(con, TLScontext_index);
298    int     timeout = ((int) SSL_CTX_get_timeout(SSL_get_SSL_CTX(con))) / 2;
299
300    if ((!sha256 && (sha256 = EVP_sha256()) == 0)
301	|| (!aes128 && (aes128 = EVP_aes_128_cbc()) == 0)
302	|| (key = tls_mgr_key(create ? 0 : name, timeout)) == 0
303	|| (create && RAND_bytes(iv, TLS_TICKET_IVLEN) <= 0))
304	return (create ? TLS_TKT_NOKEYS : TLS_TKT_STALE);
305
306    HMAC_Init_ex(hctx, key->hmac, TLS_TICKET_MACLEN, sha256, NOENGINE);
307
308    if (create) {
309	EVP_EncryptInit_ex(ctx, aes128, NOENGINE, key->bits, iv);
310	memcpy((char *) name, (char *) key->name, TLS_TICKET_NAMELEN);
311	if (TLScontext->log_mask & TLS_LOG_CACHE)
312	    msg_info("%s: Issuing session ticket, key expiration: %ld",
313		     TLScontext->namaddr, (long) key->tout);
314    } else {
315	EVP_DecryptInit_ex(ctx, aes128, NOENGINE, key->bits, iv);
316	if (TLScontext->log_mask & TLS_LOG_CACHE)
317	    msg_info("%s: Decrypting session ticket, key expiration: %ld",
318		     TLScontext->namaddr, (long) key->tout);
319    }
320    TLScontext->ticketed = 1;
321    return (TLS_TKT_ACCEPT);
322}
323
324#endif
325
326/* tls_server_init - initialize the server-side TLS engine */
327
328TLS_APPL_STATE *tls_server_init(const TLS_SERVER_INIT_PROPS *props)
329{
330    SSL_CTX *server_ctx;
331    long    off = 0;
332    int     verify_flags = SSL_VERIFY_NONE;
333    int     cachable;
334    int     scache_timeout;
335    int     ticketable = 0;
336    int     protomask;
337    TLS_APPL_STATE *app_ctx;
338    int     log_mask;
339
340    /*
341     * Convert user loglevel to internal logmask.
342     */
343    log_mask = tls_log_mask(props->log_param, props->log_level);
344
345    if (log_mask & TLS_LOG_VERBOSE)
346	msg_info("initializing the server-side TLS engine");
347
348    /*
349     * Load (mostly cipher related) TLS-library internal main.cf parameters.
350     */
351    tls_param_init();
352
353    /*
354     * Detect mismatch between compile-time headers and run-time library.
355     */
356    tls_check_version();
357
358    /*
359     * Initialize the OpenSSL library by the book! To start with, we must
360     * initialize the algorithms. We want cleartext error messages instead of
361     * just error codes, so we load the error_strings.
362     */
363    SSL_load_error_strings();
364    OpenSSL_add_ssl_algorithms();
365
366    /*
367     * First validate the protocols. If these are invalid, we can't continue.
368     */
369    protomask = tls_protocol_mask(props->protocols);
370    if (protomask == TLS_PROTOCOL_INVALID) {
371	/* tls_protocol_mask() logs no warning. */
372	msg_warn("Invalid TLS protocol list \"%s\": disabling TLS support",
373		 props->protocols);
374	return (0);
375    }
376
377    /*
378     * Create an application data index for SSL objects, so that we can
379     * attach TLScontext information; this information is needed inside
380     * tls_verify_certificate_callback().
381     */
382    if (TLScontext_index < 0) {
383	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) {
384	    msg_warn("Cannot allocate SSL application data index: "
385		     "disabling TLS support");
386	    return (0);
387	}
388    }
389
390    /*
391     * If the administrator specifies an unsupported digest algorithm, fail
392     * now, rather than in the middle of a TLS handshake.
393     */
394    if (!tls_validate_digest(props->mdalg)) {
395	msg_warn("disabling TLS support");
396	return (0);
397    }
398
399    /*
400     * Initialize the PRNG (Pseudo Random Number Generator) with some seed
401     * from external and internal sources. Don't enable TLS without some real
402     * entropy.
403     */
404    if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
405	msg_warn("no entropy for TLS key generation: disabling TLS support");
406	return (0);
407    }
408    tls_int_seed();
409
410    /*
411     * The SSL/TLS specifications require the client to send a message in the
412     * oldest specification it understands with the highest level it
413     * understands in the message. Netscape communicator can still
414     * communicate with SSLv2 servers, so it sends out a SSLv2 client hello.
415     * To deal with it, our server must be SSLv2 aware (even if we don't like
416     * SSLv2), so we need to have the SSLv23 server here. If we want to limit
417     * the protocol level, we can add an option to not use SSLv2/v3/TLSv1
418     * later.
419     */
420    ERR_clear_error();
421    if ((server_ctx = SSL_CTX_new(SSLv23_server_method())) == 0) {
422	msg_warn("cannot allocate server SSL_CTX: disabling TLS support");
423	tls_print_errors();
424	return (0);
425    }
426
427    /*
428     * See the verify callback in tls_verify.c
429     */
430    SSL_CTX_set_verify_depth(server_ctx, props->verifydepth + 1);
431
432    /*
433     * The session cache is implemented by the tlsmgr(8) server.
434     *
435     * XXX 200502 Surprise: when OpenSSL purges an entry from the in-memory
436     * cache, it also attempts to purge the entry from the on-disk cache.
437     * This is undesirable, especially when we set the in-memory cache size
438     * to 1. For this reason we don't allow OpenSSL to purge on-disk cache
439     * entries, and leave it up to the tlsmgr process instead. Found by
440     * Victor Duchovni.
441     */
442    if (tls_mgr_policy(props->cache_type, &cachable,
443		       &scache_timeout) != TLS_MGR_STAT_OK)
444	scache_timeout = 0;
445    if (scache_timeout <= 0)
446	cachable = 0;
447
448    /*
449     * Protocol work-arounds, OpenSSL version dependent.
450     */
451    off |= tls_bug_bits();
452
453    /*
454     * Add SSL_OP_NO_TICKET when the timeout is zero or library support is
455     * incomplete.  The SSL_CTX_set_tlsext_ticket_key_cb feature was added in
456     * OpenSSL 0.9.8h, while SSL_NO_TICKET was added in 0.9.8f.
457     */
458#ifdef SSL_OP_NO_TICKET
459#if !defined(OPENSSL_NO_TLSEXT) && OPENSSL_VERSION_NUMBER >= 0x0090808fL
460    ticketable = (scache_timeout > 0 && !(off & SSL_OP_NO_TICKET));
461    if (ticketable)
462	SSL_CTX_set_tlsext_ticket_key_cb(server_ctx, ticket_cb);
463#endif
464    if (!ticketable)
465	off |= SSL_OP_NO_TICKET;
466#endif
467
468    SSL_CTX_set_options(server_ctx, off);
469
470    /*
471     * Global protocol selection.
472     */
473    if (protomask != 0)
474	SSL_CTX_set_options(server_ctx,
475		   ((protomask & TLS_PROTOCOL_TLSv1) ? SSL_OP_NO_TLSv1 : 0L)
476	     | ((protomask & TLS_PROTOCOL_TLSv1_1) ? SSL_OP_NO_TLSv1_1 : 0L)
477	     | ((protomask & TLS_PROTOCOL_TLSv1_2) ? SSL_OP_NO_TLSv1_2 : 0L)
478		 | ((protomask & TLS_PROTOCOL_SSLv3) ? SSL_OP_NO_SSLv3 : 0L)
479	       | ((protomask & TLS_PROTOCOL_SSLv2) ? SSL_OP_NO_SSLv2 : 0L));
480
481    /*
482     * Some sites may want to give the client less rope. On the other hand,
483     * this could trigger inter-operability issues, the client should not
484     * offer ciphers it implements poorly, but this hasn't stopped some
485     * vendors from getting it wrong.
486     *
487     * XXX: Given OpenSSL's security history, nobody should still be using
488     * 0.9.7, let alone 0.9.6 or earlier. Warning added to TLS_README.html.
489     */
490    if (var_tls_preempt_clist)
491	SSL_CTX_set_options(server_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
492
493    /*
494     * Set the call-back routine to debug handshake progress.
495     */
496    if (log_mask & TLS_LOG_DEBUG)
497	SSL_CTX_set_info_callback(server_ctx, tls_info_callback);
498
499    /*
500     * Load the CA public key certificates for both the server cert and for
501     * the verification of client certificates. As provided by OpenSSL we
502     * support two types of CA certificate handling: One possibility is to
503     * add all CA certificates to one large CAfile, the other possibility is
504     * a directory pointed to by CApath, containing separate files for each
505     * CA with softlinks named after the hash values of the certificate. The
506     * first alternative has the advantage that the file is opened and read
507     * at startup time, so that you don't have the hassle to maintain another
508     * copy of the CApath directory for chroot-jail.
509     */
510    if (tls_set_ca_certificate_info(server_ctx,
511				    props->CAfile, props->CApath) < 0) {
512	/* tls_set_ca_certificate_info() already logs a warning. */
513	SSL_CTX_free(server_ctx);		/* 200411 */
514	return (0);
515    }
516
517    /*
518     * Load the server public key certificate and private key from file and
519     * check whether the cert matches the key. We can use RSA certificates
520     * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
521     * All three can be made available at the same time. The CA certificates
522     * for all three are handled in the same setup already finished. Which
523     * one is used depends on the cipher negotiated (that is: the first
524     * cipher listed by the client which does match the server). A client
525     * with RSA only (e.g. Netscape) will use the RSA certificate only. A
526     * client with openssl-library will use RSA first if not especially
527     * changed in the cipher setup.
528     */
529    if (tls_set_my_certificate_key_info(server_ctx,
530					props->cert_file,
531					props->key_file,
532					props->dcert_file,
533					props->dkey_file,
534					props->eccert_file,
535					props->eckey_file) < 0) {
536	/* tls_set_my_certificate_key_info() already logs a warning. */
537	SSL_CTX_free(server_ctx);		/* 200411 */
538	return (0);
539    }
540
541    /*
542     * According to OpenSSL documentation, a temporary RSA key is needed when
543     * export ciphers are in use, because the certified key cannot be
544     * directly used.
545     */
546    SSL_CTX_set_tmp_rsa_callback(server_ctx, tls_tmp_rsa_cb);
547
548    /*
549     * Diffie-Hellman key generation parameters can either be loaded from
550     * files (preferred) or taken from compiled in values. First, set the
551     * callback that will select the values when requested, then load the
552     * (possibly) available DH parameters from files. We are generous with
553     * the error handling, since we do have default values compiled in, so we
554     * will not abort but just log the error message.
555     */
556    SSL_CTX_set_tmp_dh_callback(server_ctx, tls_tmp_dh_cb);
557    if (*props->dh1024_param_file != 0)
558	tls_set_dh_from_file(props->dh1024_param_file, 1024);
559    if (*props->dh512_param_file != 0)
560	tls_set_dh_from_file(props->dh512_param_file, 512);
561
562    /*
563     * Enable EECDH if available, errors are not fatal, we just keep going
564     * with any remaining key-exchange algorithms.
565     */
566    (void) tls_set_eecdh_curve(server_ctx, props->eecdh_grade);
567
568    /*
569     * If we want to check client certificates, we have to indicate it in
570     * advance. By now we only allow to decide on a global basis. If we want
571     * to allow certificate based relaying, we must ask the client to provide
572     * one with SSL_VERIFY_PEER. The client now can decide, whether it
573     * provides one or not. We can enforce a failure of the negotiation with
574     * SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we do not allow a connection
575     * without one. In the "server hello" following the initialization by the
576     * "client hello" the server must provide a list of CAs it is willing to
577     * accept. Some clever clients will then select one from the list of
578     * available certificates matching these CAs. Netscape Communicator will
579     * present the list of certificates for selecting the one to be sent, or
580     * it will issue a warning, if there is no certificate matching the
581     * available CAs.
582     *
583     * With regard to the purpose of the certificate for relaying, we might like
584     * a later negotiation, maybe relaying would already be allowed for other
585     * reasons, but this would involve severe changes in the internal postfix
586     * logic, so we have to live with it the way it is.
587     */
588    if (props->ask_ccert)
589	verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
590    SSL_CTX_set_verify(server_ctx, verify_flags,
591		       tls_verify_certificate_callback);
592    if (*props->CAfile)
593	SSL_CTX_set_client_CA_list(server_ctx,
594				   SSL_load_client_CA_file(props->CAfile));
595
596    /*
597     * Initialize our own TLS server handle, before diving into the details
598     * of TLS session cache management.
599     */
600    app_ctx = tls_alloc_app_context(server_ctx, log_mask);
601
602    if (cachable || ticketable || props->set_sessid) {
603
604	/*
605	 * Initialize the session cache.
606	 *
607	 * With a large number of concurrent smtpd(8) processes, it is not a
608	 * good idea to cache multiple large session objects in each process.
609	 * We set the internal cache size to 1, and don't register a
610	 * "remove_cb" so as to avoid deleting good sessions from the
611	 * external cache prematurely (when the internal cache is full,
612	 * OpenSSL removes sessions from the external cache also)!
613	 *
614	 * This makes SSL_CTX_remove_session() not useful for flushing broken
615	 * sessions from the external cache, so we must delete them directly
616	 * (not via a callback).
617	 *
618	 * Set a session id context to identify to what type of server process
619	 * created a session. In our case, the context is simply the name of
620	 * the mail system: "Postfix/TLS".
621	 */
622	SSL_CTX_sess_set_cache_size(server_ctx, 1);
623	SSL_CTX_set_session_id_context(server_ctx,
624				       (void *) &server_session_id_context,
625				       sizeof(server_session_id_context));
626	SSL_CTX_set_session_cache_mode(server_ctx,
627				       SSL_SESS_CACHE_SERVER |
628				       SSL_SESS_CACHE_NO_AUTO_CLEAR);
629	if (cachable) {
630	    app_ctx->cache_type = mystrdup(props->cache_type);
631
632	    SSL_CTX_sess_set_get_cb(server_ctx, get_server_session_cb);
633	    SSL_CTX_sess_set_new_cb(server_ctx, new_server_session_cb);
634	}
635
636	/*
637	 * OpenSSL ignores timed-out sessions. We need to set the internal
638	 * cache timeout at least as high as the external cache timeout. This
639	 * applies even if no internal cache is used.  We set the session
640	 * lifetime to twice the cache lifetime, which is also the issuing
641	 * and retired key validation lifetime of session tickets keys. This
642	 * way a session always lasts longer than the server's ability to
643	 * decrypt its session ticket.  Otherwise, a bug in OpenSSL may fail
644	 * to re-issue tickets when sessions decrypt, but are expired.
645	 */
646	SSL_CTX_set_timeout(server_ctx, 2 * scache_timeout);
647    } else {
648
649	/*
650	 * If we have no external cache, disable all caching. No use wasting
651	 * server memory resources with sessions they are unlikely to be able
652	 * to reuse.
653	 */
654	SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF);
655    }
656
657    return (app_ctx);
658}
659
660 /*
661  * This is the actual startup routine for a new connection. We expect that
662  * the SMTP buffers are flushed and the "220 Ready to start TLS" was sent to
663  * the client, so that we can immediately start the TLS handshake process.
664  */
665TLS_SESS_STATE *tls_server_start(const TLS_SERVER_START_PROPS *props)
666{
667    int     sts;
668    TLS_SESS_STATE *TLScontext;
669    const char *cipher_list;
670    TLS_APPL_STATE *app_ctx = props->ctx;
671    int     log_mask = app_ctx->log_mask;
672
673    /*
674     * Implicitly enable logging of trust chain errors when verified certs
675     * are required.
676     */
677    if (props->requirecert)
678	log_mask |= TLS_LOG_UNTRUSTED;
679
680    if (log_mask & TLS_LOG_VERBOSE)
681	msg_info("setting up TLS connection from %s", props->namaddr);
682
683    cipher_list = tls_set_ciphers(app_ctx, "TLS", props->cipher_grade,
684				  props->cipher_exclusions);
685    if (cipher_list == 0) {
686	msg_warn("%s: %s: aborting TLS session", props->namaddr,
687		 vstring_str(app_ctx->why));
688	return (0);
689    }
690    if (log_mask & TLS_LOG_VERBOSE)
691	msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
692
693    /*
694     * Allocate a new TLScontext for the new connection and get an SSL
695     * structure. Add the location of TLScontext to the SSL to later retrieve
696     * the information inside the tls_verify_certificate_callback().
697     */
698    TLScontext = tls_alloc_sess_context(log_mask, props->namaddr);
699    TLScontext->cache_type = app_ctx->cache_type;
700
701    TLScontext->serverid = mystrdup(props->serverid);
702    TLScontext->am_server = 1;
703    TLScontext->stream = props->stream;
704    TLScontext->mdalg = props->mdalg;
705
706    ERR_clear_error();
707    if ((TLScontext->con = (SSL *) SSL_new(app_ctx->ssl_ctx)) == 0) {
708	msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
709	tls_print_errors();
710	tls_free_context(TLScontext);
711	return (0);
712    }
713    if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
714	msg_warn("Could not set application data for 'TLScontext->con'");
715	tls_print_errors();
716	tls_free_context(TLScontext);
717	return (0);
718    }
719
720    /*
721     * Before really starting anything, try to seed the PRNG a little bit
722     * more.
723     */
724    tls_int_seed();
725    (void) tls_ext_seed(var_tls_daemon_rand_bytes);
726
727    /*
728     * Initialize the SSL connection to accept state. This should not be
729     * necessary anymore since 0.9.3, but the call is still in the library
730     * and maintaining compatibility never hurts.
731     */
732    SSL_set_accept_state(TLScontext->con);
733
734    /*
735     * Connect the SSL connection with the network socket.
736     */
737    if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd :
738		   vstream_fileno(props->stream)) != 1) {
739	msg_info("SSL_set_fd error to %s", props->namaddr);
740	tls_print_errors();
741	uncache_session(app_ctx->ssl_ctx, TLScontext);
742	tls_free_context(TLScontext);
743	return (0);
744    }
745
746    /*
747     * If the debug level selected is high enough, all of the data is dumped:
748     * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will
749     * dump everything.
750     *
751     * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
752     * Well there is a BIO below the SSL routines that is automatically
753     * created for us, so we can use it for debugging purposes.
754     */
755    if (log_mask & TLS_LOG_TLSPKTS)
756	BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
757
758    /*
759     * If we don't trigger the handshake in the library, leave control over
760     * SSL_accept/read/write/etc with the application.
761     */
762    if (props->stream == 0)
763	return (TLScontext);
764
765    /*
766     * Turn on non-blocking I/O so that we can enforce timeouts on network
767     * I/O.
768     */
769    non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
770
771    /*
772     * Start TLS negotiations. This process is a black box that invokes our
773     * call-backs for session caching and certificate verification.
774     *
775     * Error handling: If the SSL handhake fails, we print out an error message
776     * and remove all TLS state concerning this session.
777     */
778    sts = tls_bio_accept(vstream_fileno(props->stream), props->timeout,
779			 TLScontext);
780    if (sts <= 0) {
781	if (ERR_peek_error() != 0) {
782	    msg_info("SSL_accept error from %s: %d", props->namaddr, sts);
783	    tls_print_errors();
784	} else if (errno != 0) {
785	    msg_info("SSL_accept error from %s: %m", props->namaddr);
786	} else {
787	    msg_info("SSL_accept error from %s: lost connection",
788		     props->namaddr);
789	}
790	tls_free_context(TLScontext);
791	return (0);
792    }
793    return (tls_server_post_accept(TLScontext));
794}
795
796/* tls_server_post_accept - post-handshake processing */
797
798TLS_SESS_STATE *tls_server_post_accept(TLS_SESS_STATE *TLScontext)
799{
800    SSL_CIPHER_const SSL_CIPHER *cipher;
801    X509   *peer;
802    char    buf[CCERT_BUFSIZ];
803
804    /* Turn off packet dump if only dumping the handshake */
805    if ((TLScontext->log_mask & TLS_LOG_ALLPKTS) == 0)
806	BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
807
808    /*
809     * The caller may want to know if this session was reused or if a new
810     * session was negotiated.
811     */
812    TLScontext->session_reused = SSL_session_reused(TLScontext->con);
813    if ((TLScontext->log_mask & TLS_LOG_CACHE) && TLScontext->session_reused)
814	msg_info("%s: Reusing old session%s", TLScontext->namaddr,
815		 TLScontext->ticketed ? " (RFC 5077 session ticket)" : "");
816
817    /*
818     * Let's see whether a peer certificate is available and what is the
819     * actual information. We want to save it for later use.
820     */
821    peer = SSL_get_peer_certificate(TLScontext->con);
822    if (peer != NULL) {
823	TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT;
824	if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
825	    TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
826
827	if (TLScontext->log_mask & TLS_LOG_VERBOSE) {
828	    X509_NAME_oneline(X509_get_subject_name(peer),
829			      buf, sizeof(buf));
830	    msg_info("subject=%s", buf);
831	    X509_NAME_oneline(X509_get_issuer_name(peer),
832			      buf, sizeof(buf));
833	    msg_info("issuer=%s", buf);
834	}
835	TLScontext->peer_CN = tls_peer_CN(peer, TLScontext);
836	TLScontext->issuer_CN = tls_issuer_CN(peer, TLScontext);
837	TLScontext->peer_cert_fprint = tls_cert_fprint(peer, TLScontext->mdalg);
838	TLScontext->peer_pkey_fprint = tls_pkey_fprint(peer, TLScontext->mdalg);
839
840	if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_PEERCERT)) {
841	    msg_info("%s: subject_CN=%s, issuer=%s, fingerprint=%s"
842		     ", pkey_fingerprint=%s",
843		     TLScontext->namaddr,
844		     TLScontext->peer_CN, TLScontext->issuer_CN,
845		     TLScontext->peer_cert_fprint,
846		     TLScontext->peer_pkey_fprint);
847	}
848	X509_free(peer);
849    } else {
850	TLScontext->peer_CN = mystrdup("");
851	TLScontext->issuer_CN = mystrdup("");
852	TLScontext->peer_cert_fprint = mystrdup("");
853	TLScontext->peer_pkey_fprint = mystrdup("");
854    }
855
856    /*
857     * Finally, collect information about protocol and cipher for logging
858     */
859    TLScontext->protocol = SSL_get_version(TLScontext->con);
860    cipher = SSL_get_current_cipher(TLScontext->con);
861    TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
862    TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
863					     &(TLScontext->cipher_algbits));
864
865    /*
866     * If the library triggered the SSL handshake, switch to the
867     * tls_timed_read/write() functions and make the TLScontext available to
868     * those functions. Otherwise, leave control over SSL_read/write/etc.
869     * with the application.
870     */
871    if (TLScontext->stream != 0)
872	tls_stream_start(TLScontext->stream, TLScontext);
873
874    /*
875     * All the key facts in a single log entry.
876     */
877    if (TLScontext->log_mask & TLS_LOG_SUMMARY)
878	msg_info("%s TLS connection established from %s: %s with cipher %s "
879	      "(%d/%d bits)", !TLS_CERT_IS_PRESENT(TLScontext) ? "Anonymous"
880		 : TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
881	 TLScontext->namaddr, TLScontext->protocol, TLScontext->cipher_name,
882		 TLScontext->cipher_usebits, TLScontext->cipher_algbits);
883
884    tls_int_seed();
885
886    return (TLScontext);
887}
888
889#endif					/* USE_TLS */
890