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