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 two-way TLS proxy. It
10 /*	is used by the \fBpostscreen\fR(8) server to talk SMTP-over-TLS
11 /*	with remote SMTP clients that are not allowlisted (including
12 /*	clients whose allowlist status has expired), and by the
13 /*	\fBsmtp\fR(8) client to support TLS connection reuse, but it
14 /*	should also work for non-SMTP protocols.
15 /*
16 /*	Although one \fBtlsproxy\fR(8) process can serve multiple
17 /*	sessions at the same time, it is a good idea to allow the
18 /*	number of processes to increase with load, so that the
19 /*	service remains responsive.
20 /* PROTOCOL EXAMPLE
21 /* .ad
22 /* .fi
23 /*	The example below concerns \fBpostscreen\fR(8). However,
24 /*	the \fBtlsproxy\fR(8) server is agnostic of the application
25 /*	protocol, and the example is easily adapted to other
26 /*	applications.
27 /*
28 /*	After receiving a valid remote SMTP client STARTTLS command,
29 /*	the \fBpostscreen\fR(8) server sends the remote SMTP client
30 /*	endpoint string, the requested role (server), and the
31 /*	requested timeout to \fBtlsproxy\fR(8).  \fBpostscreen\fR(8)
32 /*	then receives a "TLS available" indication from \fBtlsproxy\fR(8).
33 /*	If the TLS service is available, \fBpostscreen\fR(8) sends
34 /*	the remote SMTP client file descriptor to \fBtlsproxy\fR(8),
35 /*	and sends the plaintext 220 greeting to the remote SMTP
36 /*	client.  This triggers TLS negotiations between the remote
37 /*	SMTP client and \fBtlsproxy\fR(8).  Upon completion of the
38 /*	TLS-level handshake, \fBtlsproxy\fR(8) translates between
39 /*	plaintext from/to \fBpostscreen\fR(8) and ciphertext to/from
40 /*	the remote SMTP client.
41 /* SECURITY
42 /* .ad
43 /* .fi
44 /*	The \fBtlsproxy\fR(8) server is moderately security-sensitive.
45 /*	It talks to untrusted clients on the network. The process
46 /*	can be run chrooted at fixed low privilege.
47 /* DIAGNOSTICS
48 /*	Problems and transactions are logged to \fBsyslogd\fR(8)
49 /*	or \fBpostlogd\fR(8).
50 /* CONFIGURATION PARAMETERS
51 /* .ad
52 /* .fi
53 /*	Changes to \fBmain.cf\fR are not picked up automatically,
54 /*	as \fBtlsproxy\fR(8) processes may run for a long time
55 /*	depending on mail server load.  Use the command "\fBpostfix
56 /*	reload\fR" to speed up a change.
57 /*
58 /*	The text below provides only a parameter summary. See
59 /*	\fBpostconf\fR(5) for more details including examples.
60 /* STARTTLS GLOBAL CONTROLS
61 /* .ad
62 /* .fi
63 /*	The following settings are global and therefore cannot be
64 /*	overruled by information specified in a \fBtlsproxy\fR(8)
65 /*	client request.
66 /* .IP "\fBtls_append_default_CA (no)\fR"
67 /*	Append the system-supplied default Certification Authority
68 /*	certificates to the ones specified with *_tls_CApath or *_tls_CAfile.
69 /* .IP "\fBtls_daemon_random_bytes (32)\fR"
70 /*	The number of pseudo-random bytes that an \fBsmtp\fR(8) or \fBsmtpd\fR(8)
71 /*	process requests from the \fBtlsmgr\fR(8) server in order to seed its
72 /*	internal pseudo random number generator (PRNG).
73 /* .IP "\fBtls_high_cipherlist (see 'postconf -d' output)\fR"
74 /*	The OpenSSL cipherlist for "high" grade ciphers.
75 /* .IP "\fBtls_medium_cipherlist (see 'postconf -d' output)\fR"
76 /*	The OpenSSL cipherlist for "medium" or higher grade ciphers.
77 /* .IP "\fBtls_low_cipherlist (see 'postconf -d' output)\fR"
78 /*	The OpenSSL cipherlist for "low" or higher grade ciphers.
79 /* .IP "\fBtls_export_cipherlist (see 'postconf -d' output)\fR"
80 /*	The OpenSSL cipherlist for "export" or higher grade ciphers.
81 /* .IP "\fBtls_null_cipherlist (eNULL:!aNULL)\fR"
82 /*	The OpenSSL cipherlist for "NULL" grade ciphers that provide
83 /*	authentication without encryption.
84 /* .IP "\fBtls_eecdh_strong_curve (prime256v1)\fR"
85 /*	The elliptic curve used by the Postfix SMTP server for sensibly
86 /*	strong
87 /*	ephemeral ECDH key exchange.
88 /* .IP "\fBtls_eecdh_ultra_curve (secp384r1)\fR"
89 /*	The elliptic curve used by the Postfix SMTP server for maximally
90 /*	strong
91 /*	ephemeral ECDH key exchange.
92 /* .IP "\fBtls_disable_workarounds (see 'postconf -d' output)\fR"
93 /*	List or bit-mask of OpenSSL bug work-arounds to disable.
94 /* .IP "\fBtls_preempt_cipherlist (no)\fR"
95 /*	With SSLv3 and later, use the Postfix SMTP server's cipher
96 /*	preference order instead of the remote client's cipher preference
97 /*	order.
98 /* .PP
99 /*	Available in Postfix version 2.9 and later:
100 /* .IP "\fBtls_legacy_public_key_fingerprints (no)\fR"
101 /*	A temporary migration aid for sites that use certificate
102 /*	\fIpublic-key\fR fingerprints with Postfix 2.9.0..2.9.5, which use
103 /*	an incorrect algorithm.
104 /* .PP
105 /*	Available in Postfix version 2.11-3.1:
106 /* .IP "\fBtls_dane_digest_agility (on)\fR"
107 /*	Configure RFC7671 DANE TLSA digest algorithm agility.
108 /* .IP "\fBtls_dane_trust_anchor_digest_enable (yes)\fR"
109 /*	Enable support for RFC 6698 (DANE TLSA) DNS records that contain
110 /*	digests of trust-anchors with certificate usage "2".
111 /* .PP
112 /*	Available in Postfix version 2.11 and later:
113 /* .IP "\fBtlsmgr_service_name (tlsmgr)\fR"
114 /*	The name of the \fBtlsmgr\fR(8) service entry in master.cf.
115 /* .PP
116 /*	Available in Postfix version 3.0 and later:
117 /* .IP "\fBtls_session_ticket_cipher (Postfix >= 3.0: aes-256-cbc, Postfix < 3.0: aes-128-cbc)\fR"
118 /*	Algorithm used to encrypt RFC5077 TLS session tickets.
119 /* .IP "\fBopenssl_path (openssl)\fR"
120 /*	The location of the OpenSSL command line program \fBopenssl\fR(1).
121 /* .PP
122 /*	Available in Postfix version 3.2 and later:
123 /* .IP "\fBtls_eecdh_auto_curves (see 'postconf -d' output)\fR"
124 /*	The prioritized list of elliptic curves supported by the Postfix
125 /*	SMTP client and server.
126 /* .PP
127 /*	Available in Postfix version 3.4 and later:
128 /* .IP "\fBtls_server_sni_maps (empty)\fR"
129 /*	Optional lookup tables that map names received from remote SMTP
130 /*	clients via the TLS Server Name Indication (SNI) extension to the
131 /*	appropriate keys and certificate chains.
132 /* .PP
133 /*	Available in Postfix 3.5, 3.4.6, 3.3.5, 3.2.10, 3.1.13 and later:
134 /* .IP "\fBtls_fast_shutdown_enable (yes)\fR"
135 /*	A workaround for implementations that hang Postfix while shutting
136 /*	down a TLS session, until Postfix times out.
137 /* STARTTLS SERVER CONTROLS
138 /* .ad
139 /* .fi
140 /*	These settings are clones of Postfix SMTP server settings.
141 /*	They allow \fBtlsproxy\fR(8) to load the same certificate
142 /*	and private key information as the Postfix SMTP server,
143 /*	before dropping privileges, so that the key files can be
144 /*	kept read-only for root. These settings can currently not
145 /*	be overruled by information in a \fBtlsproxy\fR(8) client
146 /*	request, but that limitation may be removed in a future
147 /*	version.
148 /* .IP "\fBtlsproxy_tls_CAfile ($smtpd_tls_CAfile)\fR"
149 /*	A file containing (PEM format) CA certificates of root CAs
150 /*	trusted to sign either remote SMTP client certificates or intermediate
151 /*	CA certificates.
152 /* .IP "\fBtlsproxy_tls_CApath ($smtpd_tls_CApath)\fR"
153 /*	A directory containing (PEM format) CA certificates of root CAs
154 /*	trusted to sign either remote SMTP client certificates or intermediate
155 /*	CA certificates.
156 /* .IP "\fBtlsproxy_tls_always_issue_session_ids ($smtpd_tls_always_issue_session_ids)\fR"
157 /*	Force the Postfix \fBtlsproxy\fR(8) server to issue a TLS session id,
158 /*	even when TLS session caching is turned off.
159 /* .IP "\fBtlsproxy_tls_ask_ccert ($smtpd_tls_ask_ccert)\fR"
160 /*	Ask a remote SMTP client for a client certificate.
161 /* .IP "\fBtlsproxy_tls_ccert_verifydepth ($smtpd_tls_ccert_verifydepth)\fR"
162 /*	The verification depth for remote SMTP client certificates.
163 /* .IP "\fBtlsproxy_tls_cert_file ($smtpd_tls_cert_file)\fR"
164 /*	File with the Postfix \fBtlsproxy\fR(8) server RSA certificate in PEM
165 /*	format.
166 /* .IP "\fBtlsproxy_tls_ciphers ($smtpd_tls_ciphers)\fR"
167 /*	The minimum TLS cipher grade that the Postfix \fBtlsproxy\fR(8) server
168 /*	will use with opportunistic TLS encryption.
169 /* .IP "\fBtlsproxy_tls_dcert_file ($smtpd_tls_dcert_file)\fR"
170 /*	File with the Postfix \fBtlsproxy\fR(8) server DSA certificate in PEM
171 /*	format.
172 /* .IP "\fBtlsproxy_tls_dh1024_param_file ($smtpd_tls_dh1024_param_file)\fR"
173 /*	File with DH parameters that the Postfix \fBtlsproxy\fR(8) server
174 /*	should use with non-export EDH ciphers.
175 /* .IP "\fBtlsproxy_tls_dh512_param_file ($smtpd_tls_dh512_param_file)\fR"
176 /*	File with DH parameters that the Postfix \fBtlsproxy\fR(8) server
177 /*	should use with export-grade EDH ciphers.
178 /* .IP "\fBtlsproxy_tls_dkey_file ($smtpd_tls_dkey_file)\fR"
179 /*	File with the Postfix \fBtlsproxy\fR(8) server DSA private key in PEM
180 /*	format.
181 /* .IP "\fBtlsproxy_tls_eccert_file ($smtpd_tls_eccert_file)\fR"
182 /*	File with the Postfix \fBtlsproxy\fR(8) server ECDSA certificate in PEM
183 /*	format.
184 /* .IP "\fBtlsproxy_tls_eckey_file ($smtpd_tls_eckey_file)\fR"
185 /*	File with the Postfix \fBtlsproxy\fR(8) server ECDSA private key in PEM
186 /*	format.
187 /* .IP "\fBtlsproxy_tls_eecdh_grade ($smtpd_tls_eecdh_grade)\fR"
188 /*	The Postfix \fBtlsproxy\fR(8) server security grade for ephemeral
189 /*	elliptic-curve Diffie-Hellman (EECDH) key exchange.
190 /* .IP "\fBtlsproxy_tls_exclude_ciphers ($smtpd_tls_exclude_ciphers)\fR"
191 /*	List of ciphers or cipher types to exclude from the \fBtlsproxy\fR(8)
192 /*	server cipher list at all TLS security levels.
193 /* .IP "\fBtlsproxy_tls_fingerprint_digest ($smtpd_tls_fingerprint_digest)\fR"
194 /*	The message digest algorithm to construct remote SMTP
195 /*	client-certificate
196 /*	fingerprints.
197 /* .IP "\fBtlsproxy_tls_key_file ($smtpd_tls_key_file)\fR"
198 /*	File with the Postfix \fBtlsproxy\fR(8) server RSA private key in PEM
199 /*	format.
200 /* .IP "\fBtlsproxy_tls_loglevel ($smtpd_tls_loglevel)\fR"
201 /*	Enable additional Postfix \fBtlsproxy\fR(8) server logging of TLS
202 /*	activity.
203 /* .IP "\fBtlsproxy_tls_mandatory_ciphers ($smtpd_tls_mandatory_ciphers)\fR"
204 /*	The minimum TLS cipher grade that the Postfix \fBtlsproxy\fR(8) server
205 /*	will use with mandatory TLS encryption.
206 /* .IP "\fBtlsproxy_tls_mandatory_exclude_ciphers ($smtpd_tls_mandatory_exclude_ciphers)\fR"
207 /*	Additional list of ciphers or cipher types to exclude from the
208 /*	\fBtlsproxy\fR(8) server cipher list at mandatory TLS security levels.
209 /* .IP "\fBtlsproxy_tls_mandatory_protocols ($smtpd_tls_mandatory_protocols)\fR"
210 /*	The SSL/TLS protocols accepted by the Postfix \fBtlsproxy\fR(8) server
211 /*	with mandatory TLS encryption.
212 /* .IP "\fBtlsproxy_tls_protocols ($smtpd_tls_protocols)\fR"
213 /*	List of TLS protocols that the Postfix \fBtlsproxy\fR(8) server will
214 /*	exclude or include with opportunistic TLS encryption.
215 /* .IP "\fBtlsproxy_tls_req_ccert ($smtpd_tls_req_ccert)\fR"
216 /*	With mandatory TLS encryption, require a trusted remote SMTP
217 /*	client certificate in order to allow TLS connections to proceed.
218 /* .IP "\fBtlsproxy_tls_security_level ($smtpd_tls_security_level)\fR"
219 /*	The SMTP TLS security level for the Postfix \fBtlsproxy\fR(8) server;
220 /*	when a non-empty value is specified, this overrides the obsolete
221 /*	parameters smtpd_use_tls and smtpd_enforce_tls.
222 /* .IP "\fBtlsproxy_tls_chain_files ($smtpd_tls_chain_files)\fR"
223 /*	Files with the Postfix \fBtlsproxy\fR(8) server keys and certificate
224 /*	chains in PEM format.
225 /* STARTTLS CLIENT CONTROLS
226 /* .ad
227 /* .fi
228 /*	These settings are clones of Postfix SMTP client settings.
229 /*	They allow \fBtlsproxy\fR(8) to load the same certificate
230 /*	and private key information as the Postfix SMTP client,
231 /*	before dropping privileges, so that the key files can be
232 /*	kept read-only for root. Some settings may be overruled by
233 /*	information in a \fBtlsproxy\fR(8) client request.
234 /* .PP
235 /*	Available in Postfix version 3.4 and later:
236 /* .IP "\fBtlsproxy_client_CAfile ($smtp_tls_CAfile)\fR"
237 /*	A file containing CA certificates of root CAs trusted to sign
238 /*	either remote TLS server certificates or intermediate CA certificates.
239 /* .IP "\fBtlsproxy_client_CApath ($smtp_tls_CApath)\fR"
240 /*	Directory with PEM format Certification Authority certificates
241 /*	that the Postfix \fBtlsproxy\fR(8) client uses to verify a remote TLS
242 /*	server certificate.
243 /* .IP "\fBtlsproxy_client_chain_files ($smtp_tls_chain_files)\fR"
244 /*	Files with the Postfix \fBtlsproxy\fR(8) client keys and certificate
245 /*	chains in PEM format.
246 /* .IP "\fBtlsproxy_client_cert_file ($smtp_tls_cert_file)\fR"
247 /*	File with the Postfix \fBtlsproxy\fR(8) client RSA certificate in PEM
248 /*	format.
249 /* .IP "\fBtlsproxy_client_key_file ($smtp_tls_key_file)\fR"
250 /*	File with the Postfix \fBtlsproxy\fR(8) client RSA private key in PEM
251 /*	format.
252 /* .IP "\fBtlsproxy_client_dcert_file ($smtp_tls_dcert_file)\fR"
253 /*	File with the Postfix \fBtlsproxy\fR(8) client DSA certificate in PEM
254 /*	format.
255 /* .IP "\fBtlsproxy_client_dkey_file ($smtp_tls_dkey_file)\fR"
256 /*	File with the Postfix \fBtlsproxy\fR(8) client DSA private key in PEM
257 /*	format.
258 /* .IP "\fBtlsproxy_client_eccert_file ($smtp_tls_eccert_file)\fR"
259 /*	File with the Postfix \fBtlsproxy\fR(8) client ECDSA certificate in PEM
260 /*	format.
261 /* .IP "\fBtlsproxy_client_eckey_file ($smtp_tls_eckey_file)\fR"
262 /*	File with the Postfix \fBtlsproxy\fR(8) client ECDSA private key in PEM
263 /*	format.
264 /* .IP "\fBtlsproxy_client_fingerprint_digest ($smtp_tls_fingerprint_digest)\fR"
265 /*	The message digest algorithm used to construct remote TLS server
266 /*	certificate fingerprints.
267 /* .IP "\fBtlsproxy_client_loglevel ($smtp_tls_loglevel)\fR"
268 /*	Enable additional Postfix \fBtlsproxy\fR(8) client logging of TLS
269 /*	activity.
270 /* .IP "\fBtlsproxy_client_loglevel_parameter (smtp_tls_loglevel)\fR"
271 /*	The name of the parameter that provides the tlsproxy_client_loglevel
272 /*	value.
273 /* .IP "\fBtlsproxy_client_scert_verifydepth ($smtp_tls_scert_verifydepth)\fR"
274 /*	The verification depth for remote TLS server certificates.
275 /* .IP "\fBtlsproxy_client_security_level ($smtp_tls_security_level)\fR"
276 /*	The default TLS security level for the Postfix \fBtlsproxy\fR(8)
277 /*	client.
278 /* .IP "\fBtlsproxy_client_policy_maps ($smtp_tls_policy_maps)\fR"
279 /*	Optional lookup tables with the Postfix \fBtlsproxy\fR(8) client TLS
280 /*	security policy by next-hop destination.
281 /* .IP "\fBtlsproxy_client_use_tls ($smtp_use_tls)\fR"
282 /*	Opportunistic mode: use TLS when a remote server announces TLS
283 /*	support.
284 /* .IP "\fBtlsproxy_client_enforce_tls ($smtp_enforce_tls)\fR"
285 /*	Enforcement mode: require that SMTP servers use TLS encryption.
286 /* .IP "\fBtlsproxy_client_per_site ($smtp_tls_per_site)\fR"
287 /*	Optional lookup tables with the Postfix \fBtlsproxy\fR(8) client TLS
288 /*	usage policy by next-hop destination and by remote TLS server
289 /*	hostname.
290 /* OBSOLETE STARTTLS SUPPORT CONTROLS
291 /* .ad
292 /* .fi
293 /*	These parameters are supported for compatibility with
294 /*	\fBsmtpd\fR(8) legacy parameters.
295 /* .IP "\fBtlsproxy_use_tls ($smtpd_use_tls)\fR"
296 /*	Opportunistic TLS: announce STARTTLS support to remote SMTP clients,
297 /*	but do not require that clients use TLS encryption.
298 /* .IP "\fBtlsproxy_enforce_tls ($smtpd_enforce_tls)\fR"
299 /*	Mandatory TLS: announce STARTTLS support to remote SMTP clients, and
300 /*	require that clients use TLS encryption.
301 /* RESOURCE CONTROLS
302 /* .ad
303 /* .fi
304 /* .IP "\fBtlsproxy_watchdog_timeout (10s)\fR"
305 /*	How much time a \fBtlsproxy\fR(8) process may take to process local
306 /*	or remote I/O before it is terminated by a built-in watchdog timer.
307 /* MISCELLANEOUS CONTROLS
308 /* .ad
309 /* .fi
310 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
311 /*	The default location of the Postfix main.cf and master.cf
312 /*	configuration files.
313 /* .IP "\fBprocess_id (read-only)\fR"
314 /*	The process ID of a Postfix command or daemon process.
315 /* .IP "\fBprocess_name (read-only)\fR"
316 /*	The process name of a Postfix command or daemon process.
317 /* .IP "\fBsyslog_facility (mail)\fR"
318 /*	The syslog facility of Postfix logging.
319 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
320 /*	A prefix that is prepended to the process name in syslog
321 /*	records, so that, for example, "smtpd" becomes "prefix/smtpd".
322 /* .PP
323 /*	Available in Postfix 3.3 and later:
324 /* .IP "\fBservice_name (read-only)\fR"
325 /*	The master.cf service name of a Postfix daemon process.
326 /* SEE ALSO
327 /*	postscreen(8), Postfix zombie blocker
328 /*	smtpd(8), Postfix SMTP server
329 /*	postconf(5), configuration parameters
330 /*	postlogd(8), Postfix logging
331 /*	syslogd(8), system logging
332 /* LICENSE
333 /* .ad
334 /* .fi
335 /*	The Secure Mailer license must be distributed with this software.
336 /* HISTORY
337 /* .ad
338 /* .fi
339 /*	This service was introduced with Postfix version 2.8.
340 /* AUTHOR(S)
341 /*	Wietse Venema
342 /*	IBM T.J. Watson Research
343 /*	P.O. Box 704
344 /*	Yorktown Heights, NY 10598, USA
345 /*
346 /*	Wietse Venema
347 /*	Google, Inc.
348 /*	111 8th Avenue
349 /*	New York, NY 10011, USA
350 /*--*/
351 
352  /*
353   * System library.
354   */
355 #include <sys_defs.h>
356 #include <errno.h>
357 
358 #ifdef STRCASECMP_IN_STRINGS_H
359 #include <strings.h>
360 #endif
361 
362  /*
363   * Utility library.
364   */
365 #include <msg.h>
366 #include <vstream.h>
367 #include <iostuff.h>
368 #include <nbbio.h>
369 #include <mymalloc.h>
370 #include <split_at.h>
371 
372  /*
373   * Global library.
374   */
375 #include <been_here.h>
376 #include <mail_proto.h>
377 #include <mail_params.h>
378 #include <mail_conf.h>
379 #include <mail_version.h>
380 
381  /*
382   * Master library.
383   */
384 #include <mail_server.h>
385 
386  /*
387   * TLS library.
388   */
389 #ifdef USE_TLS
390 #define TLS_INTERNAL			/* XXX */
391 #include <tls.h>
392 #include <tls_proxy.h>
393 
394  /*
395   * Application-specific.
396   */
397 #include <tlsproxy.h>
398 
399  /*
400   * Tunable parameters. We define our clones of the smtpd(8) parameters to
401   * avoid any confusion about which parameters are used by this program.
402   */
403 int     var_smtpd_tls_ccert_vd;
404 char   *var_smtpd_tls_loglevel;
405 bool    var_smtpd_use_tls;
406 bool    var_smtpd_enforce_tls;
407 bool    var_smtpd_tls_ask_ccert;
408 bool    var_smtpd_tls_req_ccert;
409 bool    var_smtpd_tls_set_sessid;
410 char   *var_smtpd_relay_ccerts;
411 char   *var_smtpd_tls_chain_files;
412 char   *var_smtpd_tls_cert_file;
413 char   *var_smtpd_tls_key_file;
414 char   *var_smtpd_tls_dcert_file;
415 char   *var_smtpd_tls_dkey_file;
416 char   *var_smtpd_tls_eccert_file;
417 char   *var_smtpd_tls_eckey_file;
418 char   *var_smtpd_tls_CAfile;
419 char   *var_smtpd_tls_CApath;
420 char   *var_smtpd_tls_ciph;
421 char   *var_smtpd_tls_mand_ciph;
422 char   *var_smtpd_tls_excl_ciph;
423 char   *var_smtpd_tls_mand_excl;
424 char   *var_smtpd_tls_proto;
425 char   *var_smtpd_tls_mand_proto;
426 char   *var_smtpd_tls_dh512_param_file;
427 char   *var_smtpd_tls_dh1024_param_file;
428 char   *var_smtpd_tls_eecdh;
429 char   *var_smtpd_tls_fpt_dgst;
430 char   *var_smtpd_tls_level;
431 
432 int     var_tlsp_tls_ccert_vd;
433 char   *var_tlsp_tls_loglevel;
434 bool    var_tlsp_use_tls;
435 bool    var_tlsp_enforce_tls;
436 bool    var_tlsp_tls_ask_ccert;
437 bool    var_tlsp_tls_req_ccert;
438 bool    var_tlsp_tls_set_sessid;
439 char   *var_tlsp_tls_chain_files;
440 char   *var_tlsp_tls_cert_file;
441 char   *var_tlsp_tls_key_file;
442 char   *var_tlsp_tls_dcert_file;
443 char   *var_tlsp_tls_dkey_file;
444 char   *var_tlsp_tls_eccert_file;
445 char   *var_tlsp_tls_eckey_file;
446 char   *var_tlsp_tls_CAfile;
447 char   *var_tlsp_tls_CApath;
448 char   *var_tlsp_tls_ciph;
449 char   *var_tlsp_tls_mand_ciph;
450 char   *var_tlsp_tls_excl_ciph;
451 char   *var_tlsp_tls_mand_excl;
452 char   *var_tlsp_tls_proto;
453 char   *var_tlsp_tls_mand_proto;
454 char   *var_tlsp_tls_dh512_param_file;
455 char   *var_tlsp_tls_dh1024_param_file;
456 char   *var_tlsp_tls_eecdh;
457 char   *var_tlsp_tls_fpt_dgst;
458 char   *var_tlsp_tls_level;
459 
460 int     var_tlsp_watchdog;
461 
462  /*
463   * Defaults for tlsp_clnt_*.
464   */
465 char   *var_smtp_tls_loglevel;
466 int     var_smtp_tls_scert_vd;
467 char   *var_smtp_tls_chain_files;
468 char   *var_smtp_tls_cert_file;
469 char   *var_smtp_tls_key_file;
470 char   *var_smtp_tls_dcert_file;
471 char   *var_smtp_tls_dkey_file;
472 char   *var_smtp_tls_eccert_file;
473 char   *var_smtp_tls_eckey_file;
474 char   *var_smtp_tls_CAfile;
475 char   *var_smtp_tls_CApath;
476 char   *var_smtp_tls_fpt_dgst;
477 char   *var_smtp_tls_level;
478 bool    var_smtp_use_tls;
479 bool    var_smtp_enforce_tls;
480 char   *var_smtp_tls_per_site;
481 char   *var_smtp_tls_policy;
482 
483 char   *var_tlsp_clnt_loglevel;
484 char   *var_tlsp_clnt_logparam;
485 int     var_tlsp_clnt_scert_vd;
486 char   *var_tlsp_clnt_chain_files;
487 char   *var_tlsp_clnt_cert_file;
488 char   *var_tlsp_clnt_key_file;
489 char   *var_tlsp_clnt_dcert_file;
490 char   *var_tlsp_clnt_dkey_file;
491 char   *var_tlsp_clnt_eccert_file;
492 char   *var_tlsp_clnt_eckey_file;
493 char   *var_tlsp_clnt_CAfile;
494 char   *var_tlsp_clnt_CApath;
495 char   *var_tlsp_clnt_fpt_dgst;
496 char   *var_tlsp_clnt_level;
497 bool    var_tlsp_clnt_use_tls;
498 bool    var_tlsp_clnt_enforce_tls;
499 char   *var_tlsp_clnt_per_site;
500 char   *var_tlsp_clnt_policy;
501 
502  /*
503   * TLS per-process status.
504   */
505 static TLS_APPL_STATE *tlsp_server_ctx;
506 static bool tlsp_pre_jail_done;
507 static int ask_client_cert;
508 static char *tlsp_pre_jail_client_param_key;	/* pre-jail global params */
509 static char *tlsp_pre_jail_client_init_key;	/* pre-jail init props */
510 
511  /*
512   * TLS per-client status.
513   */
514 static HTABLE *tlsp_client_app_cache;	/* per-client init props */
515 static BH_TABLE *tlsp_params_mismatch_filter;	/* per-client nag filter */
516 
517  /*
518   * Error handling: if a function detects an error, then that function is
519   * responsible for destroying TLSP_STATE. Exceptions to this principle are
520   * indicated in the code.
521   */
522 
523  /*
524   * Internal status API.
525   */
526 #define TLSP_STAT_OK	0
527 #define TLSP_STAT_ERR	(-1)
528 
529  /*
530   * SLMs.
531   */
532 #define STR(x)	vstring_str(x)
533 #define LEN(x)	VSTRING_LEN(x)
534 
535  /*
536   * The code that implements the TLS engine looks simpler than expected. That
537   * is the result of a great deal of effort, mainly in design and analysis.
538   *
539   * The initial use case was to provide TLS support for postscreen(8).
540   *
541   * By design, postscreen(8) is an event-driven server that must scale up to a
542   * large number of clients. This means that postscreen(8) must avoid doing
543   * CPU-intensive operations such as those in OpenSSL.
544   *
545   * tlsproxy(8) runs the OpenSSL code on behalf of postscreen(8), translating
546   * plaintext SMTP messages from postscreen(8) into SMTP-over-TLS messages to
547   * the remote SMTP client, and vice versa. As long as postscreen(8) does not
548   * receive email messages, the cost of doing TLS operations will be modest.
549   *
550   * Like postscreen(8), one tlsproxy(8) process services multiple remote SMTP
551   * clients. Unlike postscreen(8), there can be more than one tlsproxy(8)
552   * process, although their number is meant to be much smaller than the
553   * number of remote SMTP clients that talk TLS.
554   *
555   * As with postscreen(8), all I/O must be event-driven: encrypted traffic
556   * between tlsproxy(8) and remote SMTP clients, and plaintext traffic
557   * between tlsproxy(8) and postscreen(8). Event-driven plaintext I/O is
558   * straightforward enough that it could be abstracted away with the nbbio(3)
559   * module.
560   *
561   * The event-driven TLS I/O implementation is founded on on-line OpenSSL
562   * documentation, supplemented by statements from OpenSSL developers on
563   * public mailing lists. After some field experience with this code, we may
564   * be able to factor it out as a library module, like nbbio(3), that can
565   * become part of the TLS library.
566   *
567   * Later in the life cycle, tlsproxy(8) has also become an enabler for TLS
568   * connection reuse across different SMTP client processes.
569   */
570 
571 static void tlsp_ciphertext_event(int, void *);
572 
573 #define TLSP_INIT_TIMEOUT	100
574 
575 static void tlsp_plaintext_event(int event, void *context);
576 
577 /* tlsp_drain - delayed exit after "postfix reload" */
578 
tlsp_drain(char * unused_service,char ** unused_argv)579 static void tlsp_drain(char *unused_service, char **unused_argv)
580 {
581     int     count;
582 
583     /*
584      * After "postfix reload", complete work-in-progress in the background,
585      * instead of dropping already-accepted connections on the floor.
586      *
587      * All error retry counts shall be limited. Instead of blocking here, we
588      * could retry failed fork() operations in the event call-back routines,
589      * but we don't need perfection. The host system is severely overloaded
590      * and service levels are already way down.
591      */
592     for (count = 0; /* see below */ ; count++) {
593 	if (count >= 5) {
594 	    msg_fatal("fork: %m");
595 	} else if (event_server_drain() != 0) {
596 	    msg_warn("fork: %m");
597 	    sleep(1);
598 	    continue;
599 	} else {
600 	    return;
601 	}
602     }
603 }
604 
605 /* tlsp_eval_tls_error - translate TLS "error" result into action */
606 
tlsp_eval_tls_error(TLSP_STATE * state,int err)607 static int tlsp_eval_tls_error(TLSP_STATE *state, int err)
608 {
609     int     ciphertext_fd = state->ciphertext_fd;
610 
611     /*
612      * The ciphertext file descriptor is in non-blocking mode, meaning that
613      * each SSL_accept/connect/read/write/shutdown request may return an
614      * "error" indication that it needs to read or write more ciphertext. The
615      * purpose of this routine is to translate those "error" indications into
616      * the appropriate read/write/timeout event requests.
617      */
618     switch (err) {
619 
620 	/*
621 	 * No error means a successful SSL_accept/connect/shutdown request or
622 	 * sequence of SSL_read/write requests. Disable read/write events on
623 	 * the ciphertext stream. Keep the ciphertext stream timer alive as a
624 	 * safety mechanism for the case that the plaintext pseudothreads get
625 	 * stuck.
626 	 */
627     case SSL_ERROR_NONE:
628 	if (state->ssl_last_err != SSL_ERROR_NONE) {
629 	    event_disable_readwrite(ciphertext_fd);
630 	    event_request_timer(tlsp_ciphertext_event, (void *) state,
631 				state->timeout);
632 	    state->ssl_last_err = SSL_ERROR_NONE;
633 	}
634 	return (TLSP_STAT_OK);
635 
636 	/*
637 	 * The TLS engine wants to write to the network. Turn on
638 	 * write/timeout events on the ciphertext stream.
639 	 */
640     case SSL_ERROR_WANT_WRITE:
641 	if (state->ssl_last_err == SSL_ERROR_WANT_READ)
642 	    event_disable_readwrite(ciphertext_fd);
643 	if (state->ssl_last_err != SSL_ERROR_WANT_WRITE) {
644 	    event_enable_write(ciphertext_fd, tlsp_ciphertext_event,
645 			       (void *) state);
646 	    state->ssl_last_err = SSL_ERROR_WANT_WRITE;
647 	}
648 	event_request_timer(tlsp_ciphertext_event, (void *) state,
649 			    state->timeout);
650 	return (TLSP_STAT_OK);
651 
652 	/*
653 	 * The TLS engine wants to read from the network. Turn on
654 	 * read/timeout events on the ciphertext stream.
655 	 */
656     case SSL_ERROR_WANT_READ:
657 	if (state->ssl_last_err == SSL_ERROR_WANT_WRITE)
658 	    event_disable_readwrite(ciphertext_fd);
659 	if (state->ssl_last_err != SSL_ERROR_WANT_READ) {
660 	    event_enable_read(ciphertext_fd, tlsp_ciphertext_event,
661 			      (void *) state);
662 	    state->ssl_last_err = SSL_ERROR_WANT_READ;
663 	}
664 	event_request_timer(tlsp_ciphertext_event, (void *) state,
665 			    state->timeout);
666 	return (TLSP_STAT_OK);
667 
668 	/*
669 	 * Some error. Self-destruct. This automagically cleans up all
670 	 * pending read/write and timeout event requests, making state a
671 	 * dangling pointer.
672 	 */
673     case SSL_ERROR_SSL:
674 	tls_print_errors();
675 	/* FALLTHROUGH */
676     default:
677 
678 	/*
679 	 * Allow buffered-up plaintext output to trickle out. Permanently
680 	 * disable read/write activity on the ciphertext stream, so that this
681 	 * function will no longer be called. Keep the ciphertext stream
682 	 * timer alive as a safety mechanism for the case that the plaintext
683 	 * pseudothreads get stuck. Return into tlsp_strategy(), which will
684 	 * enable plaintext write events.
685 	 */
686 #define TLSP_CAN_TRICKLE_OUT_PLAINTEXT(buf) \
687 	((buf) && !NBBIO_ERROR_FLAGS(buf) && NBBIO_WRITE_PEND(buf))
688 
689 	if (TLSP_CAN_TRICKLE_OUT_PLAINTEXT(state->plaintext_buf)) {
690 	    event_disable_readwrite(ciphertext_fd);
691 	    event_request_timer(tlsp_ciphertext_event, (void *) state,
692 				state->timeout);
693 	    state->flags |= TLSP_FLAG_NO_MORE_CIPHERTEXT_IO;
694 	    return (TLSP_STAT_OK);
695 	}
696 	tlsp_state_free(state);
697 	return (TLSP_STAT_ERR);
698     }
699 }
700 
701 /* tlsp_post_handshake - post-handshake processing */
702 
tlsp_post_handshake(TLSP_STATE * state)703 static int tlsp_post_handshake(TLSP_STATE *state)
704 {
705 
706     /*
707      * Do not assume that tls_server_post_accept() and
708      * tls_client_post_connect() will always succeed.
709      */
710     if (state->is_server_role)
711 	state->tls_context = tls_server_post_accept(state->tls_context);
712     else
713 	state->tls_context = tls_client_post_connect(state->tls_context,
714 						 state->client_start_props);
715     if (state->tls_context == 0) {
716 	tlsp_state_free(state);
717 	return (TLSP_STAT_ERR);
718     }
719 
720     /*
721      * Report TLS handshake results to the tlsproxy client.
722      *
723      * Security: this sends internal data over the same local plaintext stream
724      * that will also be used for sending decrypted remote content from an
725      * arbitrary remote peer. For this reason we enable decrypted I/O only
726      * after reporting the TLS handshake results. The Postfix attribute
727      * protocol is robust enough that an attacker cannot append content.
728      */
729     if ((state->req_flags & TLS_PROXY_FLAG_SEND_CONTEXT) != 0
730 	&& (attr_print(state->plaintext_stream, ATTR_FLAG_NONE,
731 		       SEND_ATTR_FUNC(tls_proxy_context_print,
732 				      (void *) state->tls_context),
733 		       ATTR_TYPE_END) != 0
734 	    || vstream_fflush(state->plaintext_stream) != 0)) {
735 	msg_warn("cannot send TLS context: %m");
736 	tlsp_state_free(state);
737 	return (TLSP_STAT_ERR);
738     }
739 
740     /*
741      * Initialize plaintext-related session state. Once we have this behind
742      * us, the TLSP_STATE destructor will automagically clean up requests for
743      * plaintext read/write/timeout events, which makes error recovery
744      * easier.
745      */
746     state->plaintext_buf =
747 	nbbio_create(vstream_fileno(state->plaintext_stream),
748 		     VSTREAM_BUFSIZE, state->server_id,
749 		     tlsp_plaintext_event,
750 		     (void *) state);
751     return (TLSP_STAT_OK);
752 }
753 
754 /* tlsp_strategy - decide what to read or write next. */
755 
tlsp_strategy(TLSP_STATE * state)756 static void tlsp_strategy(TLSP_STATE *state)
757 {
758     TLS_SESS_STATE *tls_context = state->tls_context;
759     NBBIO  *plaintext_buf;
760     int     ssl_stat;
761     int     ssl_read_err;
762     int     ssl_write_err;
763     int     handshake_err;
764 
765     /*
766      * This function is called after every ciphertext or plaintext event, to
767      * schedule new ciphertext or plaintext I/O.
768      */
769 
770     /*
771      * Try to make an SSL I/O request. If this fails with SSL_ERROR_WANT_READ
772      * or SSL_ERROR_WANT_WRITE, enable ciphertext read or write events, and
773      * retry the SSL I/O request in a later tlsp_strategy() call.
774      */
775     if ((state->flags & TLSP_FLAG_NO_MORE_CIPHERTEXT_IO) == 0) {
776 
777 	/*
778 	 * Do not enable plain-text I/O before completing the TLS handshake.
779 	 * Otherwise the remote peer can prepend plaintext to the optional
780 	 * TLS_SESS_STATE object.
781 	 */
782 	if (state->flags & TLSP_FLAG_DO_HANDSHAKE) {
783 	    state->timeout = state->handshake_timeout;
784 	    ERR_clear_error();
785 	    if (state->is_server_role)
786 		ssl_stat = SSL_accept(tls_context->con);
787 	    else
788 		ssl_stat = SSL_connect(tls_context->con);
789 	    if (ssl_stat != 1) {
790 		handshake_err = SSL_get_error(tls_context->con, ssl_stat);
791 		tlsp_eval_tls_error(state, handshake_err);
792 		/* At this point, state could be a dangling pointer. */
793 		return;
794 	    }
795 	    state->flags &= ~TLSP_FLAG_DO_HANDSHAKE;
796 	    state->timeout = state->session_timeout;
797 	    if (tlsp_post_handshake(state) != TLSP_STAT_OK) {
798 		/* At this point, state is a dangling pointer. */
799 		return;
800 	    }
801 	}
802 
803 	/*
804 	 * Shutdown and self-destruct after NBBIO error. This automagically
805 	 * cleans up all pending read/write and timeout event requests.
806 	 * Before shutting down TLS, we stop all plain-text I/O events but
807 	 * keep the NBBIO error flags.
808 	 */
809 	plaintext_buf = state->plaintext_buf;
810 	if (NBBIO_ERROR_FLAGS(plaintext_buf)) {
811 	    if (NBBIO_ACTIVE_FLAGS(plaintext_buf))
812 		nbbio_disable_readwrite(state->plaintext_buf);
813 	    ERR_clear_error();
814 	    if (!SSL_in_init(tls_context->con)
815 		&& (ssl_stat = SSL_shutdown(tls_context->con)) < 0) {
816 		handshake_err = SSL_get_error(tls_context->con, ssl_stat);
817 		tlsp_eval_tls_error(state, handshake_err);
818 		/* At this point, state could be a dangling pointer. */
819 		return;
820 	    }
821 	    tlsp_state_free(state);
822 	    return;
823 	}
824 
825 	/*
826 	 * Try to move data from the plaintext input buffer to the TLS
827 	 * engine.
828 	 *
829 	 * XXX We're supposed to repeat the exact same SSL_write() call
830 	 * arguments after an SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
831 	 * result. Rumor has it that this is because each SSL_write() call
832 	 * reads from the buffer incrementally, and returns > 0 only after
833 	 * the final byte is processed. Rumor also has it that setting
834 	 * SSL_MODE_ENABLE_PARTIAL_WRITE and
835 	 * SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER voids this requirement, and
836 	 * that repeating the request with an increased request size is OK.
837 	 * Unfortunately all this is not or poorly documented, and one has to
838 	 * rely on statements from OpenSSL developers in public mailing
839 	 * archives.
840 	 */
841 	ssl_write_err = SSL_ERROR_NONE;
842 	while (NBBIO_READ_PEND(plaintext_buf) > 0) {
843 	    ERR_clear_error();
844 	    ssl_stat = SSL_write(tls_context->con, NBBIO_READ_BUF(plaintext_buf),
845 				 NBBIO_READ_PEND(plaintext_buf));
846 	    ssl_write_err = SSL_get_error(tls_context->con, ssl_stat);
847 	    if (ssl_write_err != SSL_ERROR_NONE)
848 		break;
849 	    /* Allow the plaintext pseudothread to read more data. */
850 	    NBBIO_READ_PEND(plaintext_buf) -= ssl_stat;
851 	    if (NBBIO_READ_PEND(plaintext_buf) > 0)
852 		memmove(NBBIO_READ_BUF(plaintext_buf),
853 			NBBIO_READ_BUF(plaintext_buf) + ssl_stat,
854 			NBBIO_READ_PEND(plaintext_buf));
855 	}
856 
857 	/*
858 	 * Try to move data from the TLS engine to the plaintext output
859 	 * buffer. Note: data may arrive as a side effect of calling
860 	 * SSL_write(), therefore we call SSL_read() after calling
861 	 * SSL_write().
862 	 *
863 	 * XXX We're supposed to repeat the exact same SSL_read() call arguments
864 	 * after an SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE result. This
865 	 * supposedly means that our plaintext writer must not memmove() the
866 	 * plaintext output buffer until after the SSL_read() call succeeds.
867 	 * For now I'll ignore this, because 1) SSL_read() is documented to
868 	 * return the bytes available, instead of returning > 0 only after
869 	 * the entire buffer is processed like SSL_write() does; and 2) there
870 	 * is no "read" equivalent of the SSL_R_BAD_WRITE_RETRY,
871 	 * SSL_MODE_ENABLE_PARTIAL_WRITE or
872 	 * SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER features.
873 	 */
874 	ssl_read_err = SSL_ERROR_NONE;
875 	while (NBBIO_WRITE_PEND(state->plaintext_buf) < NBBIO_BUFSIZE(plaintext_buf)) {
876 	    ERR_clear_error();
877 	    ssl_stat = SSL_read(tls_context->con,
878 				NBBIO_WRITE_BUF(plaintext_buf)
879 				+ NBBIO_WRITE_PEND(state->plaintext_buf),
880 				NBBIO_BUFSIZE(plaintext_buf)
881 				- NBBIO_WRITE_PEND(state->plaintext_buf));
882 	    ssl_read_err = SSL_get_error(tls_context->con, ssl_stat);
883 	    if (ssl_read_err != SSL_ERROR_NONE)
884 		break;
885 	    NBBIO_WRITE_PEND(plaintext_buf) += ssl_stat;
886 	}
887 
888 	/*
889 	 * Try to enable/disable ciphertext read/write events. If SSL_write()
890 	 * was satisfied, see if SSL_read() wants to do some work. In case of
891 	 * an unrecoverable error, this automagically destroys the session
892 	 * state after cleaning up all pending read/write and timeout event
893 	 * requests.
894 	 */
895 	if (tlsp_eval_tls_error(state, ssl_write_err != SSL_ERROR_NONE ?
896 				ssl_write_err : ssl_read_err) < 0)
897 	    /* At this point, state is a dangling pointer. */
898 	    return;
899     }
900 
901     /*
902      * Destroy state when the ciphertext I/O was permanently disabled and we
903      * can no longer trickle out plaintext.
904      */
905     else {
906 	plaintext_buf = state->plaintext_buf;
907 	if (!TLSP_CAN_TRICKLE_OUT_PLAINTEXT(plaintext_buf)) {
908 	    tlsp_state_free(state);
909 	    return;
910 	}
911     }
912 
913     /*
914      * Try to enable/disable plaintext read/write events. Basically, if we
915      * have nothing to write to the plaintext stream, see if there is
916      * something to read. If the write buffer is empty and the read buffer is
917      * full, suspend plaintext I/O until conditions change (but keep the
918      * timer active, as a safety mechanism in case ciphertext I/O gets
919      * stuck).
920      *
921      * XXX In theory, if the ciphertext peer keeps writing fast enough then we
922      * would never read from the plaintext stream and cause the latter to
923      * block. In practice, postscreen(8) limits the number of client
924      * commands, and thus postscreen(8)'s output will fit in a kernel buffer.
925      * A remote SMTP server is not supposed to flood the local SMTP client
926      * with massive replies; it it does, then the local SMTP client should
927      * deal with it.
928      */
929     if (NBBIO_WRITE_PEND(plaintext_buf) > 0) {
930 	if (NBBIO_ACTIVE_FLAGS(plaintext_buf) & NBBIO_FLAG_READ)
931 	    nbbio_disable_readwrite(plaintext_buf);
932 	nbbio_enable_write(plaintext_buf, state->timeout);
933     } else if (NBBIO_READ_PEND(plaintext_buf) < NBBIO_BUFSIZE(plaintext_buf)) {
934 	if (NBBIO_ACTIVE_FLAGS(plaintext_buf) & NBBIO_FLAG_WRITE)
935 	    nbbio_disable_readwrite(plaintext_buf);
936 	nbbio_enable_read(plaintext_buf, state->timeout);
937     } else {
938 	if (NBBIO_ACTIVE_FLAGS(plaintext_buf))
939 	    nbbio_slumber(plaintext_buf, state->timeout);
940     }
941 }
942 
943 /* tlsp_plaintext_event - plaintext was read/written */
944 
tlsp_plaintext_event(int event,void * context)945 static void tlsp_plaintext_event(int event, void *context)
946 {
947     TLSP_STATE *state = (TLSP_STATE *) context;
948 
949     /*
950      * Safety alert: the plaintext pseudothreads have "slumbered" for too
951      * long (see code above). This means that the ciphertext pseudothreads
952      * are stuck.
953      */
954     if ((NBBIO_ERROR_FLAGS(state->plaintext_buf) & NBBIO_FLAG_TIMEOUT) != 0
955 	&& NBBIO_ACTIVE_FLAGS(state->plaintext_buf) == 0)
956 	msg_warn("deadlock on ciphertext stream for %s", state->remote_endpt);
957 
958     /*
959      * This is easy, because the NBBIO layer has already done the event
960      * decoding and plaintext I/O for us. All we need to do is decide if we
961      * want to read or write more plaintext.
962      */
963     tlsp_strategy(state);
964     /* At this point, state could be a dangling pointer. */
965 }
966 
967 /* tlsp_ciphertext_event - ciphertext is ready to read/write */
968 
tlsp_ciphertext_event(int event,void * context)969 static void tlsp_ciphertext_event(int event, void *context)
970 {
971     TLSP_STATE *state = (TLSP_STATE *) context;
972 
973     /*
974      * Without a TLS quivalent of the NBBIO layer, we must decode the events
975      * ourselves and do the ciphertext I/O. Then, we can decide if we want to
976      * read or write more ciphertext.
977      */
978     if (event == EVENT_READ || event == EVENT_WRITE) {
979 	tlsp_strategy(state);
980 	/* At this point, state could be a dangling pointer. */
981     } else {
982 	if (event == EVENT_TIME && state->ssl_last_err == SSL_ERROR_NONE)
983 	    msg_warn("deadlock on plaintext stream for %s",
984 		     state->remote_endpt);
985 	else
986 	    msg_warn("ciphertext read/write %s for %s",
987 		     event == EVENT_TIME ? "timeout" : "error",
988 		     state->remote_endpt);
989 	tlsp_state_free(state);
990     }
991 }
992 
993 /* tlsp_client_start_pre_handshake - turn on TLS or force disconnect */
994 
tlsp_client_start_pre_handshake(TLSP_STATE * state)995 static int tlsp_client_start_pre_handshake(TLSP_STATE *state)
996 {
997     state->client_start_props->ctx = state->appl_state;
998     state->client_start_props->fd = state->ciphertext_fd;
999     state->tls_context = tls_client_start(state->client_start_props);
1000     if (state->tls_context != 0)
1001 	return (TLSP_STAT_OK);
1002 
1003     tlsp_state_free(state);
1004     return (TLSP_STAT_ERR);
1005 }
1006 
1007 /* tlsp_server_start_pre_handshake - turn on TLS or force disconnect */
1008 
tlsp_server_start_pre_handshake(TLSP_STATE * state)1009 static int tlsp_server_start_pre_handshake(TLSP_STATE *state)
1010 {
1011     TLS_SERVER_START_PROPS props;
1012     static char *cipher_grade;
1013     static VSTRING *cipher_exclusions;
1014 
1015     /*
1016      * The code in this routine is pasted literally from smtpd(8). I am not
1017      * going to sanitize this because doing so surely will break things in
1018      * unexpected ways.
1019      */
1020 
1021     /*
1022      * Perform the before-handshake portion of per-session initialization.
1023      * Pass a null VSTREAM to indicate that this program will do the
1024      * ciphertext I/O, not libtls.
1025      *
1026      * The cipher grade and exclusions don't change between sessions. Compute
1027      * just once and cache.
1028      */
1029 #define ADD_EXCLUDE(vstr, str) \
1030     do { \
1031 	if (*(str)) \
1032 	    vstring_sprintf_append((vstr), "%s%s", \
1033 				   VSTRING_LEN(vstr) ? " " : "", (str)); \
1034     } while (0)
1035 
1036     if (cipher_grade == 0) {
1037 	cipher_grade =
1038 	    var_tlsp_enforce_tls ? var_tlsp_tls_mand_ciph : var_tlsp_tls_ciph;
1039 	cipher_exclusions = vstring_alloc(10);
1040 	ADD_EXCLUDE(cipher_exclusions, var_tlsp_tls_excl_ciph);
1041 	if (var_tlsp_enforce_tls)
1042 	    ADD_EXCLUDE(cipher_exclusions, var_tlsp_tls_mand_excl);
1043 	if (ask_client_cert)
1044 	    ADD_EXCLUDE(cipher_exclusions, "aNULL");
1045     }
1046     state->tls_context =
1047 	TLS_SERVER_START(&props,
1048 			 ctx = tlsp_server_ctx,
1049 			 stream = (VSTREAM *) 0,/* unused */
1050 			 fd = state->ciphertext_fd,
1051 			 timeout = 0,		/* unused */
1052 			 requirecert = (var_tlsp_tls_req_ccert
1053 					&& var_tlsp_enforce_tls),
1054 			 serverid = state->server_id,
1055 			 namaddr = state->remote_endpt,
1056 			 cipher_grade = cipher_grade,
1057 			 cipher_exclusions = STR(cipher_exclusions),
1058 			 mdalg = var_tlsp_tls_fpt_dgst);
1059 
1060     if (state->tls_context == 0) {
1061 	tlsp_state_free(state);
1062 	return (TLSP_STAT_ERR);
1063     }
1064 
1065     /*
1066      * XXX Do we care about TLS session rate limits? Good postscreen(8)
1067      * clients will occasionally require the tlsproxy to renew their
1068      * allowlist status, but bad clients hammering the server can suck up
1069      * lots of CPU cycles. Per-client concurrency limits in postscreen(8)
1070      * will divert only naive security "researchers".
1071      */
1072     return (TLSP_STAT_OK);
1073 }
1074 
1075  /*
1076   * From here on down is low-level code that sets up the plumbing before
1077   * passing control to the TLS engine above.
1078   */
1079 
1080 /* tlsp_request_read_event - pre-handshake event boiler plate */
1081 
tlsp_request_read_event(int fd,EVENT_NOTIFY_FN handler,int timeout,void * context)1082 static void tlsp_request_read_event(int fd, EVENT_NOTIFY_FN handler,
1083 				            int timeout, void *context)
1084 {
1085     event_enable_read(fd, handler, context);
1086     event_request_timer(handler, context, timeout);
1087 }
1088 
1089 /* tlsp_accept_event - pre-handshake event boiler plate */
1090 
tlsp_accept_event(int event,EVENT_NOTIFY_FN handler,void * context)1091 static void tlsp_accept_event(int event, EVENT_NOTIFY_FN handler,
1092 			              void *context)
1093 {
1094     if (event != EVENT_TIME)
1095 	event_cancel_timer(handler, context);
1096     else
1097 	errno = ETIMEDOUT;
1098     /* tlsp_state_free() disables pre-handshake plaintext I/O events. */
1099 }
1100 
1101 /* tlsp_get_fd_event - receive final connection hand-off information */
1102 
tlsp_get_fd_event(int event,void * context)1103 static void tlsp_get_fd_event(int event, void *context)
1104 {
1105     const char *myname = "tlsp_get_fd_event";
1106     TLSP_STATE *state = (TLSP_STATE *) context;
1107     int     plaintext_fd = vstream_fileno(state->plaintext_stream);
1108     int     status;
1109 
1110     /*
1111      * At this point we still manually manage plaintext read/write/timeout
1112      * events. Disable I/O events on the plaintext stream until the TLS
1113      * handshake is completed. Every code path must either destroy state, or
1114      * request the next event, otherwise we have a file and memory leak.
1115      */
1116     tlsp_accept_event(event, tlsp_get_fd_event, (void *) state);
1117     event_disable_readwrite(plaintext_fd);
1118 
1119     if (event != EVENT_READ
1120 	|| (state->ciphertext_fd = LOCAL_RECV_FD(plaintext_fd)) < 0) {
1121 	msg_warn("%s: receive remote SMTP peer file descriptor: %m", myname);
1122 	tlsp_state_free(state);
1123 	return;
1124     }
1125 
1126     /*
1127      * This is a bit early, to ensure that timer events for this file handle
1128      * are guaranteed to be turned off by the TLSP_STATE destructor.
1129      */
1130     state->ciphertext_timer = tlsp_ciphertext_event;
1131     non_blocking(state->ciphertext_fd, NON_BLOCKING);
1132 
1133     /*
1134      * Perform the TLS layer before-handshake initialization. We perform the
1135      * remainder after the actual TLS handshake completes.
1136      */
1137     if (state->is_server_role)
1138 	status = tlsp_server_start_pre_handshake(state);
1139     else
1140 	status = tlsp_client_start_pre_handshake(state);
1141     if (status != TLSP_STAT_OK)
1142 	/* At this point, state is a dangling pointer. */
1143 	return;
1144 
1145     /*
1146      * Trigger the initial proxy server I/Os.
1147      */
1148     tlsp_strategy(state);
1149     /* At this point, state could be a dangling pointer. */
1150 }
1151 
1152 /* tlsp_config_diff - report server-client config differences */
1153 
tlsp_log_config_diff(const char * server_cfg,const char * client_cfg)1154 static void tlsp_log_config_diff(const char *server_cfg, const char *client_cfg)
1155 {
1156     VSTRING *diff_summary = vstring_alloc(100);
1157     char   *saved_server = mystrdup(server_cfg);
1158     char   *saved_client = mystrdup(client_cfg);
1159     char   *server_field;
1160     char   *client_field;
1161     char   *server_next;
1162     char   *client_next;
1163 
1164     /*
1165      * Not using argv_split(), because it would treat multiple consecutive
1166      * newline characters as one.
1167      */
1168     for (server_field = saved_server, client_field = saved_client;
1169 	 server_field && client_field;
1170 	 server_field = server_next, client_field = client_next) {
1171 	server_next = split_at(server_field, '\n');
1172 	client_next = split_at(client_field, '\n');
1173 	if (strcmp(server_field, client_field) != 0) {
1174 	    if (LEN(diff_summary) > 0)
1175 		vstring_sprintf_append(diff_summary, "; ");
1176 	    vstring_sprintf_append(diff_summary,
1177 				   "(server) '%s' != (client) '%s'",
1178 				   server_field, client_field);
1179 	}
1180     }
1181     msg_warn("%s", STR(diff_summary));
1182 
1183     vstring_free(diff_summary);
1184     myfree(saved_client);
1185     myfree(saved_server);
1186 }
1187 
1188 /* tlsp_client_init - initialize a TLS client engine */
1189 
tlsp_client_init(TLS_CLIENT_PARAMS * tls_params,TLS_CLIENT_INIT_PROPS * init_props)1190 static TLS_APPL_STATE *tlsp_client_init(TLS_CLIENT_PARAMS *tls_params,
1191 				          TLS_CLIENT_INIT_PROPS *init_props)
1192 {
1193     TLS_APPL_STATE *appl_state;
1194     VSTRING *param_buf;
1195     char   *param_key;
1196     VSTRING *init_buf;
1197     char   *init_key;
1198     int     log_hints = 0;
1199 
1200     /*
1201      * Use one TLS_APPL_STATE object for all requests that specify the same
1202      * TLS_CLIENT_INIT_PROPS. Each TLS_APPL_STATE owns an SSL_CTX, which is
1203      * expensive to create. Bug: TLS_CLIENT_PARAMS are not used when creating
1204      * a TLS_APPL_STATE instance.
1205      *
1206      * First, compute the TLS_APPL_STATE cache lookup key. Save a copy of the
1207      * pre-jail request TLS_CLIENT_PARAMS and TLSPROXY_CLIENT_INIT_PROPS
1208      * settings, so that we can detect post-jail requests that do not match.
1209      */
1210     param_buf = vstring_alloc(100);
1211     param_key = tls_proxy_client_param_serialize(attr_print_plain, param_buf,
1212 						 tls_params);
1213     init_buf = vstring_alloc(100);
1214     init_key = tls_proxy_client_init_serialize(attr_print_plain, init_buf,
1215 					       init_props);
1216     if (tlsp_pre_jail_done == 0) {
1217 	if (tlsp_pre_jail_client_param_key == 0
1218 	    || tlsp_pre_jail_client_init_key == 0) {
1219 	    tlsp_pre_jail_client_param_key = mystrdup(param_key);
1220 	    tlsp_pre_jail_client_init_key = mystrdup(init_key);
1221 	} else if (strcmp(tlsp_pre_jail_client_param_key, param_key) != 0
1222 		   || strcmp(tlsp_pre_jail_client_init_key, init_key) != 0) {
1223 	    msg_panic("tlsp_client_init: too many pre-jail calls");
1224 	}
1225     }
1226 
1227     /*
1228      * Log a warning if a post-jail request uses unexpected TLS_CLIENT_PARAMS
1229      * settings. Bug: TLS_CLIENT_PARAMS settings are not used when creating a
1230      * TLS_APPL_STATE instance; this makes a mismatch of TLS_CLIENT_PARAMS
1231      * settings problematic.
1232      */
1233     if (tlsp_pre_jail_done
1234 	&& !been_here_fixed(tlsp_params_mismatch_filter, param_key)
1235 	&& strcmp(tlsp_pre_jail_client_param_key, param_key) != 0) {
1236 	msg_warn("request from tlsproxy client with unexpected settings");
1237 	tlsp_log_config_diff(tlsp_pre_jail_client_param_key, param_key);
1238 	log_hints = 1;
1239     }
1240 
1241     /*
1242      * Look up the cached TLS_APPL_STATE for this tls_client_init request.
1243      */
1244     if ((appl_state = (TLS_APPL_STATE *)
1245 	 htable_find(tlsp_client_app_cache, init_key)) == 0) {
1246 
1247 	/*
1248 	 * Before creating a TLS_APPL_STATE instance, log a warning if a
1249 	 * post-jail request differs from the saved pre-jail request AND the
1250 	 * post-jail request specifies file/directory pathname arguments.
1251 	 * Unexpected requests containing pathnames are problematic after
1252 	 * chroot (pathname resolution) and after dropping privileges (key
1253 	 * files must be root read-only). Unexpected requests are not a
1254 	 * problem as long as they contain no pathnames (for example a
1255 	 * tls_loglevel change).
1256 	 *
1257 	 * We could eliminate some of this complication by adding code that
1258 	 * opens a cert/key lookup table at pre-jail time, and by reading
1259 	 * cert/key info on-the-fly from that table. But then all requests
1260 	 * would still have to specify the same table.
1261 	 */
1262 #define NOT_EMPTY(x) ((x) && *(x))
1263 
1264 	if (tlsp_pre_jail_done
1265 	    && strcmp(tlsp_pre_jail_client_init_key, init_key) != 0
1266 	    && (NOT_EMPTY(init_props->chain_files)
1267 		|| NOT_EMPTY(init_props->cert_file)
1268 		|| NOT_EMPTY(init_props->key_file)
1269 		|| NOT_EMPTY(init_props->dcert_file)
1270 		|| NOT_EMPTY(init_props->dkey_file)
1271 		|| NOT_EMPTY(init_props->eccert_file)
1272 		|| NOT_EMPTY(init_props->eckey_file)
1273 		|| NOT_EMPTY(init_props->CAfile)
1274 		|| NOT_EMPTY(init_props->CApath))) {
1275 	    msg_warn("request from tlsproxy client with unexpected settings");
1276 	    tlsp_log_config_diff(tlsp_pre_jail_client_init_key, init_key);
1277 	    log_hints = 1;
1278 	}
1279     }
1280     if (log_hints)
1281 	msg_warn("to avoid this warning, 1) identify the tlsproxy "
1282 		 "client that is making this request, 2) configure "
1283 		 "a custom tlsproxy service with settings that "
1284 		 "match that tlsproxy client, and 3) configure "
1285 		 "that tlsproxy client with a tlsproxy_service_name "
1286 		 "setting that resolves to that custom tlsproxy "
1287 		 "service");
1288 
1289     /*
1290      * TLS_APPL_STATE creation may fail when a post-jail request specifies
1291      * unexpected cert/key information, but that is OK because we already
1292      * logged a warning with configuration suggestions.
1293      */
1294     if (appl_state == 0
1295 	&& (appl_state = tls_client_init(init_props)) != 0) {
1296 	(void) htable_enter(tlsp_client_app_cache, init_key,
1297 			    (void *) appl_state);
1298 
1299 	/*
1300 	 * To maintain sanity, allow partial SSL_write() operations, and
1301 	 * allow SSL_write() buffer pointers to change after a WANT_READ or
1302 	 * WANT_WRITE result. This is based on OpenSSL developers talking on
1303 	 * a mailing list, but is not supported by documentation. If this
1304 	 * code stops working then no-one can be held responsible.
1305 	 */
1306 	SSL_CTX_set_mode(appl_state->ssl_ctx,
1307 			 SSL_MODE_ENABLE_PARTIAL_WRITE
1308 			 | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1309     }
1310     vstring_free(init_buf);
1311     vstring_free(param_buf);
1312     return (appl_state);
1313 }
1314 
1315 /* tlsp_close_event - pre-handshake plaintext-client close event */
1316 
tlsp_close_event(int event,void * context)1317 static void tlsp_close_event(int event, void *context)
1318 {
1319     TLSP_STATE *state = (TLSP_STATE *) context;
1320 
1321     tlsp_accept_event(event, tlsp_close_event, (void *) state);
1322     tlsp_state_free(state);
1323 }
1324 
1325 /* tlsp_get_request_event - receive initial hand-off info */
1326 
tlsp_get_request_event(int event,void * context)1327 static void tlsp_get_request_event(int event, void *context)
1328 {
1329     const char *myname = "tlsp_get_request_event";
1330     TLSP_STATE *state = (TLSP_STATE *) context;
1331     VSTREAM *plaintext_stream = state->plaintext_stream;
1332     int     plaintext_fd = vstream_fileno(plaintext_stream);
1333     static VSTRING *remote_endpt;
1334     static VSTRING *server_id;
1335     int     req_flags;
1336     int     handshake_timeout;
1337     int     session_timeout;
1338     int     ready = 0;
1339 
1340     /*
1341      * At this point we still manually manage plaintext read/write/timeout
1342      * events. Every code path must either destroy state or request the next
1343      * event, otherwise this pseudo-thread is idle until the client goes
1344      * away.
1345      */
1346     tlsp_accept_event(event, tlsp_get_request_event, (void *) state);
1347 
1348     /*
1349      * One-time initialization.
1350      */
1351     if (remote_endpt == 0) {
1352 	remote_endpt = vstring_alloc(10);
1353 	server_id = vstring_alloc(10);
1354     }
1355 
1356     /*
1357      * Receive the initial request attributes. Receive the remainder after we
1358      * figure out what role we are expected to play.
1359      *
1360      * The tlsproxy server does not enforce per-request read/write deadlines or
1361      * minimal data rates. Instead, the tlsproxy server relies on the
1362      * tlsproxy client to enforce these context-dependent limits. When a
1363      * tlsproxy client decides to time out, it will close its end of the
1364      * tlsproxy stream, and the tlsproxy server will handle that immediately.
1365      */
1366     if (event != EVENT_READ
1367 	|| attr_scan(plaintext_stream, ATTR_FLAG_STRICT,
1368 		     RECV_ATTR_STR(TLS_ATTR_REMOTE_ENDPT, remote_endpt),
1369 		     RECV_ATTR_INT(TLS_ATTR_FLAGS, &req_flags),
1370 		     RECV_ATTR_INT(TLS_ATTR_TIMEOUT, &handshake_timeout),
1371 		     RECV_ATTR_INT(TLS_ATTR_TIMEOUT, &session_timeout),
1372 		     RECV_ATTR_STR(TLS_ATTR_SERVERID, server_id),
1373 		     ATTR_TYPE_END) != 5) {
1374 	msg_warn("%s: receive request attributes: %m", myname);
1375 	tlsp_state_free(state);
1376 	return;
1377     }
1378 
1379     /*
1380      * XXX We use the same fixed timeout throughout the entire session for
1381      * both plaintext and ciphertext communication. This timeout is just a
1382      * safety feature; the real timeout will be enforced by our plaintext
1383      * peer (except during TLS the handshake, when we intentionally disable
1384      * plaintext I/O).
1385      */
1386     state->remote_endpt = mystrdup(STR(remote_endpt));
1387     state->server_id = mystrdup(STR(server_id));
1388     msg_info("CONNECT %s %s",
1389 	     (req_flags & TLS_PROXY_FLAG_ROLE_SERVER) ? "from" :
1390 	     (req_flags & TLS_PROXY_FLAG_ROLE_CLIENT) ? "to" :
1391 	     "(bogus_direction)", state->remote_endpt);
1392     state->req_flags = req_flags;
1393     /* state->is_server_role is set below. */
1394     state->handshake_timeout = handshake_timeout;
1395     state->session_timeout = session_timeout + 10;	/* XXX */
1396 
1397     /*
1398      * Receive the TLS preferences now, to reduce the number of protocol
1399      * roundtrips.
1400      */
1401     switch (req_flags & (TLS_PROXY_FLAG_ROLE_CLIENT | TLS_PROXY_FLAG_ROLE_SERVER)) {
1402     case TLS_PROXY_FLAG_ROLE_CLIENT:
1403 	state->is_server_role = 0;
1404 	if (attr_scan(plaintext_stream, ATTR_FLAG_STRICT,
1405 		      RECV_ATTR_FUNC(tls_proxy_client_param_scan,
1406 				     (void *) &state->tls_params),
1407 		      RECV_ATTR_FUNC(tls_proxy_client_init_scan,
1408 				     (void *) &state->client_init_props),
1409 		      RECV_ATTR_FUNC(tls_proxy_client_start_scan,
1410 				     (void *) &state->client_start_props),
1411 		      ATTR_TYPE_END) != 3) {
1412 	    msg_warn("%s: receive client TLS settings: %m", myname);
1413 	    tlsp_state_free(state);
1414 	    return;
1415 	}
1416 	state->appl_state = tlsp_client_init(state->tls_params,
1417 					     state->client_init_props);
1418 	ready = state->appl_state != 0;
1419 	break;
1420     case TLS_PROXY_FLAG_ROLE_SERVER:
1421 	state->is_server_role = 1;
1422 	ready = (tlsp_server_ctx != 0);
1423 	break;
1424     default:
1425 	state->is_server_role = 0;
1426 	msg_warn("%s: bad request flags: 0x%x", myname, req_flags);
1427 	ready = 0;
1428     }
1429 
1430     /*
1431      * For portability we must send some data, after receiving the request
1432      * attributes and before receiving the remote file descriptor.
1433      *
1434      * If the requested TLS engine is unavailable, hang up after making sure
1435      * that the plaintext peer has received our "sorry" indication.
1436      */
1437     if (attr_print(plaintext_stream, ATTR_FLAG_NONE,
1438 		   SEND_ATTR_INT(MAIL_ATTR_STATUS, ready),
1439 		   ATTR_TYPE_END) != 0
1440 	|| vstream_fflush(plaintext_stream) != 0
1441 	|| ready == 0) {
1442 	tlsp_request_read_event(plaintext_fd, tlsp_close_event,
1443 				TLSP_INIT_TIMEOUT, (void *) state);
1444 	return;
1445     } else {
1446 	tlsp_request_read_event(plaintext_fd, tlsp_get_fd_event,
1447 				TLSP_INIT_TIMEOUT, (void *) state);
1448 	return;
1449     }
1450 }
1451 
1452 /* tlsp_service - handle new client connection */
1453 
tlsp_service(VSTREAM * plaintext_stream,char * service,char ** argv)1454 static void tlsp_service(VSTREAM *plaintext_stream,
1455 			         char *service,
1456 			         char **argv)
1457 {
1458     TLSP_STATE *state;
1459     int     plaintext_fd = vstream_fileno(plaintext_stream);
1460 
1461     /*
1462      * Sanity check. This service takes no command-line arguments.
1463      */
1464     if (argv[0])
1465 	msg_fatal("unexpected command-line argument: %s", argv[0]);
1466 
1467     /*
1468      * This program handles multiple connections, so it must not block. We
1469      * use event-driven code for all operations that introduce latency.
1470      * Except that attribute lists are sent/received synchronously, once the
1471      * socket is found to be ready for transmission.
1472      */
1473     non_blocking(plaintext_fd, NON_BLOCKING);
1474     vstream_control(plaintext_stream,
1475 		    CA_VSTREAM_CTL_PATH("plaintext"),
1476 		    CA_VSTREAM_CTL_TIMEOUT(5),
1477 		    CA_VSTREAM_CTL_END);
1478 
1479     (void) attr_print(plaintext_stream, ATTR_FLAG_NONE,
1480 		   SEND_ATTR_STR(MAIL_ATTR_PROTO, MAIL_ATTR_PROTO_TLSPROXY),
1481 		      ATTR_TYPE_END);
1482     if (vstream_fflush(plaintext_stream) != 0)
1483 	msg_warn("write %s attribute: %m", MAIL_ATTR_PROTO);
1484 
1485     /*
1486      * Receive postscreen's remote SMTP client address/port and socket.
1487      */
1488     state = tlsp_state_create(service, plaintext_stream);
1489     tlsp_request_read_event(plaintext_fd, tlsp_get_request_event,
1490 			    TLSP_INIT_TIMEOUT, (void *) state);
1491 }
1492 
1493 /* pre_jail_init_server - pre-jail initialization */
1494 
pre_jail_init_server(void)1495 static void pre_jail_init_server(void)
1496 {
1497     TLS_SERVER_INIT_PROPS props;
1498     const char *cert_file;
1499     int     have_server_cert;
1500     int     no_server_cert_ok;
1501     int     require_server_cert;
1502 
1503     /*
1504      * The code in this routine is pasted literally from smtpd(8). I am not
1505      * going to sanitize this because doing so surely will break things in
1506      * unexpected ways.
1507      */
1508     if (*var_tlsp_tls_level) {
1509 	switch (tls_level_lookup(var_tlsp_tls_level)) {
1510 	default:
1511 	    msg_fatal("Invalid TLS level \"%s\"", var_tlsp_tls_level);
1512 	    /* NOTREACHED */
1513 	    break;
1514 	case TLS_LEV_SECURE:
1515 	case TLS_LEV_VERIFY:
1516 	case TLS_LEV_FPRINT:
1517 	    msg_warn("%s: unsupported TLS level \"%s\", using \"encrypt\"",
1518 		     VAR_TLSP_TLS_LEVEL, var_tlsp_tls_level);
1519 	    /* FALLTHROUGH */
1520 	case TLS_LEV_ENCRYPT:
1521 	    var_tlsp_enforce_tls = var_tlsp_use_tls = 1;
1522 	    break;
1523 	case TLS_LEV_MAY:
1524 	    var_tlsp_enforce_tls = 0;
1525 	    var_tlsp_use_tls = 1;
1526 	    break;
1527 	case TLS_LEV_NONE:
1528 	    var_tlsp_enforce_tls = var_tlsp_use_tls = 0;
1529 	    break;
1530 	}
1531     }
1532     var_tlsp_use_tls = var_tlsp_use_tls || var_tlsp_enforce_tls;
1533     if (!var_tlsp_use_tls) {
1534 	msg_warn("TLS server role is disabled with %s or %s",
1535 		 VAR_TLSP_TLS_LEVEL, VAR_TLSP_USE_TLS);
1536 	return;
1537     }
1538 
1539     /*
1540      * Load TLS keys before dropping privileges.
1541      *
1542      * Can't use anonymous ciphers if we want client certificates. Must use
1543      * anonymous ciphers if we have no certificates.
1544      */
1545     ask_client_cert = require_server_cert =
1546 	(var_tlsp_tls_ask_ccert
1547 	 || (var_tlsp_enforce_tls && var_tlsp_tls_req_ccert));
1548     if (strcasecmp(var_tlsp_tls_cert_file, "none") == 0) {
1549 	no_server_cert_ok = 1;
1550 	cert_file = "";
1551     } else {
1552 	no_server_cert_ok = 0;
1553 	cert_file = var_tlsp_tls_cert_file;
1554     }
1555     have_server_cert =
1556 	(*cert_file || *var_tlsp_tls_dcert_file || *var_tlsp_tls_eccert_file);
1557 
1558     if (*var_tlsp_tls_chain_files != 0) {
1559 	if (!have_server_cert)
1560 	    have_server_cert = 1;
1561 	else
1562 	    msg_warn("Both %s and one or more of the legacy "
1563 		     " %s, %s or %s are non-empty; the legacy "
1564 		     " parameters will be ignored",
1565 		     VAR_TLSP_TLS_CHAIN_FILES,
1566 		     VAR_TLSP_TLS_CERT_FILE,
1567 		     VAR_TLSP_TLS_ECCERT_FILE,
1568 		     VAR_TLSP_TLS_DCERT_FILE);
1569     }
1570     /* Some TLS configuration errors are not show stoppers. */
1571     if (!have_server_cert && require_server_cert)
1572 	msg_warn("Need a server cert to request client certs");
1573     if (!var_tlsp_enforce_tls && var_tlsp_tls_req_ccert)
1574 	msg_warn("Can't require client certs unless TLS is required");
1575     /* After a show-stopper error, log a warning. */
1576     if (have_server_cert || (no_server_cert_ok && !require_server_cert)) {
1577 
1578 	tls_pre_jail_init(TLS_ROLE_SERVER);
1579 
1580 	/*
1581 	 * Large parameter lists are error-prone, so we emulate a language
1582 	 * feature that C does not have natively: named parameter lists.
1583 	 */
1584 	tlsp_server_ctx =
1585 	    TLS_SERVER_INIT(&props,
1586 			    log_param = VAR_TLSP_TLS_LOGLEVEL,
1587 			    log_level = var_tlsp_tls_loglevel,
1588 			    verifydepth = var_tlsp_tls_ccert_vd,
1589 			    cache_type = TLS_MGR_SCACHE_SMTPD,
1590 			    set_sessid = var_tlsp_tls_set_sessid,
1591 			    chain_files = var_tlsp_tls_chain_files,
1592 			    cert_file = cert_file,
1593 			    key_file = var_tlsp_tls_key_file,
1594 			    dcert_file = var_tlsp_tls_dcert_file,
1595 			    dkey_file = var_tlsp_tls_dkey_file,
1596 			    eccert_file = var_tlsp_tls_eccert_file,
1597 			    eckey_file = var_tlsp_tls_eckey_file,
1598 			    CAfile = var_tlsp_tls_CAfile,
1599 			    CApath = var_tlsp_tls_CApath,
1600 			    dh1024_param_file
1601 			    = var_tlsp_tls_dh1024_param_file,
1602 			    dh512_param_file
1603 			    = var_tlsp_tls_dh512_param_file,
1604 			    eecdh_grade = var_tlsp_tls_eecdh,
1605 			    protocols = var_tlsp_enforce_tls ?
1606 			    var_tlsp_tls_mand_proto :
1607 			    var_tlsp_tls_proto,
1608 			    ask_ccert = ask_client_cert,
1609 			    mdalg = var_tlsp_tls_fpt_dgst);
1610     } else {
1611 	msg_warn("No server certs available. TLS can't be enabled");
1612     }
1613 
1614     /*
1615      * To maintain sanity, allow partial SSL_write() operations, and allow
1616      * SSL_write() buffer pointers to change after a WANT_READ or WANT_WRITE
1617      * result. This is based on OpenSSL developers talking on a mailing list,
1618      * but is not supported by documentation. If this code stops working then
1619      * no-one can be held responsible.
1620      */
1621     if (tlsp_server_ctx)
1622 	SSL_CTX_set_mode(tlsp_server_ctx->ssl_ctx,
1623 			 SSL_MODE_ENABLE_PARTIAL_WRITE
1624 			 | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1625 }
1626 
1627 /* pre_jail_init_client - pre-jail initialization */
1628 
pre_jail_init_client(void)1629 static void pre_jail_init_client(void)
1630 {
1631     int     clnt_use_tls;
1632 
1633     /*
1634      * The cache with TLS_APPL_STATE instances for different TLS_CLIENT_INIT
1635      * configurations.
1636      */
1637     tlsp_client_app_cache = htable_create(10);
1638 
1639     /*
1640      * Most sites don't use TLS client certs/keys. In that case, enabling
1641      * tlsproxy-based connection caching is trivial.
1642      *
1643      * But some sites do use TLS client certs/keys, and that is challenging when
1644      * tlsproxy runs in a post-jail environment: chroot breaks pathname
1645      * resolution, and an unprivileged process should not be able to open
1646      * files with secrets. The workaround: assume that most of those sites
1647      * will use a fixed TLS client identity. In that case, tlsproxy can load
1648      * the corresponding certs/keys at pre-jail time, so that secrets can
1649      * remain read-only for root. As long as the tlsproxy pre-jail TLS client
1650      * configuration with cert or key pathnames is the same as the one used
1651      * in the Postfix SMTP client, sites can selectively or globally enable
1652      * tlsproxy-based connection caching without additional TLS
1653      * configuration.
1654      *
1655      * Loading one TLS client configuration at pre-jail time is not sufficient
1656      * for the minority of sites that want to use TLS connection caching with
1657      * multiple TLS client identities. To alert the operator, tlsproxy will
1658      * log a warning when a TLS_CLIENT_INIT message specifies a different
1659      * configuration than the tlsproxy pre-jail client configuration, and
1660      * that different configuration specifies file/directory pathname
1661      * arguments. The workaround is to have one tlsproxy process per TLS
1662      * client identity.
1663      *
1664      * The general solution for single-identity or multi-identity clients is to
1665      * stop loading certs and keys from individual files. Instead, have a
1666      * cert/key map, indexed by client identity, read-only by root. After
1667      * opening the map as root at pre-jail time, tlsproxy can read certs/keys
1668      * on-the-fly as an unprivileged process at post-jail time. This is the
1669      * approach that was already proposed for server-side SNI support, and it
1670      * could be reused here. It would also end the proliferation of RSA
1671      * cert/key parameters, DSA cert/key parameters, EC cert/key parameters,
1672      * and so on.
1673      *
1674      * Horror: In order to create the same pre-jail TLS client context as the
1675      * one used in the Postfix SMTP client, we have to duplicate intricate
1676      * SMTP client code, including a handful configuration parameters that
1677      * tlsproxy does not need. We must duplicate the logic, so that we only
1678      * load certs and keys when the SMTP client would load them.
1679      */
1680     if (*var_tlsp_clnt_level != 0)
1681 	switch (tls_level_lookup(var_tlsp_clnt_level)) {
1682 	case TLS_LEV_SECURE:
1683 	case TLS_LEV_VERIFY:
1684 	case TLS_LEV_DANE_ONLY:
1685 	case TLS_LEV_FPRINT:
1686 	case TLS_LEV_ENCRYPT:
1687 	    var_tlsp_clnt_use_tls = var_tlsp_clnt_enforce_tls = 1;
1688 	    break;
1689 	case TLS_LEV_DANE:
1690 	case TLS_LEV_MAY:
1691 	    var_tlsp_clnt_use_tls = 1;
1692 	    var_tlsp_clnt_enforce_tls = 0;
1693 	    break;
1694 	case TLS_LEV_NONE:
1695 	    var_tlsp_clnt_use_tls = var_tlsp_clnt_enforce_tls = 0;
1696 	    break;
1697 	default:
1698 	    /* tls_level_lookup() logs no warning. */
1699 	    /* session_tls_init() assumes that var_tlsp_clnt_level is sane. */
1700 	    msg_fatal("Invalid TLS level \"%s\"", var_tlsp_clnt_level);
1701 	}
1702     clnt_use_tls = (var_tlsp_clnt_use_tls || var_tlsp_clnt_enforce_tls);
1703 
1704     /*
1705      * Initialize the TLS data before entering the chroot jail.
1706      */
1707     if (clnt_use_tls || var_tlsp_clnt_per_site[0] || var_tlsp_clnt_policy[0]) {
1708 	TLS_CLIENT_PARAMS tls_params;
1709 	TLS_CLIENT_INIT_PROPS init_props;
1710 
1711 	tls_pre_jail_init(TLS_ROLE_CLIENT);
1712 
1713 	/*
1714 	 * We get stronger type safety and a cleaner interface by combining
1715 	 * the various parameters into a single tls_client_props structure.
1716 	 *
1717 	 * Large parameter lists are error-prone, so we emulate a language
1718 	 * feature that C does not have natively: named parameter lists.
1719 	 */
1720 	(void) tls_proxy_client_param_from_config(&tls_params);
1721 	(void) TLS_CLIENT_INIT_ARGS(&init_props,
1722 				    log_param = var_tlsp_clnt_logparam,
1723 				    log_level = var_tlsp_clnt_loglevel,
1724 				    verifydepth = var_tlsp_clnt_scert_vd,
1725 				    cache_type = TLS_MGR_SCACHE_SMTP,
1726 				    chain_files = var_tlsp_clnt_chain_files,
1727 				    cert_file = var_tlsp_clnt_cert_file,
1728 				    key_file = var_tlsp_clnt_key_file,
1729 				    dcert_file = var_tlsp_clnt_dcert_file,
1730 				    dkey_file = var_tlsp_clnt_dkey_file,
1731 				    eccert_file = var_tlsp_clnt_eccert_file,
1732 				    eckey_file = var_tlsp_clnt_eckey_file,
1733 				    CAfile = var_tlsp_clnt_CAfile,
1734 				    CApath = var_tlsp_clnt_CApath,
1735 				    mdalg = var_tlsp_clnt_fpt_dgst);
1736 	if (tlsp_client_init(&tls_params, &init_props) == 0)
1737 	    msg_warn("TLS client initialization failed");
1738     }
1739 }
1740 
1741 /* pre_jail_init - pre-jail initialization */
1742 
pre_jail_init(char * unused_name,char ** unused_argv)1743 static void pre_jail_init(char *unused_name, char **unused_argv)
1744 {
1745 
1746     /*
1747      * Initialize roles separately.
1748      */
1749     pre_jail_init_server();
1750     pre_jail_init_client();
1751 
1752     /*
1753      * tlsp_client_init() needs to know if it is called pre-jail or
1754      * post-jail.
1755      */
1756     tlsp_pre_jail_done = 1;
1757 
1758     /*
1759      * Bug: TLS_CLIENT_PARAMS attributes are not used when creating a
1760      * TLS_APPL_STATE instance; we can only warn about attribute mismatches.
1761      */
1762     tlsp_params_mismatch_filter = been_here_init(BH_BOUND_NONE, BH_FLAG_NONE);
1763 }
1764 
1765 MAIL_VERSION_STAMP_DECLARE;
1766 
1767 /* main - the main program */
1768 
main(int argc,char ** argv)1769 int     main(int argc, char **argv)
1770 {
1771 
1772     /*
1773      * Each table below initializes the named variables to their implicit
1774      * default value, or to the explicit value in main.cf or master.cf. Here,
1775      * "compat" means that a table initializes a variable "smtpd_blah" or
1776      * "smtp_blah" that provides the implicit default value for variable
1777      * "tlsproxy_blah" which is initialized by a different table. To make
1778      * this work, the variables in a "compat" table must be initialized
1779      * before the variables in the corresponding non-compat table.
1780      */
1781     static const CONFIG_INT_TABLE compat_int_table[] = {
1782 	VAR_SMTPD_TLS_CCERT_VD, DEF_SMTPD_TLS_CCERT_VD, &var_smtpd_tls_ccert_vd, 0, 0,
1783 	VAR_SMTP_TLS_SCERT_VD, DEF_SMTP_TLS_SCERT_VD, &var_smtp_tls_scert_vd, 0, 0,
1784 	0,
1785     };
1786     static const CONFIG_NINT_TABLE nint_table[] = {
1787 	VAR_TLSP_TLS_CCERT_VD, DEF_TLSP_TLS_CCERT_VD, &var_tlsp_tls_ccert_vd, 0, 0,
1788 	VAR_TLSP_CLNT_SCERT_VD, DEF_TLSP_CLNT_SCERT_VD, &var_tlsp_clnt_scert_vd, 0, 0,
1789 	0,
1790     };
1791     static const CONFIG_TIME_TABLE time_table[] = {
1792 	VAR_TLSP_WATCHDOG, DEF_TLSP_WATCHDOG, &var_tlsp_watchdog, 10, 0,
1793 	0,
1794     };
1795     static const CONFIG_BOOL_TABLE compat_bool_table[] = {
1796 	VAR_SMTPD_USE_TLS, DEF_SMTPD_USE_TLS, &var_smtpd_use_tls,
1797 	VAR_SMTPD_ENFORCE_TLS, DEF_SMTPD_ENFORCE_TLS, &var_smtpd_enforce_tls,
1798 	VAR_SMTPD_TLS_ACERT, DEF_SMTPD_TLS_ACERT, &var_smtpd_tls_ask_ccert,
1799 	VAR_SMTPD_TLS_RCERT, DEF_SMTPD_TLS_RCERT, &var_smtpd_tls_req_ccert,
1800 	VAR_SMTPD_TLS_SET_SESSID, DEF_SMTPD_TLS_SET_SESSID, &var_smtpd_tls_set_sessid,
1801 	VAR_SMTP_USE_TLS, DEF_SMTP_USE_TLS, &var_smtp_use_tls,
1802 	VAR_SMTP_ENFORCE_TLS, DEF_SMTP_ENFORCE_TLS, &var_smtp_enforce_tls,
1803 	0,
1804     };
1805     static const CONFIG_NBOOL_TABLE nbool_table[] = {
1806 	VAR_TLSP_USE_TLS, DEF_TLSP_USE_TLS, &var_tlsp_use_tls,
1807 	VAR_TLSP_ENFORCE_TLS, DEF_TLSP_ENFORCE_TLS, &var_tlsp_enforce_tls,
1808 	VAR_TLSP_TLS_ACERT, DEF_TLSP_TLS_ACERT, &var_tlsp_tls_ask_ccert,
1809 	VAR_TLSP_TLS_RCERT, DEF_TLSP_TLS_RCERT, &var_tlsp_tls_req_ccert,
1810 	VAR_TLSP_TLS_SET_SESSID, DEF_TLSP_TLS_SET_SESSID, &var_tlsp_tls_set_sessid,
1811 	VAR_TLSP_CLNT_USE_TLS, DEF_TLSP_CLNT_USE_TLS, &var_tlsp_clnt_use_tls,
1812 	VAR_TLSP_CLNT_ENFORCE_TLS, DEF_TLSP_CLNT_ENFORCE_TLS, &var_tlsp_clnt_enforce_tls,
1813 	0,
1814     };
1815     static const CONFIG_STR_TABLE compat_str_table[] = {
1816 	VAR_SMTPD_TLS_CHAIN_FILES, DEF_SMTPD_TLS_CHAIN_FILES, &var_smtpd_tls_chain_files, 0, 0,
1817 	VAR_SMTPD_TLS_CERT_FILE, DEF_SMTPD_TLS_CERT_FILE, &var_smtpd_tls_cert_file, 0, 0,
1818 	VAR_SMTPD_TLS_KEY_FILE, DEF_SMTPD_TLS_KEY_FILE, &var_smtpd_tls_key_file, 0, 0,
1819 	VAR_SMTPD_TLS_DCERT_FILE, DEF_SMTPD_TLS_DCERT_FILE, &var_smtpd_tls_dcert_file, 0, 0,
1820 	VAR_SMTPD_TLS_DKEY_FILE, DEF_SMTPD_TLS_DKEY_FILE, &var_smtpd_tls_dkey_file, 0, 0,
1821 	VAR_SMTPD_TLS_ECCERT_FILE, DEF_SMTPD_TLS_ECCERT_FILE, &var_smtpd_tls_eccert_file, 0, 0,
1822 	VAR_SMTPD_TLS_ECKEY_FILE, DEF_SMTPD_TLS_ECKEY_FILE, &var_smtpd_tls_eckey_file, 0, 0,
1823 	VAR_SMTPD_TLS_CA_FILE, DEF_SMTPD_TLS_CA_FILE, &var_smtpd_tls_CAfile, 0, 0,
1824 	VAR_SMTPD_TLS_CA_PATH, DEF_SMTPD_TLS_CA_PATH, &var_smtpd_tls_CApath, 0, 0,
1825 	VAR_SMTPD_TLS_CIPH, DEF_SMTPD_TLS_CIPH, &var_smtpd_tls_ciph, 1, 0,
1826 	VAR_SMTPD_TLS_MAND_CIPH, DEF_SMTPD_TLS_MAND_CIPH, &var_smtpd_tls_mand_ciph, 1, 0,
1827 	VAR_SMTPD_TLS_EXCL_CIPH, DEF_SMTPD_TLS_EXCL_CIPH, &var_smtpd_tls_excl_ciph, 0, 0,
1828 	VAR_SMTPD_TLS_MAND_EXCL, DEF_SMTPD_TLS_MAND_EXCL, &var_smtpd_tls_mand_excl, 0, 0,
1829 	VAR_SMTPD_TLS_PROTO, DEF_SMTPD_TLS_PROTO, &var_smtpd_tls_proto, 0, 0,
1830 	VAR_SMTPD_TLS_MAND_PROTO, DEF_SMTPD_TLS_MAND_PROTO, &var_smtpd_tls_mand_proto, 0, 0,
1831 	VAR_SMTPD_TLS_512_FILE, DEF_SMTPD_TLS_512_FILE, &var_smtpd_tls_dh512_param_file, 0, 0,
1832 	VAR_SMTPD_TLS_1024_FILE, DEF_SMTPD_TLS_1024_FILE, &var_smtpd_tls_dh1024_param_file, 0, 0,
1833 	VAR_SMTPD_TLS_EECDH, DEF_SMTPD_TLS_EECDH, &var_smtpd_tls_eecdh, 1, 0,
1834 	VAR_SMTPD_TLS_FPT_DGST, DEF_SMTPD_TLS_FPT_DGST, &var_smtpd_tls_fpt_dgst, 1, 0,
1835 	VAR_SMTPD_TLS_LOGLEVEL, DEF_SMTPD_TLS_LOGLEVEL, &var_smtpd_tls_loglevel, 0, 0,
1836 	VAR_SMTPD_TLS_LEVEL, DEF_SMTPD_TLS_LEVEL, &var_smtpd_tls_level, 0, 0,
1837 	VAR_SMTP_TLS_CHAIN_FILES, DEF_SMTP_TLS_CHAIN_FILES, &var_smtp_tls_chain_files, 0, 0,
1838 	VAR_SMTP_TLS_CERT_FILE, DEF_SMTP_TLS_CERT_FILE, &var_smtp_tls_cert_file, 0, 0,
1839 	VAR_SMTP_TLS_KEY_FILE, DEF_SMTP_TLS_KEY_FILE, &var_smtp_tls_key_file, 0, 0,
1840 	VAR_SMTP_TLS_DCERT_FILE, DEF_SMTP_TLS_DCERT_FILE, &var_smtp_tls_dcert_file, 0, 0,
1841 	VAR_SMTP_TLS_DKEY_FILE, DEF_SMTP_TLS_DKEY_FILE, &var_smtp_tls_dkey_file, 0, 0,
1842 	VAR_SMTP_TLS_CA_FILE, DEF_SMTP_TLS_CA_FILE, &var_smtp_tls_CAfile, 0, 0,
1843 	VAR_SMTP_TLS_CA_PATH, DEF_SMTP_TLS_CA_PATH, &var_smtp_tls_CApath, 0, 0,
1844 	VAR_SMTP_TLS_FPT_DGST, DEF_SMTP_TLS_FPT_DGST, &var_smtp_tls_fpt_dgst, 1, 0,
1845 	VAR_SMTP_TLS_ECCERT_FILE, DEF_SMTP_TLS_ECCERT_FILE, &var_smtp_tls_eccert_file, 0, 0,
1846 	VAR_SMTP_TLS_ECKEY_FILE, DEF_SMTP_TLS_ECKEY_FILE, &var_smtp_tls_eckey_file, 0, 0,
1847 	VAR_SMTP_TLS_LOGLEVEL, DEF_SMTP_TLS_LOGLEVEL, &var_smtp_tls_loglevel, 0, 0,
1848 	VAR_SMTP_TLS_PER_SITE, DEF_SMTP_TLS_PER_SITE, &var_smtp_tls_per_site, 0, 0,
1849 	VAR_SMTP_TLS_LEVEL, DEF_SMTP_TLS_LEVEL, &var_smtp_tls_level, 0, 0,
1850 	VAR_SMTP_TLS_POLICY, DEF_SMTP_TLS_POLICY, &var_smtp_tls_policy, 0, 0,
1851 	0,
1852     };
1853     static const CONFIG_STR_TABLE str_table[] = {
1854 	VAR_TLSP_TLS_CHAIN_FILES, DEF_TLSP_TLS_CHAIN_FILES, &var_tlsp_tls_chain_files, 0, 0,
1855 	VAR_TLSP_TLS_CERT_FILE, DEF_TLSP_TLS_CERT_FILE, &var_tlsp_tls_cert_file, 0, 0,
1856 	VAR_TLSP_TLS_KEY_FILE, DEF_TLSP_TLS_KEY_FILE, &var_tlsp_tls_key_file, 0, 0,
1857 	VAR_TLSP_TLS_DCERT_FILE, DEF_TLSP_TLS_DCERT_FILE, &var_tlsp_tls_dcert_file, 0, 0,
1858 	VAR_TLSP_TLS_DKEY_FILE, DEF_TLSP_TLS_DKEY_FILE, &var_tlsp_tls_dkey_file, 0, 0,
1859 	VAR_TLSP_TLS_ECCERT_FILE, DEF_TLSP_TLS_ECCERT_FILE, &var_tlsp_tls_eccert_file, 0, 0,
1860 	VAR_TLSP_TLS_ECKEY_FILE, DEF_TLSP_TLS_ECKEY_FILE, &var_tlsp_tls_eckey_file, 0, 0,
1861 	VAR_TLSP_TLS_CA_FILE, DEF_TLSP_TLS_CA_FILE, &var_tlsp_tls_CAfile, 0, 0,
1862 	VAR_TLSP_TLS_CA_PATH, DEF_TLSP_TLS_CA_PATH, &var_tlsp_tls_CApath, 0, 0,
1863 	VAR_TLSP_TLS_CIPH, DEF_TLSP_TLS_CIPH, &var_tlsp_tls_ciph, 1, 0,
1864 	VAR_TLSP_TLS_MAND_CIPH, DEF_TLSP_TLS_MAND_CIPH, &var_tlsp_tls_mand_ciph, 1, 0,
1865 	VAR_TLSP_TLS_EXCL_CIPH, DEF_TLSP_TLS_EXCL_CIPH, &var_tlsp_tls_excl_ciph, 0, 0,
1866 	VAR_TLSP_TLS_MAND_EXCL, DEF_TLSP_TLS_MAND_EXCL, &var_tlsp_tls_mand_excl, 0, 0,
1867 	VAR_TLSP_TLS_PROTO, DEF_TLSP_TLS_PROTO, &var_tlsp_tls_proto, 0, 0,
1868 	VAR_TLSP_TLS_MAND_PROTO, DEF_TLSP_TLS_MAND_PROTO, &var_tlsp_tls_mand_proto, 0, 0,
1869 	VAR_TLSP_TLS_512_FILE, DEF_TLSP_TLS_512_FILE, &var_tlsp_tls_dh512_param_file, 0, 0,
1870 	VAR_TLSP_TLS_1024_FILE, DEF_TLSP_TLS_1024_FILE, &var_tlsp_tls_dh1024_param_file, 0, 0,
1871 	VAR_TLSP_TLS_EECDH, DEF_TLSP_TLS_EECDH, &var_tlsp_tls_eecdh, 1, 0,
1872 	VAR_TLSP_TLS_FPT_DGST, DEF_TLSP_TLS_FPT_DGST, &var_tlsp_tls_fpt_dgst, 1, 0,
1873 	VAR_TLSP_TLS_LOGLEVEL, DEF_TLSP_TLS_LOGLEVEL, &var_tlsp_tls_loglevel, 0, 0,
1874 	VAR_TLSP_TLS_LEVEL, DEF_TLSP_TLS_LEVEL, &var_tlsp_tls_level, 0, 0,
1875 	VAR_TLSP_CLNT_LOGLEVEL, DEF_TLSP_CLNT_LOGLEVEL, &var_tlsp_clnt_loglevel, 0, 0,
1876 	VAR_TLSP_CLNT_LOGPARAM, DEF_TLSP_CLNT_LOGPARAM, &var_tlsp_clnt_logparam, 0, 0,
1877 	VAR_TLSP_CLNT_CHAIN_FILES, DEF_TLSP_CLNT_CHAIN_FILES, &var_tlsp_clnt_chain_files, 0, 0,
1878 	VAR_TLSP_CLNT_CERT_FILE, DEF_TLSP_CLNT_CERT_FILE, &var_tlsp_clnt_cert_file, 0, 0,
1879 	VAR_TLSP_CLNT_KEY_FILE, DEF_TLSP_CLNT_KEY_FILE, &var_tlsp_clnt_key_file, 0, 0,
1880 	VAR_TLSP_CLNT_DCERT_FILE, DEF_TLSP_CLNT_DCERT_FILE, &var_tlsp_clnt_dcert_file, 0, 0,
1881 	VAR_TLSP_CLNT_DKEY_FILE, DEF_TLSP_CLNT_DKEY_FILE, &var_tlsp_clnt_dkey_file, 0, 0,
1882 	VAR_TLSP_CLNT_ECCERT_FILE, DEF_TLSP_CLNT_ECCERT_FILE, &var_tlsp_clnt_eccert_file, 0, 0,
1883 	VAR_TLSP_CLNT_ECKEY_FILE, DEF_TLSP_CLNT_ECKEY_FILE, &var_tlsp_clnt_eckey_file, 0, 0,
1884 	VAR_TLSP_CLNT_CAFILE, DEF_TLSP_CLNT_CAFILE, &var_tlsp_clnt_CAfile, 0, 0,
1885 	VAR_TLSP_CLNT_CAPATH, DEF_TLSP_CLNT_CAPATH, &var_tlsp_clnt_CApath, 0, 0,
1886 	VAR_TLSP_CLNT_FPT_DGST, DEF_TLSP_CLNT_FPT_DGST, &var_tlsp_clnt_fpt_dgst, 1, 0,
1887 	VAR_TLSP_CLNT_LEVEL, DEF_TLSP_CLNT_LEVEL, &var_tlsp_clnt_level, 0, 0,
1888 	VAR_TLSP_CLNT_PER_SITE, DEF_TLSP_CLNT_PER_SITE, &var_tlsp_clnt_per_site, 0, 0,
1889 	VAR_TLSP_CLNT_POLICY, DEF_TLSP_CLNT_POLICY, &var_tlsp_clnt_policy, 0, 0,
1890 	0,
1891     };
1892 
1893     /*
1894      * Fingerprint executables and core dumps.
1895      */
1896     MAIL_VERSION_STAMP_ALLOCATE;
1897 
1898     /*
1899      * Pass control to the event-driven service skeleton.
1900      */
1901     event_server_main(argc, argv, tlsp_service,
1902 		      CA_MAIL_SERVER_INT_TABLE(compat_int_table),
1903 		      CA_MAIL_SERVER_NINT_TABLE(nint_table),
1904 		      CA_MAIL_SERVER_STR_TABLE(compat_str_table),
1905 		      CA_MAIL_SERVER_STR_TABLE(str_table),
1906 		      CA_MAIL_SERVER_BOOL_TABLE(compat_bool_table),
1907 		      CA_MAIL_SERVER_NBOOL_TABLE(nbool_table),
1908 		      CA_MAIL_SERVER_TIME_TABLE(time_table),
1909 		      CA_MAIL_SERVER_PRE_INIT(pre_jail_init),
1910 		      CA_MAIL_SERVER_SLOW_EXIT(tlsp_drain),
1911 		      CA_MAIL_SERVER_RETIRE_ME,
1912 		      CA_MAIL_SERVER_WATCHDOG(&var_tlsp_watchdog),
1913 		      CA_MAIL_SERVER_UNLIMITED,
1914 		      0);
1915 }
1916 
1917 #else
1918 
1919 /* tlsp_service - respond to external trigger(s), non-TLS version */
1920 
tlsp_service(VSTREAM * stream,char * unused_service,char ** unused_argv)1921 static void tlsp_service(VSTREAM *stream, char *unused_service,
1922 			         char **unused_argv)
1923 {
1924     msg_info("TLS support is not compiled in -- exiting");
1925     event_server_disconnect(stream);
1926 }
1927 
1928 /* main - the main program */
1929 
main(int argc,char ** argv)1930 int     main(int argc, char **argv)
1931 {
1932 
1933     /*
1934      * We can't simply use msg_fatal() here, because the logging hasn't been
1935      * initialized. The text would disappear because stderr is redirected to
1936      * /dev/null.
1937      *
1938      * We invoke event_server_main() to complete program initialization
1939      * (including logging) and then invoke the tlsp_service() routine to log
1940      * the message that says why this program will not run.
1941      */
1942     event_server_main(argc, argv, tlsp_service,
1943 		      0);
1944 }
1945 
1946 #endif
1947