5
/* server-side TLS engine
9
/* SSL_CTX *tls_server_init(verifydepth, askcert)
13
/* TLScontext_t *tls_server_start(server_ctx, stream, timeout,
14
/* peername, peeraddr,
15
/* tls_info, requirecert)
16
/* SSL_CTX *server_ctx;
19
/* const char *peername;
20
/* const char *peeraddr;
21
/* tls_info_t *tls_info;
24
/* void tls_server_stop(server_ctx, stream, failure, tls_info)
25
/* SSL_CTX *server_ctx;
28
/* tls_info_t *tls_info;
30
/* This module is the interface between Postfix TLS servers
31
/* and the OpenSSL library and TLS entropy and cache manager.
33
/* tls_server_init() is called once when the SMTP server
35
/* Certificate details are also decided during this phase,
36
/* so that peer-specific behavior is not possible.
38
/* tls_server_start() activates the TLS feature for the VSTREAM
39
/* passed as argument. We assume that network buffers are flushed and the
40
/* TLS handshake can begin immediately. Information about the peer
41
/* is stored into the tls_info structure passed as argument.
43
/* tls_server_stop() sends the "close notify" alert via
44
/* SSL_shutdown() to the peer and resets all connection specific
45
/* TLS data. As RFC2487 does not specify a separate shutdown, it
46
/* is assumed that the underlying TCP connection is shut down
47
/* immediately afterwards, so we don't care about additional data
48
/* coming through the channel.
49
/* If the failure flag is set, no SSL_shutdown() handshake is performed.
51
/* Once the TLS connection is initiated, information about the TLS
52
/* state is available via the tls_info structure:
53
/* .IP tls_info->protocol
54
/* the protocol name (SSLv2, SSLv3, TLSv1),
55
/* .IP tls_info->cipher_name
56
/* the cipher name (e.g. RC4/MD5),
57
/* .IP tls_info->cipher_usebits
58
/* the number of bits actually used (e.g. 40),
59
/* .IP tls_info->cipher_algbits
60
/* the number of bits the algorithm is based on (e.g. 128).
62
/* The last two values may differ from each other when export-strength
63
/* encryption is used.
65
/* The status of the peer certificate verification is available in
66
/* tls_info->peer_verified. It is set to 1 when the certificate could
68
/* If the peer offered a certificate, part of the certificate data are
70
/* .IP tls_info->peer_subject
71
/* X509v3-oneline with the DN of the peer
72
/* .IP tls_info->peer_CN
73
/* extracted CommonName of the peer
74
/* .IP tls_info->peer_issuer
75
/* X509v3-oneline with the DN of the issuer
76
/* .IP tls_info->issuer_CN
77
/* extracted CommonName of the issuer
78
/* .IP tls_info->peer_fingerprint
79
/* fingerprint of the certificate
83
/* This software is free. You can do with it whatever you want.
84
/* The original author kindly requests that you acknowledge
85
/* the use of his software.
87
/* Originally written by:
90
/* Allgemeine Elektrotechnik
91
/* Universitaetsplatz 3-4
92
/* D-03044 Cottbus, Germany
96
/* IBM T.J. Watson Research
98
/* Yorktown Heights, NY 10598, USA
101
/* System library. */
103
#include <sys_defs.h>
109
/* Utility library. */
111
#include <mymalloc.h>
115
#include <stringops.h>
117
#include <hex_code.h>
119
/* Global library. */
121
#include <mail_params.h>
129
#define STR(x) vstring_str(x)
130
#define LEN(x) VSTRING_LEN(x)
132
/* Application-specific. */
134
/* We must keep some of the info available */
135
static const char hexcodes[] = "0123456789ABCDEF";
138
* The session_id_context indentifies the service that created a session.
139
* This information is used to distinguish between multiple TLS-based
140
* servers running on the same server. We use the name of the mail system.
142
static char server_session_id_context[] = "Postfix/TLS";
144
static int tls_server_cache = 0;
146
/* server_verify_callback - server verification wrapper */
148
static int server_verify_callback(int ok, X509_STORE_CTX *ctx)
150
return (tls_verify_certificate_callback(ok, ctx, TLS_VERIFY_DEFAULT));
153
/* get_server_session_cb - callback to retrieve session from server cache */
155
static SSL_SESSION *get_server_session_cb(SSL *unused_ssl,
156
unsigned char *session_id,
157
int session_id_length,
161
VSTRING *session_data = vstring_alloc(2048);
162
SSL_SESSION *session = 0;
164
#define MAKE_SERVER_CACHE_ID(id, len) \
165
hex_encode(vstring_alloc(2 * (len) + 1), (char *) (id), (len))
168
* Encode the session ID.
170
cache_id = MAKE_SERVER_CACHE_ID(session_id, session_id_length);
171
if (var_smtpd_tls_loglevel >= 3)
172
msg_info("looking up session %s in server cache", STR(cache_id));
175
* Load the session from cache and decode it.
177
if (tls_mgr_lookup(tls_server_cache, STR(cache_id),
178
OPENSSL_VERSION_NUMBER, TLS_MGR_NO_FLAGS,
179
session_data) == TLS_MGR_STAT_OK) {
180
session = tls_session_activate(STR(session_data), LEN(session_data));
181
if (session && (var_smtpd_tls_loglevel >= 3))
182
msg_info("reloaded session %s from server cache", STR(cache_id));
188
vstring_free(cache_id);
189
vstring_free(session_data);
194
/* new_server_session_cb - callback to save session to server cache */
196
static int new_server_session_cb(SSL *unused_ssl, SSL_SESSION *session)
199
VSTRING *session_data;
202
* Encode the session ID.
205
MAKE_SERVER_CACHE_ID(session->session_id, session->session_id_length);
206
if (var_smtpd_tls_loglevel >= 3)
207
msg_info("save session %s to server cache", STR(cache_id));
210
* Passivate and save the session state.
212
session_data = tls_session_passivate(session);
214
tls_mgr_update(tls_server_cache, STR(cache_id),
215
OPENSSL_VERSION_NUMBER, TLS_MGR_NO_FLAGS,
216
STR(session_data), LEN(session_data));
222
vstring_free(session_data);
223
vstring_free(cache_id);
224
SSL_SESSION_free(session); /* 200502 */
229
/* tls_server_init - initialize the server-side TLS engine */
231
SSL_CTX *tls_server_init(int unused_verifydepth, int askcert)
234
int verify_flags = SSL_VERIFY_NONE;
238
/* See skeleton at OpenSSL apps/s_server.c. */
240
if (var_smtpd_tls_loglevel >= 2)
241
msg_info("initializing the server-side TLS engine");
244
* Initialize the OpenSSL library by the book! To start with, we must
245
* initialize the algorithms. We want cleartext error messages instead of
246
* just error codes, so we load the error_strings.
248
SSL_load_error_strings();
249
OpenSSL_add_ssl_algorithms();
252
* Initialize the PRNG (Pseudo Random Number Generator) with some seed
253
* from external and internal sources. Don't enable TLS without some real
256
if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
257
msg_warn("no entropy for TLS key generation: disabling TLS support");
263
* The SSL/TLS specifications require the client to send a message in the
264
* oldest specification it understands with the highest level it
265
* understands in the message. Netscape communicator can still
266
* communicate with SSLv2 servers, so it sends out a SSLv2 client hello.
267
* To deal with it, our server must be SSLv2 aware (even if we don't like
268
* SSLv2), so we need to have the SSLv23 server here. If we want to limit
269
* the protocol level, we can add an option to not use SSLv2/v3/TLSv1
272
server_ctx = SSL_CTX_new(SSLv23_server_method());
273
if (server_ctx == NULL) {
279
* Here we might set SSL_OP_NO_SSLv2, SSL_OP_NO_SSLv3, SSL_OP_NO_TLSv1.
280
* Of course, the last one would not make sense, since RFC2487 is only
281
* defined for TLS, but we also want to accept Netscape communicator
282
* requests, and it only supports SSLv3.
284
off |= SSL_OP_ALL; /* Work around all known bugs */
285
SSL_CTX_set_options(server_ctx, off);
288
* Set the call-back routine for verbose logging.
290
if (var_smtpd_tls_loglevel >= 2)
291
SSL_CTX_set_info_callback(server_ctx, tls_info_callback);
294
* Override the default cipher list with our own list.
296
if (*var_smtpd_tls_cipherlist != 0)
297
if (SSL_CTX_set_cipher_list(server_ctx, var_smtpd_tls_cipherlist) == 0) {
299
SSL_CTX_free(server_ctx); /* 200411 */
304
* Load the CA public key certificates for both the server cert and for
305
* the verification of client certificates. As provided by OpenSSL we
306
* support two types of CA certificate handling: One possibility is to
307
* add all CA certificates to one large CAfile, the other possibility is
308
* a directory pointed to by CApath, containing separate files for each
309
* CA with softlinks named after the hash values of the certificate. The
310
* first alternative has the advantage that the file is opened and read
311
* at startup time, so that you don't have the hassle to maintain another
312
* copy of the CApath directory for chroot-jail.
314
if (tls_set_ca_certificate_info(server_ctx, var_smtpd_tls_CAfile,
315
var_smtpd_tls_CApath) < 0) {
316
SSL_CTX_free(server_ctx); /* 200411 */
321
* Load the server public key certificate and private key from file and
322
* check whether the cert matches the key. We cannot run without (we do
323
* not support ADH anonymous Diffie-Hellman ciphers as of now). We can
324
* use RSA certificates ("cert") and DSA certificates ("dcert"), both can
325
* be made available at the same time. The CA certificates for both are
326
* handled in the same setup already finished. Which one is used depends
327
* on the cipher negotiated (that is: the first cipher listed by the
328
* client which does match the server). A client with RSA only (e.g.
329
* Netscape) will use the RSA certificate only. A client with
330
* openssl-library will use RSA first if not especially changed in the
333
if (tls_set_my_certificate_key_info(server_ctx, var_smtpd_tls_cert_file,
334
var_smtpd_tls_key_file,
335
var_smtpd_tls_dcert_file,
336
var_smtpd_tls_dkey_file) < 0) {
337
SSL_CTX_free(server_ctx); /* 200411 */
342
* According to the OpenSSL documentation, temporary RSA key is needed
343
* export ciphers are in use. We have to provide one, so well, we just do
346
SSL_CTX_set_tmp_rsa_callback(server_ctx, tls_tmp_rsa_cb);
349
* Diffie-Hellman key generation parameters can either be loaded from
350
* files (preferred) or taken from compiled in values. First, set the
351
* callback that will select the values when requested, then load the
352
* (possibly) available DH parameters from files. We are generous with
353
* the error handling, since we do have default values compiled in, so we
354
* will not abort but just log the error message.
356
SSL_CTX_set_tmp_dh_callback(server_ctx, tls_tmp_dh_cb);
357
if (*var_smtpd_tls_dh1024_param_file != 0)
358
tls_set_dh_1024_from_file(var_smtpd_tls_dh1024_param_file);
359
if (*var_smtpd_tls_dh512_param_file != 0)
360
tls_set_dh_512_from_file(var_smtpd_tls_dh512_param_file);
363
* If we want to check client certificates, we have to indicate it in
364
* advance. By now we only allow to decide on a global basis. If we want
365
* to allow certificate based relaying, we must ask the client to provide
366
* one with SSL_VERIFY_PEER. The client now can decide, whether it
367
* provides one or not. We can enforce a failure of the negotiation with
368
* SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we do not allow a connection
369
* without one. In the "server hello" following the initialization by the
370
* "client hello" the server must provide a list of CAs it is willing to
371
* accept. Some clever clients will then select one from the list of
372
* available certificates matching these CAs. Netscape Communicator will
373
* present the list of certificates for selecting the one to be sent, or
374
* it will issue a warning, if there is no certificate matching the
377
* With regard to the purpose of the certificate for relaying, we might like
378
* a later negotiation, maybe relaying would already be allowed for other
379
* reasons, but this would involve severe changes in the internal postfix
380
* logic, so we have to live with it the way it is.
383
verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
384
SSL_CTX_set_verify(server_ctx, verify_flags, server_verify_callback);
385
if (*var_smtpd_tls_CAfile)
386
SSL_CTX_set_client_CA_list(server_ctx,
387
SSL_load_client_CA_file(var_smtpd_tls_CAfile));
390
* Initialize the session cache. In order to share cached sessions among
391
* multiple SMTP server processes, we use an external cache and set the
392
* internal cache size to a minimum value of 1. Access to the external
393
* cache is handled by the appropriate callback functions.
395
* Set a session id context to identify to what type of server process
396
* created a session. In our case, the context is simply the name of the
397
* mail system: "Postfix/TLS".
399
SSL_CTX_sess_set_cache_size(server_ctx, 1);
400
SSL_CTX_set_timeout(server_ctx, var_smtpd_tls_scache_timeout);
401
SSL_CTX_set_session_id_context(server_ctx,
402
(void *) &server_session_id_context,
403
sizeof(server_session_id_context));
406
* The session cache is implemented by the tlsmgr(8) server.
408
* XXX 200502 Surprise: when OpenSSL purges an entry from the in-memory
409
* cache, it also attempts to purge the entry from the on-disk cache.
410
* This is undesirable, especially when we set the in-memory cache size
411
* to 1. For this reason we don't allow OpenSSL to purge on-disk cache
412
* entries, and leave it up to the tlsmgr process instead. Found by
415
if (tls_mgr_policy(&cache_types) == TLS_MGR_STAT_OK
416
&& (tls_server_cache = (cache_types & TLS_MGR_SCACHE_SERVER)) != 0) {
417
SSL_CTX_set_session_cache_mode(server_ctx,
418
SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
419
SSL_CTX_sess_set_get_cb(server_ctx, get_server_session_cb);
420
SSL_CTX_sess_set_new_cb(server_ctx, new_server_session_cb);
424
* Create a global index so that we can attach TLScontext information to
425
* SSL objects; this information is needed inside
426
* tls_verify_certificate_callback().
428
if (TLScontext_index < 0)
429
TLScontext_index = SSL_get_ex_new_index(0, "TLScontext ex_data index",
436
* This is the actual startup routine for a new connection. We expect that
437
* the SMTP buffers are flushed and the "220 Ready to start TLS" was sent to
438
* the client, so that we can immediately start the TLS handshake process.
440
TLScontext_t *tls_server_start(SSL_CTX *server_ctx, VSTREAM *stream,
441
int timeout, const char *peername,
442
const char *peeraddr,
443
tls_info_t *tls_info,
450
TLScontext_t *TLScontext;
451
SSL_SESSION *session;
455
if (var_smtpd_tls_loglevel >= 1)
456
msg_info("setting up TLS connection from %s[%s]", peername, peeraddr);
459
* Allocate a new TLScontext for the new connection and get an SSL
460
* structure. Add the location of TLScontext to the SSL to later retrieve
461
* the information inside the tls_verify_certificate_callback().
463
* XXX Need a dedicated procedure for consistent initialization of all the
464
* fields in this structure.
466
#define PEERNAME_SIZE sizeof(TLScontext->peername_save)
468
NEW_TLS_CONTEXT(TLScontext);
469
TLScontext->log_level = var_smtpd_tls_loglevel;
470
strncpy(TLScontext->peername_save, peername, PEERNAME_SIZE - 1);
471
TLScontext->peername_save[PEERNAME_SIZE - 1] = 0;
472
(void) lowercase(TLScontext->peername_save);
474
if ((TLScontext->con = (SSL *) SSL_new(server_ctx)) == NULL) {
475
msg_info("Could not allocate 'TLScontext->con' with SSL_new()");
477
FREE_TLS_CONTEXT(TLScontext);
480
if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
481
msg_info("Could not set application data for 'TLScontext->con'");
483
SSL_free(TLScontext->con);
484
FREE_TLS_CONTEXT(TLScontext);
489
* Set the verification parameters to be checked in
490
* tls_verify_certificate_callback().
493
verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
494
verify_flags |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
495
TLScontext->enforce_verify_errors = 1;
496
SSL_set_verify(TLScontext->con, verify_flags, server_verify_callback);
498
TLScontext->enforce_verify_errors = 0;
500
TLScontext->enforce_CN = 0;
503
* The TLS connection is realized by a BIO_pair, so obtain the pair.
505
* XXX There is no need to store the internal_bio handle in the TLScontext
506
* structure. It will be attached to and destroyed with TLScontext->con.
507
* The network_bio, however, needs to be freed explicitly, so we need to
508
* store its handle in TLScontext.
510
if (!BIO_new_bio_pair(&TLScontext->internal_bio, TLS_BIO_BUFSIZE,
511
&TLScontext->network_bio, TLS_BIO_BUFSIZE)) {
512
msg_info("Could not obtain BIO_pair");
514
SSL_free(TLScontext->con);
515
FREE_TLS_CONTEXT(TLScontext);
520
* Before really starting anything, try to seed the PRNG a little bit
524
(void) tls_ext_seed(var_tls_daemon_rand_bytes);
527
* Initialize the SSL connection to accept state. This should not be
528
* necessary anymore since 0.9.3, but the call is still in the library
529
* and maintaining compatibility never hurts.
531
SSL_set_accept_state(TLScontext->con);
534
* Connect the SSL connection with the Postfix side of the BIO-pair for
535
* reading and writing.
537
SSL_set_bio(TLScontext->con, TLScontext->internal_bio,
538
TLScontext->internal_bio);
541
* If the debug level selected is high enough, all of the data is dumped:
542
* 3 will dump the SSL negotiation, 4 will dump everything.
544
* We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
545
* Well there is a BIO below the SSL routines that is automatically
546
* created for us, so we can use it for debugging purposes.
548
if (var_smtpd_tls_loglevel >= 3)
549
BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
552
* Start TLS negotiations. This process is a black box that invokes our
553
* call-backs for session caching and certificate verification.
555
* Error handling: If the SSL handhake fails, we print out an error message
556
* and remove all TLS state concerning this session.
558
sts = tls_bio_accept(vstream_fileno(stream), timeout, TLScontext);
560
msg_info("SSL_accept error from %s[%s]: %d", peername, peeraddr, sts);
562
SSL_free(TLScontext->con);
563
BIO_free(TLScontext->network_bio); /* 200411 */
564
FREE_TLS_CONTEXT(TLScontext);
567
/* Only loglevel==4 dumps everything */
568
if (var_smtpd_tls_loglevel < 4)
569
BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
572
* Let's see whether a peer certificate is available and what is the
573
* actual information. We want to save it for later use.
575
peer = SSL_get_peer_certificate(TLScontext->con);
577
if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
578
tls_info->peer_verified = 1;
580
X509_NAME_oneline(X509_get_subject_name(peer),
581
TLScontext->peer_subject,
582
sizeof(TLScontext->peer_subject));
583
if (var_smtpd_tls_loglevel >= 2)
584
msg_info("subject=%s", TLScontext->peer_subject);
585
tls_info->peer_subject = TLScontext->peer_subject;
587
X509_NAME_oneline(X509_get_issuer_name(peer),
588
TLScontext->peer_issuer,
589
sizeof(TLScontext->peer_issuer));
590
if (var_smtpd_tls_loglevel >= 2)
591
msg_info("issuer=%s", TLScontext->peer_issuer);
592
tls_info->peer_issuer = TLScontext->peer_issuer;
594
if (X509_digest(peer, EVP_md5(), TLScontext->md, &n)) {
595
for (j = 0; j < (int) n; j++) {
596
TLScontext->fingerprint[j * 3] =
597
hexcodes[(TLScontext->md[j] & 0xf0) >> 4];
598
TLScontext->fingerprint[(j * 3) + 1] =
599
hexcodes[(TLScontext->md[j] & 0x0f)];
600
if (j + 1 != (int) n)
601
TLScontext->fingerprint[(j * 3) + 2] = ':';
603
TLScontext->fingerprint[(j * 3) + 2] = '\0';
605
if (var_smtpd_tls_loglevel >= 1)
606
msg_info("fingerprint=%s", TLScontext->fingerprint);
607
tls_info->peer_fingerprint = TLScontext->fingerprint;
609
TLScontext->peer_CN[0] = '\0';
610
if (!X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
611
NID_commonName, TLScontext->peer_CN,
612
sizeof(TLScontext->peer_CN))) {
613
msg_info("Could not parse client's subject CN");
616
tls_info->peer_CN = TLScontext->peer_CN;
618
TLScontext->issuer_CN[0] = '\0';
619
if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer),
620
NID_commonName, TLScontext->issuer_CN,
621
sizeof(TLScontext->issuer_CN))) {
622
msg_info("Could not parse client's issuer CN");
625
if (!TLScontext->issuer_CN[0]) {
626
/* No issuer CN field, use Organization instead */
627
if (!X509_NAME_get_text_by_NID(X509_get_issuer_name(peer),
628
NID_organizationName, TLScontext->issuer_CN,
629
sizeof(TLScontext->issuer_CN))) {
630
msg_info("Could not parse client's issuer Organization");
634
tls_info->issuer_CN = TLScontext->issuer_CN;
636
if (var_smtpd_tls_loglevel >= 1) {
637
if (tls_info->peer_verified)
638
msg_info("Verified: subject_CN=%s, issuer=%s",
639
TLScontext->peer_CN, TLScontext->issuer_CN);
641
msg_info("Unverified: subject_CN=%s, issuer=%s",
642
TLScontext->peer_CN, TLScontext->issuer_CN);
648
* If this is a cached session, we have to check by hand if the cached
649
* session peer was verified.
652
if (!tls_info->peer_verified || !tls_info->peer_CN) {
653
msg_info("Re-used session without peer certificate removed");
654
session = SSL_get_session(TLScontext->con);
655
SSL_CTX_remove_session(server_ctx, session);
656
SSL_free(TLScontext->con);
657
BIO_free(TLScontext->network_bio); /* 200411 */
658
FREE_TLS_CONTEXT(TLScontext);
664
* Finally, collect information about protocol and cipher for logging
666
tls_info->protocol = SSL_get_version(TLScontext->con);
667
cipher = SSL_get_current_cipher(TLScontext->con);
668
tls_info->cipher_name = SSL_CIPHER_get_name(cipher);
669
tls_info->cipher_usebits = SSL_CIPHER_get_bits(cipher,
670
&(tls_info->cipher_algbits));
673
* The TLS engine is active. Switch to the tls_timed_read/write()
674
* functions and make the TLScontext available to those functions.
676
tls_stream_start(stream, TLScontext);
678
if (var_smtpd_tls_loglevel >= 1)
679
msg_info("TLS connection established from %s[%s]: %s with cipher %s (%d/%d bits)",
681
tls_info->protocol, tls_info->cipher_name,
682
tls_info->cipher_usebits, tls_info->cipher_algbits);