~ubuntu-branches/ubuntu/saucy/postfix/saucy

« back to all changes in this revision

Viewing changes to src/tlsproxy/tlsproxy.c

  • Committer: Bazaar Package Importer
  • Author(s): LaMont Jones
  • Date: 2011-02-22 11:20:43 UTC
  • mfrom: (1.1.27 upstream)
  • Revision ID: james.westby@ubuntu.com-20110222112043-c34ht219w3ybrilr
Tags: 2.8.0-2
* a little more lintian cleanup
* Fix missing format strings in smtp-sink.c

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*++
 
2
/* NAME
 
3
/*      tlsproxy 8
 
4
/* SUMMARY
 
5
/*      Postfix TLS proxy
 
6
/* SYNOPSIS
 
7
/*      \fBtlsproxy\fR [generic Postfix daemon options]
 
8
/* DESCRIPTION
 
9
/*      The \fBtlsproxy\fR(8) server implements a server-side TLS
 
10
/*      proxy. It is used by \fBpostscreen\fR(8) to talk SMTP-over-TLS
 
11
/*      with remote SMTP clients whose whitelist status has expired,
 
12
/*      but it should also work for non-SMTP protocols.
 
13
/*
 
14
/*      Although one \fBtlsproxy\fR(8) process can serve multiple
 
15
/*      sessions at the same time, it is a good idea to allow the
 
16
/*      number of processes to increase with load, so that the
 
17
/*      service remains responsive.
 
18
/* PROTOCOL EXAMPLE
 
19
/* .ad
 
20
/* .fi
 
21
/*      The example below concerns \fBpostscreen\fR(8). However,
 
22
/*      the \fBtlsproxy\fR(8) server is agnostic of the application
 
23
/*      protocol, and the example is easily adapted to other
 
24
/*      applications.
 
25
/*
 
26
/*      The \fBpostscreen\fR(8) server sends the remote SMTP client
 
27
/*      endpoint string, the requested role (server), and the
 
28
/*      requested timeout to \fBtlsproxy\fR(8).  \fBpostscreen\fR(8)
 
29
/*      then receives a "TLS available" indication from \fBtlsproxy\fR(8).
 
30
/*      If the TLS service is available, \fBpostscreen\fR(8) sends
 
31
/*      the remote SMTP client file descriptor to \fBtlsproxy\fR(8),
 
32
/*      and sends the plaintext 220 greeting to the remote SMTP
 
33
/*      client.  This triggers TLS negotiations between the remote
 
34
/*      SMTP client and \fBtlsproxy\fR(8).  Upon completion of the
 
35
/*      TLS-level handshake, \fBtlsproxy\fR(8) translates between
 
36
/*      plaintext from/to \fBpostscreen\fR(8) and ciphertext to/from
 
37
/*      the remote SMTP client.
 
38
/* SECURITY
 
39
/* .ad
 
40
/* .fi
 
41
/*      The \fBtlsproxy\fR(8) server is moderately security-sensitive.
 
42
/*      It talks to untrusted clients on the network. The process
 
43
/*      can be run chrooted at fixed low privilege.
 
44
/* DIAGNOSTICS
 
45
/*      Problems and transactions are logged to \fBsyslogd\fR(8).
 
46
/* CONFIGURATION PARAMETERS
 
47
/* .ad
 
48
/* .fi
 
49
/*      Changes to \fBmain.cf\fR are not picked up automatically,
 
50
/*      as \fBtlsproxy\fR(8) processes may run for a long time
 
51
/*      depending on mail server load.  Use the command "\fBpostfix
 
52
/*      reload\fR" to speed up a change.
 
53
/*
 
54
/*      The text below provides only a parameter summary. See
 
55
/*      \fBpostconf\fR(5) for more details including examples.
 
56
/* STARTTLS SUPPORT CONTROLS
 
57
/* .ad
 
58
/* .fi
 
59
/* .IP "\fBtlsproxy_tls_CAfile ($smtpd_tls_CAfile)\fR"
 
60
/*      A file containing (PEM format) CA certificates of root CAs
 
61
/*      trusted to sign either remote SMTP client certificates or intermediate
 
62
/*      CA certificates.
 
63
/* .IP "\fBtlsproxy_tls_CApath ($smtpd_tls_CApath)\fR"
 
64
/*      A directory containing (PEM format) CA certificates of root CAs
 
65
/*      trusted to sign either remote SMTP client certificates or intermediate
 
66
/*      CA certificates.
 
67
/* .IP "\fBtlsproxy_tls_always_issue_session_ids ($smtpd_tls_always_issue_session_ids)\fR"
 
68
/*      Force the Postfix \fBtlsproxy\fR(8) server to issue a TLS session id,
 
69
/*      even when TLS session caching is turned off.
 
70
/* .IP "\fBtlsproxy_tls_ask_ccert ($smtpd_tls_ask_ccert)\fR"
 
71
/*      Ask a remote SMTP client for a client certificate.
 
72
/* .IP "\fBtlsproxy_tls_ccert_verifydepth ($smtpd_tls_ccert_verifydepth)\fR"
 
73
/*      The verification depth for remote SMTP client certificates.
 
74
/* .IP "\fBtlsproxy_tls_cert_file ($smtpd_tls_cert_file)\fR"
 
75
/*      File with the Postfix \fBtlsproxy\fR(8) server RSA certificate in PEM
 
76
/*      format.
 
77
/* .IP "\fBtlsproxy_tls_ciphers ($smtpd_tls_ciphers)\fR"
 
78
/*      The minimum TLS cipher grade that the Postfix \fBtlsproxy\fR(8) server
 
79
/*      will use with opportunistic TLS encryption.
 
80
/* .IP "\fBtlsproxy_tls_dcert_file ($smtpd_tls_dcert_file)\fR"
 
81
/*      File with the Postfix \fBtlsproxy\fR(8) server DSA certificate in PEM
 
82
/*      format.
 
83
/* .IP "\fBtlsproxy_tls_dh1024_param_file ($smtpd_tls_dh1024_param_file)\fR"
 
84
/*      File with DH parameters that the Postfix \fBtlsproxy\fR(8) server
 
85
/*      should use with EDH ciphers.
 
86
/* .IP "\fBtlsproxy_tls_dh512_param_file ($smtpd_tls_dh512_param_file)\fR"
 
87
/*      File with DH parameters that the Postfix \fBtlsproxy\fR(8) server
 
88
/*      should use with EDH ciphers.
 
89
/* .IP "\fBtlsproxy_tls_dkey_file ($smtpd_tls_dkey_file)\fR"
 
90
/*      File with the Postfix \fBtlsproxy\fR(8) server DSA private key in PEM
 
91
/*      format.
 
92
/* .IP "\fBtlsproxy_tls_eccert_file ($smtpd_tls_eccert_file)\fR"
 
93
/*      File with the Postfix \fBtlsproxy\fR(8) server ECDSA certificate in
 
94
/*      PEM format.
 
95
/* .IP "\fBtlsproxy_tls_eckey_file ($smtpd_tls_eckey_file)\fR"
 
96
/*      File with the Postfix \fBtlsproxy\fR(8) server ECDSA private key in
 
97
/*      PEM format.
 
98
/* .IP "\fBtlsproxy_tls_eecdh_grade ($smtpd_tls_eecdh_grade)\fR"
 
99
/*      The Postfix \fBtlsproxy\fR(8) server security grade for ephemeral
 
100
/*      elliptic-curve Diffie-Hellman (EECDH) key exchange.
 
101
/* .IP "\fBtlsproxy_tls_exclude_ciphers ($smtpd_tls_exclude_ciphers)\fR"
 
102
/*      List of ciphers or cipher types to exclude from the \fBtlsproxy\fR(8)
 
103
/*      server cipher list at all TLS security levels.
 
104
/* .IP "\fBtlsproxy_tls_fingerprint_digest ($smtpd_tls_fingerprint_digest)\fR"
 
105
/*      The message digest algorithm used to construct client-certificate
 
106
/*      fingerprints.
 
107
/* .IP "\fBtlsproxy_tls_key_file ($smtpd_tls_key_file)\fR"
 
108
/*      File with the Postfix \fBtlsproxy\fR(8) server RSA private key in PEM
 
109
/*      format.
 
110
/* .IP "\fBtlsproxy_tls_loglevel ($smtpd_tls_loglevel)\fR"
 
111
/*      Enable additional Postfix \fBtlsproxy\fR(8) server logging of TLS
 
112
/*      activity.
 
113
/* .IP "\fBtlsproxy_tls_mandatory_ciphers ($smtpd_tls_mandatory_ciphers)\fR"
 
114
/*      The minimum TLS cipher grade that the Postfix \fBtlsproxy\fR(8) server
 
115
/*      will use with mandatory TLS encryption.
 
116
/* .IP "\fBtlsproxy_tls_mandatory_exclude_ciphers ($smtpd_tls_mandatory_exclude_ciphers)\fR"
 
117
/*      Additional list of ciphers or cipher types to exclude from the
 
118
/*      \fBtlsproxy\fR(8) server cipher list at mandatory TLS security levels.
 
119
/* .IP "\fBtlsproxy_tls_mandatory_protocols ($smtpd_tls_mandatory_protocols)\fR"
 
120
/*      The SSL/TLS protocols accepted by the Postfix \fBtlsproxy\fR(8) server
 
121
/*      with mandatory TLS encryption.
 
122
/* .IP "\fBtlsproxy_tls_protocols ($smtpd_tls_protocols)\fR"
 
123
/*      List of TLS protocols that the Postfix \fBtlsproxy\fR(8) server will
 
124
/*      exclude or include with opportunistic TLS encryption.
 
125
/* .IP "\fBtlsproxy_tls_req_ccert ($smtpd_tls_req_ccert)\fR"
 
126
/*      With mandatory TLS encryption, require a trusted remote SMTP
 
127
/*      client certificate in order to allow TLS connections to proceed.
 
128
/* .IP "\fBtlsproxy_tls_security_level ($smtpd_tls_security_level)\fR"
 
129
/*      The SMTP TLS security level for the Postfix \fBtlsproxy\fR(8) server;
 
130
/*      when a non-empty value is specified, this overrides the obsolete
 
131
/*      parameters smtpd_use_tls and smtpd_enforce_tls.
 
132
/* .IP "\fBtlsproxy_tls_session_cache_timeout ($smtpd_tls_session_cache_timeout)\fR"
 
133
/*      The expiration time of Postfix \fBtlsproxy\fR(8) server TLS session
 
134
/*      cache information.
 
135
/* OBSOLETE STARTTLS SUPPORT CONTROLS
 
136
/* .ad
 
137
/* .fi
 
138
/*      These parameters are supported for compatibility with
 
139
/*      \fBsmtpd\fR(8) legacy parameters.
 
140
/* .IP "\fBtlsproxy_use_tls ($smtpd_use_tls)\fR"
 
141
/*      Opportunistic TLS: announce STARTTLS support to SMTP clients,
 
142
/*      but do not require that clients use TLS encryption.
 
143
/* .IP "\fBtlsproxy_enforce_tls ($smtpd_enforce_tls)\fR"
 
144
/*      Mandatory TLS: announce STARTTLS support to SMTP clients, and
 
145
/*      require that clients use TLS encryption.
 
146
/* RESOURCE CONTROLS
 
147
/* .ad
 
148
/* .fi
 
149
/* .IP "\fBtlsproxy_watchdog_timeout (10s)\fR"
 
150
/*      How much time a \fBtlsproxy\fR(8) process may take to process local
 
151
/*      or remote I/O before it is terminated by a built-in watchdog timer.
 
152
/* MISCELLANEOUS CONTROLS
 
153
/* .ad
 
154
/* .fi
 
155
/* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
 
156
/*      The default location of the Postfix main.cf and master.cf
 
157
/*      configuration files.
 
158
/* .IP "\fBprocess_id (read-only)\fR"
 
159
/*      The process ID of a Postfix command or daemon process.
 
160
/* .IP "\fBprocess_name (read-only)\fR"
 
161
/*      The process name of a Postfix command or daemon process.
 
162
/* .IP "\fBsyslog_facility (mail)\fR"
 
163
/*      The syslog facility of Postfix logging.
 
164
/* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
 
165
/*      The mail system name that is prepended to the process name in syslog
 
166
/*      records, so that "smtpd" becomes, for example, "postfix/smtpd".
 
167
/* SEE ALSO
 
168
/*      postscreen(8), Postfix zombie blocker
 
169
/*      smtpd(8), Postfix SMTP server
 
170
/*      postconf(5), configuration parameters
 
171
/*      syslogd(5), system logging
 
172
/* LICENSE
 
173
/* .ad
 
174
/* .fi
 
175
/*      The Secure Mailer license must be distributed with this software.
 
176
/* HISTORY
 
177
/* .ad
 
178
/* .fi
 
179
/*      This service was introduced with Postfix version 2.8.
 
180
/* AUTHOR(S)
 
181
/*      Wietse Venema
 
182
/*      IBM T.J. Watson Research
 
183
/*      P.O. Box 704
 
184
/*      Yorktown Heights, NY 10598, USA
 
185
/*--*/
 
186
 
 
187
 /*
 
188
  * System library.
 
189
  */
 
190
#include <sys_defs.h>
 
191
 
 
192
 /*
 
193
  * Utility library.
 
194
  */
 
195
#include <msg.h>
 
196
#include <vstream.h>
 
197
#include <iostuff.h>
 
198
#include <nbbio.h>
 
199
#include <mymalloc.h>
 
200
 
 
201
 /*
 
202
  * Global library.
 
203
  */
 
204
#include <mail_proto.h>
 
205
#include <mail_params.h>
 
206
#include <mail_conf.h>
 
207
#include <mail_version.h>
 
208
 
 
209
 /*
 
210
  * Master library.
 
211
  */
 
212
#include <mail_server.h>
 
213
 
 
214
 /*
 
215
  * TLS library.
 
216
  */
 
217
#ifdef USE_TLS
 
218
#define TLS_INTERNAL                    /* XXX */
 
219
#include <tls.h>
 
220
#include <tls_proxy.h>
 
221
 
 
222
 /*
 
223
  * Application-specific.
 
224
  */
 
225
#include <tlsproxy.h>
 
226
 
 
227
 /*
 
228
  * Tunable parameters. We define our clones of the smtpd(8) parameters to
 
229
  * avoid any confusion about which parameters are used by this program.
 
230
  */
 
231
int     var_smtpd_tls_ccert_vd;
 
232
int     var_smtpd_tls_loglevel;
 
233
int     var_smtpd_tls_scache_timeout;
 
234
bool    var_smtpd_use_tls;
 
235
bool    var_smtpd_enforce_tls;
 
236
bool    var_smtpd_tls_ask_ccert;
 
237
bool    var_smtpd_tls_req_ccert;
 
238
bool    var_smtpd_tls_set_sessid;
 
239
char   *var_smtpd_relay_ccerts;
 
240
char   *var_smtpd_tls_cert_file;
 
241
char   *var_smtpd_tls_key_file;
 
242
char   *var_smtpd_tls_dcert_file;
 
243
char   *var_smtpd_tls_dkey_file;
 
244
char   *var_smtpd_tls_eccert_file;
 
245
char   *var_smtpd_tls_eckey_file;
 
246
char   *var_smtpd_tls_CAfile;
 
247
char   *var_smtpd_tls_CApath;
 
248
char   *var_smtpd_tls_ciph;
 
249
char   *var_smtpd_tls_mand_ciph;
 
250
char   *var_smtpd_tls_excl_ciph;
 
251
char   *var_smtpd_tls_mand_excl;
 
252
char   *var_smtpd_tls_proto;
 
253
char   *var_smtpd_tls_mand_proto;
 
254
char   *var_smtpd_tls_dh512_param_file;
 
255
char   *var_smtpd_tls_dh1024_param_file;
 
256
char   *var_smtpd_tls_eecdh;
 
257
char   *var_smtpd_tls_fpt_dgst;
 
258
char   *var_smtpd_tls_level;
 
259
 
 
260
int     var_tlsp_tls_ccert_vd;
 
261
int     var_tlsp_tls_loglevel;
 
262
int     var_tlsp_tls_scache_timeout;
 
263
bool    var_tlsp_use_tls;
 
264
bool    var_tlsp_enforce_tls;
 
265
bool    var_tlsp_tls_ask_ccert;
 
266
bool    var_tlsp_tls_req_ccert;
 
267
bool    var_tlsp_tls_set_sessid;
 
268
char   *var_tlsp_tls_cert_file;
 
269
char   *var_tlsp_tls_key_file;
 
270
char   *var_tlsp_tls_dcert_file;
 
271
char   *var_tlsp_tls_dkey_file;
 
272
char   *var_tlsp_tls_eccert_file;
 
273
char   *var_tlsp_tls_eckey_file;
 
274
char   *var_tlsp_tls_CAfile;
 
275
char   *var_tlsp_tls_CApath;
 
276
char   *var_tlsp_tls_ciph;
 
277
char   *var_tlsp_tls_mand_ciph;
 
278
char   *var_tlsp_tls_excl_ciph;
 
279
char   *var_tlsp_tls_mand_excl;
 
280
char   *var_tlsp_tls_proto;
 
281
char   *var_tlsp_tls_mand_proto;
 
282
char   *var_tlsp_tls_dh512_param_file;
 
283
char   *var_tlsp_tls_dh1024_param_file;
 
284
char   *var_tlsp_tls_eecdh;
 
285
char   *var_tlsp_tls_fpt_dgst;
 
286
char   *var_tlsp_tls_level;
 
287
 
 
288
int     var_tlsp_watchdog;
 
289
 
 
290
 /*
 
291
  * TLS per-process status.
 
292
  */
 
293
static TLS_APPL_STATE *tlsp_server_ctx;
 
294
static int ask_client_cert;
 
295
 
 
296
 /*
 
297
  * SLMs.
 
298
  */
 
299
#define STR(x)  vstring_str(x)
 
300
 
 
301
 /*
 
302
  * This code looks simpler than expected. That is the result of a great deal
 
303
  * of effort, mainly in design and analysis.
 
304
  * 
 
305
  * By design, postscreen(8) is an event-driven server that must scale up to a
 
306
  * large number of clients. This means that postscreen(8) must avoid doing
 
307
  * CPU-intensive operations such as those in OpenSSL.
 
308
  * 
 
309
  * tlsproxy(8) runs the OpenSSL code on behalf of postscreen(8), translating
 
310
  * plaintext SMTP messages from postscreen(8) into SMTP-over-TLS messages to
 
311
  * the remote SMTP client, and vice versa. As long as postscreen(8) does not
 
312
  * receive email messages, the cost of doing TLS operations will be modest.
 
313
  * 
 
314
  * Like postscreen(8), one tlsproxy(8) process services multiple remote SMTP
 
315
  * clients. Unlike postscreen(8), there can be more than one tlsproxy(8)
 
316
  * process, although their number is meant to be much smaller than the
 
317
  * number of remote SMTP clients that talk TLS.
 
318
  * 
 
319
  * As with postscreen(8), all I/O must be event-driven: encrypted traffic
 
320
  * between tlsproxy(8) and remote SMTP clients, and plaintext traffic
 
321
  * between tlsproxy(8) and postscreen(8). Event-driven plaintext I/O is
 
322
  * straightforward enough that it could be abstracted away with the nbbio(3)
 
323
  * module.
 
324
  * 
 
325
  * The event-driven TLS I/O implementation is founded on on-line OpenSSL
 
326
  * documentation, supplemented by statements from OpenSSL developers on
 
327
  * public mailing lists. After some field experience with this code, we may
 
328
  * be able to factor it out as a library module, like nbbio(3), that can
 
329
  * become part of the TLS library.
 
330
  */
 
331
 
 
332
static void tlsp_ciphertext_event(int, char *);
 
333
 
 
334
#define TLSP_INIT_TIMEOUT       100
 
335
 
 
336
/* tlsp_drain - delayed exit after "postfix reload" */
 
337
 
 
338
static void tlsp_drain(char *unused_service, char **unused_argv)
 
339
{
 
340
    int     count;
 
341
 
 
342
    /*
 
343
     * After "postfix reload", complete work-in-progress in the background,
 
344
     * instead of dropping already-accepted connections on the floor.
 
345
     * 
 
346
     * All error retry counts shall be limited. Instead of blocking here, we
 
347
     * could retry failed fork() operations in the event call-back routines,
 
348
     * but we don't need perfection. The host system is severely overloaded
 
349
     * and service levels are already way down.
 
350
     */
 
351
    for (count = 0; /* see below */ ; count++) {
 
352
        if (count >= 5) {
 
353
            msg_fatal("fork: %m");
 
354
        } else if (event_server_drain() != 0) {
 
355
            msg_warn("fork: %m");
 
356
            sleep(1);
 
357
            continue;
 
358
        } else {
 
359
            return;
 
360
        }
 
361
    }
 
362
}
 
363
 
 
364
/* tlsp_eval_tls_error - translate TLS "error" result into action */
 
365
 
 
366
static int tlsp_eval_tls_error(TLSP_STATE *state, int err)
 
367
{
 
368
    int     ciphertext_fd = state->ciphertext_fd;
 
369
 
 
370
    /*
 
371
     * The ciphertext file descriptor is in non-blocking mode, meaning that
 
372
     * each SSL_accept/connect/read/write/shutdown request may return an
 
373
     * "error" indication that it needs to read or write more ciphertext. The
 
374
     * purpose of this routine is to translate those "error" indications into
 
375
     * the appropriate read/write/timeout event requests.
 
376
     */
 
377
    switch (err) {
 
378
 
 
379
        /*
 
380
         * No error from SSL_read and SSL_write means that the plaintext
 
381
         * output buffer is full and that the plaintext input buffer is
 
382
         * empty. Stop read/write events on the ciphertext stream. Keep the
 
383
         * timer alive as a safety mechanism for the case that the plaintext
 
384
         * pseudothreads get stuck.
 
385
         */
 
386
    case SSL_ERROR_NONE:
 
387
        if (state->ssl_last_err != SSL_ERROR_NONE) {
 
388
            event_disable_readwrite(ciphertext_fd);
 
389
            event_request_timer(tlsp_ciphertext_event, (char *) state,
 
390
                                state->timeout);
 
391
            state->ssl_last_err = SSL_ERROR_NONE;
 
392
        }
 
393
        return (0);
 
394
 
 
395
        /*
 
396
         * The TLS engine wants to write to the network. Turn on
 
397
         * write/timeout events on the ciphertext stream.
 
398
         */
 
399
    case SSL_ERROR_WANT_WRITE:
 
400
        if (state->ssl_last_err == SSL_ERROR_WANT_READ)
 
401
            event_disable_readwrite(ciphertext_fd);
 
402
        if (state->ssl_last_err != SSL_ERROR_WANT_WRITE) {
 
403
            event_enable_write(ciphertext_fd, tlsp_ciphertext_event,
 
404
                               (char *) state);
 
405
            state->ssl_last_err = SSL_ERROR_WANT_WRITE;
 
406
        }
 
407
        event_request_timer(tlsp_ciphertext_event, (char *) state,
 
408
                            state->timeout);
 
409
        return (0);
 
410
 
 
411
        /*
 
412
         * The TLS engine wants to read from the network. Turn on
 
413
         * read/timeout events on the ciphertext stream.
 
414
         */
 
415
    case SSL_ERROR_WANT_READ:
 
416
        if (state->ssl_last_err == SSL_ERROR_WANT_WRITE)
 
417
            event_disable_readwrite(ciphertext_fd);
 
418
        if (state->ssl_last_err != SSL_ERROR_WANT_READ) {
 
419
            event_enable_read(ciphertext_fd, tlsp_ciphertext_event,
 
420
                              (char *) state);
 
421
            state->ssl_last_err = SSL_ERROR_WANT_READ;
 
422
        }
 
423
        event_request_timer(tlsp_ciphertext_event, (char *) state,
 
424
                            state->timeout);
 
425
        return (0);
 
426
 
 
427
        /*
 
428
         * Some error. Self-destruct. This automagically cleans up all
 
429
         * pending read/write and timeout event requests, making state a
 
430
         * dangling pointer.
 
431
         */
 
432
    case SSL_ERROR_SSL:
 
433
        tls_print_errors();
 
434
        /* FALLTHROUGH */
 
435
    default:
 
436
        tlsp_state_free(state);
 
437
        return (-1);
 
438
    }
 
439
}
 
440
 
 
441
/* tlsp_strategy - decide what to read or write next. */
 
442
 
 
443
static void tlsp_strategy(TLSP_STATE *state)
 
444
{
 
445
    TLS_SESS_STATE *tls_context = state->tls_context;
 
446
    NBBIO  *plaintext_buf;
 
447
    int     ssl_stat;
 
448
    int     ssl_read_err;
 
449
    int     ssl_write_err;
 
450
    int     handshake_err;
 
451
 
 
452
    /*
 
453
     * Be sure to complete the TLS handshake before enabling plain-text I/O.
 
454
     * In case of an unrecoverable error, this automagically cleans up all
 
455
     * pending read/write and timeout event requests.
 
456
     */
 
457
    if (state->flags & TLSP_FLAG_DO_HANDSHAKE) {
 
458
        ssl_stat = SSL_accept(tls_context->con);
 
459
        if (ssl_stat != 1) {
 
460
            handshake_err = SSL_get_error(tls_context->con, ssl_stat);
 
461
            tlsp_eval_tls_error(state, handshake_err);
 
462
            /* At this point, state could be a dangling pointer. */
 
463
            return;
 
464
        }
 
465
        if ((state->tls_context = tls_server_post_accept(tls_context)) == 0) {
 
466
            tlsp_state_free(state);
 
467
            return;
 
468
        }
 
469
        if ((state->req_flags & TLS_PROXY_FLAG_SEND_CONTEXT) != 0
 
470
            && (attr_print(state->plaintext_stream, ATTR_FLAG_NONE,
 
471
                           ATTR_TYPE_FUNC, tls_proxy_context_print,
 
472
                           (char *) state->tls_context, ATTR_TYPE_END) != 0
 
473
                || vstream_fflush(state->plaintext_stream) != 0)) {
 
474
            msg_warn("cannot send TLS context: %m");
 
475
            tlsp_state_free(state);
 
476
            return;
 
477
        }
 
478
        state->flags &= ~TLSP_FLAG_DO_HANDSHAKE;
 
479
    }
 
480
 
 
481
    /*
 
482
     * Shutdown and self-destruct after NBBIO error. This automagically
 
483
     * cleans up all pending read/write and timeout event requests. Before
 
484
     * shutting down TLS, we stop all plain-text I/O events but keep the
 
485
     * NBBIO error flags.
 
486
     */
 
487
    plaintext_buf = state->plaintext_buf;
 
488
    if (NBBIO_ERROR_FLAGS(plaintext_buf)) {
 
489
        if (NBBIO_ACTIVE_FLAGS(plaintext_buf))
 
490
            nbbio_disable_readwrite(state->plaintext_buf);
 
491
        ssl_stat = SSL_shutdown(tls_context->con);
 
492
        /* XXX Wait for return value 1 if sessions are to be reused? */
 
493
        if (ssl_stat < 0) {
 
494
            handshake_err = SSL_get_error(tls_context->con, ssl_stat);
 
495
            tlsp_eval_tls_error(state, handshake_err);
 
496
            /* At this point, state could be a dangling pointer. */
 
497
            return;
 
498
        }
 
499
        tlsp_state_free(state);
 
500
        return;
 
501
    }
 
502
 
 
503
    /*
 
504
     * Try to move data from the plaintext input buffer to the TLS engine.
 
505
     * 
 
506
     * XXX We're supposed to repeat the exact same SSL_write() call arguments
 
507
     * after an SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE result. Rumor has
 
508
     * it that this is because each SSL_write() call reads from the buffer
 
509
     * incrementally, and returns > 0 only after the final byte is processed.
 
510
     * Rumor also has it that setting SSL_MODE_ENABLE_PARTIAL_WRITE and
 
511
     * SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER voids this requirement, and that
 
512
     * repeating the request with an increased request size is OK.
 
513
     * Unfortunately all this is not or poorly documented, and one has to
 
514
     * rely on statements from OpenSSL developers in public mailing archives.
 
515
     */
 
516
    ssl_write_err = SSL_ERROR_NONE;
 
517
    while (NBBIO_READ_PEND(plaintext_buf) > 0) {
 
518
        ssl_stat = SSL_write(tls_context->con, NBBIO_READ_BUF(plaintext_buf),
 
519
                             NBBIO_READ_PEND(plaintext_buf));
 
520
        ssl_write_err = SSL_get_error(tls_context->con, ssl_stat);
 
521
        if (ssl_write_err != SSL_ERROR_NONE)
 
522
            break;
 
523
        /* Allow the plaintext pseudothread to read more data. */
 
524
        NBBIO_READ_PEND(plaintext_buf) -= ssl_stat;
 
525
        if (NBBIO_READ_PEND(plaintext_buf) > 0)
 
526
            memmove(NBBIO_READ_BUF(plaintext_buf),
 
527
                    NBBIO_READ_BUF(plaintext_buf) + ssl_stat,
 
528
                    NBBIO_READ_PEND(plaintext_buf));
 
529
    }
 
530
 
 
531
    /*
 
532
     * Try to move data from the TLS engine to the plaintext output buffer.
 
533
     * Note: data may arrive as a side effect of calling SSL_write(),
 
534
     * therefore we call SSL_read() after calling SSL_write().
 
535
     * 
 
536
     * XXX We're supposed to repeat the exact same SSL_read() call arguments
 
537
     * after an SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE result. This
 
538
     * supposedly means that our plaintext writer must not memmove() the
 
539
     * plaintext output buffer until after the SSL_read() call succeeds. For
 
540
     * now I'll ignore this, because 1) SSL_read() is documented to return
 
541
     * the bytes available, instead of returning > 0 only after the entire
 
542
     * buffer is processed like SSL_write() does; and 2) there is no "read"
 
543
     * equivalent of the SSL_R_BAD_WRITE_RETRY, SSL_MODE_ENABLE_PARTIAL_WRITE
 
544
     * or SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER features.
 
545
     */
 
546
    ssl_read_err = SSL_ERROR_NONE;
 
547
    while (NBBIO_WRITE_PEND(state->plaintext_buf) < NBBIO_BUFSIZE(plaintext_buf)) {
 
548
        ssl_stat = SSL_read(tls_context->con,
 
549
                            NBBIO_WRITE_BUF(plaintext_buf)
 
550
                            + NBBIO_WRITE_PEND(state->plaintext_buf),
 
551
                            NBBIO_BUFSIZE(plaintext_buf)
 
552
                            - NBBIO_WRITE_PEND(state->plaintext_buf));
 
553
        ssl_read_err = SSL_get_error(tls_context->con, ssl_stat);
 
554
        if (ssl_read_err != SSL_ERROR_NONE)
 
555
            break;
 
556
        NBBIO_WRITE_PEND(plaintext_buf) += ssl_stat;
 
557
    }
 
558
 
 
559
    /*
 
560
     * Try to enable/disable ciphertext read/write events. If SSL_write() was
 
561
     * satisfied, see if SSL_read() wants to do some work. In case of an
 
562
     * unrecoverable error, this automagically destroys the session state
 
563
     * after cleaning up all pending read/write and timeout event requests.
 
564
     */
 
565
    if (tlsp_eval_tls_error(state, ssl_write_err != SSL_ERROR_NONE ?
 
566
                            ssl_write_err : ssl_read_err) < 0)
 
567
        return;
 
568
 
 
569
    /*
 
570
     * Try to enable/disable plaintext read/write events. Basically, if we
 
571
     * have nothing to write to the postscreen(8) server, see if there is
 
572
     * something to read. If the write buffer is empty and the read buffer is
 
573
     * full, suspend plaintext I/O until conditions change (but keep the
 
574
     * timer active, as a safety mechanism in case ciphertext I/O gets
 
575
     * stuck).
 
576
     * 
 
577
     * XXX In theory, if the client keeps writing fast enough then we would
 
578
     * never read from postscreen(8), and cause postscreen(8) to block. In
 
579
     * practice, postscreen(8) limits the number of client commands, and thus
 
580
     * postscreen(8)'s output will fit in a kernel buffer. This may not be
 
581
     * true in other scenarios where the tlsproxy(8) server could be used.
 
582
     */
 
583
    if (NBBIO_WRITE_PEND(plaintext_buf) > 0) {
 
584
        if (NBBIO_ACTIVE_FLAGS(plaintext_buf) & NBBIO_FLAG_READ)
 
585
            nbbio_disable_readwrite(plaintext_buf);
 
586
        if ((NBBIO_ACTIVE_FLAGS(plaintext_buf) & NBBIO_FLAG_WRITE) == 0)
 
587
            nbbio_enable_write(plaintext_buf, state->timeout);
 
588
    } else if (NBBIO_READ_PEND(plaintext_buf) < NBBIO_BUFSIZE(plaintext_buf)) {
 
589
        if (NBBIO_ACTIVE_FLAGS(plaintext_buf) & NBBIO_FLAG_WRITE)
 
590
            nbbio_disable_readwrite(plaintext_buf);
 
591
        if ((NBBIO_ACTIVE_FLAGS(plaintext_buf) & NBBIO_FLAG_READ) == 0)
 
592
            nbbio_enable_read(plaintext_buf, state->timeout);
 
593
    } else {
 
594
        if (NBBIO_ACTIVE_FLAGS(plaintext_buf))
 
595
            nbbio_slumber(plaintext_buf, state->timeout);
 
596
    }
 
597
}
 
598
 
 
599
/* tlsp_plaintext_event - plaintext was read/written */
 
600
 
 
601
static void tlsp_plaintext_event(int event, char *context)
 
602
{
 
603
    TLSP_STATE *state = (TLSP_STATE *) context;
 
604
 
 
605
    /*
 
606
     * Safety alert: the plaintext pseudothreads have "slumbered" for too
 
607
     * long (see code above). This means that the ciphertext pseudothreads
 
608
     * are stuck.
 
609
     */
 
610
    if ((NBBIO_ERROR_FLAGS(state->plaintext_buf) & NBBIO_FLAG_TIMEOUT) != 0
 
611
        && NBBIO_ACTIVE_FLAGS(state->plaintext_buf) == 0)
 
612
        msg_warn("deadlock on ciphertext stream for %s", state->remote_endpt);
 
613
 
 
614
    /*
 
615
     * This is easy, because the NBBIO layer has already done the event
 
616
     * decoding and plaintext I/O for us. All we need to do is decide if we
 
617
     * want to read or write more plaintext.
 
618
     */
 
619
    tlsp_strategy(state);
 
620
}
 
621
 
 
622
/* tlsp_ciphertext_event - ciphertext is ready to read/write */
 
623
 
 
624
static void tlsp_ciphertext_event(int event, char *context)
 
625
{
 
626
    TLSP_STATE *state = (TLSP_STATE *) context;
 
627
 
 
628
    /*
 
629
     * Without a TLS quivalent of the NBBIO layer, we must decode the events
 
630
     * ourselves and do the ciphertext I/O. Then, we can decide if we want to
 
631
     * read or write more ciphertext.
 
632
     */
 
633
    if (event == EVENT_READ || event == EVENT_WRITE) {
 
634
        tlsp_strategy(state);
 
635
    } else {
 
636
        if (event == EVENT_TIME && state->ssl_last_err == SSL_ERROR_NONE)
 
637
            msg_warn("deadlock on plaintext stream for %s",
 
638
                     state->remote_endpt);
 
639
        else
 
640
            msg_warn("ciphertext read/write %s for %s",
 
641
                     event == EVENT_TIME ? "timeout" : "error",
 
642
                     state->remote_endpt);
 
643
        tlsp_state_free(state);
 
644
    }
 
645
}
 
646
 
 
647
/* tlsp_start_tls - turn on TLS or force disconnect */
 
648
 
 
649
static void tlsp_start_tls(TLSP_STATE *state)
 
650
{
 
651
    TLS_SERVER_START_PROPS props;
 
652
    static char *cipher_grade;
 
653
    static VSTRING *cipher_exclusions;
 
654
 
 
655
    /*
 
656
     * The code in this routine is pasted literally from smtpd(8). I am not
 
657
     * going to sanitize this because doing so surely will break things in
 
658
     * unexpected ways.
 
659
     */
 
660
 
 
661
    /*
 
662
     * Perform the before-handshake portion of the per-session initalization.
 
663
     * Pass a null VSTREAM to indicate that this program, will do the
 
664
     * ciphertext I/O, not libtls.
 
665
     * 
 
666
     * The cipher grade and exclusions don't change between sessions. Compute
 
667
     * just once and cache.
 
668
     */
 
669
#define ADD_EXCLUDE(vstr, str) \
 
670
    do { \
 
671
        if (*(str)) \
 
672
            vstring_sprintf_append((vstr), "%s%s", \
 
673
                                   VSTRING_LEN(vstr) ? " " : "", (str)); \
 
674
    } while (0)
 
675
 
 
676
    if (cipher_grade == 0) {
 
677
        cipher_grade =
 
678
            var_tlsp_enforce_tls ? var_tlsp_tls_mand_ciph : var_tlsp_tls_ciph;
 
679
        cipher_exclusions = vstring_alloc(10);
 
680
        ADD_EXCLUDE(cipher_exclusions, var_tlsp_tls_excl_ciph);
 
681
        if (var_tlsp_enforce_tls)
 
682
            ADD_EXCLUDE(cipher_exclusions, var_tlsp_tls_mand_excl);
 
683
        if (ask_client_cert)
 
684
            ADD_EXCLUDE(cipher_exclusions, "aNULL");
 
685
    }
 
686
    state->tls_context =
 
687
        TLS_SERVER_START(&props,
 
688
                         ctx = tlsp_server_ctx,
 
689
                         stream = (VSTREAM *) 0,/* unused */
 
690
                         log_level = var_tlsp_tls_loglevel,
 
691
                         timeout = 0,           /* unused */
 
692
                         requirecert = (var_tlsp_tls_req_ccert
 
693
                                        && var_tlsp_enforce_tls),
 
694
                         serverid = state->service,
 
695
                         namaddr = state->remote_endpt,
 
696
                         cipher_grade = cipher_grade,
 
697
                         cipher_exclusions = STR(cipher_exclusions),
 
698
                         fpt_dgst = var_tlsp_tls_fpt_dgst);
 
699
 
 
700
    if (state->tls_context == 0) {
 
701
        tlsp_state_free(state);
 
702
        return;
 
703
    }
 
704
 
 
705
    /*
 
706
     * This program will do the ciphertext I/O, not libtls. In the future,
 
707
     * the above event-driven engine may be factored out as a libtls library
 
708
     * module.
 
709
     */
 
710
    if (SSL_set_fd(state->tls_context->con, state->ciphertext_fd) != 1) {
 
711
        msg_info("SSL_set_fd error to %s", state->remote_endpt);
 
712
        tls_print_errors();
 
713
        tlsp_state_free(state);
 
714
        return;
 
715
    }
 
716
 
 
717
    /*
 
718
     * XXX Do we care about TLS session rate limits? Good postscreen(8)
 
719
     * clients will occasionally require the tlsproxy to renew their
 
720
     * whitelist status, but bad clients hammering the server can suck up
 
721
     * lots of CPU cycles. Per-client concurrency limits in postscreen(8)
 
722
     * will divert only naive security "researchers".
 
723
     * 
 
724
     * XXX Do we care about certificate verification results? Not as long as
 
725
     * postscreen(8) doesn't actually receive email.
 
726
     */
 
727
}
 
728
 
 
729
/* tlsp_get_fd_event - receive final postscreen(8) hand-off information */
 
730
 
 
731
static void tlsp_get_fd_event(int event, char *context)
 
732
{
 
733
    const char *myname = "tlsp_get_fd_event";
 
734
    TLSP_STATE *state = (TLSP_STATE *) context;
 
735
    int     plaintext_fd = vstream_fileno(state->plaintext_stream);
 
736
 
 
737
    /*
 
738
     * At this point we still manually manage plaintext read/write/timeout
 
739
     * events. Disable I/O and timer events. Don't assume that the first
 
740
     * plaintext request will be a read.
 
741
     */
 
742
    event_disable_readwrite(plaintext_fd);
 
743
    if (event != EVENT_TIME)
 
744
        event_cancel_timer(tlsp_get_fd_event, (char *) state);
 
745
 
 
746
    /*
 
747
     * Initialize plaintext-related session state.  Once we have this behind
 
748
     * us, the TLSP_STATE destructor will automagically clean up requests for
 
749
     * read/write/timeout events, which makes error recovery easier.
 
750
     * 
 
751
     * Register the plaintext event handler for timer cleanup in the TLSP_STATE
 
752
     * destructor. Insert the NBBIO event-driven I/O layer between the
 
753
     * postscreen(8) server and the TLS engine.
 
754
     */
 
755
    if (event != EVENT_READ
 
756
        || (state->ciphertext_fd = LOCAL_RECV_FD(plaintext_fd)) < 0) {
 
757
        msg_warn("%s: receive SMTP client file descriptor: %m", myname);
 
758
        tlsp_state_free(state);
 
759
        return;
 
760
    }
 
761
    non_blocking(state->ciphertext_fd, NON_BLOCKING);
 
762
    state->ciphertext_timer = tlsp_ciphertext_event;
 
763
    state->plaintext_buf = nbbio_create(plaintext_fd,
 
764
                                        VSTREAM_BUFSIZE, "postscreen",
 
765
                                        tlsp_plaintext_event,
 
766
                                        (char *) state);
 
767
 
 
768
    /*
 
769
     * Perform the TLS layer before-handshake initialization. We perform the
 
770
     * remainder after the TLS handshake completes.
 
771
     */
 
772
    tlsp_start_tls(state);
 
773
 
 
774
    /*
 
775
     * Trigger the initial proxy server I/Os.
 
776
     */
 
777
    tlsp_strategy(state);
 
778
}
 
779
 
 
780
/* tlsp_get_request_event - receive initial postscreen(8) hand-off info */
 
781
 
 
782
static void tlsp_get_request_event(int event, char *context)
 
783
{
 
784
    const char *myname = "tlsp_get_request_event";
 
785
    TLSP_STATE *state = (TLSP_STATE *) context;
 
786
    VSTREAM *plaintext_stream = state->plaintext_stream;
 
787
    int     plaintext_fd = vstream_fileno(plaintext_stream);
 
788
    static VSTRING *remote_endpt;
 
789
    int     req_flags;
 
790
    int     timeout;
 
791
    int     ready;
 
792
 
 
793
    /*
 
794
     * One-time initialization.
 
795
     */
 
796
    if (remote_endpt == 0)
 
797
        remote_endpt = vstring_alloc(10);
 
798
 
 
799
    /*
 
800
     * At this point we still manually manage plaintext read/write/timeout
 
801
     * events. Turn off timer events. Below we disable read events on error,
 
802
     * and redefine read events on success.
 
803
     */
 
804
    if (event != EVENT_TIME)
 
805
        event_cancel_timer(tlsp_get_request_event, (char *) state);
 
806
 
 
807
    /*
 
808
     * We must send some data, after receiving the request attributes and
 
809
     * before receiving the remote file descriptor. We can't assume
 
810
     * UNIX-domain socket semantics here.
 
811
     */
 
812
    if (event != EVENT_READ
 
813
        || attr_scan(plaintext_stream, ATTR_FLAG_STRICT,
 
814
                     ATTR_TYPE_STR, MAIL_ATTR_REMOTE_ENDPT, remote_endpt,
 
815
                     ATTR_TYPE_INT, MAIL_ATTR_FLAGS, &req_flags,
 
816
                     ATTR_TYPE_INT, MAIL_ATTR_TIMEOUT, &timeout,
 
817
                     ATTR_TYPE_END) != 3) {
 
818
        msg_warn("%s: receive request attributes: %m", myname);
 
819
        event_disable_readwrite(plaintext_fd);
 
820
        tlsp_state_free(state);
 
821
        return;
 
822
    }
 
823
 
 
824
    /*
 
825
     * If the requested TLS engine is unavailable, hang up after making sure
 
826
     * that the plaintext peer has received our "sorry" indication.
 
827
     */
 
828
    ready = ((req_flags & TLS_PROXY_FLAG_ROLE_SERVER) != 0
 
829
             && tlsp_server_ctx != 0);
 
830
    if (attr_print(plaintext_stream, ATTR_FLAG_NONE,
 
831
                   ATTR_TYPE_INT, MAIL_ATTR_STATUS, ready,
 
832
                   ATTR_TYPE_END) != 0
 
833
        || vstream_fflush(plaintext_stream) != 0
 
834
        || ready == 0) {
 
835
        read_wait(plaintext_fd, TLSP_INIT_TIMEOUT);     /* XXX */
 
836
        event_disable_readwrite(plaintext_fd);
 
837
        tlsp_state_free(state);
 
838
        return;
 
839
    }
 
840
 
 
841
    /*
 
842
     * XXX We use the same fixed timeout throughout the entire session for
 
843
     * both plaintext and ciphertext communication. This timeout is just a
 
844
     * safety feature; the real timeout will be enforced by our plaintext
 
845
     * peer.
 
846
     */
 
847
    else {
 
848
        state->remote_endpt = mystrdup(STR(remote_endpt));
 
849
        msg_info("CONNECT %s %s",
 
850
                 (req_flags & TLS_PROXY_FLAG_ROLE_SERVER) ? "from" :
 
851
                 (req_flags & TLS_PROXY_FLAG_ROLE_CLIENT) ? "to" :
 
852
                 "(bogus_direction)", state->remote_endpt);
 
853
        state->req_flags = req_flags;
 
854
        state->timeout = timeout + 10;          /* XXX */
 
855
        event_enable_read(plaintext_fd, tlsp_get_fd_event, (char *) state);
 
856
        event_request_timer(tlsp_get_fd_event, (char *) state,
 
857
                            TLSP_INIT_TIMEOUT);
 
858
        return;
 
859
    }
 
860
}
 
861
 
 
862
/* tlsp_service - handle new client connection */
 
863
 
 
864
static void tlsp_service(VSTREAM *plaintext_stream,
 
865
                                 char *service,
 
866
                                 char **argv)
 
867
{
 
868
    TLSP_STATE *state;
 
869
    int     plaintext_fd = vstream_fileno(plaintext_stream);
 
870
 
 
871
    /*
 
872
     * Sanity check. This service takes no command-line arguments.
 
873
     */
 
874
    if (argv[0])
 
875
        msg_fatal("unexpected command-line argument: %s", argv[0]);
 
876
 
 
877
    /*
 
878
     * This program handles multiple connections, so it must not block. We
 
879
     * use event-driven code for all operations that introduce latency.
 
880
     * Except that attribute lists are sent/received synchronously, once the
 
881
     * socket is found to be ready for transmission.
 
882
     */
 
883
    non_blocking(plaintext_fd, NON_BLOCKING);
 
884
    vstream_control(plaintext_stream,
 
885
                    VSTREAM_CTL_PATH, "plaintext",
 
886
                    VSTREAM_CTL_TIMEOUT, 5,
 
887
                    VSTREAM_CTL_END);
 
888
 
 
889
    /*
 
890
     * Receive postscreen's remote SMTP client address/port and socket.
 
891
     */
 
892
    state = tlsp_state_create(service, plaintext_stream);
 
893
    event_enable_read(plaintext_fd, tlsp_get_request_event, (char *) state);
 
894
    event_request_timer(tlsp_get_request_event, (char *) state,
 
895
                        TLSP_INIT_TIMEOUT);
 
896
}
 
897
 
 
898
/* pre_jail_init - pre-jail initialization */
 
899
 
 
900
static void pre_jail_init(char *unused_name, char **unused_argv)
 
901
{
 
902
    TLS_SERVER_INIT_PROPS props;
 
903
    const char *cert_file;
 
904
    int     have_server_cert;
 
905
    int     no_server_cert_ok;
 
906
    int     require_server_cert;
 
907
 
 
908
    /*
 
909
     * The code in this routine is pasted literally from smtpd(8). I am not
 
910
     * going to sanitize this because doing so surely will break things in
 
911
     * unexpected ways.
 
912
     */
 
913
    if (*var_tlsp_tls_level) {
 
914
        switch (tls_level_lookup(var_tlsp_tls_level)) {
 
915
        default:
 
916
            msg_fatal("Invalid TLS level \"%s\"", var_tlsp_tls_level);
 
917
            /* NOTREACHED */
 
918
            break;
 
919
        case TLS_LEV_SECURE:
 
920
        case TLS_LEV_VERIFY:
 
921
        case TLS_LEV_FPRINT:
 
922
            msg_warn("%s: unsupported TLS level \"%s\", using \"encrypt\"",
 
923
                     VAR_TLSP_TLS_LEVEL, var_tlsp_tls_level);
 
924
            /* FALLTHROUGH */
 
925
        case TLS_LEV_ENCRYPT:
 
926
            var_tlsp_enforce_tls = var_tlsp_use_tls = 1;
 
927
            break;
 
928
        case TLS_LEV_MAY:
 
929
            var_tlsp_enforce_tls = 0;
 
930
            var_tlsp_use_tls = 1;
 
931
            break;
 
932
        case TLS_LEV_NONE:
 
933
            var_tlsp_enforce_tls = var_tlsp_use_tls = 0;
 
934
            break;
 
935
        }
 
936
    }
 
937
    var_tlsp_use_tls = var_tlsp_use_tls || var_tlsp_enforce_tls;
 
938
    if (!var_tlsp_use_tls) {
 
939
        msg_warn("TLS service is requested, but disabled with %s or %s",
 
940
                 VAR_TLSP_TLS_LEVEL, VAR_TLSP_USE_TLS);
 
941
        return;
 
942
    }
 
943
 
 
944
    /*
 
945
     * Load TLS keys before dropping privileges.
 
946
     * 
 
947
     * Can't use anonymous ciphers if we want client certificates. Must use
 
948
     * anonymous ciphers if we have no certificates.
 
949
     */
 
950
    ask_client_cert = require_server_cert =
 
951
        (var_tlsp_tls_ask_ccert
 
952
         || (var_tlsp_enforce_tls && var_tlsp_tls_req_ccert));
 
953
    if (strcasecmp(var_tlsp_tls_cert_file, "none") == 0) {
 
954
        no_server_cert_ok = 1;
 
955
        cert_file = "";
 
956
    } else {
 
957
        no_server_cert_ok = 0;
 
958
        cert_file = var_tlsp_tls_cert_file;
 
959
    }
 
960
    have_server_cert =
 
961
        (*cert_file || *var_tlsp_tls_dcert_file || *var_tlsp_tls_eccert_file);
 
962
 
 
963
    /* Some TLS configuration errors are not show stoppers. */
 
964
    if (!have_server_cert && require_server_cert)
 
965
        msg_warn("Need a server cert to request client certs");
 
966
    if (!var_tlsp_enforce_tls && var_tlsp_tls_req_ccert)
 
967
        msg_warn("Can't require client certs unless TLS is required");
 
968
    /* After a show-stopper error, log a warning. */
 
969
    if (have_server_cert || (no_server_cert_ok && !require_server_cert))
 
970
 
 
971
        /*
 
972
         * Large parameter lists are error-prone, so we emulate a language
 
973
         * feature that C does not have natively: named parameter lists.
 
974
         */
 
975
        tlsp_server_ctx =
 
976
            TLS_SERVER_INIT(&props,
 
977
                            log_level = var_tlsp_tls_loglevel,
 
978
                            verifydepth = var_tlsp_tls_ccert_vd,
 
979
                            cache_type = TLS_MGR_SCACHE_SMTPD,
 
980
                            scache_timeout = var_tlsp_tls_scache_timeout,
 
981
                            set_sessid = var_tlsp_tls_set_sessid,
 
982
                            cert_file = cert_file,
 
983
                            key_file = var_tlsp_tls_key_file,
 
984
                            dcert_file = var_tlsp_tls_dcert_file,
 
985
                            dkey_file = var_tlsp_tls_dkey_file,
 
986
                            eccert_file = var_tlsp_tls_eccert_file,
 
987
                            eckey_file = var_tlsp_tls_eckey_file,
 
988
                            CAfile = var_tlsp_tls_CAfile,
 
989
                            CApath = var_tlsp_tls_CApath,
 
990
                            dh1024_param_file
 
991
                            = var_tlsp_tls_dh1024_param_file,
 
992
                            dh512_param_file
 
993
                            = var_tlsp_tls_dh512_param_file,
 
994
                            eecdh_grade = var_tlsp_tls_eecdh,
 
995
                            protocols = var_tlsp_enforce_tls ?
 
996
                            var_tlsp_tls_mand_proto :
 
997
                            var_tlsp_tls_proto,
 
998
                            ask_ccert = ask_client_cert,
 
999
                            fpt_dgst = var_tlsp_tls_fpt_dgst);
 
1000
    else
 
1001
        msg_warn("No server certs available. TLS can't be enabled");
 
1002
 
 
1003
    /*
 
1004
     * To maintain sanity, allow partial SSL_write() operations, and allow
 
1005
     * SSL_write() buffer pointers to change after a WANT_READ or WANT_WRITE
 
1006
     * result. This is based on OpenSSL developers talking on a mailing list,
 
1007
     * but is not supported by documentation. If this code stops working then
 
1008
     * no-one can be held responsible.
 
1009
     */
 
1010
    if (tlsp_server_ctx)
 
1011
        SSL_CTX_set_mode(tlsp_server_ctx->ssl_ctx,
 
1012
                         SSL_MODE_ENABLE_PARTIAL_WRITE
 
1013
                         | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
 
1014
}
 
1015
 
 
1016
/* post_jail_init - post-jail initialization */
 
1017
 
 
1018
static void post_jail_init(char *unused_name, char **unused_argv)
 
1019
{
 
1020
     /* void */ ;
 
1021
}
 
1022
 
 
1023
MAIL_VERSION_STAMP_DECLARE;
 
1024
 
 
1025
/* main - the main program */
 
1026
 
 
1027
int     main(int argc, char **argv)
 
1028
{
 
1029
    static const CONFIG_INT_TABLE int_table[] = {
 
1030
        VAR_SMTPD_TLS_CCERT_VD, DEF_SMTPD_TLS_CCERT_VD, &var_smtpd_tls_ccert_vd, 0, 0,
 
1031
        VAR_SMTPD_TLS_LOGLEVEL, DEF_SMTPD_TLS_LOGLEVEL, &var_smtpd_tls_loglevel, 0, 0,
 
1032
        0,
 
1033
    };
 
1034
    static const CONFIG_NINT_TABLE nint_table[] = {
 
1035
        VAR_TLSP_TLS_CCERT_VD, DEF_TLSP_TLS_CCERT_VD, &var_tlsp_tls_ccert_vd, 0, 0,
 
1036
        VAR_TLSP_TLS_LOGLEVEL, DEF_TLSP_TLS_LOGLEVEL, &var_tlsp_tls_loglevel, 0, 0,
 
1037
        0,
 
1038
    };
 
1039
    static const CONFIG_TIME_TABLE time_table[] = {
 
1040
        VAR_SMTPD_TLS_SCACHTIME, DEF_SMTPD_TLS_SCACHTIME, &var_smtpd_tls_scache_timeout, 0, 0,
 
1041
        VAR_TLSP_WATCHDOG, DEF_TLSP_WATCHDOG, &var_tlsp_watchdog, 10, 0,
 
1042
        VAR_TLSP_TLS_SCACHTIME, DEF_TLSP_TLS_SCACHTIME, &var_tlsp_tls_scache_timeout, 0, 0,
 
1043
        0,
 
1044
    };
 
1045
    static const CONFIG_BOOL_TABLE bool_table[] = {
 
1046
        VAR_SMTPD_USE_TLS, DEF_SMTPD_USE_TLS, &var_smtpd_use_tls,
 
1047
        VAR_SMTPD_ENFORCE_TLS, DEF_SMTPD_ENFORCE_TLS, &var_smtpd_enforce_tls,
 
1048
        VAR_SMTPD_TLS_ACERT, DEF_SMTPD_TLS_ACERT, &var_smtpd_tls_ask_ccert,
 
1049
        VAR_SMTPD_TLS_RCERT, DEF_SMTPD_TLS_RCERT, &var_smtpd_tls_req_ccert,
 
1050
        VAR_SMTPD_TLS_SET_SESSID, DEF_SMTPD_TLS_SET_SESSID, &var_smtpd_tls_set_sessid,
 
1051
        0,
 
1052
    };
 
1053
    static const CONFIG_NBOOL_TABLE nbool_table[] = {
 
1054
        VAR_TLSP_USE_TLS, DEF_TLSP_USE_TLS, &var_tlsp_use_tls,
 
1055
        VAR_TLSP_ENFORCE_TLS, DEF_TLSP_ENFORCE_TLS, &var_tlsp_enforce_tls,
 
1056
        VAR_TLSP_TLS_ACERT, DEF_TLSP_TLS_ACERT, &var_tlsp_tls_ask_ccert,
 
1057
        VAR_TLSP_TLS_RCERT, DEF_TLSP_TLS_RCERT, &var_tlsp_tls_req_ccert,
 
1058
        VAR_TLSP_TLS_SET_SESSID, DEF_TLSP_TLS_SET_SESSID, &var_tlsp_tls_set_sessid,
 
1059
        0,
 
1060
    };
 
1061
    static const CONFIG_STR_TABLE str_table[] = {
 
1062
        VAR_SMTPD_TLS_CERT_FILE, DEF_SMTPD_TLS_CERT_FILE, &var_smtpd_tls_cert_file, 0, 0,
 
1063
        VAR_SMTPD_TLS_KEY_FILE, DEF_SMTPD_TLS_KEY_FILE, &var_smtpd_tls_key_file, 0, 0,
 
1064
        VAR_SMTPD_TLS_DCERT_FILE, DEF_SMTPD_TLS_DCERT_FILE, &var_smtpd_tls_dcert_file, 0, 0,
 
1065
        VAR_SMTPD_TLS_DKEY_FILE, DEF_SMTPD_TLS_DKEY_FILE, &var_smtpd_tls_dkey_file, 0, 0,
 
1066
        VAR_SMTPD_TLS_ECCERT_FILE, DEF_SMTPD_TLS_ECCERT_FILE, &var_smtpd_tls_eccert_file, 0, 0,
 
1067
        VAR_SMTPD_TLS_ECKEY_FILE, DEF_SMTPD_TLS_ECKEY_FILE, &var_smtpd_tls_eckey_file, 0, 0,
 
1068
        VAR_SMTPD_TLS_CA_FILE, DEF_SMTPD_TLS_CA_FILE, &var_smtpd_tls_CAfile, 0, 0,
 
1069
        VAR_SMTPD_TLS_CA_PATH, DEF_SMTPD_TLS_CA_PATH, &var_smtpd_tls_CApath, 0, 0,
 
1070
        VAR_SMTPD_TLS_CIPH, DEF_SMTPD_TLS_CIPH, &var_smtpd_tls_ciph, 1, 0,
 
1071
        VAR_SMTPD_TLS_MAND_CIPH, DEF_SMTPD_TLS_MAND_CIPH, &var_smtpd_tls_mand_ciph, 1, 0,
 
1072
        VAR_SMTPD_TLS_EXCL_CIPH, DEF_SMTPD_TLS_EXCL_CIPH, &var_smtpd_tls_excl_ciph, 0, 0,
 
1073
        VAR_SMTPD_TLS_MAND_EXCL, DEF_SMTPD_TLS_MAND_EXCL, &var_smtpd_tls_mand_excl, 0, 0,
 
1074
        VAR_SMTPD_TLS_PROTO, DEF_SMTPD_TLS_PROTO, &var_smtpd_tls_proto, 0, 0,
 
1075
        VAR_SMTPD_TLS_MAND_PROTO, DEF_SMTPD_TLS_MAND_PROTO, &var_smtpd_tls_mand_proto, 0, 0,
 
1076
        VAR_SMTPD_TLS_512_FILE, DEF_SMTPD_TLS_512_FILE, &var_smtpd_tls_dh512_param_file, 0, 0,
 
1077
        VAR_SMTPD_TLS_1024_FILE, DEF_SMTPD_TLS_1024_FILE, &var_smtpd_tls_dh1024_param_file, 0, 0,
 
1078
        VAR_SMTPD_TLS_EECDH, DEF_SMTPD_TLS_EECDH, &var_smtpd_tls_eecdh, 1, 0,
 
1079
        VAR_SMTPD_TLS_FPT_DGST, DEF_SMTPD_TLS_FPT_DGST, &var_smtpd_tls_fpt_dgst, 1, 0,
 
1080
        VAR_SMTPD_TLS_LEVEL, DEF_SMTPD_TLS_LEVEL, &var_smtpd_tls_level, 0, 0,
 
1081
        VAR_TLSP_TLS_CERT_FILE, DEF_TLSP_TLS_CERT_FILE, &var_tlsp_tls_cert_file, 0, 0,
 
1082
        VAR_TLSP_TLS_KEY_FILE, DEF_TLSP_TLS_KEY_FILE, &var_tlsp_tls_key_file, 0, 0,
 
1083
        VAR_TLSP_TLS_DCERT_FILE, DEF_TLSP_TLS_DCERT_FILE, &var_tlsp_tls_dcert_file, 0, 0,
 
1084
        VAR_TLSP_TLS_DKEY_FILE, DEF_TLSP_TLS_DKEY_FILE, &var_tlsp_tls_dkey_file, 0, 0,
 
1085
        VAR_TLSP_TLS_ECCERT_FILE, DEF_TLSP_TLS_ECCERT_FILE, &var_tlsp_tls_eccert_file, 0, 0,
 
1086
        VAR_TLSP_TLS_ECKEY_FILE, DEF_TLSP_TLS_ECKEY_FILE, &var_tlsp_tls_eckey_file, 0, 0,
 
1087
        VAR_TLSP_TLS_CA_FILE, DEF_TLSP_TLS_CA_FILE, &var_tlsp_tls_CAfile, 0, 0,
 
1088
        VAR_TLSP_TLS_CA_PATH, DEF_TLSP_TLS_CA_PATH, &var_tlsp_tls_CApath, 0, 0,
 
1089
        VAR_TLSP_TLS_CIPH, DEF_TLSP_TLS_CIPH, &var_tlsp_tls_ciph, 1, 0,
 
1090
        VAR_TLSP_TLS_MAND_CIPH, DEF_TLSP_TLS_MAND_CIPH, &var_tlsp_tls_mand_ciph, 1, 0,
 
1091
        VAR_TLSP_TLS_EXCL_CIPH, DEF_TLSP_TLS_EXCL_CIPH, &var_tlsp_tls_excl_ciph, 0, 0,
 
1092
        VAR_TLSP_TLS_MAND_EXCL, DEF_TLSP_TLS_MAND_EXCL, &var_tlsp_tls_mand_excl, 0, 0,
 
1093
        VAR_TLSP_TLS_PROTO, DEF_TLSP_TLS_PROTO, &var_tlsp_tls_proto, 0, 0,
 
1094
        VAR_TLSP_TLS_MAND_PROTO, DEF_TLSP_TLS_MAND_PROTO, &var_tlsp_tls_mand_proto, 0, 0,
 
1095
        VAR_TLSP_TLS_512_FILE, DEF_TLSP_TLS_512_FILE, &var_tlsp_tls_dh512_param_file, 0, 0,
 
1096
        VAR_TLSP_TLS_1024_FILE, DEF_TLSP_TLS_1024_FILE, &var_tlsp_tls_dh1024_param_file, 0, 0,
 
1097
        VAR_TLSP_TLS_EECDH, DEF_TLSP_TLS_EECDH, &var_tlsp_tls_eecdh, 1, 0,
 
1098
        VAR_TLSP_TLS_FPT_DGST, DEF_TLSP_TLS_FPT_DGST, &var_tlsp_tls_fpt_dgst, 1, 0,
 
1099
        VAR_TLSP_TLS_LEVEL, DEF_TLSP_TLS_LEVEL, &var_tlsp_tls_level, 0, 0,
 
1100
        0,
 
1101
    };
 
1102
 
 
1103
    /*
 
1104
     * Fingerprint executables and core dumps.
 
1105
     */
 
1106
    MAIL_VERSION_STAMP_ALLOCATE;
 
1107
 
 
1108
    /*
 
1109
     * Pass control to the single-threaded service skeleton.
 
1110
     */
 
1111
    event_server_main(argc, argv, tlsp_service,
 
1112
                      MAIL_SERVER_INT_TABLE, int_table,
 
1113
                      MAIL_SERVER_NINT_TABLE, nint_table,
 
1114
                      MAIL_SERVER_STR_TABLE, str_table,
 
1115
                      MAIL_SERVER_BOOL_TABLE, bool_table,
 
1116
                      MAIL_SERVER_NBOOL_TABLE, nbool_table,
 
1117
                      MAIL_SERVER_TIME_TABLE, time_table,
 
1118
                      MAIL_SERVER_PRE_INIT, pre_jail_init,
 
1119
                      MAIL_SERVER_POST_INIT, post_jail_init,
 
1120
                      MAIL_SERVER_SLOW_EXIT, tlsp_drain,
 
1121
                      MAIL_SERVER_WATCHDOG, &var_tlsp_watchdog,
 
1122
                      0);
 
1123
}
 
1124
 
 
1125
#else
 
1126
 
 
1127
/* tlsp_service - respond to external trigger(s), non-TLS version */
 
1128
 
 
1129
static void tlsp_service(VSTREAM *stream, char *unused_service,
 
1130
                                 char **unused_argv)
 
1131
{
 
1132
    msg_info("TLS support is not compiled in -- exiting");
 
1133
    event_server_disconnect(stream);
 
1134
}
 
1135
 
 
1136
/* main - the main program */
 
1137
 
 
1138
int     main(int argc, char **argv)
 
1139
{
 
1140
 
 
1141
    /*
 
1142
     * We can't simply use msg_fatal() here, because the logging hasn't been
 
1143
     * initialized. The text would disappear because stderr is redirected to
 
1144
     * /dev/null.
 
1145
     * 
 
1146
     * We invoke event_server_main() to complete program initialization
 
1147
     * (including logging) and then invoke the tlsp_service() routine to log
 
1148
     * the message that says why this program will not run.
 
1149
     */
 
1150
    event_server_main(argc, argv, tlsp_service,
 
1151
                      0);
 
1152
}
 
1153
 
 
1154
#endif