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