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