~ubuntu-branches/ubuntu/dapper/postfix/dapper-security

« back to all changes in this revision

Viewing changes to src/tls/tls_server.c

  • Committer: Bazaar Package Importer
  • Author(s): LaMont Jones
  • Date: 2005-12-07 15:39:11 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20051207153911-hutf07z6i8ty25z5
Tags: 2.2.6-1
* New upstream.
  - the *SQL clients did not uniformly choose the database host from
    the available pool
  - raise the "policy violation" flag when a client request exceeds
    a concurrency or rate limit.
  - don't do smtpd_end_of_data_restrictions after the transaction
    failed due to, e.g., a write error.
  - two messages could get the same message ID due to a race
    condition. This time window was increased when queue file creation
    was postponed from MAIL FROM until the first accepted RCPT TO.  The
    window is closed again.
  - the queue manager did not write a per-recipient defer logfile record
    when the delivery agent crashed after the initial handshake with the
    queue manager, and before reporting the delivery status to the queue
    manager.
  - moved code around from one place to another to make REDIRECT, FILTER,
    HOLD and DISCARD access(5) table actions work in
    smtpd_end_of_data_restrictions.  PREPEND will not be fixed; it must
    be specified before the message content is received.
* Updated Italian translations.  Closes: #336925
* Swedish translations.  Closes: #339746
* Switch to libdb4.3.  Closes: #336488
* Add Replaces: mail-transport-agent.  Closes: #325624
* Merge changes from ubuntu.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*++
 
2
/* NAME
 
3
/*      tls_server 3
 
4
/* SUMMARY
 
5
/*      server-side TLS engine
 
6
/* SYNOPSIS
 
7
/*      #include <tls.h>
 
8
/*
 
9
/*      SSL_CTX *tls_server_init(verifydepth, askcert)
 
10
/*      int     verifydepth;
 
11
/*      int     askcert;
 
12
/*
 
13
/*      TLScontext_t *tls_server_start(server_ctx, stream, timeout,
 
14
/*                                      peername, peeraddr,
 
15
/*                                      tls_info, requirecert)
 
16
/*      SSL_CTX *server_ctx;
 
17
/*      VSTREAM *stream;
 
18
/*      int     timeout;
 
19
/*      const char *peername;
 
20
/*      const char *peeraddr;
 
21
/*      tls_info_t *tls_info;
 
22
/*      int     requirecert;
 
23
/*
 
24
/*      void    tls_server_stop(server_ctx, stream, failure, tls_info)
 
25
/*      SSL_CTX *server_ctx;
 
26
/*      VSTREAM *stream;
 
27
/*      int     failure;
 
28
/*      tls_info_t *tls_info;
 
29
/* DESCRIPTION
 
30
/*      This module is the interface between Postfix TLS servers
 
31
/*      and the OpenSSL library and TLS entropy and cache manager.
 
32
/*
 
33
/*      tls_server_init() is called once when the SMTP server
 
34
/*      initializes.
 
35
/*      Certificate details are also decided during this phase,
 
36
/*      so that peer-specific behavior is not possible.
 
37
/*
 
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.
 
42
/*
 
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.
 
50
/*
 
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).
 
61
/* .PP
 
62
/*      The last two values may differ from each other when export-strength
 
63
/*      encryption is used.
 
64
/*
 
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
 
67
/*      be verified.
 
68
/*      If the peer offered a certificate, part of the certificate data are
 
69
/*      available as:
 
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
 
80
/* LICENSE
 
81
/* .ad
 
82
/* .fi
 
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.
 
86
/* AUTHOR(S)
 
87
/*      Originally written by:
 
88
/*      Lutz Jaenicke
 
89
/*      BTU Cottbus
 
90
/*      Allgemeine Elektrotechnik
 
91
/*      Universitaetsplatz 3-4
 
92
/*      D-03044 Cottbus, Germany
 
93
/*
 
94
/*      Updated by:
 
95
/*      Wietse Venema
 
96
/*      IBM T.J. Watson Research
 
97
/*      P.O. Box 704
 
98
/*      Yorktown Heights, NY 10598, USA
 
99
/*--*/
 
100
 
 
101
/* System library. */
 
102
 
 
103
#include <sys_defs.h>
 
104
 
 
105
#ifdef USE_TLS
 
106
#include <unistd.h>
 
107
#include <string.h>
 
108
 
 
109
/* Utility library. */
 
110
 
 
111
#include <mymalloc.h>
 
112
#include <vstring.h>
 
113
#include <vstream.h>
 
114
#include <dict.h>
 
115
#include <stringops.h>
 
116
#include <msg.h>
 
117
#include <hex_code.h>
 
118
 
 
119
/* Global library. */
 
120
 
 
121
#include <mail_params.h>
 
122
 
 
123
/* TLS library. */
 
124
 
 
125
#include <tls_mgr.h>
 
126
#define TLS_INTERNAL
 
127
#include <tls.h>
 
128
 
 
129
#define STR(x)  vstring_str(x)
 
130
#define LEN(x)  VSTRING_LEN(x)
 
131
 
 
132
/* Application-specific. */
 
133
 
 
134
/* We must keep some of the info available */
 
135
static const char hexcodes[] = "0123456789ABCDEF";
 
136
 
 
137
 /*
 
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.
 
141
  */
 
142
static char server_session_id_context[] = "Postfix/TLS";
 
143
 
 
144
static int tls_server_cache = 0;
 
145
 
 
146
/* server_verify_callback - server verification wrapper */
 
147
 
 
148
static int server_verify_callback(int ok, X509_STORE_CTX *ctx)
 
149
{
 
150
    return (tls_verify_certificate_callback(ok, ctx, TLS_VERIFY_DEFAULT));
 
151
}
 
152
 
 
153
/* get_server_session_cb - callback to retrieve session from server cache */
 
154
 
 
155
static SSL_SESSION *get_server_session_cb(SSL *unused_ssl,
 
156
                                                  unsigned char *session_id,
 
157
                                                  int session_id_length,
 
158
                                                  int *unused_copy)
 
159
{
 
160
    VSTRING *cache_id;
 
161
    VSTRING *session_data = vstring_alloc(2048);
 
162
    SSL_SESSION *session = 0;
 
163
 
 
164
#define MAKE_SERVER_CACHE_ID(id, len) \
 
165
    hex_encode(vstring_alloc(2 * (len) + 1), (char *) (id), (len))
 
166
 
 
167
    /*
 
168
     * Encode the session ID.
 
169
     */
 
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));
 
173
 
 
174
    /*
 
175
     * Load the session from cache and decode it.
 
176
     */
 
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));
 
183
    }
 
184
 
 
185
    /*
 
186
     * Clean up.
 
187
     */
 
188
    vstring_free(cache_id);
 
189
    vstring_free(session_data);
 
190
 
 
191
    return (session);
 
192
}
 
193
 
 
194
/* new_server_session_cb - callback to save session to server cache */
 
195
 
 
196
static int new_server_session_cb(SSL *unused_ssl, SSL_SESSION *session)
 
197
{
 
198
    VSTRING *cache_id;
 
199
    VSTRING *session_data;
 
200
 
 
201
    /*
 
202
     * Encode the session ID.
 
203
     */
 
204
    cache_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));
 
208
 
 
209
    /*
 
210
     * Passivate and save the session state.
 
211
     */
 
212
    session_data = tls_session_passivate(session);
 
213
    if (session_data)
 
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));
 
217
 
 
218
    /*
 
219
     * Clean up.
 
220
     */
 
221
    if (session_data)
 
222
        vstring_free(session_data);
 
223
    vstring_free(cache_id);
 
224
    SSL_SESSION_free(session);                  /* 200502 */
 
225
 
 
226
    return (1);
 
227
}
 
228
 
 
229
/* tls_server_init - initialize the server-side TLS engine */
 
230
 
 
231
SSL_CTX *tls_server_init(int unused_verifydepth, int askcert)
 
232
{
 
233
    int     off = 0;
 
234
    int     verify_flags = SSL_VERIFY_NONE;
 
235
    SSL_CTX *server_ctx;
 
236
    int     cache_types;
 
237
 
 
238
    /* See skeleton at OpenSSL apps/s_server.c. */
 
239
 
 
240
    if (var_smtpd_tls_loglevel >= 2)
 
241
        msg_info("initializing the server-side TLS engine");
 
242
 
 
243
    /*
 
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.
 
247
     */
 
248
    SSL_load_error_strings();
 
249
    OpenSSL_add_ssl_algorithms();
 
250
 
 
251
    /*
 
252
     * Initialize the PRNG (Pseudo Random Number Generator) with some seed
 
253
     * from external and internal sources. Don't enable TLS without some real
 
254
     * entropy.
 
255
     */
 
256
    if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
 
257
        msg_warn("no entropy for TLS key generation: disabling TLS support");
 
258
        return (0);
 
259
    }
 
260
    tls_int_seed();
 
261
 
 
262
    /*
 
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
 
270
     * later.
 
271
     */
 
272
    server_ctx = SSL_CTX_new(SSLv23_server_method());
 
273
    if (server_ctx == NULL) {
 
274
        tls_print_errors();
 
275
        return (0);
 
276
    }
 
277
 
 
278
    /*
 
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.
 
283
     */
 
284
    off |= SSL_OP_ALL;                          /* Work around all known bugs */
 
285
    SSL_CTX_set_options(server_ctx, off);
 
286
 
 
287
    /*
 
288
     * Set the call-back routine for verbose logging.
 
289
     */
 
290
    if (var_smtpd_tls_loglevel >= 2)
 
291
        SSL_CTX_set_info_callback(server_ctx, tls_info_callback);
 
292
 
 
293
    /*
 
294
     * Override the default cipher list with our own list.
 
295
     */
 
296
    if (*var_smtpd_tls_cipherlist != 0)
 
297
        if (SSL_CTX_set_cipher_list(server_ctx, var_smtpd_tls_cipherlist) == 0) {
 
298
            tls_print_errors();
 
299
            SSL_CTX_free(server_ctx);           /* 200411 */
 
300
            return (0);
 
301
        }
 
302
 
 
303
    /*
 
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.
 
313
     */
 
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 */
 
317
        return (0);
 
318
    }
 
319
 
 
320
    /*
 
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
 
331
     * cipher setup.
 
332
     */
 
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 */
 
338
        return (0);
 
339
    }
 
340
 
 
341
    /*
 
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
 
344
     * it.
 
345
     */
 
346
    SSL_CTX_set_tmp_rsa_callback(server_ctx, tls_tmp_rsa_cb);
 
347
 
 
348
    /*
 
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.
 
355
     */
 
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);
 
361
 
 
362
    /*
 
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
 
375
     * available CAs.
 
376
     * 
 
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.
 
381
     */
 
382
    if (askcert)
 
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));
 
388
 
 
389
    /*
 
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.
 
394
     * 
 
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".
 
398
     */
 
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));
 
404
 
 
405
    /*
 
406
     * The session cache is implemented by the tlsmgr(8) server.
 
407
     * 
 
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
 
413
     * Victor Duchovni.
 
414
     */
 
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);
 
421
    }
 
422
 
 
423
    /*
 
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().
 
427
     */
 
428
    if (TLScontext_index < 0)
 
429
        TLScontext_index = SSL_get_ex_new_index(0, "TLScontext ex_data index",
 
430
                                                NULL, NULL, NULL);
 
431
 
 
432
    return (server_ctx);
 
433
}
 
434
 
 
435
 /*
 
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.
 
439
  */
 
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,
 
444
                                       int requirecert)
 
445
{
 
446
    int     sts;
 
447
    int     j;
 
448
    int     verify_flags;
 
449
    unsigned int n;
 
450
    TLScontext_t *TLScontext;
 
451
    SSL_SESSION *session;
 
452
    SSL_CIPHER *cipher;
 
453
    X509   *peer;
 
454
 
 
455
    if (var_smtpd_tls_loglevel >= 1)
 
456
        msg_info("setting up TLS connection from %s[%s]", peername, peeraddr);
 
457
 
 
458
    /*
 
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().
 
462
     * 
 
463
     * XXX Need a dedicated procedure for consistent initialization of all the
 
464
     * fields in this structure.
 
465
     */
 
466
#define PEERNAME_SIZE sizeof(TLScontext->peername_save)
 
467
 
 
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);
 
473
 
 
474
    if ((TLScontext->con = (SSL *) SSL_new(server_ctx)) == NULL) {
 
475
        msg_info("Could not allocate 'TLScontext->con' with SSL_new()");
 
476
        tls_print_errors();
 
477
        FREE_TLS_CONTEXT(TLScontext);
 
478
        return (0);
 
479
    }
 
480
    if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
 
481
        msg_info("Could not set application data for 'TLScontext->con'");
 
482
        tls_print_errors();
 
483
        SSL_free(TLScontext->con);
 
484
        FREE_TLS_CONTEXT(TLScontext);
 
485
        return (0);
 
486
    }
 
487
 
 
488
    /*
 
489
     * Set the verification parameters to be checked in
 
490
     * tls_verify_certificate_callback().
 
491
     */
 
492
    if (requirecert) {
 
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);
 
497
    } else {
 
498
        TLScontext->enforce_verify_errors = 0;
 
499
    }
 
500
    TLScontext->enforce_CN = 0;
 
501
 
 
502
    /*
 
503
     * The TLS connection is realized by a BIO_pair, so obtain the pair.
 
504
     * 
 
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.
 
509
     */
 
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");
 
513
        tls_print_errors();
 
514
        SSL_free(TLScontext->con);
 
515
        FREE_TLS_CONTEXT(TLScontext);
 
516
        return (0);
 
517
    }
 
518
 
 
519
    /*
 
520
     * Before really starting anything, try to seed the PRNG a little bit
 
521
     * more.
 
522
     */
 
523
    tls_int_seed();
 
524
    (void) tls_ext_seed(var_tls_daemon_rand_bytes);
 
525
 
 
526
    /*
 
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.
 
530
     */
 
531
    SSL_set_accept_state(TLScontext->con);
 
532
 
 
533
    /*
 
534
     * Connect the SSL connection with the Postfix side of the BIO-pair for
 
535
     * reading and writing.
 
536
     */
 
537
    SSL_set_bio(TLScontext->con, TLScontext->internal_bio,
 
538
                TLScontext->internal_bio);
 
539
 
 
540
    /*
 
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.
 
543
     * 
 
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.
 
547
     */
 
548
    if (var_smtpd_tls_loglevel >= 3)
 
549
        BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
 
550
 
 
551
    /*
 
552
     * Start TLS negotiations. This process is a black box that invokes our
 
553
     * call-backs for session caching and certificate verification.
 
554
     * 
 
555
     * Error handling: If the SSL handhake fails, we print out an error message
 
556
     * and remove all TLS state concerning this session.
 
557
     */
 
558
    sts = tls_bio_accept(vstream_fileno(stream), timeout, TLScontext);
 
559
    if (sts <= 0) {
 
560
        msg_info("SSL_accept error from %s[%s]: %d", peername, peeraddr, sts);
 
561
        tls_print_errors();
 
562
        SSL_free(TLScontext->con);
 
563
        BIO_free(TLScontext->network_bio);      /* 200411 */
 
564
        FREE_TLS_CONTEXT(TLScontext);
 
565
        return (0);
 
566
    }
 
567
    /* Only loglevel==4 dumps everything */
 
568
    if (var_smtpd_tls_loglevel < 4)
 
569
        BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
 
570
 
 
571
    /*
 
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.
 
574
     */
 
575
    peer = SSL_get_peer_certificate(TLScontext->con);
 
576
    if (peer != NULL) {
 
577
        if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
 
578
            tls_info->peer_verified = 1;
 
579
 
 
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;
 
586
 
 
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;
 
593
 
 
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] = ':';
 
602
                else
 
603
                    TLScontext->fingerprint[(j * 3) + 2] = '\0';
 
604
            }
 
605
            if (var_smtpd_tls_loglevel >= 1)
 
606
                msg_info("fingerprint=%s", TLScontext->fingerprint);
 
607
            tls_info->peer_fingerprint = TLScontext->fingerprint;
 
608
        }
 
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");
 
614
            tls_print_errors();
 
615
        }
 
616
        tls_info->peer_CN = TLScontext->peer_CN;
 
617
 
 
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");
 
623
            tls_print_errors();
 
624
        }
 
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");
 
631
                tls_print_errors();
 
632
            }
 
633
        }
 
634
        tls_info->issuer_CN = TLScontext->issuer_CN;
 
635
 
 
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);
 
640
            else
 
641
                msg_info("Unverified: subject_CN=%s, issuer=%s",
 
642
                         TLScontext->peer_CN, TLScontext->issuer_CN);
 
643
        }
 
644
        X509_free(peer);
 
645
    }
 
646
 
 
647
    /*
 
648
     * If this is a cached session, we have to check by hand if the cached
 
649
     * session peer was verified.
 
650
     */
 
651
    if (requirecert) {
 
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);
 
659
            return (0);
 
660
        }
 
661
    }
 
662
 
 
663
    /*
 
664
     * Finally, collect information about protocol and cipher for logging
 
665
     */
 
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));
 
671
 
 
672
    /*
 
673
     * The TLS engine is active. Switch to the tls_timed_read/write()
 
674
     * functions and make the TLScontext available to those functions.
 
675
     */
 
676
    tls_stream_start(stream, TLScontext);
 
677
 
 
678
    if (var_smtpd_tls_loglevel >= 1)
 
679
        msg_info("TLS connection established from %s[%s]: %s with cipher %s (%d/%d bits)",
 
680
                 peername, peeraddr,
 
681
                 tls_info->protocol, tls_info->cipher_name,
 
682
                 tls_info->cipher_usebits, tls_info->cipher_algbits);
 
683
    tls_int_seed();
 
684
 
 
685
    return (TLScontext);
 
686
}
 
687
 
 
688
#endif                                  /* USE_TLS */