1 /*++
2 /* NAME
3 /*	postscreen 8
4 /* SUMMARY
5 /*	Postfix zombie blocker
6 /* SYNOPSIS
7 /*	\fBpostscreen\fR [generic Postfix daemon options]
8 /* DESCRIPTION
9 /*	The Postfix \fBpostscreen\fR(8) server provides additional
10 /*	protection against mail server overload. One \fBpostscreen\fR(8)
11 /*	process handles multiple inbound SMTP connections, and decides
12 /*	which clients may talk to a Postfix SMTP server process.
13 /*	By keeping spambots away, \fBpostscreen\fR(8) leaves more
14 /*	SMTP server processes available for legitimate clients, and
15 /*	delays the onset of server overload conditions.
16 /*
17 /*	This program should not be used on SMTP ports that receive
18 /*	mail from end-user clients (MUAs). In a typical deployment,
19 /*	\fBpostscreen\fR(8) handles the MX service on TCP port 25, and
20 /*	\fBsmtpd\fR(8) receives mail from MUAs on the \fBsubmission\fR
21 /*	service (TCP port 587) which requires client authentication.
22 /*	Alternatively, a site could set up a dedicated, non-postscreen,
23 /*	"port 25" server that provides \fBsubmission\fR service and
24 /*	client authentication, but no MX service.
25 /*
26 /*	\fBpostscreen\fR(8) maintains a temporary allowlist for
27 /*	clients that have passed a number of tests.  When an SMTP
28 /*	client IP address is allowlisted, \fBpostscreen\fR(8) hands
29 /*	off the connection immediately to a Postfix SMTP server
30 /*	process. This minimizes the overhead for legitimate mail.
31 /*
32 /*	By default, \fBpostscreen\fR(8) logs statistics and hands
33 /*	off each connection to a Postfix SMTP server process, while
34 /*	excluding clients in mynetworks from all tests (primarily,
35 /*	to avoid problems with non-standard SMTP implementations
36 /*	in network appliances).  This default mode blocks no clients,
37 /*	and is useful for non-destructive testing.
38 /*
39 /*	In a typical production setting, \fBpostscreen\fR(8) is
40 /*	configured to reject mail from clients that fail one or
41 /*	more tests. \fBpostscreen\fR(8) logs rejected mail with the
42 /*	client address, helo, sender and recipient information.
43 /*
44 /*	\fBpostscreen\fR(8) is not an SMTP proxy; this is intentional.
45 /*	The purpose is to keep spambots away from Postfix SMTP
46 /*	server processes, while minimizing overhead for legitimate
47 /*	traffic.
48 /* SECURITY
49 /* .ad
50 /* .fi
51 /*	The \fBpostscreen\fR(8) server is moderately security-sensitive.
52 /*	It talks to untrusted clients on the network. The process
53 /*	can be run chrooted at fixed low privilege.
54 /* STANDARDS
55 /*	RFC 821 (SMTP protocol)
56 /*	RFC 1123 (Host requirements)
57 /*	RFC 1652 (8bit-MIME transport)
58 /*	RFC 1869 (SMTP service extensions)
59 /*	RFC 1870 (Message Size Declaration)
60 /*	RFC 1985 (ETRN command)
61 /*	RFC 2034 (SMTP Enhanced Status Codes)
62 /*	RFC 2821 (SMTP protocol)
63 /*	Not: RFC 2920 (SMTP Pipelining)
64 /*	RFC 3030 (CHUNKING without BINARYMIME)
65 /*	RFC 3207 (STARTTLS command)
66 /*	RFC 3461 (SMTP DSN Extension)
67 /*	RFC 3463 (Enhanced Status Codes)
68 /*	RFC 5321 (SMTP protocol, including multi-line 220 banners)
69 /* DIAGNOSTICS
70 /*	Problems and transactions are logged to \fBsyslogd\fR(8)
71 /*	or \fBpostlogd\fR(8).
72 /* BUGS
73 /*	The \fBpostscreen\fR(8) built-in SMTP protocol engine
74 /*	currently does not announce support for AUTH, XCLIENT or
75 /*	XFORWARD.
76 /*	If you need to make these services available
77 /*	on port 25, then do not enable the optional "after 220
78 /*	server greeting" tests.
79 /*
80 /*	The optional "after 220 server greeting" tests may result in
81 /*	unexpected delivery delays from senders that retry email delivery
82 /*	from a different IP address.  Reason: after passing these tests a
83 /*	new client must disconnect, and reconnect from the same IP
84 /*	address before it can deliver mail. See POSTSCREEN_README, section
85 /*	"Tests after the 220 SMTP server greeting", for a discussion.
86 /* CONFIGURATION PARAMETERS
87 /* .ad
88 /* .fi
89 /*	Changes to main.cf are not picked up automatically, as
90 /*	\fBpostscreen\fR(8) processes may run for several hours.
91 /*	Use the command "postfix reload" after a configuration
92 /*	change.
93 /*
94 /*	The text below provides only a parameter summary. See
95 /*	\fBpostconf\fR(5) for more details including examples.
96 /*
97 /*	NOTE: Some \fBpostscreen\fR(8) parameters implement
98 /*	stress-dependent behavior.  This is supported only when the
99 /*	default parameter value is stress-dependent (that is, it
100 /*	looks like ${stress?{X}:{Y}}, or it is the $\fIname\fR
101 /*	of an smtpd parameter with a stress-dependent default).
102 /*	Other parameters always evaluate as if the \fBstress\fR
103 /*	parameter value is the empty string.
104 /* COMPATIBILITY CONTROLS
105 /* .ad
106 /* .fi
107 /* .IP "\fBpostscreen_command_filter ($smtpd_command_filter)\fR"
108 /*	A mechanism to transform commands from remote SMTP clients.
109 /* .IP "\fBpostscreen_discard_ehlo_keyword_address_maps ($smtpd_discard_ehlo_keyword_address_maps)\fR"
110 /*	Lookup tables, indexed by the remote SMTP client address, with
111 /*	case insensitive lists of EHLO keywords (pipelining, starttls, auth,
112 /*	etc.) that the \fBpostscreen\fR(8) server will not send in the EHLO response
113 /*	to a remote SMTP client.
114 /* .IP "\fBpostscreen_discard_ehlo_keywords ($smtpd_discard_ehlo_keywords)\fR"
115 /*	A case insensitive list of EHLO keywords (pipelining, starttls,
116 /*	auth, etc.) that the \fBpostscreen\fR(8) server will not send in the EHLO
117 /*	response to a remote SMTP client.
118 /* .PP
119 /*	Available in Postfix version 3.1 and later:
120 /* .IP "\fBdns_ncache_ttl_fix_enable (no)\fR"
121 /*	Enable a workaround for future libc incompatibility.
122 /* .PP
123 /*	Available in Postfix version 3.4 and later:
124 /* .IP "\fBpostscreen_reject_footer_maps ($smtpd_reject_footer_maps)\fR"
125 /*	Optional lookup table for information that is appended after a 4XX
126 /*	or 5XX \fBpostscreen\fR(8) server response.
127 /* .PP
128 /*	Available in Postfix 3.6 and later:
129 /* .IP "\fBrespectful_logging (see 'postconf -d' output)\fR"
130 /*	Avoid logging that implies white is better than black.
131 /* TROUBLE SHOOTING CONTROLS
132 /* .ad
133 /* .fi
134 /* .IP "\fBpostscreen_expansion_filter (see 'postconf -d' output)\fR"
135 /*	List of characters that are permitted in postscreen_reject_footer
136 /*	attribute expansions.
137 /* .IP "\fBpostscreen_reject_footer ($smtpd_reject_footer)\fR"
138 /*	Optional information that is appended after a 4XX or 5XX
139 /*	\fBpostscreen\fR(8) server
140 /*	response.
141 /* .IP "\fBsoft_bounce (no)\fR"
142 /*	Safety net to keep mail queued that would otherwise be returned to
143 /*	the sender.
144 /* BEFORE-POSTSCREEN PROXY AGENT
145 /* .ad
146 /* .fi
147 /*	Available in Postfix version 2.10 and later:
148 /* .IP "\fBpostscreen_upstream_proxy_protocol (empty)\fR"
149 /*	The name of the proxy protocol used by an optional before-postscreen
150 /*	proxy agent.
151 /* .IP "\fBpostscreen_upstream_proxy_timeout (5s)\fR"
152 /*	The time limit for the proxy protocol specified with the
153 /*	postscreen_upstream_proxy_protocol parameter.
154 /* PERMANENT ALLOW/DENYLIST TEST
155 /* .ad
156 /* .fi
157 /*	This test is executed immediately after a remote SMTP client
158 /*	connects. If a client is permanently allowlisted, the client
159 /*	will be handed off immediately to a Postfix SMTP server
160 /*	process.
161 /* .IP "\fBpostscreen_access_list (permit_mynetworks)\fR"
162 /*	Permanent allow/denylist for remote SMTP client IP addresses.
163 /* .IP "\fBpostscreen_blacklist_action (ignore)\fR"
164 /*	Renamed to postscreen_denylist_action in Postfix 3.6.
165 /* MAIL EXCHANGER POLICY TESTS
166 /* .ad
167 /* .fi
168 /*	When \fBpostscreen\fR(8) is configured to monitor all primary
169 /*	and backup MX addresses, it can refuse to allowlist clients
170 /*	that connect to a backup MX address only. For small sites,
171 /*	this requires configuring primary and backup MX addresses
172 /*	on the same MTA. Larger sites would have to share the
173 /*	\fBpostscreen\fR(8) cache between primary and backup MTAs,
174 /*	which would introduce a common point of failure.
175 /* .IP "\fBpostscreen_whitelist_interfaces (static:all)\fR"
176 /*	Renamed to postscreen_allowlist_interfaces in Postfix 3.6.
177 /* BEFORE 220 GREETING TESTS
178 /* .ad
179 /* .fi
180 /*	These tests are executed before the remote SMTP client
181 /*	receives the "220 servername" greeting. If no tests remain
182 /*	after the successful completion of this phase, the client
183 /*	will be handed off immediately to a Postfix SMTP server
184 /*	process.
185 /* .IP "\fBdnsblog_service_name (dnsblog)\fR"
186 /*	The name of the \fBdnsblog\fR(8) service entry in master.cf.
187 /* .IP "\fBpostscreen_dnsbl_action (ignore)\fR"
188 /*	The action that \fBpostscreen\fR(8) takes when a remote SMTP client's combined
189 /*	DNSBL score is equal to or greater than a threshold (as defined
190 /*	with the postscreen_dnsbl_sites and postscreen_dnsbl_threshold
191 /*	parameters).
192 /* .IP "\fBpostscreen_dnsbl_reply_map (empty)\fR"
193 /*	A mapping from actual DNSBL domain name which includes a secret
194 /*	password, to the DNSBL domain name that postscreen will reply with
195 /*	when it rejects mail.
196 /* .IP "\fBpostscreen_dnsbl_sites (empty)\fR"
197 /*	Optional list of DNS allow/denylist domains, filters and weight
198 /*	factors.
199 /* .IP "\fBpostscreen_dnsbl_threshold (1)\fR"
200 /*	The inclusive lower bound for blocking a remote SMTP client, based on
201 /*	its combined DNSBL score as defined with the postscreen_dnsbl_sites
202 /*	parameter.
203 /* .IP "\fBpostscreen_greet_action (ignore)\fR"
204 /*	The action that \fBpostscreen\fR(8) takes when a remote SMTP client speaks
205 /*	before its turn within the time specified with the postscreen_greet_wait
206 /*	parameter.
207 /* .IP "\fBpostscreen_greet_banner ($smtpd_banner)\fR"
208 /*	The \fItext\fR in the optional "220-\fItext\fR..." server
209 /*	response that
210 /*	\fBpostscreen\fR(8) sends ahead of the real Postfix SMTP server's "220
211 /*	text..." response, in an attempt to confuse bad SMTP clients so
212 /*	that they speak before their turn (pre-greet).
213 /* .IP "\fBpostscreen_greet_wait (normal: 6s, overload: 2s)\fR"
214 /*	The amount of time that \fBpostscreen\fR(8) will wait for an SMTP
215 /*	client to send a command before its turn, and for DNS blocklist
216 /*	lookup results to arrive (default: up to 2 seconds under stress,
217 /*	up to 6 seconds otherwise).
218 /* .IP "\fBsmtpd_service_name (smtpd)\fR"
219 /*	The internal service that \fBpostscreen\fR(8) hands off allowed
220 /*	connections to.
221 /* .PP
222 /*	Available in Postfix version 2.11 and later:
223 /* .IP "\fBpostscreen_dnsbl_whitelist_threshold (0)\fR"
224 /*	Renamed to postscreen_dnsbl_allowlist_threshold in Postfix 3.6.
225 /* .PP
226 /*	Available in Postfix version 3.0 and later:
227 /* .IP "\fBpostscreen_dnsbl_timeout (10s)\fR"
228 /*	The time limit for DNSBL or DNSWL lookups.
229 /* .PP
230 /*	Available in Postfix version 3.6 and later:
231 /* .IP "\fBpostscreen_denylist_action (ignore)\fR"
232 /*	The action that \fBpostscreen\fR(8) takes when a remote SMTP client is
233 /*	permanently denylisted with the postscreen_access_list parameter.
234 /* .IP "\fBpostscreen_allowlist_interfaces (static:all)\fR"
235 /*	A list of local \fBpostscreen\fR(8) server IP addresses where a
236 /*	non-allowlisted remote SMTP client can obtain \fBpostscreen\fR(8)'s temporary
237 /*	allowlist status.
238 /* .IP "\fBpostscreen_dnsbl_allowlist_threshold (0)\fR"
239 /*	Allow a remote SMTP client to skip "before" and "after 220
240 /*	greeting" protocol tests, based on its combined DNSBL score as
241 /*	defined with the postscreen_dnsbl_sites parameter.
242 /* AFTER 220 GREETING TESTS
243 /* .ad
244 /* .fi
245 /*	These tests are executed after the remote SMTP client
246 /*	receives the "220 servername" greeting. If a client passes
247 /*	all tests during this phase, it will receive a 4XX response
248 /*	to all RCPT TO commands. After the client reconnects, it
249 /*	will be allowed to talk directly to a Postfix SMTP server
250 /*	process.
251 /* .IP "\fBpostscreen_bare_newline_action (ignore)\fR"
252 /*	The action that \fBpostscreen\fR(8) takes when a remote SMTP client sends
253 /*	a bare newline character, that is, a newline not preceded by carriage
254 /*	return.
255 /* .IP "\fBpostscreen_bare_newline_enable (no)\fR"
256 /*	Enable "bare newline" SMTP protocol tests in the \fBpostscreen\fR(8)
257 /*	server.
258 /* .IP "\fBpostscreen_disable_vrfy_command ($disable_vrfy_command)\fR"
259 /*	Disable the SMTP VRFY command in the \fBpostscreen\fR(8) daemon.
260 /* .IP "\fBpostscreen_forbidden_commands ($smtpd_forbidden_commands)\fR"
261 /*	List of commands that the \fBpostscreen\fR(8) server considers in
262 /*	violation of the SMTP protocol.
263 /* .IP "\fBpostscreen_helo_required ($smtpd_helo_required)\fR"
264 /*	Require that a remote SMTP client sends HELO or EHLO before
265 /*	commencing a MAIL transaction.
266 /* .IP "\fBpostscreen_non_smtp_command_action (drop)\fR"
267 /*	The action that \fBpostscreen\fR(8) takes when a remote SMTP client sends
268 /*	non-SMTP commands as specified with the postscreen_forbidden_commands
269 /*	parameter.
270 /* .IP "\fBpostscreen_non_smtp_command_enable (no)\fR"
271 /*	Enable "non-SMTP command" tests in the \fBpostscreen\fR(8) server.
272 /* .IP "\fBpostscreen_pipelining_action (enforce)\fR"
273 /*	The action that \fBpostscreen\fR(8) takes when a remote SMTP client
274 /*	sends
275 /*	multiple commands instead of sending one command and waiting for
276 /*	the server to respond.
277 /* .IP "\fBpostscreen_pipelining_enable (no)\fR"
278 /*	Enable "pipelining" SMTP protocol tests in the \fBpostscreen\fR(8)
279 /*	server.
280 /* CACHE CONTROLS
281 /* .ad
282 /* .fi
283 /* .IP "\fBpostscreen_cache_cleanup_interval (12h)\fR"
284 /*	The amount of time between \fBpostscreen\fR(8) cache cleanup runs.
285 /* .IP "\fBpostscreen_cache_map (btree:$data_directory/postscreen_cache)\fR"
286 /*	Persistent storage for the \fBpostscreen\fR(8) server decisions.
287 /* .IP "\fBpostscreen_cache_retention_time (7d)\fR"
288 /*	The amount of time that \fBpostscreen\fR(8) will cache an expired
289 /*	temporary allowlist entry before it is removed.
290 /* .IP "\fBpostscreen_bare_newline_ttl (30d)\fR"
291 /*	The amount of time that \fBpostscreen\fR(8) will use the result from
292 /*	a successful "bare newline" SMTP protocol test.
293 /* .IP "\fBpostscreen_dnsbl_max_ttl (${postscreen_dnsbl_ttl?{$postscreen_dnsbl_ttl}:{1}}h)\fR"
294 /*	The maximum amount of time that \fBpostscreen\fR(8) will use the
295 /*	result from a successful DNS-based reputation test before a
296 /*	client IP address is required to pass that test again.
297 /* .IP "\fBpostscreen_dnsbl_min_ttl (60s)\fR"
298 /*	The minimum amount of time that \fBpostscreen\fR(8) will use the
299 /*	result from a successful DNS-based reputation test before a
300 /*	client IP address is required to pass that test again.
301 /* .IP "\fBpostscreen_greet_ttl (1d)\fR"
302 /*	The amount of time that \fBpostscreen\fR(8) will use the result from
303 /*	a successful PREGREET test.
304 /* .IP "\fBpostscreen_non_smtp_command_ttl (30d)\fR"
305 /*	The amount of time that \fBpostscreen\fR(8) will use the result from
306 /*	a successful "non_smtp_command" SMTP protocol test.
307 /* .IP "\fBpostscreen_pipelining_ttl (30d)\fR"
308 /*	The amount of time that \fBpostscreen\fR(8) will use the result from
309 /*	a successful "pipelining" SMTP protocol test.
310 /* RESOURCE CONTROLS
311 /* .ad
312 /* .fi
313 /* .IP "\fBline_length_limit (2048)\fR"
314 /*	Upon input, long lines are chopped up into pieces of at most
315 /*	this length; upon delivery, long lines are reconstructed.
316 /* .IP "\fBpostscreen_client_connection_count_limit ($smtpd_client_connection_count_limit)\fR"
317 /*	How many simultaneous connections any remote SMTP client is
318 /*	allowed to have
319 /*	with the \fBpostscreen\fR(8) daemon.
320 /* .IP "\fBpostscreen_command_count_limit (20)\fR"
321 /*	The limit on the total number of commands per SMTP session for
322 /*	\fBpostscreen\fR(8)'s built-in SMTP protocol engine.
323 /* .IP "\fBpostscreen_command_time_limit (normal: 300s, overload: 10s)\fR"
324 /*	The time limit to read an entire command line with \fBpostscreen\fR(8)'s
325 /*	built-in SMTP protocol engine.
326 /* .IP "\fBpostscreen_post_queue_limit ($default_process_limit)\fR"
327 /*	The number of clients that can be waiting for service from a
328 /*	real Postfix SMTP server process.
329 /* .IP "\fBpostscreen_pre_queue_limit ($default_process_limit)\fR"
330 /*	The number of non-allowlisted clients that can be waiting for
331 /*	a decision whether they will receive service from a real Postfix
332 /*	SMTP server
333 /*	process.
334 /* .IP "\fBpostscreen_watchdog_timeout (10s)\fR"
335 /*	How much time a \fBpostscreen\fR(8) process may take to respond to
336 /*	a remote SMTP client command or to perform a cache operation before it
337 /*	is terminated by a built-in watchdog timer.
338 /* STARTTLS CONTROLS
339 /* .ad
340 /* .fi
341 /* .IP "\fBpostscreen_tls_security_level ($smtpd_tls_security_level)\fR"
342 /*	The SMTP TLS security level for the \fBpostscreen\fR(8) server; when
343 /*	a non-empty value is specified, this overrides the obsolete parameters
344 /*	postscreen_use_tls and postscreen_enforce_tls.
345 /* .IP "\fBtlsproxy_service_name (tlsproxy)\fR"
346 /*	The name of the \fBtlsproxy\fR(8) service entry in master.cf.
347 /* OBSOLETE STARTTLS SUPPORT CONTROLS
348 /* .ad
349 /* .fi
350 /*	These parameters are supported for compatibility with
351 /*	\fBsmtpd\fR(8) legacy parameters.
352 /* .IP "\fBpostscreen_use_tls ($smtpd_use_tls)\fR"
353 /*	Opportunistic TLS: announce STARTTLS support to remote SMTP clients,
354 /*	but do not require that clients use TLS encryption.
355 /* .IP "\fBpostscreen_enforce_tls ($smtpd_enforce_tls)\fR"
356 /*	Mandatory TLS: announce STARTTLS support to remote SMTP clients, and
357 /*	require that clients use TLS encryption.
358 /* MISCELLANEOUS CONTROLS
359 /* .ad
360 /* .fi
361 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
362 /*	The default location of the Postfix main.cf and master.cf
363 /*	configuration files.
364 /* .IP "\fBdelay_logging_resolution_limit (2)\fR"
365 /*	The maximal number of digits after the decimal point when logging
366 /*	sub-second delay values.
367 /* .IP "\fBcommand_directory (see 'postconf -d' output)\fR"
368 /*	The location of all postfix administrative commands.
369 /* .IP "\fBmax_idle (100s)\fR"
370 /*	The maximum amount of time that an idle Postfix daemon process waits
371 /*	for an incoming connection before terminating voluntarily.
372 /* .IP "\fBprocess_id (read-only)\fR"
373 /*	The process ID of a Postfix command or daemon process.
374 /* .IP "\fBprocess_name (read-only)\fR"
375 /*	The process name of a Postfix command or daemon process.
376 /* .IP "\fBsyslog_facility (mail)\fR"
377 /*	The syslog facility of Postfix logging.
378 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
379 /*	A prefix that is prepended to the process name in syslog
380 /*	records, so that, for example, "smtpd" becomes "prefix/smtpd".
381 /* .PP
382 /*	Available in Postfix 3.3 and later:
383 /* .IP "\fBservice_name (read-only)\fR"
384 /*	The master.cf service name of a Postfix daemon process.
385 /* .PP
386 /*	Available in Postfix 3.5 and later:
387 /* .IP "\fBinfo_log_address_format (external)\fR"
388 /*	The email address form that will be used in non-debug logging
389 /*	(info, warning, etc.).
390 /* SEE ALSO
391 /*	smtpd(8), Postfix SMTP server
392 /*	tlsproxy(8), Postfix TLS proxy server
393 /*	dnsblog(8), DNS allow/denylist logger
394 /*	postlogd(8), Postfix logging
395 /*	syslogd(8), system logging
396 /* README FILES
397 /* .ad
398 /* .fi
399 /*	Use "\fBpostconf readme_directory\fR" or "\fBpostconf
400 /*	html_directory\fR" to locate this information.
401 /* .nf
402 /* .na
403 /*	POSTSCREEN_README, Postfix Postscreen Howto
404 /* LICENSE
405 /* .ad
406 /* .fi
407 /*	The Secure Mailer license must be distributed with this software.
408 /* HISTORY
409 /* .ad
410 /* .fi
411 /*	This service was introduced with Postfix version 2.8.
412 /*
413 /*	Many ideas in \fBpostscreen\fR(8) were explored in earlier
414 /*	work by Michael Tokarev, in OpenBSD spamd, and in MailChannels
415 /*	Traffic Control.
416 /* AUTHOR(S)
417 /*	Wietse Venema
418 /*	IBM T.J. Watson Research
419 /*	P.O. Box 704
420 /*	Yorktown Heights, NY 10598, USA
421 /*
422 /*	Wietse Venema
423 /*	Google, Inc.
424 /*	111 8th Avenue
425 /*	New York, NY 10011, USA
426 /*--*/
427 
428 /* System library. */
429 
430 #include <sys_defs.h>
431 #include <sys/stat.h>
432 #include <stdlib.h>
433 
434 /* Utility library. */
435 
436 #include <msg.h>
437 #include <mymalloc.h>
438 #include <events.h>
439 #include <myaddrinfo.h>
440 #include <dict_cache.h>
441 #include <set_eugid.h>
442 #include <vstream.h>
443 #include <name_code.h>
444 #include <inet_proto.h>
445 
446 /* Global library. */
447 
448 #include <mail_conf.h>
449 #include <mail_params.h>
450 #include <mail_version.h>
451 #include <mail_proto.h>
452 #include <data_redirect.h>
453 #include <string_list.h>
454 
455 /* Master server protocols. */
456 
457 #include <mail_server.h>
458 
459 /* Application-specific. */
460 
461 #include <postscreen.h>
462 
463  /*
464   * Configuration parameters.
465   */
466 char   *var_smtpd_service;
467 char   *var_smtpd_banner;
468 bool    var_disable_vrfy_cmd;
469 bool    var_helo_required;
470 
471 char   *var_smtpd_cmd_filter;
472 char   *var_psc_cmd_filter;
473 
474 char   *var_smtpd_forbid_cmds;
475 char   *var_psc_forbid_cmds;
476 
477 char   *var_smtpd_ehlo_dis_words;
478 char   *var_smtpd_ehlo_dis_maps;
479 char   *var_psc_ehlo_dis_words;
480 char   *var_psc_ehlo_dis_maps;
481 
482 char   *var_smtpd_tls_level;
483 bool    var_smtpd_use_tls;
484 bool    var_smtpd_enforce_tls;
485 char   *var_psc_tls_level;
486 bool    var_psc_use_tls;
487 bool    var_psc_enforce_tls;
488 
489 bool    var_psc_disable_vrfy;
490 bool    var_psc_helo_required;
491 
492 char   *var_psc_cache_map;
493 int     var_psc_cache_scan;
494 int     var_psc_cache_ret;
495 int     var_psc_post_queue_limit;
496 int     var_psc_pre_queue_limit;
497 int     var_psc_watchdog;
498 
499 char   *var_psc_acl;
500 char   *var_psc_dnlist_action;
501 
502 char   *var_psc_greet_ttl;
503 int     var_psc_greet_wait;
504 
505 char   *var_psc_pregr_banner;
506 char   *var_psc_pregr_action;
507 int     var_psc_pregr_ttl;
508 
509 char   *var_psc_dnsbl_sites;
510 char   *var_psc_dnsbl_reply;
511 int     var_psc_dnsbl_thresh;
512 int     var_psc_dnsbl_althresh;
513 char   *var_psc_dnsbl_action;
514 int     var_psc_dnsbl_min_ttl;
515 int     var_psc_dnsbl_max_ttl;
516 int     var_psc_dnsbl_tmout;
517 
518 bool    var_psc_pipel_enable;
519 char   *var_psc_pipel_action;
520 int     var_psc_pipel_ttl;
521 
522 bool    var_psc_nsmtp_enable;
523 char   *var_psc_nsmtp_action;
524 int     var_psc_nsmtp_ttl;
525 
526 bool    var_psc_barlf_enable;
527 char   *var_psc_barlf_action;
528 int     var_psc_barlf_ttl;
529 
530 int     var_psc_cmd_count;
531 int     var_psc_cmd_time;
532 
533 char   *var_dnsblog_service;
534 char   *var_tlsproxy_service;
535 
536 char   *var_smtpd_rej_footer;
537 char   *var_psc_rej_footer;
538 char   *var_psc_rej_ftr_maps;
539 
540 int     var_smtpd_cconn_limit;
541 int     var_psc_cconn_limit;
542 
543 char   *var_smtpd_exp_filter;
544 char   *var_psc_exp_filter;
545 
546 char   *var_psc_allist_if;
547 char   *var_psc_uproxy_proto;
548 int     var_psc_uproxy_tmout;
549 
550  /*
551   * Global variables.
552   */
553 int     psc_check_queue_length;		/* connections being checked */
554 int     psc_post_queue_length;		/* being sent to real SMTPD */
555 DICT_CACHE *psc_cache_map;		/* cache table handle */
556 VSTRING *psc_temp;			/* scratchpad */
557 char   *psc_smtpd_service_name;		/* path to real SMTPD */
558 int     psc_pregr_action;		/* PSC_ACT_DROP/ENFORCE/etc */
559 int     psc_dnsbl_action;		/* PSC_ACT_DROP/ENFORCE/etc */
560 int     psc_pipel_action;		/* PSC_ACT_DROP/ENFORCE/etc */
561 int     psc_nsmtp_action;		/* PSC_ACT_DROP/ENFORCE/etc */
562 int     psc_barlf_action;		/* PSC_ACT_DROP/ENFORCE/etc */
563 int     psc_min_ttl;			/* Update with new tests! */
564 STRING_LIST *psc_forbid_cmds;		/* CONNECT GET POST */
565 int     psc_stress_greet_wait;		/* stressed greet wait */
566 int     psc_normal_greet_wait;		/* stressed greet wait */
567 int     psc_stress_cmd_time_limit;	/* stressed command limit */
568 int     psc_normal_cmd_time_limit;	/* normal command time limit */
569 int     psc_stress;			/* stress level */
570 int     psc_lowat_check_queue_length;	/* stress low-water mark */
571 int     psc_hiwat_check_queue_length;	/* stress high-water mark */
572 DICT   *psc_dnsbl_reply;		/* DNSBL name mapper */
573 HTABLE *psc_client_concurrency;		/* per-client concurrency */
574 
575  /*
576   * Local variables and functions.
577   */
578 static ARGV *psc_acl;			/* permanent allow/denylist */
579 static int psc_dnlist_action;		/* PSC_ACT_DROP/ENFORCE/etc */
580 static ADDR_MATCH_LIST *psc_allist_if;	/* allowlist interfaces */
581 
582 static void psc_endpt_lookup_done(int, VSTREAM *,
583 			             MAI_HOSTADDR_STR *, MAI_SERVPORT_STR *,
584 			            MAI_HOSTADDR_STR *, MAI_SERVPORT_STR *);
585 
586 /* psc_dump - dump some statistics before exit */
587 
psc_dump(char * unused_service,char ** unused_argv)588 static void psc_dump(char *unused_service, char **unused_argv)
589 {
590 
591     /*
592      * Dump preliminary cache cleanup statistics when the process commits
593      * suicide while a cache cleanup run is in progress. We can't currently
594      * distinguish between "postfix reload" (we should restart) or "maximal
595      * idle time reached" (we could finish the cache cleanup first).
596      */
597     if (psc_cache_map) {
598 	dict_cache_close(psc_cache_map);
599 	psc_cache_map = 0;
600     }
601 }
602 
603 /* psc_drain - delayed exit after "postfix reload" */
604 
psc_drain(char * unused_service,char ** unused_argv)605 static void psc_drain(char *unused_service, char **unused_argv)
606 {
607     int     count;
608 
609     /*
610      * After "postfix reload", complete work-in-progress in the background,
611      * instead of dropping already-accepted connections on the floor.
612      *
613      * Unfortunately we must close all writable tables, so we can't store or
614      * look up reputation information. The reason is that we don't have any
615      * multi-writer safety guarantees. We also can't use the single-writer
616      * proxywrite service, because its latency guarantees are too weak.
617      *
618      * All error retry counts shall be limited. Instead of blocking here, we
619      * could retry failed fork() operations in the event call-back routines,
620      * but we don't need perfection. The host system is severely overloaded
621      * and service levels are already way down.
622      *
623      * XXX Some Berkeley DB versions break with close-after-fork. Every new
624      * version is an improvement over its predecessor.
625      *
626      * XXX Don't assume that it is OK to share the same LMDB lockfile descriptor
627      * between different processes.
628      */
629     if (psc_cache_map != 0			/* XXX && psc_cache_map
630 	    requires locking */ ) {
631 	dict_cache_close(psc_cache_map);
632 	psc_cache_map = 0;
633     }
634     for (count = 0; /* see below */ ; count++) {
635 	if (count >= 5) {
636 	    msg_fatal("fork: %m");
637 	} else if (event_server_drain() != 0) {
638 	    msg_warn("fork: %m");
639 	    sleep(1);
640 	    continue;
641 	} else {
642 	    return;
643 	}
644     }
645 }
646 
647 /* psc_service - handle new client connection */
648 
psc_service(VSTREAM * smtp_client_stream,char * unused_service,char ** unused_argv)649 static void psc_service(VSTREAM *smtp_client_stream,
650 			        char *unused_service,
651 			        char **unused_argv)
652 {
653 
654     /*
655      * For sanity, require that at least one of INET or INET6 is enabled.
656      * Otherwise, we can't look up interface information, and we can't
657      * convert names or addresses.
658      */
659     if (inet_proto_info()->ai_family_list[0] == 0)
660 	msg_fatal("all network protocols are disabled (%s = %s)",
661 		  VAR_INET_PROTOCOLS, var_inet_protocols);
662 
663     /*
664      * This program handles all incoming connections, so it must not block.
665      * We use event-driven code for all operations that introduce latency.
666      *
667      * Note: instead of using VSTREAM-level timeouts, we enforce limits on the
668      * total amount of time to receive a complete SMTP command line.
669      */
670     non_blocking(vstream_fileno(smtp_client_stream), NON_BLOCKING);
671 
672     /*
673      * Look up the remote SMTP client address and port.
674      */
675     psc_endpt_lookup(smtp_client_stream, psc_endpt_lookup_done);
676 }
677 
678 /* psc_warn_compat_respectful_logging - compatibility warning */
679 
psc_warn_compat_respectful_logging(PSC_STATE * state)680 static void psc_warn_compat_respectful_logging(PSC_STATE *state)
681 {
682     msg_info("using backwards-compatible default setting "
683 	     VAR_RESPECTFUL_LOGGING "=no for client [%s]:%s",
684 	     PSC_CLIENT_ADDR_PORT(state));
685     warn_compat_respectful_logging = 0;
686 }
687 
688 /* psc_endpt_lookup_done - endpoint lookup completed */
689 
psc_endpt_lookup_done(int endpt_status,VSTREAM * smtp_client_stream,MAI_HOSTADDR_STR * smtp_client_addr,MAI_SERVPORT_STR * smtp_client_port,MAI_HOSTADDR_STR * smtp_server_addr,MAI_SERVPORT_STR * smtp_server_port)690 static void psc_endpt_lookup_done(int endpt_status,
691 				          VSTREAM *smtp_client_stream,
692 				          MAI_HOSTADDR_STR *smtp_client_addr,
693 				          MAI_SERVPORT_STR *smtp_client_port,
694 				          MAI_HOSTADDR_STR *smtp_server_addr,
695 				          MAI_SERVPORT_STR *smtp_server_port)
696 {
697     const char *myname = "psc_endpt_lookup_done";
698     PSC_STATE *state;
699     const char *stamp_str;
700     int     saved_flags;
701 
702     /*
703      * Best effort - if this non-blocking write(2) fails, so be it.
704      */
705     if (endpt_status < 0) {
706 	(void) write(vstream_fileno(smtp_client_stream),
707 		     "421 4.3.2 No system resources\r\n",
708 		     sizeof("421 4.3.2 No system resources\r\n") - 1);
709 	event_server_disconnect(smtp_client_stream);
710 	return;
711     }
712     if (msg_verbose > 1)
713 	msg_info("%s: sq=%d cq=%d connect from [%s]:%s",
714 		 myname, psc_post_queue_length, psc_check_queue_length,
715 		 smtp_client_addr->buf, smtp_client_port->buf);
716 
717     msg_info("CONNECT from [%s]:%s to [%s]:%s",
718 	     smtp_client_addr->buf, smtp_client_port->buf,
719 	     smtp_server_addr->buf, smtp_server_port->buf);
720 
721     /*
722      * Bundle up all the loose session pieces. This zeroes all flags and time
723      * stamps.
724      */
725     state = psc_new_session_state(smtp_client_stream, smtp_client_addr->buf,
726 				  smtp_client_port->buf,
727 				  smtp_server_addr->buf,
728 				  smtp_server_port->buf);
729 
730     /*
731      * Reply with 421 when the client has too many open connections.
732      */
733     if (var_psc_cconn_limit > 0
734 	&& state->client_info->concurrency > var_psc_cconn_limit) {
735 	msg_info("NOQUEUE: reject: CONNECT from [%s]:%s: too many connections",
736 		 state->smtp_client_addr, state->smtp_client_port);
737 	PSC_DROP_SESSION_STATE(state,
738 			       "421 4.7.0 Error: too many connections\r\n");
739 	return;
740     }
741 
742     /*
743      * Reply with 421 when we can't forward more connections.
744      */
745     if (var_psc_post_queue_limit > 0
746 	&& psc_post_queue_length >= var_psc_post_queue_limit) {
747 	msg_info("NOQUEUE: reject: CONNECT from [%s]:%s: all server ports busy",
748 		 state->smtp_client_addr, state->smtp_client_port);
749 	PSC_DROP_SESSION_STATE(state,
750 			       "421 4.3.2 All server ports are busy\r\n");
751 	return;
752     }
753 
754     /*
755      * The permanent allow/denylist has highest precedence.
756      */
757     if (psc_acl != 0) {
758 	switch (psc_acl_eval(state, psc_acl, VAR_PSC_ACL)) {
759 
760 	    /*
761 	     * Permanently denylisted.
762 	     */
763 	case PSC_ACL_ACT_DENYLIST:
764 	    msg_info("%sLISTED [%s]:%s",
765 		     var_respectful_logging ? "DENY" : "BLACK",
766 		     PSC_CLIENT_ADDR_PORT(state));
767 	    if (warn_compat_respectful_logging)
768 		psc_warn_compat_respectful_logging(state);
769 	    PSC_FAIL_SESSION_STATE(state, PSC_STATE_FLAG_DNLIST_FAIL);
770 	    switch (psc_dnlist_action) {
771 	    case PSC_ACT_DROP:
772 		PSC_DROP_SESSION_STATE(state,
773 			     "521 5.3.2 Service currently unavailable\r\n");
774 		return;
775 	    case PSC_ACT_ENFORCE:
776 		PSC_ENFORCE_SESSION_STATE(state,
777 			     "550 5.3.2 Service currently unavailable\r\n");
778 		break;
779 	    case PSC_ACT_IGNORE:
780 		PSC_UNFAIL_SESSION_STATE(state, PSC_STATE_FLAG_DNLIST_FAIL);
781 
782 		/*
783 		 * Not: PSC_PASS_SESSION_STATE. Repeat this test the next
784 		 * time.
785 		 */
786 		break;
787 	    default:
788 		msg_panic("%s: unknown denylist action value %d",
789 			  myname, psc_dnlist_action);
790 	    }
791 	    break;
792 
793 	    /*
794 	     * Permanently allowlisted.
795 	     */
796 	case PSC_ACL_ACT_ALLOWLIST:
797 	    msg_info("%sLISTED [%s]:%s",
798 		     var_respectful_logging ? "ALLOW" : "WHITE",
799 		     PSC_CLIENT_ADDR_PORT(state));
800 	    if (warn_compat_respectful_logging)
801 		psc_warn_compat_respectful_logging(state);
802 	    psc_conclude(state);
803 	    return;
804 
805 	    /*
806 	     * Other: dunno (don't know) or error.
807 	     */
808 	default:
809 	    break;
810 	}
811     }
812 
813     /*
814      * The temporary allowlist (i.e. the postscreen cache) has the lowest
815      * precedence. This cache contains information about the results of prior
816      * tests. Allowlist the client when all enabled test results are still
817      * valid.
818      */
819     if ((state->flags & PSC_STATE_MASK_ANY_FAIL) == 0
820 	&& state->client_info->concurrency == 1
821 	&& psc_cache_map != 0
822 	&& (stamp_str = psc_cache_lookup(psc_cache_map, state->smtp_client_addr)) != 0) {
823 	saved_flags = state->flags;
824 	psc_parse_tests(state, stamp_str, event_time());
825 	state->flags |= saved_flags;
826 	if (msg_verbose)
827 	    msg_info("%s: cached + recent flags: %s",
828 		     myname, psc_print_state_flags(state->flags, myname));
829 	if ((state->flags & PSC_STATE_MASK_ANY_TODO_FAIL) == 0) {
830 	    msg_info("PASS OLD [%s]:%s", PSC_CLIENT_ADDR_PORT(state));
831 	    psc_conclude(state);
832 	    return;
833 	}
834     } else if (state->client_info->concurrency > 1) {
835 	saved_flags = state->flags;
836 	psc_todo_tests(state, event_time());
837 	state->flags |= saved_flags;
838 	if (msg_verbose)
839 	    msg_info("%s: new + recent flags: %s",
840 		     myname, psc_print_state_flags(state->flags, myname));
841     } else {
842 	saved_flags = state->flags;
843 	psc_new_tests(state);
844 	state->flags |= saved_flags;
845 	if (msg_verbose)
846 	    msg_info("%s: new + recent flags: %s",
847 		     myname, psc_print_state_flags(state->flags, myname));
848     }
849 
850     /*
851      * Don't allowlist clients that connect to backup MX addresses. Fail
852      * "closed" on error.
853      */
854     if (addr_match_list_match(psc_allist_if, smtp_server_addr->buf) == 0) {
855 	state->flags |= (PSC_STATE_FLAG_ALLIST_FAIL | PSC_STATE_FLAG_NOFORWARD);
856 	msg_info("%sLIST VETO [%s]:%s", var_respectful_logging ?
857 		 "ALLOW" : "WHITE", PSC_CLIENT_ADDR_PORT(state));
858 	if (warn_compat_respectful_logging)
859 	    psc_warn_compat_respectful_logging(state);
860     }
861 
862     /*
863      * Reply with 421 when we can't analyze more connections. That also means
864      * no deep protocol tests when the noforward flag is raised.
865      */
866     if (var_psc_pre_queue_limit > 0
867 	&& psc_check_queue_length - psc_post_queue_length
868 	>= var_psc_pre_queue_limit) {
869 	msg_info("reject: connect from [%s]:%s: all screening ports busy",
870 		 state->smtp_client_addr, state->smtp_client_port);
871 	PSC_DROP_SESSION_STATE(state,
872 			       "421 4.3.2 All screening ports are busy\r\n");
873 	return;
874     }
875 
876     /*
877      * If the client has no up-to-date results for some tests, do those tests
878      * first. Otherwise, skip the tests and hand off the connection.
879      */
880     if (state->flags & PSC_STATE_MASK_EARLY_TODO)
881 	psc_early_tests(state);
882     else if (state->flags & (PSC_STATE_MASK_SMTPD_TODO | PSC_STATE_FLAG_NOFORWARD))
883 	psc_smtpd_tests(state);
884     else
885 	psc_conclude(state);
886 }
887 
888 /* psc_cache_validator - validate one cache entry */
889 
psc_cache_validator(const char * client_addr,const char * stamp_str,void * unused_context)890 static int psc_cache_validator(const char *client_addr,
891 			               const char *stamp_str,
892 			               void *unused_context)
893 {
894     PSC_STATE dummy_state;
895     PSC_CLIENT_INFO dummy_client_info;
896 
897     /*
898      * This function is called by the cache cleanup pseudo thread.
899      *
900      * When an entry is removed from the cache, the client will be reported as
901      * "NEW" in the next session where it passes all tests again. To avoid
902      * silly logging we remove the cache entry only after all tests have
903      * expired longer ago than the cache retention time.
904      */
905     dummy_state.client_info = &dummy_client_info;
906     psc_parse_tests(&dummy_state, stamp_str, event_time() - var_psc_cache_ret);
907     return ((dummy_state.flags & PSC_STATE_MASK_ANY_TODO) == 0);
908 }
909 
910 /* pre_jail_init - pre-jail initialization */
911 
pre_jail_init(char * unused_name,char ** unused_argv)912 static void pre_jail_init(char *unused_name, char **unused_argv)
913 {
914     VSTRING *redirect;
915 
916     /*
917      * Open read-only maps before dropping privilege, for consistency with
918      * other Postfix daemons.
919      */
920     psc_acl_pre_jail_init(var_mynetworks, VAR_PSC_ACL);
921     if (*var_psc_acl)
922 	psc_acl = psc_acl_parse(var_psc_acl, VAR_PSC_ACL);
923     /* Ignore smtpd_forbid_cmds lookup errors. Non-critical feature. */
924     if (*var_psc_forbid_cmds)
925 	psc_forbid_cmds = string_list_init(VAR_PSC_FORBID_CMDS,
926 					   MATCH_FLAG_RETURN,
927 					   var_psc_forbid_cmds);
928     if (*var_psc_dnsbl_reply)
929 	psc_dnsbl_reply = dict_open(var_psc_dnsbl_reply, O_RDONLY,
930 				    DICT_FLAG_DUP_WARN);
931 
932     /*
933      * Never, ever, get killed by a master signal, as that would corrupt the
934      * database when we're in the middle of an update.
935      */
936     if (setsid() < 0)
937 	msg_warn("setsid: %m");
938 
939     /*
940      * Security: don't create root-owned files that contain untrusted data.
941      * And don't create Postfix-owned files in root-owned directories,
942      * either. We want a correct relationship between (file or directory)
943      * ownership and (file or directory) content. To open files before going
944      * to jail, temporarily drop root privileges.
945      */
946     SAVE_AND_SET_EUGID(var_owner_uid, var_owner_gid);
947     redirect = vstring_alloc(100);
948 
949     /*
950      * Keep state in persistent external map. As a safety measure we sync the
951      * database on each update. This hurts on LINUX file systems that sync
952      * all dirty disk blocks whenever any application invokes fsync().
953      *
954      * Start the cache maintenance pseudo thread after dropping privileges.
955      */
956 #define PSC_DICT_OPEN_FLAGS (DICT_FLAG_DUP_REPLACE | DICT_FLAG_SYNC_UPDATE | \
957 	    DICT_FLAG_OPEN_LOCK)
958 
959     if (*var_psc_cache_map)
960 	psc_cache_map =
961 	    dict_cache_open(data_redirect_map(redirect, var_psc_cache_map),
962 			    O_CREAT | O_RDWR, PSC_DICT_OPEN_FLAGS);
963 
964     /*
965      * Clean up and restore privilege.
966      */
967     vstring_free(redirect);
968     RESTORE_SAVED_EUGID();
969 
970     /*
971      * Initialize the dummy SMTP engine.
972      */
973     psc_smtpd_pre_jail_init();
974 }
975 
976 /* pre_accept - see if tables have changed */
977 
pre_accept(char * unused_name,char ** unused_argv)978 static void pre_accept(char *unused_name, char **unused_argv)
979 {
980     static time_t last_event_time;
981     time_t  new_event_time;
982     const char *name;
983 
984     /*
985      * If some table has changed then stop accepting new connections. Don't
986      * check the tables more than once a second.
987      */
988     new_event_time = event_time();
989     if (new_event_time >= last_event_time + 1
990 	&& (name = dict_changed_name()) != 0) {
991 	msg_info("table %s has changed - finishing in the background", name);
992 	event_server_drain();
993     } else {
994 	last_event_time = new_event_time;
995     }
996 }
997 
998 /* post_jail_init - post-jail initialization */
999 
post_jail_init(char * unused_name,char ** unused_argv)1000 static void post_jail_init(char *unused_name, char **unused_argv)
1001 {
1002     const NAME_CODE actions[] = {
1003 	PSC_NAME_ACT_DROP, PSC_ACT_DROP,
1004 	PSC_NAME_ACT_ENFORCE, PSC_ACT_ENFORCE,
1005 	PSC_NAME_ACT_IGNORE, PSC_ACT_IGNORE,
1006 	PSC_NAME_ACT_CONT, PSC_ACT_IGNORE,	/* compatibility */
1007 	0, -1,
1008     };
1009     int     cache_flags;
1010     const char *tmp;
1011 
1012     /*
1013      * This routine runs after the skeleton code has entered the chroot jail.
1014      * Prevent automatic process suicide after a limited number of client
1015      * requests. It is OK to terminate after a limited amount of idle time.
1016      */
1017     var_use_limit = 0;
1018 
1019     /*
1020      * Workaround for parameters whose values may contain "$", and that have
1021      * a default of "$parametername". Not sure if it would be a good idea to
1022      * always to this in the mail_conf_raw(3) module.
1023      */
1024     if (*var_psc_rej_footer == '$'
1025 	&& mail_conf_lookup(var_psc_rej_footer + 1)) {
1026 	tmp = mail_conf_eval_once(var_psc_rej_footer);
1027 	myfree(var_psc_rej_footer);
1028 	var_psc_rej_footer = mystrdup(tmp);
1029     }
1030     if (*var_psc_exp_filter == '$'
1031 	&& mail_conf_lookup(var_psc_exp_filter + 1)) {
1032 	tmp = mail_conf_eval_once(var_psc_exp_filter);
1033 	myfree(var_psc_exp_filter);
1034 	var_psc_exp_filter = mystrdup(tmp);
1035     }
1036 
1037     /*
1038      * Other one-time initialization.
1039      */
1040     psc_temp = vstring_alloc(10);
1041     vstring_sprintf(psc_temp, "%s/%s", MAIL_CLASS_PRIVATE, var_smtpd_service);
1042     psc_smtpd_service_name = mystrdup(STR(psc_temp));
1043     psc_dnsbl_init();
1044     psc_early_init();
1045     psc_smtpd_init();
1046 
1047     if ((psc_dnlist_action = name_code(actions, NAME_CODE_FLAG_NONE,
1048 				       var_psc_dnlist_action)) < 0)
1049 	msg_fatal("bad %s value: %s", VAR_PSC_DNLIST_ACTION,
1050 		  var_psc_dnlist_action);
1051     if ((psc_dnsbl_action = name_code(actions, NAME_CODE_FLAG_NONE,
1052 				      var_psc_dnsbl_action)) < 0)
1053 	msg_fatal("bad %s value: %s", VAR_PSC_DNSBL_ACTION,
1054 		  var_psc_dnsbl_action);
1055     if ((psc_pregr_action = name_code(actions, NAME_CODE_FLAG_NONE,
1056 				      var_psc_pregr_action)) < 0)
1057 	msg_fatal("bad %s value: %s", VAR_PSC_PREGR_ACTION,
1058 		  var_psc_pregr_action);
1059     if ((psc_pipel_action = name_code(actions, NAME_CODE_FLAG_NONE,
1060 				      var_psc_pipel_action)) < 0)
1061 	msg_fatal("bad %s value: %s", VAR_PSC_PIPEL_ACTION,
1062 		  var_psc_pipel_action);
1063     if ((psc_nsmtp_action = name_code(actions, NAME_CODE_FLAG_NONE,
1064 				      var_psc_nsmtp_action)) < 0)
1065 	msg_fatal("bad %s value: %s", VAR_PSC_NSMTP_ACTION,
1066 		  var_psc_nsmtp_action);
1067     if ((psc_barlf_action = name_code(actions, NAME_CODE_FLAG_NONE,
1068 				      var_psc_barlf_action)) < 0)
1069 	msg_fatal("bad %s value: %s", VAR_PSC_BARLF_ACTION,
1070 		  var_psc_barlf_action);
1071     /* Fail "closed" on error. */
1072     psc_allist_if = addr_match_list_init(VAR_PSC_ALLIST_IF, MATCH_FLAG_RETURN,
1073 					 var_psc_allist_if);
1074 
1075     /*
1076      * Start the cache maintenance pseudo thread last. Early cleanup makes
1077      * verbose logging more informative (we get positive confirmation that
1078      * the cleanup thread runs).
1079      */
1080     cache_flags = DICT_CACHE_FLAG_STATISTICS;
1081     if (msg_verbose > 1)
1082 	cache_flags |= DICT_CACHE_FLAG_VERBOSE;
1083     if (psc_cache_map != 0 && var_psc_cache_scan > 0)
1084 	dict_cache_control(psc_cache_map,
1085 			   CA_DICT_CACHE_CTL_FLAGS(cache_flags),
1086 			   CA_DICT_CACHE_CTL_INTERVAL(var_psc_cache_scan),
1087 			   CA_DICT_CACHE_CTL_VALIDATOR(psc_cache_validator),
1088 			   CA_DICT_CACHE_CTL_CONTEXT((void *) 0),
1089 			   CA_DICT_CACHE_CTL_END);
1090 
1091     /*
1092      * Pre-compute the minimal and maximal TTL.
1093      */
1094     psc_min_ttl =
1095 	PSC_MIN(PSC_MIN(var_psc_pregr_ttl, var_psc_dnsbl_min_ttl),
1096 		PSC_MIN(PSC_MIN(var_psc_pipel_ttl, var_psc_nsmtp_ttl),
1097 			var_psc_barlf_ttl));
1098 
1099     /*
1100      * Pre-compute the stress and normal command time limits.
1101      */
1102     mail_conf_update(VAR_STRESS, "yes");
1103     psc_stress_cmd_time_limit =
1104 	get_mail_conf_time(VAR_PSC_CMD_TIME, DEF_PSC_CMD_TIME, 1, 0);
1105     psc_stress_greet_wait =
1106 	get_mail_conf_time(VAR_PSC_GREET_WAIT, DEF_PSC_GREET_WAIT, 1, 0);
1107 
1108     mail_conf_update(VAR_STRESS, "");
1109     psc_normal_cmd_time_limit =
1110 	get_mail_conf_time(VAR_PSC_CMD_TIME, DEF_PSC_CMD_TIME, 1, 0);
1111     psc_normal_greet_wait =
1112 	get_mail_conf_time(VAR_PSC_GREET_WAIT, DEF_PSC_GREET_WAIT, 1, 0);
1113 
1114     psc_lowat_check_queue_length = .7 * var_psc_pre_queue_limit;
1115     psc_hiwat_check_queue_length = .9 * var_psc_pre_queue_limit;
1116     if (msg_verbose)
1117 	msg_info(VAR_PSC_CMD_TIME ": stress=%d normal=%d lowat=%d hiwat=%d",
1118 		 psc_stress_cmd_time_limit, psc_normal_cmd_time_limit,
1119 		 psc_lowat_check_queue_length, psc_hiwat_check_queue_length);
1120 
1121     if (psc_lowat_check_queue_length == 0)
1122 	msg_panic("compiler error: 0.7 * %d = %d", var_psc_pre_queue_limit,
1123 		  psc_lowat_check_queue_length);
1124     if (psc_hiwat_check_queue_length == 0)
1125 	msg_panic("compiler error: 0.9 * %d = %d", var_psc_pre_queue_limit,
1126 		  psc_hiwat_check_queue_length);
1127 
1128     /*
1129      * Per-client concurrency.
1130      */
1131     psc_client_concurrency = htable_create(var_psc_pre_queue_limit);
1132 }
1133 
1134 MAIL_VERSION_STAMP_DECLARE;
1135 
1136 /* main - pass control to the multi-threaded skeleton */
1137 
main(int argc,char ** argv)1138 int     main(int argc, char **argv)
1139 {
1140 
1141     /*
1142      * List smtpd(8) parameters before any postscreen(8) parameters that have
1143      * defaults dependencies on them.
1144      */
1145     static const CONFIG_STR_TABLE str_table[] = {
1146 	VAR_SMTPD_SERVICE, DEF_SMTPD_SERVICE, &var_smtpd_service, 1, 0,
1147 	VAR_SMTPD_BANNER, DEF_SMTPD_BANNER, &var_smtpd_banner, 1, 0,
1148 	VAR_SMTPD_FORBID_CMDS, DEF_SMTPD_FORBID_CMDS, &var_smtpd_forbid_cmds, 0, 0,
1149 	VAR_SMTPD_EHLO_DIS_WORDS, DEF_SMTPD_EHLO_DIS_WORDS, &var_smtpd_ehlo_dis_words, 0, 0,
1150 	VAR_SMTPD_EHLO_DIS_MAPS, DEF_SMTPD_EHLO_DIS_MAPS, &var_smtpd_ehlo_dis_maps, 0, 0,
1151 	VAR_SMTPD_TLS_LEVEL, DEF_SMTPD_TLS_LEVEL, &var_smtpd_tls_level, 0, 0,
1152 	VAR_SMTPD_CMD_FILTER, DEF_SMTPD_CMD_FILTER, &var_smtpd_cmd_filter, 0, 0,
1153 	VAR_PSC_CACHE_MAP, DEF_PSC_CACHE_MAP, &var_psc_cache_map, 0, 0,
1154 	VAR_PSC_PREGR_BANNER, DEF_PSC_PREGR_BANNER, &var_psc_pregr_banner, 0, 0,
1155 	VAR_PSC_PREGR_ACTION, DEF_PSC_PREGR_ACTION, &var_psc_pregr_action, 1, 0,
1156 	VAR_PSC_DNSBL_SITES, DEF_PSC_DNSBL_SITES, &var_psc_dnsbl_sites, 0, 0,
1157 	VAR_PSC_DNSBL_ACTION, DEF_PSC_DNSBL_ACTION, &var_psc_dnsbl_action, 1, 0,
1158 	VAR_PSC_PIPEL_ACTION, DEF_PSC_PIPEL_ACTION, &var_psc_pipel_action, 1, 0,
1159 	VAR_PSC_NSMTP_ACTION, DEF_PSC_NSMTP_ACTION, &var_psc_nsmtp_action, 1, 0,
1160 	VAR_PSC_BARLF_ACTION, DEF_PSC_BARLF_ACTION, &var_psc_barlf_action, 1, 0,
1161 	VAR_PSC_ACL, DEF_PSC_ACL, &var_psc_acl, 0, 0,
1162 	VAR_PSC_DNLIST_ACTION, DEF_PSC_DNLIST_ACTION, &var_psc_dnlist_action, 1, 0,
1163 	VAR_PSC_FORBID_CMDS, DEF_PSC_FORBID_CMDS, &var_psc_forbid_cmds, 0, 0,
1164 	VAR_PSC_EHLO_DIS_WORDS, DEF_PSC_EHLO_DIS_WORDS, &var_psc_ehlo_dis_words, 0, 0,
1165 	VAR_PSC_EHLO_DIS_MAPS, DEF_PSC_EHLO_DIS_MAPS, &var_psc_ehlo_dis_maps, 0, 0,
1166 	VAR_PSC_DNSBL_REPLY, DEF_PSC_DNSBL_REPLY, &var_psc_dnsbl_reply, 0, 0,
1167 	VAR_PSC_TLS_LEVEL, DEF_PSC_TLS_LEVEL, &var_psc_tls_level, 0, 0,
1168 	VAR_PSC_CMD_FILTER, DEF_PSC_CMD_FILTER, &var_psc_cmd_filter, 0, 0,
1169 	VAR_DNSBLOG_SERVICE, DEF_DNSBLOG_SERVICE, &var_dnsblog_service, 1, 0,
1170 	VAR_TLSPROXY_SERVICE, DEF_TLSPROXY_SERVICE, &var_tlsproxy_service, 1, 0,
1171 	VAR_PSC_ALLIST_IF, DEF_PSC_ALLIST_IF, &var_psc_allist_if, 0, 0,
1172 	VAR_PSC_UPROXY_PROTO, DEF_PSC_UPROXY_PROTO, &var_psc_uproxy_proto, 0, 0,
1173 	VAR_PSC_REJ_FTR_MAPS, DEF_PSC_REJ_FTR_MAPS, &var_psc_rej_ftr_maps, 0, 0,
1174 	0,
1175     };
1176     static const CONFIG_INT_TABLE int_table[] = {
1177 	VAR_PSC_DNSBL_THRESH, DEF_PSC_DNSBL_THRESH, &var_psc_dnsbl_thresh, 0, 0,
1178 	VAR_PSC_CMD_COUNT, DEF_PSC_CMD_COUNT, &var_psc_cmd_count, 1, 0,
1179 	VAR_SMTPD_CCONN_LIMIT, DEF_SMTPD_CCONN_LIMIT, &var_smtpd_cconn_limit, 0, 0,
1180 	0,
1181     };
1182     static const CONFIG_NINT_TABLE nint_table[] = {
1183 	VAR_PSC_POST_QLIMIT, DEF_PSC_POST_QLIMIT, &var_psc_post_queue_limit, 5, 0,
1184 	VAR_PSC_PRE_QLIMIT, DEF_PSC_PRE_QLIMIT, &var_psc_pre_queue_limit, 10, 0,
1185 	VAR_PSC_CCONN_LIMIT, DEF_PSC_CCONN_LIMIT, &var_psc_cconn_limit, 0, 0,
1186 	VAR_PSC_DNSBL_ALTHRESH, DEF_PSC_DNSBL_ALTHRESH, &var_psc_dnsbl_althresh, 0, 0,
1187 	0,
1188     };
1189     static const CONFIG_TIME_TABLE time_table[] = {
1190 	VAR_PSC_CMD_TIME, DEF_PSC_CMD_TIME, &var_psc_cmd_time, 1, 0,
1191 	VAR_PSC_GREET_WAIT, DEF_PSC_GREET_WAIT, &var_psc_greet_wait, 1, 0,
1192 	VAR_PSC_PREGR_TTL, DEF_PSC_PREGR_TTL, &var_psc_pregr_ttl, 1, 0,
1193 	VAR_PSC_DNSBL_MIN_TTL, DEF_PSC_DNSBL_MIN_TTL, &var_psc_dnsbl_min_ttl, 1, 0,
1194 	VAR_PSC_DNSBL_MAX_TTL, DEF_PSC_DNSBL_MAX_TTL, &var_psc_dnsbl_max_ttl, 1, 0,
1195 	VAR_PSC_PIPEL_TTL, DEF_PSC_PIPEL_TTL, &var_psc_pipel_ttl, 1, 0,
1196 	VAR_PSC_NSMTP_TTL, DEF_PSC_NSMTP_TTL, &var_psc_nsmtp_ttl, 1, 0,
1197 	VAR_PSC_BARLF_TTL, DEF_PSC_BARLF_TTL, &var_psc_barlf_ttl, 1, 0,
1198 	VAR_PSC_CACHE_RET, DEF_PSC_CACHE_RET, &var_psc_cache_ret, 1, 0,
1199 	VAR_PSC_CACHE_SCAN, DEF_PSC_CACHE_SCAN, &var_psc_cache_scan, 0, 0,
1200 	VAR_PSC_WATCHDOG, DEF_PSC_WATCHDOG, &var_psc_watchdog, 10, 0,
1201 	VAR_PSC_UPROXY_TMOUT, DEF_PSC_UPROXY_TMOUT, &var_psc_uproxy_tmout, 1, 0,
1202 	VAR_PSC_DNSBL_TMOUT, DEF_PSC_DNSBL_TMOUT, &var_psc_dnsbl_tmout, 1, 0,
1203 
1204 	0,
1205     };
1206     static const CONFIG_BOOL_TABLE bool_table[] = {
1207 	VAR_HELO_REQUIRED, DEF_HELO_REQUIRED, &var_helo_required,
1208 	VAR_DISABLE_VRFY_CMD, DEF_DISABLE_VRFY_CMD, &var_disable_vrfy_cmd,
1209 	VAR_SMTPD_USE_TLS, DEF_SMTPD_USE_TLS, &var_smtpd_use_tls,
1210 	VAR_SMTPD_ENFORCE_TLS, DEF_SMTPD_ENFORCE_TLS, &var_smtpd_enforce_tls,
1211 	VAR_PSC_PIPEL_ENABLE, DEF_PSC_PIPEL_ENABLE, &var_psc_pipel_enable,
1212 	VAR_PSC_NSMTP_ENABLE, DEF_PSC_NSMTP_ENABLE, &var_psc_nsmtp_enable,
1213 	VAR_PSC_BARLF_ENABLE, DEF_PSC_BARLF_ENABLE, &var_psc_barlf_enable,
1214 	0,
1215     };
1216     static const CONFIG_RAW_TABLE raw_table[] = {
1217 	VAR_SMTPD_REJ_FOOTER, DEF_SMTPD_REJ_FOOTER, &var_smtpd_rej_footer, 0, 0,
1218 	VAR_PSC_REJ_FOOTER, DEF_PSC_REJ_FOOTER, &var_psc_rej_footer, 0, 0,
1219 	VAR_SMTPD_EXP_FILTER, DEF_SMTPD_EXP_FILTER, &var_smtpd_exp_filter, 1, 0,
1220 	VAR_PSC_EXP_FILTER, DEF_PSC_EXP_FILTER, &var_psc_exp_filter, 1, 0,
1221 	0,
1222     };
1223     static const CONFIG_NBOOL_TABLE nbool_table[] = {
1224 	VAR_PSC_HELO_REQUIRED, DEF_PSC_HELO_REQUIRED, &var_psc_helo_required,
1225 	VAR_PSC_DISABLE_VRFY, DEF_PSC_DISABLE_VRFY, &var_psc_disable_vrfy,
1226 	VAR_PSC_USE_TLS, DEF_PSC_USE_TLS, &var_psc_use_tls,
1227 	VAR_PSC_ENFORCE_TLS, DEF_PSC_ENFORCE_TLS, &var_psc_enforce_tls,
1228 	0,
1229     };
1230 
1231     /*
1232      * Fingerprint executables and core dumps.
1233      */
1234     MAIL_VERSION_STAMP_ALLOCATE;
1235 
1236     event_server_main(argc, argv, psc_service,
1237 		      CA_MAIL_SERVER_STR_TABLE(str_table),
1238 		      CA_MAIL_SERVER_INT_TABLE(int_table),
1239 		      CA_MAIL_SERVER_NINT_TABLE(nint_table),
1240 		      CA_MAIL_SERVER_TIME_TABLE(time_table),
1241 		      CA_MAIL_SERVER_BOOL_TABLE(bool_table),
1242 		      CA_MAIL_SERVER_RAW_TABLE(raw_table),
1243 		      CA_MAIL_SERVER_NBOOL_TABLE(nbool_table),
1244 		      CA_MAIL_SERVER_PRE_INIT(pre_jail_init),
1245 		      CA_MAIL_SERVER_POST_INIT(post_jail_init),
1246 		      CA_MAIL_SERVER_PRE_ACCEPT(pre_accept),
1247 		      CA_MAIL_SERVER_SOLITARY,
1248 		      CA_MAIL_SERVER_SLOW_EXIT(psc_drain),
1249 		      CA_MAIL_SERVER_EXIT(psc_dump),
1250 		      CA_MAIL_SERVER_WATCHDOG(&var_psc_watchdog),
1251 		      0);
1252 }
1253