1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2020 - 2024 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
10 /* Code for handling Access Control Lists (ACLs) */
16 /* Default callout timeout */
18 #define CALLOUT_TIMEOUT_DEFAULT 30
20 /* Default quota cache TTLs */
22 #define QUOTA_POS_DEFAULT (5*60)
23 #define QUOTA_NEG_DEFAULT (60*60)
26 /* ACL verb codes - keep in step with the table of verbs that follows */
28 enum { ACL_ACCEPT, ACL_DEFER, ACL_DENY, ACL_DISCARD, ACL_DROP, ACL_REQUIRE,
33 static uschar *verbs[] = {
34 [ACL_ACCEPT] = US"accept",
35 [ACL_DEFER] = US"defer",
36 [ACL_DENY] = US"deny",
37 [ACL_DISCARD] = US"discard",
38 [ACL_DROP] = US"drop",
39 [ACL_REQUIRE] = US"require",
43 /* For each verb, the conditions for which "message" or "log_message" are used
44 are held as a bitmap. This is to avoid expanding the strings unnecessarily. For
45 "accept", the FAIL case is used only after "endpass", but that is selected in
48 static int msgcond[] = {
49 [ACL_ACCEPT] = BIT(OK) | BIT(FAIL) | BIT(FAIL_DROP),
50 [ACL_DEFER] = BIT(OK),
52 [ACL_DISCARD] = BIT(OK) | BIT(FAIL) | BIT(FAIL_DROP),
54 [ACL_REQUIRE] = BIT(FAIL) | BIT(FAIL_DROP),
60 /* ACL condition and modifier codes */
66 #ifdef EXPERIMENTAL_BRIGHTMAIL
72 #ifdef EXPERIMENTAL_DCC
75 #ifdef WITH_CONTENT_SCAN
93 ACLC_LOG_REJECT_TARGET,
95 #ifdef WITH_CONTENT_SCAN
99 #ifdef WITH_CONTENT_SCAN
105 #ifdef WITH_CONTENT_SCAN
113 #ifdef WITH_CONTENT_SCAN
124 /* ACL conditions/modifiers: "delay", "control", "continue", "endpass",
125 "message", "log_message", "log_reject_target", "logwrite", "queue" and "set" are
126 modifiers that look like conditions but always return TRUE. They are used for
127 their side effects. Do not invent new modifier names that result in one name
128 being the prefix of another; the binary-search in the list will go wrong. */
130 typedef struct condition_def {
133 /* Flags for actions or checks to do during readconf for this condition */
135 #define ACD_EXP BIT(0) /* do expansion at outer level*/
136 #define ACD_MOD BIT(1) /* is a modifier */
137 #define ACD_LOAD BIT(2) /* supported by a dynamic-load module */
139 /* Bit map vector of which conditions and modifiers are not allowed at certain
140 times. For each condition and modifier, there's a bitmap of dis-allowed times.
141 For some, it is easier to specify the negation of a small number of allowed
144 #define FORBIDDEN(times) (times)
145 #define PERMITTED(times) ((unsigned) ~(times))
149 static condition_def conditions[] = {
150 [ACLC_ACL] = { US"acl", 0,
153 [ACLC_ADD_HEADER] = { US"add_header", ACD_EXP | ACD_MOD,
154 PERMITTED(ACL_BIT_MAIL | ACL_BIT_RCPT |
155 ACL_BIT_PREDATA | ACL_BIT_DATA |
159 ACL_BIT_MIME | ACL_BIT_NOTSMTP |
161 ACL_BIT_NOTSMTP_START),
164 [ACLC_ATRN_DOMAINS] = { US"atrn_domains", ACD_EXP,
165 PERMITTED(ACL_BIT_ATRN)
168 [ACLC_AUTHENTICATED] = { US"authenticated", 0,
169 FORBIDDEN(ACL_BIT_NOTSMTP |
170 ACL_BIT_NOTSMTP_START |
171 ACL_BIT_CONNECT | ACL_BIT_HELO),
173 #ifdef EXPERIMENTAL_BRIGHTMAIL
174 [ACLC_BMI_OPTIN] = { US"bmi_optin", ACD_EXP | ACD_MOD,
175 FORBIDDEN(ACL_BIT_AUTH |
176 ACL_BIT_CONNECT | ACL_BIT_HELO |
177 ACL_BIT_DATA | ACL_BIT_MIME |
178 # ifndef DISABLE_PRDR
181 ACL_BIT_ETRN | ACL_BIT_EXPN |
183 ACL_BIT_MAIL | ACL_BIT_STARTTLS |
184 ACL_BIT_VRFY | ACL_BIT_PREDATA |
185 ACL_BIT_NOTSMTP_START),
188 [ACLC_CONDITION] = { US"condition", ACD_EXP,
190 [ACLC_CONTINUE] = { US"continue", ACD_EXP | ACD_MOD,
193 /* Certain types of control are always allowed, so we let it through
194 always and check in the control processing itself. */
195 [ACLC_CONTROL] = { US"control", ACD_EXP | ACD_MOD,
198 #ifdef EXPERIMENTAL_DCC
199 [ACLC_DCC] = { US"dcc", ACD_EXP,
200 PERMITTED(ACL_BIT_DATA |
201 # ifndef DISABLE_PRDR
207 #ifdef WITH_CONTENT_SCAN
208 [ACLC_DECODE] = { US"decode", ACD_EXP,
209 PERMITTED(ACL_BIT_MIME) },
212 [ACLC_DELAY] = { US"delay", ACD_EXP | ACD_MOD,
213 FORBIDDEN(ACL_BIT_NOTQUIT) },
215 [ACLC_DKIM_SIGNER] = { US"dkim_signers",
220 PERMITTED(ACL_BIT_DKIM) },
221 [ACLC_DKIM_STATUS] = { US"dkim_status",
226 PERMITTED(ACL_BIT_DKIM | ACL_BIT_DATA | ACL_BIT_MIME
227 # ifndef DISABLE_PRDR
234 [ACLC_DMARC_STATUS] = { US"dmarc_status",
235 # if SUPPORT_DMARC==2
239 PERMITTED(ACL_BIT_DATA) },
242 /* Explicit key lookups can be made in non-smtp ACLs so pass
243 always and check in the verify processing itself. */
244 [ACLC_DNSLISTS] = { US"dnslists", ACD_EXP,
247 [ACLC_DOMAINS] = { US"domains", 0,
248 PERMITTED(ACL_BIT_RCPT | ACL_BIT_VRFY
254 [ACLC_ENCRYPTED] = { US"encrypted", 0,
255 FORBIDDEN(ACL_BIT_NOTSMTP |
256 ACL_BIT_NOTSMTP_START | ACL_BIT_CONNECT)
259 [ACLC_ENDPASS] = { US"endpass", ACD_EXP | ACD_MOD,
262 [ACLC_HOSTS] = { US"hosts", 0,
263 FORBIDDEN(ACL_BIT_NOTSMTP |
264 ACL_BIT_NOTSMTP_START),
266 [ACLC_LOCAL_PARTS] = { US"local_parts", 0,
267 PERMITTED(ACL_BIT_RCPT | ACL_BIT_VRFY
274 [ACLC_LOG_MESSAGE] = { US"log_message", ACD_EXP | ACD_MOD,
276 [ACLC_LOG_REJECT_TARGET] = { US"log_reject_target", ACD_EXP | ACD_MOD,
278 [ACLC_LOGWRITE] = { US"logwrite", ACD_EXP | ACD_MOD,
281 #ifdef WITH_CONTENT_SCAN
282 [ACLC_MALWARE] = { US"malware", ACD_EXP,
283 PERMITTED(ACL_BIT_DATA |
284 # ifndef DISABLE_PRDR
291 [ACLC_MESSAGE] = { US"message", ACD_EXP | ACD_MOD,
293 #ifdef WITH_CONTENT_SCAN
294 [ACLC_MIME_REGEX] = { US"mime_regex", ACD_EXP,
295 PERMITTED(ACL_BIT_MIME) },
298 [ACLC_QUEUE] = { US"queue", ACD_EXP | ACD_MOD,
299 FORBIDDEN(ACL_BIT_NOTSMTP |
306 [ACLC_RATELIMIT] = { US"ratelimit", ACD_EXP,
308 [ACLC_RECIPIENTS] = { US"recipients", 0,
309 PERMITTED(ACL_BIT_RCPT) },
311 #ifdef WITH_CONTENT_SCAN
312 [ACLC_REGEX] = { US"regex", ACD_EXP,
313 PERMITTED(ACL_BIT_DATA |
314 # ifndef DISABLE_PRDR
322 [ACLC_REMOVE_HEADER] = { US"remove_header", ACD_EXP | ACD_MOD,
323 PERMITTED(ACL_BIT_MAIL|ACL_BIT_RCPT |
324 ACL_BIT_PREDATA | ACL_BIT_DATA |
328 ACL_BIT_MIME | ACL_BIT_NOTSMTP |
329 ACL_BIT_NOTSMTP_START),
331 [ACLC_SEEN] = { US"seen", ACD_EXP,
333 [ACLC_SENDER_DOMAINS] = { US"sender_domains", 0,
334 FORBIDDEN(ACL_BIT_AUTH | ACL_BIT_CONNECT |
336 ACL_BIT_MAILAUTH | ACL_BIT_QUIT |
337 ACL_BIT_ETRN | ACL_BIT_EXPN |
338 ACL_BIT_STARTTLS | ACL_BIT_VRFY),
340 [ACLC_SENDERS] = { US"senders", 0,
341 FORBIDDEN(ACL_BIT_AUTH | ACL_BIT_CONNECT |
343 ACL_BIT_MAILAUTH | ACL_BIT_QUIT |
344 ACL_BIT_ETRN | ACL_BIT_EXPN |
345 ACL_BIT_STARTTLS | ACL_BIT_VRFY),
348 [ACLC_SET] = { US"set", ACD_EXP | ACD_MOD,
351 #ifdef WITH_CONTENT_SCAN
352 [ACLC_SPAM] = { US"spam", ACD_EXP,
353 PERMITTED(ACL_BIT_DATA |
354 # ifndef DISABLE_PRDR
361 [ACLC_SPF] = { US"spf",
366 FORBIDDEN(ACL_BIT_AUTH | ACL_BIT_CONNECT |
367 ACL_BIT_HELO | ACL_BIT_MAILAUTH |
368 ACL_BIT_ETRN | ACL_BIT_EXPN |
369 ACL_BIT_STARTTLS | ACL_BIT_VRFY |
370 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START),
372 [ACLC_SPF_GUESS] = { US"spf_guess",
377 FORBIDDEN(ACL_BIT_AUTH | ACL_BIT_CONNECT |
378 ACL_BIT_HELO | ACL_BIT_MAILAUTH |
379 ACL_BIT_ETRN | ACL_BIT_EXPN |
380 ACL_BIT_STARTTLS | ACL_BIT_VRFY |
381 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START),
384 [ACLC_UDPSEND] = { US"udpsend", ACD_EXP | ACD_MOD,
387 /* Certain types of verify are always allowed, so we let it through
388 always and check in the verify function itself */
389 [ACLC_VERIFY] = { US"verify", ACD_EXP,
395 # include "macro_predef.h"
399 for (condition_def * c = conditions; c < conditions + nelem(conditions); c++)
401 uschar buf[64], * p, * s;
402 int n = sprintf(CS buf, "_ACL_%s_", c->flags & ACD_MOD ? "MOD" : "COND");
403 for (p = buf + n, s = c->name; *s; s++) *p++ = toupper(*s);
405 builtin_macro_create(buf);
410 /******************************************************************************/
414 /* These tables support loading of dynamic modules triggered by an ACL
415 condition use, spotted during readconf. See acl_read(). */
417 # ifdef LOOKUP_MODULE_DIR
418 typedef struct condition_module {
419 const uschar * mod_name; /* module for the givien conditions */
420 misc_module_info * info; /* NULL when not loaded */
421 const int * conditions; /* array of ACLC_*, -1 terminated */
425 static int spf_condx[] = { ACLC_SPF, ACLC_SPF_GUESS, -1 };
428 static int dkim_condx[] = { ACLC_DKIM_SIGNER, ACLC_DKIM_STATUS, -1 };
430 # if SUPPORT_DMARC==2
431 static int dmarc_condx[] = { ACLC_DMARC_STATUS, -1 };
434 /* These are modules which can be loaded on seeing an ACL condition
435 during readconf, The "arc" module is handled by custom coding. */
437 static condition_module condition_modules[] = {
439 {.mod_name = US"spf", .conditions = spf_condx},
442 {.mod_name = US"dkim", .conditions = dkim_condx},
444 # if SUPPORT_DMARC==2
445 {.mod_name = US"dmarc", .conditions = dmarc_condx},
449 # endif /*LOOKUP_MODULE_DIR*/
451 /****************************/
453 /* Return values from decode_control() */
456 CONTROL_AUTH_UNADVERTISED,
457 #ifdef EXPERIMENTAL_BRIGHTMAIL
460 CONTROL_CASEFUL_LOCAL_PART,
461 CONTROL_CASELOWER_LOCAL_PART,
462 CONTROL_CUTTHROUGH_DELIVERY,
468 CONTROL_DMARC_VERIFY,
469 CONTROL_DMARC_FORENSIC,
472 CONTROL_ENFORCE_SYNC,
473 CONTROL_ERROR, /* pseudo-value for decode errors */
478 CONTROL_NO_CALLOUT_FLUSH,
479 CONTROL_NO_DELAY_FLUSH,
480 CONTROL_NO_ENFORCE_SYNC,
481 #ifdef WITH_CONTENT_SCAN
482 CONTROL_NO_MBOX_UNSPOOL,
484 CONTROL_NO_MULTILINE,
485 CONTROL_NO_PIPELINING,
489 CONTROL_SUPPRESS_LOCAL_FIXUPS,
491 CONTROL_UTF8_DOWNCONVERT,
493 #ifndef DISABLE_WELLKNOWN
500 /* Structure listing various control arguments, with their characteristics.
501 For each control, there's a bitmap of dis-allowed times. For some, it is easier
502 to specify the negation of a small number of allowed times. */
504 typedef struct control_def {
506 BOOL has_option; /* Has /option(s) following */
507 unsigned forbids; /* bitmap of dis-allowed times */
510 static control_def controls_list[] = {
511 /* name has_option forbids */
512 [CONTROL_AUTH_UNADVERTISED] =
513 { US"allow_auth_unadvertised", FALSE,
515 ~(ACL_BIT_CONNECT | ACL_BIT_HELO)
517 #ifdef EXPERIMENTAL_BRIGHTMAIL
519 { US"bmi_run", FALSE, 0 },
521 [CONTROL_CASEFUL_LOCAL_PART] =
522 { US"caseful_local_part", FALSE, (unsigned) ~ACL_BIT_RCPT },
523 [CONTROL_CASELOWER_LOCAL_PART] =
524 { US"caselower_local_part", FALSE, (unsigned) ~ACL_BIT_RCPT },
525 [CONTROL_CUTTHROUGH_DELIVERY] =
526 { US"cutthrough_delivery", TRUE, 0 },
528 { US"debug", TRUE, 0 },
531 [CONTROL_DKIM_VERIFY] =
532 { US"dkim_disable_verify", FALSE,
533 ACL_BIT_DATA | ACL_BIT_NOTSMTP |
534 # ifndef DISABLE_PRDR
537 ACL_BIT_NOTSMTP_START
542 [CONTROL_DMARC_VERIFY] =
543 { US"dmarc_disable_verify", FALSE,
544 ACL_BIT_DATA | ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
546 [CONTROL_DMARC_FORENSIC] =
547 { US"dmarc_enable_forensic", FALSE,
548 ACL_BIT_DATA | ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
554 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START | ACL_BIT_NOTQUIT
556 [CONTROL_ENFORCE_SYNC] =
557 { US"enforce_sync", FALSE,
558 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
561 /* Pseudo-value for decode errors */
563 { US"error", FALSE, 0 },
565 [CONTROL_FAKEDEFER] =
566 { US"fakedefer", TRUE,
568 ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
569 ACL_BIT_PREDATA | ACL_BIT_DATA |
575 [CONTROL_FAKEREJECT] =
576 { US"fakereject", TRUE,
578 ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
579 ACL_BIT_PREDATA | ACL_BIT_DATA |
588 ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
589 ACL_BIT_PREDATA | ACL_BIT_DATA |
590 // ACL_BIT_PRDR| /* Not allow one user to freeze for all */
591 ACL_BIT_NOTSMTP | ACL_BIT_MIME)
594 [CONTROL_NO_CALLOUT_FLUSH] =
595 { US"no_callout_flush", FALSE,
596 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
598 [CONTROL_NO_DELAY_FLUSH] =
599 { US"no_delay_flush", FALSE,
600 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
603 [CONTROL_NO_ENFORCE_SYNC] =
604 { US"no_enforce_sync", FALSE,
605 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
607 #ifdef WITH_CONTENT_SCAN
608 [CONTROL_NO_MBOX_UNSPOOL] =
609 { US"no_mbox_unspool", FALSE,
611 ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
612 ACL_BIT_PREDATA | ACL_BIT_DATA |
613 // ACL_BIT_PRDR| /* Not allow one user to freeze for all */
617 [CONTROL_NO_MULTILINE] =
618 { US"no_multiline_responses", FALSE,
619 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
621 [CONTROL_NO_PIPELINING] =
622 { US"no_pipelining", FALSE,
623 ACL_BIT_NOTSMTP | ACL_BIT_NOTSMTP_START
629 ~(ACL_BIT_MAIL | ACL_BIT_RCPT |
630 ACL_BIT_PREDATA | ACL_BIT_DATA |
631 // ACL_BIT_PRDR| /* Not allow one user to freeze for all */
632 ACL_BIT_NOTSMTP | ACL_BIT_MIME)
635 [CONTROL_SUBMISSION] =
636 { US"submission", TRUE,
638 ~(ACL_BIT_MAIL | ACL_BIT_RCPT | ACL_BIT_PREDATA)
640 [CONTROL_SUPPRESS_LOCAL_FIXUPS] =
641 { US"suppress_local_fixups", FALSE,
643 ~(ACL_BIT_MAIL | ACL_BIT_RCPT | ACL_BIT_PREDATA |
644 ACL_BIT_NOTSMTP_START)
647 [CONTROL_UTF8_DOWNCONVERT] =
648 { US"utf8_downconvert", TRUE, (unsigned) ~(ACL_BIT_RCPT | ACL_BIT_VRFY)
651 #ifndef DISABLE_WELLKNOWN
652 [CONTROL_WELLKNOWN] =
653 { US"wellknown", TRUE, (unsigned) ~ACL_BIT_WELLKNOWN
658 /* Support data structures for Client SMTP Authorization. acl_verify_csa()
659 caches its result in a tree to avoid repeated DNS queries. The result is an
660 integer code which is used as an index into the following tables of
661 explanatory strings and verification return codes. */
663 static tree_node *csa_cache = NULL;
665 enum { CSA_UNKNOWN, CSA_OK, CSA_DEFER_SRV, CSA_DEFER_ADDR,
666 CSA_FAIL_EXPLICIT, CSA_FAIL_DOMAIN, CSA_FAIL_NOADDR, CSA_FAIL_MISMATCH };
668 /* The acl_verify_csa() return code is translated into an acl_verify() return
669 code using the following table. It is OK unless the client is definitely not
670 authorized. This is because CSA is supposed to be optional for sending sites,
671 so recipients should not be too strict about checking it - especially because
672 DNS problems are quite likely to occur. It's possible to use $csa_status in
673 further ACL conditions to distinguish ok, unknown, and defer if required, but
674 the aim is to make the usual configuration simple. */
676 static int csa_return_code[] = {
679 [CSA_DEFER_SRV] = OK,
680 [CSA_DEFER_ADDR] = OK,
681 [CSA_FAIL_EXPLICIT] = FAIL,
682 [CSA_FAIL_DOMAIN] = FAIL,
683 [CSA_FAIL_NOADDR] = FAIL,
684 [CSA_FAIL_MISMATCH] = FAIL
687 static uschar *csa_status_string[] = {
688 [CSA_UNKNOWN] = US"unknown",
690 [CSA_DEFER_SRV] = US"defer",
691 [CSA_DEFER_ADDR] = US"defer",
692 [CSA_FAIL_EXPLICIT] = US"fail",
693 [CSA_FAIL_DOMAIN] = US"fail",
694 [CSA_FAIL_NOADDR] = US"fail",
695 [CSA_FAIL_MISMATCH] = US"fail"
698 static uschar *csa_reason_string[] = {
699 [CSA_UNKNOWN] = US"unknown",
701 [CSA_DEFER_SRV] = US"deferred (SRV lookup failed)",
702 [CSA_DEFER_ADDR] = US"deferred (target address lookup failed)",
703 [CSA_FAIL_EXPLICIT] = US"failed (explicit authorization required)",
704 [CSA_FAIL_DOMAIN] = US"failed (host name not authorized)",
705 [CSA_FAIL_NOADDR] = US"failed (no authorized addresses)",
706 [CSA_FAIL_MISMATCH] = US"failed (client address mismatch)"
709 /* Options for the ratelimit condition. Note that there are two variants of
710 the per_rcpt option, depending on the ACL that is used to measure the rate.
711 However any ACL must be able to look up per_rcpt rates in /noupdate mode,
712 so the two variants must have the same internal representation as well as
713 the same configuration string. */
716 RATE_PER_WHAT, RATE_PER_CLASH, RATE_PER_ADDR, RATE_PER_BYTE, RATE_PER_CMD,
717 RATE_PER_CONN, RATE_PER_MAIL, RATE_PER_RCPT, RATE_PER_ALLRCPTS
720 #define RATE_SET(var,new) \
721 (((var) == RATE_PER_WHAT) ? ((var) = RATE_##new) : ((var) = RATE_PER_CLASH))
723 static uschar *ratelimit_option_string[] = {
724 [RATE_PER_WHAT] = US"?",
725 [RATE_PER_CLASH] = US"!",
726 [RATE_PER_ADDR] = US"per_addr",
727 [RATE_PER_BYTE] = US"per_byte",
728 [RATE_PER_CMD] = US"per_cmd",
729 [RATE_PER_CONN] = US"per_conn",
730 [RATE_PER_MAIL] = US"per_mail",
731 [RATE_PER_RCPT] = US"per_rcpt",
732 [RATE_PER_ALLRCPTS] = US"per_rcpt"
735 /* Enable recursion between acl_check_internal() and acl_check_condition() */
737 static int acl_check_wargs(int, address_item *, const uschar *, uschar **,
740 static acl_block * acl_current = NULL;
743 /*************************************************
744 * Find control in list *
745 *************************************************/
747 /* The lists are always in order, so binary chop can be used.
750 name the control name to search for
751 ol the first entry in the control list
752 last one more than the offset of the last entry in the control list
754 Returns: index of a control entry, or -1 if not found
758 find_control(const uschar * name, control_def * ol, int last)
760 for (int first = 0; last > first; )
762 int middle = (first + last)/2;
763 uschar * s = ol[middle].name;
764 int c = Ustrncmp(name, s, Ustrlen(s));
765 if (c == 0) return middle;
766 else if (c > 0) first = middle + 1;
774 /*************************************************
775 * Pick out condition from list *
776 *************************************************/
778 /* Use a binary chop method
782 list list of conditions
785 Returns: offset in list, or -1 if not found
789 acl_checkcondition(uschar * name, condition_def * list, int end)
791 for (int start = 0; start < end; )
793 int mid = (start + end)/2;
794 int c = Ustrcmp(name, list[mid].name);
795 if (c == 0) return mid;
796 if (c < 0) end = mid;
797 else start = mid + 1;
803 /*************************************************
804 * Pick out name from list *
805 *************************************************/
807 /* Use a binary chop method
814 Returns: offset in list, or -1 if not found
818 acl_checkname(uschar *name, uschar **list, int end)
820 for (int start = 0; start < end; )
822 int mid = (start + end)/2;
823 int c = Ustrcmp(name, list[mid]);
824 if (c == 0) return mid;
825 if (c < 0) end = mid; else start = mid + 1;
833 acl_varname_to_cond(const uschar ** sp, acl_condition_block * cond, uschar ** error)
835 const uschar * s = *sp, * endptr;
838 if ( Ustrncmp(s, "dkim_verify_status", 18) == 0
839 || Ustrncmp(s, "dkim_verify_reason", 18) == 0)
842 if (isalnum(*endptr))
844 *error = string_sprintf("invalid variable name after \"set\" in ACL "
845 "modifier \"set %s\" "
846 "(only \"dkim_verify_status\" or \"dkim_verify_reason\" permitted)",
850 cond->u.varname = string_copyn(s, 18);
855 if (Ustrncmp(s, "acl_c", 5) != 0 && Ustrncmp(s, "acl_m", 5) != 0)
857 *error = string_sprintf("invalid variable name after \"set\" in ACL "
858 "modifier \"set %s\" (must start \"acl_c\" or \"acl_m\")", s);
863 if (!isdigit(*endptr) && *endptr != '_')
865 *error = string_sprintf("invalid variable name after \"set\" in ACL "
866 "modifier \"set %s\" (digit or underscore must follow acl_c or acl_m)",
871 for ( ; *endptr && *endptr != '=' && !isspace(*endptr); endptr++)
872 if (!isalnum(*endptr) && *endptr != '_')
874 *error = string_sprintf("invalid character \"%c\" in variable name "
875 "in ACL modifier \"set %s\"", *endptr, s);
879 cond->u.varname = string_copyn(s + 4, endptr - s - 4);
882 Uskip_whitespace(&s);
889 acl_data_to_cond(const uschar * s, acl_condition_block * cond,
890 const uschar * name, BOOL taint, uschar ** error)
894 *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
895 conditions[cond->type].flags & ACD_MOD ? US"modifier" : US"condition");
898 Uskip_whitespace(&s);
899 cond->arg = taint ? string_copy_taint(s, GET_TAINTED) : string_copy(s);
904 /*************************************************
905 * Read and parse one ACL *
906 *************************************************/
908 /* This function is called both from readconf in order to parse the ACLs in the
909 configuration file, and also when an ACL is encountered dynamically (e.g. as
910 the result of an expansion). It is given a function to call in order to
911 retrieve the lines of the ACL. This function handles skipping comments and
912 blank lines (where relevant).
915 func function to get next line of ACL
916 error where to put an error message
918 Returns: pointer to ACL, or NULL
919 NULL can be legal (empty ACL); in this case error will be NULL
923 acl_read(uschar *(*func)(void), uschar **error)
925 acl_block *yield = NULL;
926 acl_block **lastp = &yield;
927 acl_block *this = NULL;
928 acl_condition_block *cond;
929 acl_condition_block **condp = NULL;
934 while ((s = (*func)()))
937 BOOL negated = FALSE;
938 const uschar * saveline = s;
939 uschar name[EXIM_DRIVERNAME_MAX];
941 /* Conditions (but not verbs) are allowed to be negated by an initial
944 if (Uskip_whitespace(&s) == '!')
950 /* Read the name of a verb or a condition, or the start of a new ACL, which
951 can be started by a name, or by a macro definition. */
953 s = readconf_readname(name, sizeof(name), s);
954 if (*s == ':' || (isupper(name[0]) && *s == '=')) return yield;
956 /* If a verb is unrecognized, it may be another condition or modifier that
957 continues the previous verb. */
959 if ((v = acl_checkname(name, verbs, nelem(verbs))) < 0)
961 if (!this) /* not handling a verb right now */
963 *error = string_sprintf("unknown ACL verb \"%s\" in \"%s\"", name,
975 *error = string_sprintf("malformed ACL line \"%s\"", saveline);
978 *lastp = this = store_get(sizeof(acl_block), GET_UNTAINTED);
981 this->condition = NULL;
983 this->srcline = config_lineno; /* for debug output */
984 this->srcfile = config_filename; /**/
985 condp = &this->condition;
986 if (!*s) continue; /* No condition on this line */
992 s = readconf_readname(name, sizeof(name), s); /* Condition name */
995 /* Handle a condition or modifier. */
997 if ((c = acl_checkcondition(name, conditions, nelem(conditions))) < 0)
999 *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
1004 /* The modifiers may not be negated */
1006 if (negated && conditions[c].flags & ACD_MOD)
1008 *error = string_sprintf("ACL error: negation is not allowed with "
1009 "\"%s\"", conditions[c].name);
1013 /* ENDPASS may occur only with ACCEPT or DISCARD. */
1015 if (c == ACLC_ENDPASS &&
1016 this->verb != ACL_ACCEPT &&
1017 this->verb != ACL_DISCARD)
1019 *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
1020 conditions[c].name, verbs[this->verb]);
1024 #ifdef LOOKUP_MODULE_DIR
1025 if (conditions[c].flags & ACD_LOAD)
1026 { /* a loadable module supports this condition */
1027 condition_module * cm;
1030 /* Over the list of modules we support, check the list of ACL conditions
1031 each supports. This assumes no duplicates. */
1033 for (cm = condition_modules;
1034 cm < condition_modules + nelem(condition_modules); cm++)
1035 for (const int * cond = cm->conditions; *cond != -1; cond++)
1036 if (*cond == c) goto found;
1039 if (cm >= condition_modules + nelem(condition_modules))
1040 { /* shouldn't happen */
1041 *error = string_sprintf("ACL error: failed to locate support for '%s'",
1042 conditions[c].name);
1045 if ( !cm->info /* module not loaded */
1046 && !(cm->info = misc_mod_find(cm->mod_name, &s)))
1048 *error = string_sprintf("ACL error: failed to find module for '%s': %s",
1049 conditions[c].name, s);
1053 # ifdef EXPERIMENTAL_ARC
1054 else if (c == ACLC_VERIFY) /* Special handling for verify=arc; */
1055 { /* not invented a more general method yet- flag in verify_type_list? */
1056 const uschar * t = s;
1058 if ( *t++ == '=' && Uskip_whitespace(&t) && Ustrncmp(t, "arc", 3) == 0
1059 && !misc_mod_find(US"arc", &e))
1061 *error = string_sprintf("ACL error: failed to find module for '%s': %s",
1062 conditions[c].name, e);
1067 #endif /*LOOKUP_MODULE_DIR*/
1069 cond = store_get(sizeof(acl_condition_block), GET_UNTAINTED);
1072 cond->u.negated = negated;
1075 condp = &cond->next;
1077 /* The "set" modifier is different in that its argument is "name=value"
1078 rather than just a value, and we can check the validity of the name, which
1079 gives us a variable name to insert into the data block. The original ACL
1080 variable names were acl_c0 ... acl_c9 and acl_m0 ... acl_m9. This was
1081 extended to 20 of each type, but after that people successfully argued for
1082 arbitrary names. In the new scheme, the names must start with acl_c or acl_m.
1083 After that, we allow alphanumerics and underscores, but the first character
1084 after c or m must be a digit or an underscore. This retains backwards
1088 if (!acl_varname_to_cond(&s, cond, error)) return NULL;
1090 /* For "set", we are now positioned for the data. For the others, only
1091 "endpass" has no data */
1093 if (c != ACLC_ENDPASS)
1094 if (!acl_data_to_cond(s, cond, name, FALSE, error)) return NULL;
1102 /*************************************************
1103 * Set up added header line(s) *
1104 *************************************************/
1106 /* This function is called by the add_header modifier, and also from acl_warn()
1107 to implement the now-deprecated way of adding header lines using "message" on a
1108 "warn" verb. The argument is treated as a sequence of header lines which are
1109 added to a chain, provided there isn't an identical one already there.
1111 Argument: string of header lines
1116 setup_header(const uschar *hstring)
1118 const uschar *p, *q;
1119 int hlen = Ustrlen(hstring);
1121 /* Ignore any leading newlines */
1122 while (*hstring == '\n') hstring++, hlen--;
1124 /* An empty string does nothing; ensure exactly one final newline. */
1125 if (hlen <= 0) return;
1126 if (hstring[--hlen] != '\n') /* no newline */
1127 q = string_sprintf("%s\n", hstring);
1128 else if (hstring[hlen-1] == '\n') /* double newline */
1130 uschar * s = string_copy(hstring);
1131 while(s[--hlen] == '\n')
1138 /* Loop for multiple header lines, taking care about continuations */
1140 for (p = q; *p; p = q)
1144 int newtype = htype_add_bot;
1145 header_line **hptr = &acl_added_headers;
1147 /* Find next header line within the string */
1151 q = Ustrchr(q, '\n'); /* we know there was a newline */
1152 if (*++q != ' ' && *q != '\t') break;
1155 /* If the line starts with a colon, interpret the instruction for where to
1156 add it. This temporarily sets up a new type. */
1160 if (strncmpic(p, US":after_received:", 16) == 0)
1162 newtype = htype_add_rec;
1165 else if (strncmpic(p, US":at_start_rfc:", 14) == 0)
1167 newtype = htype_add_rfc;
1170 else if (strncmpic(p, US":at_start:", 10) == 0)
1172 newtype = htype_add_top;
1175 else if (strncmpic(p, US":at_end:", 8) == 0)
1177 newtype = htype_add_bot;
1180 while (*p == ' ' || *p == '\t') p++;
1183 /* See if this line starts with a header name, and if not, add X-ACL-Warn:
1184 to the front of it. */
1186 for (s = p; s < q - 1; s++)
1187 if (*s == ':' || !isgraph(*s)) break;
1189 hdr = string_sprintf("%s%.*s", *s == ':' ? "" : "X-ACL-Warn: ", (int) (q - p), p);
1190 hlen = Ustrlen(hdr);
1192 /* See if this line has already been added */
1196 if (Ustrncmp((*hptr)->text, hdr, hlen) == 0) break;
1197 hptr = &(*hptr)->next;
1200 /* Add if not previously present */
1204 /* The header_line struct itself is not tainted, though it points to
1205 possibly tainted data. */
1206 header_line * h = store_get(sizeof(header_line), GET_UNTAINTED);
1219 /*************************************************
1220 * List the added header lines *
1221 *************************************************/
1227 for (header_line * h = acl_added_headers; h; h = h->next)
1230 if (h->text[i-1] == '\n') i--;
1231 g = string_append_listele_n(g, '\n', h->text, i);
1234 return string_from_gstring(g);
1238 /*************************************************
1239 * Set up removed header line(s) *
1240 *************************************************/
1242 /* This function is called by the remove_header modifier. The argument is
1243 treated as a sequence of header names which are added to a colon separated
1244 list, provided there isn't an identical one already there.
1246 Argument: string of header names
1251 setup_remove_header(const uschar *hnames)
1254 acl_removed_headers = acl_removed_headers
1255 ? string_sprintf("%s : %s", acl_removed_headers, hnames)
1256 : string_copy(hnames);
1261 /*************************************************
1263 *************************************************/
1265 /* This function is called when a WARN verb's conditions are true. It adds to
1266 the message's headers, and/or writes information to the log. In each case, this
1267 only happens once (per message for headers, per connection for log).
1269 ** NOTE: The header adding action using the "message" setting is historic, and
1270 its use is now deprecated. The new add_header modifier should be used instead.
1273 where ACL_WHERE_xxxx indicating which ACL this is
1274 user_message message for adding to headers
1275 log_message message for logging, if different
1281 acl_warn(int where, uschar * user_message, uschar * log_message)
1283 if (log_message && log_message != user_message)
1286 string_item *logged;
1288 text = string_sprintf("%s Warning: %s", host_and_ident(TRUE),
1289 string_printing(log_message));
1291 /* If a sender verification has failed, and the log message is "sender verify
1292 failed", add the failure message. */
1294 if ( sender_verified_failed
1295 && sender_verified_failed->message
1296 && strcmpic(log_message, US"sender verify failed") == 0)
1297 text = string_sprintf("%s: %s", text, sender_verified_failed->message);
1299 /* Search previously logged warnings. They are kept in malloc
1300 store so they can be freed at the start of a new message. */
1302 for (logged = acl_warn_logged; logged; logged = logged->next)
1303 if (Ustrcmp(logged->text, text) == 0) break;
1307 int length = Ustrlen(text) + 1;
1308 log_write(0, LOG_MAIN, "%s", text);
1309 logged = store_malloc(sizeof(string_item) + length);
1310 logged->text = US logged + sizeof(string_item);
1311 memcpy(logged->text, text, length);
1312 logged->next = acl_warn_logged;
1313 acl_warn_logged = logged;
1317 /* If there's no user message, we are done. */
1319 if (!user_message) return;
1321 /* If this isn't a message ACL, we can't do anything with a user message.
1324 if (where > ACL_WHERE_NOTSMTP)
1326 log_write(0, LOG_MAIN|LOG_PANIC, "ACL \"warn\" with \"message\" setting "
1327 "found in a non-message (%s) ACL: cannot specify header lines here: "
1328 "message ignored", acl_wherenames[where]);
1332 /* The code for setting up header lines is now abstracted into a separate
1333 function so that it can be used for the add_header modifier as well. */
1335 setup_header(user_message);
1340 /*************************************************
1341 * Verify and check reverse DNS *
1342 *************************************************/
1344 /* Called from acl_verify() below. We look up the host name(s) of the client IP
1345 address if this has not yet been done. The host_name_lookup() function checks
1346 that one of these names resolves to an address list that contains the client IP
1347 address, so we don't actually have to do the check here.
1350 user_msgptr pointer for user message
1351 log_msgptr pointer for log message
1353 Returns: OK verification condition succeeded
1354 FAIL verification failed
1355 DEFER there was a problem verifying
1359 acl_verify_reverse(uschar **user_msgptr, uschar **log_msgptr)
1363 /* Previous success */
1365 if (sender_host_name) return OK;
1367 /* Previous failure */
1369 if (host_lookup_failed)
1371 *log_msgptr = string_sprintf("host lookup failed%s", host_lookup_msg);
1375 /* Need to do a lookup */
1378 debug_printf_indent("looking up host name to force name/address consistency check\n");
1380 if ((rc = host_name_lookup()) != OK)
1382 *log_msgptr = rc == DEFER
1383 ? US"host lookup deferred for reverse lookup check"
1384 : string_sprintf("host lookup failed for reverse lookup check%s",
1386 return rc; /* DEFER or FAIL */
1389 host_build_sender_fullhost();
1395 /*************************************************
1396 * Check client IP address matches CSA target *
1397 *************************************************/
1399 /* Called from acl_verify_csa() below. This routine scans a section of a DNS
1400 response for address records belonging to the CSA target hostname. The section
1401 is specified by the reset argument, either RESET_ADDITIONAL or RESET_ANSWERS.
1402 If one of the addresses matches the client's IP address, then the client is
1403 authorized by CSA. If there are target IP addresses but none of them match
1404 then the client is using an unauthorized IP address. If there are no target IP
1405 addresses then the client cannot be using an authorized IP address. (This is
1406 an odd configuration - why didn't the SRV record have a weight of 1 instead?)
1409 dnsa the DNS answer block
1410 dnss a DNS scan block for us to use
1411 reset option specifying what portion to scan, as described above
1412 target the target hostname to use for matching RR names
1414 Returns: CSA_OK successfully authorized
1415 CSA_FAIL_MISMATCH addresses found but none matched
1416 CSA_FAIL_NOADDR no target addresses found
1420 acl_verify_csa_address(dns_answer *dnsa, dns_scan *dnss, int reset,
1423 int rc = CSA_FAIL_NOADDR;
1425 for (dns_record * rr = dns_next_rr(dnsa, dnss, reset);
1427 rr = dns_next_rr(dnsa, dnss, RESET_NEXT))
1429 /* Check this is an address RR for the target hostname. */
1433 && rr->type != T_AAAA
1437 if (strcmpic(target, rr->name) != 0) continue;
1439 rc = CSA_FAIL_MISMATCH;
1441 /* Turn the target address RR into a list of textual IP addresses and scan
1442 the list. There may be more than one if it is an A6 RR. */
1444 for (dns_address * da = dns_address_from_rr(dnsa, rr); da; da = da->next)
1446 /* If the client IP address matches the target IP address, it's good! */
1448 DEBUG(D_acl) debug_printf_indent("CSA target address is %s\n", da->address);
1450 if (strcmpic(sender_host_address, da->address) == 0) return CSA_OK;
1454 /* If we found some target addresses but none of them matched, the client is
1455 using an unauthorized IP address, otherwise the target has no authorized IP
1463 /*************************************************
1464 * Verify Client SMTP Authorization *
1465 *************************************************/
1467 /* Called from acl_verify() below. This routine calls dns_lookup_special()
1468 to find the CSA SRV record corresponding to the domain argument, or
1469 $sender_helo_name if no argument is provided. It then checks that the
1470 client is authorized, and that its IP address corresponds to the SRV
1471 target's address by calling acl_verify_csa_address() above. The address
1472 should have been returned in the DNS response's ADDITIONAL section, but if
1473 not we perform another DNS lookup to get it.
1476 domain pointer to optional parameter following verify = csa
1478 Returns: CSA_UNKNOWN no valid CSA record found
1479 CSA_OK successfully authorized
1480 CSA_FAIL_* client is definitely not authorized
1481 CSA_DEFER_* there was a DNS problem
1485 acl_verify_csa(const uschar *domain)
1488 const uschar *found;
1489 int priority, weight, port;
1493 int rc, type, yield;
1494 #define TARGET_SIZE 256
1495 uschar * target = store_get(TARGET_SIZE, GET_TAINTED);
1497 /* Work out the domain we are using for the CSA lookup. The default is the
1498 client's HELO domain. If the client has not said HELO, use its IP address
1499 instead. If it's a local client (exim -bs), CSA isn't applicable. */
1501 while (isspace(*domain) && *domain) ++domain;
1502 if (*domain == '\0') domain = sender_helo_name;
1503 if (!domain) domain = sender_host_address;
1504 if (!sender_host_address) return CSA_UNKNOWN;
1506 /* If we have an address literal, strip off the framing ready for turning it
1507 into a domain. The framing consists of matched square brackets possibly
1508 containing a keyword and a colon before the actual IP address. */
1510 if (domain[0] == '[')
1512 const uschar *start = Ustrchr(domain, ':');
1513 if (start == NULL) start = domain;
1514 domain = string_copyn(start + 1, Ustrlen(start) - 2);
1517 /* Turn domains that look like bare IP addresses into domains in the reverse
1518 DNS. This code also deals with address literals and $sender_host_address. It's
1519 not quite kosher to treat bare domains such as EHLO 192.0.2.57 the same as
1520 address literals, but it's probably the most friendly thing to do. This is an
1521 extension to CSA, so we allow it to be turned off for proper conformance. */
1523 if (string_is_ip_address(domain, NULL) != 0)
1525 if (!dns_csa_use_reverse) return CSA_UNKNOWN;
1526 domain = dns_build_reverse(domain);
1529 /* Find out if we've already done the CSA check for this domain. If we have,
1530 return the same result again. Otherwise build a new cached result structure
1531 for this domain. The name is filled in now, and the value is filled in when
1532 we return from this function. */
1534 if ((t = tree_search(csa_cache, domain)))
1537 t = store_get_perm(sizeof(tree_node) + Ustrlen(domain), domain);
1538 Ustrcpy(t->name, domain);
1539 (void)tree_insertnode(&csa_cache, t);
1541 /* Now we are ready to do the actual DNS lookup(s). */
1544 dnsa = store_get_dns_answer();
1545 switch (dns_special_lookup(dnsa, domain, T_CSA, &found))
1547 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1550 yield = CSA_DEFER_SRV;
1553 /* If we found nothing, the client's authorization is unknown. */
1557 yield = CSA_UNKNOWN;
1560 /* We got something! Go on to look at the reply in more detail. */
1566 /* Scan the reply for well-formed CSA SRV records. */
1568 for (rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS);
1570 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)) if (rr->type == T_SRV)
1572 const uschar * p = rr->data;
1574 /* Extract the numerical SRV fields (p is incremented) */
1576 if (rr_bad_size(rr, 3 * sizeof(uint16_t))) continue;
1577 GETSHORT(priority, p);
1578 GETSHORT(weight, p);
1582 debug_printf_indent("CSA priority=%d weight=%d port=%d\n", priority, weight, port);
1584 /* Check the CSA version number */
1586 if (priority != 1) continue;
1588 /* If the domain does not have a CSA SRV record of its own (i.e. the domain
1589 found by dns_special_lookup() is a parent of the one we asked for), we check
1590 the subdomain assertions in the port field. At the moment there's only one
1591 assertion: legitimate SMTP clients are all explicitly authorized with CSA
1592 SRV records of their own. */
1594 if (Ustrcmp(found, domain) != 0)
1596 yield = port & 1 ? CSA_FAIL_EXPLICIT : CSA_UNKNOWN;
1600 /* This CSA SRV record refers directly to our domain, so we check the value
1601 in the weight field to work out the domain's authorization. 0 and 1 are
1602 unauthorized; 3 means the client is authorized but we can't check the IP
1603 address in order to authenticate it, so we treat it as unknown; values
1604 greater than 3 are undefined. */
1608 yield = CSA_FAIL_DOMAIN;
1612 if (weight > 2) continue;
1614 /* Weight == 2, which means the domain is authorized. We must check that the
1615 client's IP address is listed as one of the SRV target addresses. Save the
1616 target hostname then break to scan the additional data for its addresses. */
1618 (void)dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, p,
1619 (DN_EXPAND_ARG4_TYPE)target, TARGET_SIZE);
1621 DEBUG(D_acl) debug_printf_indent("CSA target is %s\n", target);
1626 /* If we didn't break the loop then no appropriate records were found. */
1630 yield = CSA_UNKNOWN;
1634 /* Do not check addresses if the target is ".", in accordance with RFC 2782.
1635 A target of "." indicates there are no valid addresses, so the client cannot
1636 be authorized. (This is an odd configuration because weight=2 target=. is
1637 equivalent to weight=1, but we check for it in order to keep load off the
1638 root name servers.) Note that dn_expand() turns "." into "". */
1640 if (Ustrcmp(target, "") == 0)
1642 yield = CSA_FAIL_NOADDR;
1646 /* Scan the additional section of the CSA SRV reply for addresses belonging
1647 to the target. If the name server didn't return any additional data (e.g.
1648 because it does not fully support SRV records), we need to do another lookup
1649 to obtain the target addresses; otherwise we have a definitive result. */
1651 rc = acl_verify_csa_address(dnsa, &dnss, RESET_ADDITIONAL, target);
1652 if (rc != CSA_FAIL_NOADDR)
1658 /* The DNS lookup type corresponds to the IP version used by the client. */
1661 if (Ustrchr(sender_host_address, ':') != NULL)
1664 #endif /* HAVE_IPV6 */
1668 lookup_dnssec_authenticated = NULL;
1669 switch (dns_lookup(dnsa, target, type, NULL))
1671 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1674 yield = CSA_DEFER_ADDR;
1677 /* If the query succeeded, scan the addresses and return the result. */
1680 rc = acl_verify_csa_address(dnsa, &dnss, RESET_ANSWERS, target);
1681 if (rc != CSA_FAIL_NOADDR)
1686 /* else fall through */
1688 /* If the target has no IP addresses, the client cannot have an authorized
1689 IP address. However, if the target site uses A6 records (not AAAA records)
1690 we have to do yet another lookup in order to check them. */
1694 yield = CSA_FAIL_NOADDR;
1700 store_free_dns_answer(dnsa);
1701 return t->data.val = yield;
1706 /*************************************************
1707 * Handle verification (address & other) *
1708 *************************************************/
1710 enum { VERIFY_REV_HOST_LKUP, VERIFY_CERT, VERIFY_HELO, VERIFY_CSA, VERIFY_HDR_SYNTAX,
1711 VERIFY_NOT_BLIND, VERIFY_HDR_SNDR, VERIFY_SNDR, VERIFY_RCPT,
1712 VERIFY_HDR_NAMES_ASCII, VERIFY_ARC
1717 unsigned where_allowed; /* bitmap */
1718 BOOL no_options; /* Never has /option(s) following */
1719 unsigned alt_opt_sep; /* >0 Non-/ option separator (custom parser) */
1721 static verify_type_t verify_type_list[] = {
1722 /* name value where no-opt opt-sep */
1723 { US"reverse_host_lookup", VERIFY_REV_HOST_LKUP, (unsigned)~0, FALSE, 0 },
1724 { US"certificate", VERIFY_CERT, (unsigned)~0, TRUE, 0 },
1725 { US"helo", VERIFY_HELO, (unsigned)~0, TRUE, 0 },
1726 { US"csa", VERIFY_CSA, (unsigned)~0, FALSE, 0 },
1727 { US"header_syntax", VERIFY_HDR_SYNTAX, ACL_BITS_HAVEDATA, TRUE, 0 },
1728 { US"not_blind", VERIFY_NOT_BLIND, ACL_BITS_HAVEDATA, FALSE, 0 },
1729 { US"header_sender", VERIFY_HDR_SNDR, ACL_BITS_HAVEDATA, FALSE, 0 },
1730 { US"sender", VERIFY_SNDR, ACL_BIT_MAIL | ACL_BIT_RCPT
1731 | ACL_BIT_PREDATA | ACL_BIT_DATA | ACL_BIT_NOTSMTP,
1733 { US"recipient", VERIFY_RCPT, ACL_BIT_RCPT, FALSE, 0 },
1734 { US"header_names_ascii", VERIFY_HDR_NAMES_ASCII, ACL_BITS_HAVEDATA, TRUE, 0 },
1735 #ifdef EXPERIMENTAL_ARC
1736 { US"arc", VERIFY_ARC, ACL_BIT_DATA, FALSE , 0 },
1741 enum { CALLOUT_DEFER_OK, CALLOUT_NOCACHE, CALLOUT_RANDOM, CALLOUT_USE_SENDER,
1742 CALLOUT_USE_POSTMASTER, CALLOUT_POSTMASTER, CALLOUT_FULLPOSTMASTER,
1743 CALLOUT_MAILFROM, CALLOUT_POSTMASTER_MAILFROM, CALLOUT_MAXWAIT, CALLOUT_CONNECT,
1744 CALLOUT_HOLD, CALLOUT_TIME /* TIME must be last */
1750 BOOL has_option; /* Has =option(s) following */
1751 BOOL timeval; /* Has a time value */
1753 static callout_opt_t callout_opt_list[] = {
1754 /* name value flag has-opt has-time */
1755 { US"defer_ok", CALLOUT_DEFER_OK, 0, FALSE, FALSE },
1756 { US"no_cache", CALLOUT_NOCACHE, vopt_callout_no_cache, FALSE, FALSE },
1757 { US"random", CALLOUT_RANDOM, vopt_callout_random, FALSE, FALSE },
1758 { US"use_sender", CALLOUT_USE_SENDER, vopt_callout_recipsender, FALSE, FALSE },
1759 { US"use_postmaster", CALLOUT_USE_POSTMASTER,vopt_callout_recippmaster, FALSE, FALSE },
1760 { US"postmaster_mailfrom",CALLOUT_POSTMASTER_MAILFROM,0, TRUE, FALSE },
1761 { US"postmaster", CALLOUT_POSTMASTER, 0, FALSE, FALSE },
1762 { US"fullpostmaster", CALLOUT_FULLPOSTMASTER,vopt_callout_fullpm, FALSE, FALSE },
1763 { US"mailfrom", CALLOUT_MAILFROM, 0, TRUE, FALSE },
1764 { US"maxwait", CALLOUT_MAXWAIT, 0, TRUE, TRUE },
1765 { US"connect", CALLOUT_CONNECT, 0, TRUE, TRUE },
1766 { US"hold", CALLOUT_HOLD, vopt_callout_hold, FALSE, FALSE },
1767 { NULL, CALLOUT_TIME, 0, FALSE, TRUE }
1773 v_period(const uschar * s, const uschar * arg, uschar ** log_msgptr)
1776 if ((period = readconf_readtime(s, 0, FALSE)) < 0)
1778 *log_msgptr = string_sprintf("bad time value in ACL condition "
1779 "\"verify %s\"", arg);
1787 sender_helo_verified_internal(void)
1789 /* We can test the result of optional HELO verification that might have
1790 occurred earlier. If not, we can attempt the verification now. */
1792 if (!f.helo_verified && !f.helo_verify_failed) smtp_verify_helo();
1793 return f.helo_verified;
1797 sender_helo_verified_cond(void)
1799 return sender_helo_verified_internal() ? OK : FAIL;
1803 sender_helo_verified_boolstr(void)
1805 return sender_helo_verified_internal() ? US"yes" : US"no";
1810 /* This function implements the "verify" condition. It is called when
1811 encountered in any ACL, because some tests are almost always permitted. Some
1812 just don't make sense, and always fail (for example, an attempt to test a host
1813 lookup for a non-TCP/IP message). Others are restricted to certain ACLs.
1816 where where called from
1817 addr the recipient address that the ACL is handling, or NULL
1818 arg the argument of "verify"
1819 user_msgptr pointer for user message
1820 log_msgptr pointer for log message
1821 basic_errno where to put verify errno
1823 Returns: OK verification condition succeeded
1824 FAIL verification failed
1825 DEFER there was a problem verifying
1830 acl_verify(int where, address_item *addr, const uschar *arg,
1831 uschar **user_msgptr, uschar **log_msgptr, int *basic_errno)
1835 int callout_overall = -1;
1836 int callout_connect = -1;
1837 int verify_options = 0;
1839 BOOL verify_header_sender = FALSE;
1840 BOOL defer_ok = FALSE;
1841 BOOL callout_defer_ok = FALSE;
1842 BOOL no_details = FALSE;
1843 BOOL success_on_redirect = FALSE;
1845 int quota_pos_cache = QUOTA_POS_DEFAULT, quota_neg_cache = QUOTA_NEG_DEFAULT;
1846 address_item * sender_vaddr = NULL;
1847 const uschar * verify_sender_address = NULL;
1848 uschar * pm_mailfrom = NULL;
1849 uschar * se_mailfrom = NULL;
1851 /* Some of the verify items have slash-separated options; some do not. Diagnose
1852 an error if options are given for items that don't expect them.
1855 uschar *slash = Ustrchr(arg, '/');
1856 const uschar *list = arg;
1857 uschar *ss = string_nextinlist(&list, &sep, NULL, 0);
1860 if (!ss) goto BAD_VERIFY;
1862 /* Handle name/address consistency verification in a separate function. */
1864 for (vp = verify_type_list;
1865 CS vp < CS verify_type_list + sizeof(verify_type_list);
1868 if (vp->alt_opt_sep ? strncmpic(ss, vp->name, vp->alt_opt_sep) == 0
1869 : strcmpic (ss, vp->name) == 0)
1871 if (CS vp >= CS verify_type_list + sizeof(verify_type_list))
1874 if (vp->no_options && slash)
1876 *log_msgptr = string_sprintf("unexpected '/' found in \"%s\" "
1877 "(this verify item has no options)", arg);
1880 if (!(vp->where_allowed & BIT(where)))
1882 *log_msgptr = string_sprintf("cannot verify %s in ACL for %s",
1883 vp->name, acl_wherenames[where]);
1888 case VERIFY_REV_HOST_LKUP:
1889 if (!sender_host_address) return OK;
1890 if ((rc = acl_verify_reverse(user_msgptr, log_msgptr)) == DEFER)
1891 while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
1892 if (strcmpic(ss, US"defer_ok") == 0)
1897 /* TLS certificate verification is done at STARTTLS time; here we just
1898 test whether it was successful or not. (This is for optional verification; for
1899 mandatory verification, the connection doesn't last this long.) */
1901 if (tls_in.certificate_verified) return OK;
1902 *user_msgptr = US"no verified certificate";
1906 return sender_helo_verified_cond();
1909 /* Do Client SMTP Authorization checks in a separate function, and turn the
1910 result code into user-friendly strings. */
1912 rc = acl_verify_csa(list);
1913 *log_msgptr = *user_msgptr = string_sprintf("client SMTP authorization %s",
1914 csa_reason_string[rc]);
1915 csa_status = csa_status_string[rc];
1916 DEBUG(D_acl) debug_printf_indent("CSA result %s\n", csa_status);
1917 return csa_return_code[rc];
1919 #ifdef EXPERIMENTAL_ARC
1922 const misc_module_info * mi = misc_mod_findonly(US"arc");
1923 typedef int (*fn_t)(const uschar *);
1924 if (mi) return (((fn_t *) mi->functions)[ARC_VERIFY])
1925 (CUS string_nextinlist(&list, &sep, NULL, 0));
1929 case VERIFY_HDR_SYNTAX:
1930 /* Check that all relevant header lines have the correct 5322-syntax. If there is
1931 a syntax error, we return details of the error to the sender if configured to
1932 send out full details. (But a "message" setting on the ACL can override, as
1935 rc = verify_check_headers(log_msgptr);
1936 if (rc != OK && *log_msgptr)
1937 if (smtp_return_error_details)
1938 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1940 acl_verify_message = *log_msgptr;
1943 case VERIFY_HDR_NAMES_ASCII:
1944 /* Check that all header names are true 7 bit strings
1945 See RFC 5322, 2.2. and RFC 6532, 3. */
1947 rc = verify_check_header_names_ascii(log_msgptr);
1948 if (rc != OK && smtp_return_error_details && *log_msgptr)
1949 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1952 case VERIFY_NOT_BLIND:
1953 /* Check that no recipient of this message is "blind", that is, every envelope
1954 recipient must be mentioned in either To: or Cc:. */
1956 BOOL case_sensitive = TRUE;
1958 while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
1959 if (strcmpic(ss, US"case_insensitive") == 0)
1960 case_sensitive = FALSE;
1963 *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1964 "condition \"verify %s\"", ss, arg);
1968 if ((rc = verify_check_notblind(case_sensitive)) != OK)
1970 *log_msgptr = US"bcc recipient detected";
1971 if (smtp_return_error_details)
1972 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1977 /* The remaining verification tests check recipient and sender addresses,
1978 either from the envelope or from the header. There are a number of
1979 slash-separated options that are common to all of them. */
1981 case VERIFY_HDR_SNDR:
1982 verify_header_sender = TRUE;
1986 /* In the case of a sender, this can optionally be followed by an address to use
1987 in place of the actual sender (rare special-case requirement). */
1991 verify_sender_address = sender_address;
1994 if (Uskip_whitespace(&s) != '=')
1997 Uskip_whitespace(&s);
1998 verify_sender_address = string_copy(s);
2009 /* Remaining items are optional; they apply to sender and recipient
2010 verification, including "header sender" verification. */
2012 while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
2014 if (strcmpic(ss, US"defer_ok") == 0) defer_ok = TRUE;
2015 else if (strcmpic(ss, US"no_details") == 0) no_details = TRUE;
2016 else if (strcmpic(ss, US"success_on_redirect") == 0) success_on_redirect = TRUE;
2018 /* These two old options are left for backwards compatibility */
2020 else if (strcmpic(ss, US"callout_defer_ok") == 0)
2022 callout_defer_ok = TRUE;
2023 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
2026 else if (strcmpic(ss, US"check_postmaster") == 0)
2029 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
2032 /* The callout option has a number of sub-options, comma separated */
2034 else if (strncmpic(ss, US"callout", 7) == 0)
2036 callout = CALLOUT_TIMEOUT_DEFAULT;
2039 Uskip_whitespace(&ss);
2042 const uschar * sublist = ss;
2045 Uskip_whitespace(&sublist);
2046 for (uschar * opt; opt = string_nextinlist(&sublist, &optsep, NULL, 0); )
2049 double period = 1.0F;
2051 for (op= callout_opt_list; op->name; op++)
2052 if (strncmpic(opt, op->name, Ustrlen(op->name)) == 0)
2055 verify_options |= op->flag;
2058 opt += Ustrlen(op->name);
2059 Uskip_whitespace(&opt);
2062 *log_msgptr = string_sprintf("'=' expected after "
2063 "\"%s\" in ACL verify condition \"%s\"", op->name, arg);
2066 Uskip_whitespace(&opt);
2068 if (op->timeval && (period = v_period(opt, arg, log_msgptr)) < 0)
2073 case CALLOUT_DEFER_OK: callout_defer_ok = TRUE; break;
2074 case CALLOUT_POSTMASTER: pm_mailfrom = US""; break;
2075 case CALLOUT_FULLPOSTMASTER: pm_mailfrom = US""; break;
2076 case CALLOUT_MAILFROM:
2077 if (!verify_header_sender)
2079 *log_msgptr = string_sprintf("\"mailfrom\" is allowed as a "
2080 "callout option only for verify=header_sender (detected in ACL "
2081 "condition \"%s\")", arg);
2084 se_mailfrom = string_copy(opt);
2086 case CALLOUT_POSTMASTER_MAILFROM: pm_mailfrom = string_copy(opt); break;
2087 case CALLOUT_MAXWAIT: callout_overall = period; break;
2088 case CALLOUT_CONNECT: callout_connect = period; break;
2089 case CALLOUT_TIME: callout = period; break;
2095 *log_msgptr = string_sprintf("'=' expected after \"callout\" in "
2096 "ACL condition \"%s\"", arg);
2102 /* The quota option has sub-options, comma-separated */
2104 else if (strncmpic(ss, US"quota", 5) == 0)
2109 Uskip_whitespace(&ss);
2112 const uschar * sublist = ss;
2116 Uskip_whitespace(&sublist);
2117 for (uschar * opt; opt = string_nextinlist(&sublist, &optsep, NULL, 0); )
2118 if (Ustrncmp(opt, "cachepos=", 9) == 0)
2119 if ((period = v_period(opt += 9, arg, log_msgptr)) < 0)
2122 quota_pos_cache = period;
2123 else if (Ustrncmp(opt, "cacheneg=", 9) == 0)
2124 if ((period = v_period(opt += 9, arg, log_msgptr)) < 0)
2127 quota_neg_cache = period;
2128 else if (Ustrcmp(opt, "no_cache") == 0)
2129 quota_pos_cache = quota_neg_cache = 0;
2134 /* Option not recognized */
2138 *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
2139 "condition \"verify %s\"", ss, arg);
2144 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)) ==
2145 (vopt_callout_recipsender|vopt_callout_recippmaster))
2147 *log_msgptr = US"only one of use_sender and use_postmaster can be set "
2148 "for a recipient callout";
2152 /* Handle quota verification */
2155 if (vp->value != VERIFY_RCPT)
2157 *log_msgptr = US"can only verify quota of recipient";
2161 if ((rc = verify_quota_call(addr->address,
2162 quota_pos_cache, quota_neg_cache, log_msgptr)) != OK)
2164 *basic_errno = errno;
2165 if (smtp_return_error_details)
2167 if (!*user_msgptr && *log_msgptr)
2168 *user_msgptr = string_sprintf("Rejected after %s: %s",
2169 smtp_names[smtp_connection_had[SMTP_HBUFF_PREV(smtp_ch_index)]],
2171 if (rc == DEFER) f.acl_temp_details = TRUE;
2178 /* Handle sender-in-header verification. Default the user message to the log
2179 message if giving out verification details. */
2181 if (verify_header_sender)
2185 if ((rc = verify_check_header_address(user_msgptr, log_msgptr, callout,
2186 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, verify_options,
2189 *basic_errno = verrno;
2190 if (smtp_return_error_details)
2192 if (!*user_msgptr && *log_msgptr)
2193 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
2194 if (rc == DEFER) f.acl_temp_details = TRUE;
2199 /* Handle a sender address. The default is to verify *the* sender address, but
2200 optionally a different address can be given, for special requirements. If the
2201 address is empty, we are dealing with a bounce message that has no sender, so
2202 we cannot do any checking. If the real sender address gets rewritten during
2203 verification (e.g. DNS widening), set the flag to stop it being rewritten again
2204 during message reception.
2206 A list of verified "sender" addresses is kept to try to avoid doing to much
2207 work repetitively when there are multiple recipients in a message and they all
2208 require sender verification. However, when callouts are involved, it gets too
2209 complicated because different recipients may require different callout options.
2210 Therefore, we always do a full sender verify when any kind of callout is
2211 specified. Caching elsewhere, for instance in the DNS resolver and in the
2212 callout handling, should ensure that this is not terribly inefficient. */
2214 else if (verify_sender_address)
2216 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)))
2218 *log_msgptr = US"use_sender or use_postmaster cannot be used for a "
2219 "sender verify callout";
2223 sender_vaddr = verify_checked_sender(verify_sender_address);
2224 if ( sender_vaddr /* Previously checked */
2225 && callout <= 0) /* No callout needed this time */
2227 /* If the "routed" flag is set, it means that routing worked before, so
2228 this check can give OK (the saved return code value, if set, belongs to a
2229 callout that was done previously). If the "routed" flag is not set, routing
2230 must have failed, so we use the saved return code. */
2232 if (testflag(sender_vaddr, af_verify_routed))
2236 rc = sender_vaddr->special_action;
2237 *basic_errno = sender_vaddr->basic_errno;
2239 HDEBUG(D_acl) debug_printf_indent("using cached sender verify result\n");
2242 /* Do a new verification, and cache the result. The cache is used to avoid
2243 verifying the sender multiple times for multiple RCPTs when callouts are not
2244 specified (see comments above).
2246 The cache is also used on failure to give details in response to the first
2247 RCPT that gets bounced for this reason. However, this can be suppressed by
2248 the no_details option, which sets the flag that says "this detail has already
2249 been sent". The cache normally contains just one address, but there may be
2250 more in esoteric circumstances. */
2255 uschar *save_address_data = deliver_address_data;
2257 sender_vaddr = deliver_make_addr(verify_sender_address, TRUE);
2259 if ((sender_vaddr->prop.utf8_msg = message_smtputf8))
2261 sender_vaddr->prop.utf8_downcvt = message_utf8_downconvert == 1;
2262 sender_vaddr->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1;
2265 if (no_details) setflag(sender_vaddr, af_sverify_told);
2266 if (verify_sender_address[0] != 0)
2268 /* If this is the real sender address, save the unrewritten version
2269 for use later in receive. Otherwise, set a flag so that rewriting the
2270 sender in verify_address() does not update sender_address. */
2272 if (verify_sender_address == sender_address)
2273 sender_address_unrewritten = sender_address;
2275 verify_options |= vopt_fake_sender;
2277 if (success_on_redirect)
2278 verify_options |= vopt_success_on_redirect;
2280 /* The recipient, qualify, and expn options are never set in
2283 rc = verify_address(sender_vaddr, NULL, verify_options, callout,
2284 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, &routed);
2286 HDEBUG(D_acl) debug_printf_indent("----------- end verify ------------\n");
2289 *basic_errno = sender_vaddr->basic_errno;
2292 if (Ustrcmp(sender_vaddr->address, verify_sender_address) != 0)
2293 debug_printf_indent("sender %s verified ok as %s\n",
2294 verify_sender_address, sender_vaddr->address);
2296 debug_printf_indent("sender %s verified ok\n",
2297 verify_sender_address);
2300 rc = OK; /* Null sender */
2302 /* Cache the result code */
2304 if (routed) setflag(sender_vaddr, af_verify_routed);
2305 if (callout > 0) setflag(sender_vaddr, af_verify_callout);
2306 sender_vaddr->special_action = rc;
2307 sender_vaddr->next = sender_verified_list;
2308 sender_verified_list = sender_vaddr;
2310 /* Restore the recipient address data, which might have been clobbered by
2311 the sender verification. */
2313 deliver_address_data = save_address_data;
2316 /* Put the sender address_data value into $sender_address_data */
2318 sender_address_data = sender_vaddr->prop.address_data;
2321 /* A recipient address just gets a straightforward verify; again we must handle
2322 the DEFER overrides. */
2328 if (success_on_redirect)
2329 verify_options |= vopt_success_on_redirect;
2331 /* We must use a copy of the address for verification, because it might
2335 rc = verify_address(&addr2, NULL, verify_options|vopt_is_recipient, callout,
2336 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, NULL);
2337 HDEBUG(D_acl) debug_printf_indent("----------- end verify ------------\n");
2339 *basic_errno = addr2.basic_errno;
2340 *log_msgptr = addr2.message;
2341 *user_msgptr = addr2.user_message ? addr2.user_message : addr2.message;
2343 /* Allow details for temporary error if the address is so flagged. */
2344 if (testflag((&addr2), af_pass_message)) f.acl_temp_details = TRUE;
2346 /* Make $address_data visible */
2347 deliver_address_data = addr2.prop.address_data;
2350 /* We have a result from the relevant test. Handle defer overrides first. */
2354 || callout_defer_ok && *basic_errno == ERRNO_CALLOUTDEFER
2357 HDEBUG(D_acl) debug_printf_indent("verify defer overridden by %s\n",
2358 defer_ok? "defer_ok" : "callout_defer_ok");
2362 /* If we've failed a sender, set up a recipient message, and point
2363 sender_verified_failed to the address item that actually failed. */
2365 if (rc != OK && verify_sender_address)
2368 *log_msgptr = *user_msgptr = US"Sender verify failed";
2369 else if (*basic_errno != ERRNO_CALLOUTDEFER)
2370 *log_msgptr = *user_msgptr = US"Could not complete sender verify";
2373 *log_msgptr = US"Could not complete sender verify callout";
2374 *user_msgptr = smtp_return_error_details? sender_vaddr->user_message :
2378 sender_verified_failed = sender_vaddr;
2381 /* Verifying an address messes up the values of $domain and $local_part,
2382 so reset them before returning if this is a RCPT ACL. */
2386 deliver_domain = addr->domain;
2387 deliver_localpart = addr->local_part;
2391 /* Syntax errors in the verify argument come here. */
2394 *log_msgptr = string_sprintf("expected \"sender[=address]\", \"recipient\", "
2395 "\"helo\", \"header_syntax\", \"header_sender\", \"header_names_ascii\" "
2396 "or \"reverse_host_lookup\" at start of ACL condition "
2397 "\"verify %s\"", arg);
2404 /*************************************************
2405 * Check argument for control= modifier *
2406 *************************************************/
2408 /* Called from acl_check_condition() below.
2409 To handle the case "queue_only" we accept an _ in the
2410 initial / option-switch position.
2413 arg the argument string for control=
2414 pptr set to point to the terminating character
2415 where which ACL we are in
2416 log_msgptr for error messages
2418 Returns: CONTROL_xxx value
2422 decode_control(const uschar *arg, const uschar **pptr, int where, uschar **log_msgptr)
2428 if ( (idx = find_control(arg, controls_list, nelem(controls_list))) < 0
2429 || ( (c = arg[len = Ustrlen((d = controls_list+idx)->name)]) != 0
2430 && (!d->has_option || c != '/' && c != '_')
2433 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2434 return CONTROL_ERROR;
2444 /*************************************************
2445 * Return a ratelimit error *
2446 *************************************************/
2448 /* Called from acl_ratelimit() below
2451 log_msgptr for error messages
2452 format format string
2453 ... supplementary arguments
2459 ratelimit_error(uschar **log_msgptr, const char *format, ...)
2463 string_cat(NULL, US"error in arguments to \"ratelimit\" condition: ");
2465 va_start(ap, format);
2466 g = string_vformat(g, SVFMT_EXTEND|SVFMT_REBUFFER, format, ap);
2469 gstring_release_unused(g);
2470 *log_msgptr = string_from_gstring(g);
2477 /*************************************************
2478 * Handle rate limiting *
2479 *************************************************/
2481 /* Called by acl_check_condition() below to calculate the result
2482 of the ACL ratelimit condition.
2484 Note that the return value might be slightly unexpected: if the
2485 sender's rate is above the limit then the result is OK. This is
2486 similar to the dnslists condition, and is so that you can write
2487 ACL clauses like: defer ratelimit = 15 / 1h
2490 arg the option string for ratelimit=
2491 where ACL_WHERE_xxxx indicating which ACL this is
2492 log_msgptr for error messages
2494 Returns: OK - Sender's rate is above limit
2495 FAIL - Sender's rate is below limit
2496 DEFER - Problem opening ratelimit database
2497 ERROR - Syntax error in options.
2501 acl_ratelimit(const uschar *arg, int where, uschar **log_msgptr)
2503 double limit, period, count;
2506 uschar *unique = NULL;
2508 BOOL leaky = FALSE, strict = FALSE, readonly = FALSE;
2509 BOOL noupdate = FALSE, badacl = FALSE;
2510 int mode = RATE_PER_WHAT;
2512 tree_node **anchor, *t;
2513 open_db dbblock, *dbm;
2515 dbdata_ratelimit *dbd;
2516 dbdata_ratelimit_unique *dbdb;
2519 /* Parse the first two options and record their values in expansion
2520 variables. These variables allow the configuration to have informative
2521 error messages based on rate limits obtained from a table lookup. */
2523 /* First is the maximum number of messages per period / maximum burst
2524 size, which must be greater than or equal to zero. Zero is useful for
2525 rate measurement as opposed to rate limiting. */
2527 if (!(sender_rate_limit = string_nextinlist(&arg, &sep, NULL, 0)))
2528 return ratelimit_error(log_msgptr, "sender rate limit not set");
2530 limit = Ustrtod(sender_rate_limit, &ss);
2531 if (tolower(*ss) == 'k') { limit *= 1024.0; ss++; }
2532 else if (tolower(*ss) == 'm') { limit *= 1024.0*1024.0; ss++; }
2533 else if (tolower(*ss) == 'g') { limit *= 1024.0*1024.0*1024.0; ss++; }
2535 if (limit < 0.0 || *ss != '\0')
2536 return ratelimit_error(log_msgptr,
2537 "\"%s\" is not a positive number", sender_rate_limit);
2539 /* Second is the rate measurement period / exponential smoothing time
2540 constant. This must be strictly greater than zero, because zero leads to
2541 run-time division errors. */
2543 period = !(sender_rate_period = string_nextinlist(&arg, &sep, NULL, 0))
2544 ? -1.0 : readconf_readtime(sender_rate_period, 0, FALSE);
2546 return ratelimit_error(log_msgptr,
2547 "\"%s\" is not a time value", sender_rate_period);
2549 /* By default we are counting one of something, but the per_rcpt,
2550 per_byte, and count options can change this. */
2554 /* Parse the other options. */
2556 while ((ss = string_nextinlist(&arg, &sep, NULL, 0)))
2558 if (strcmpic(ss, US"leaky") == 0) leaky = TRUE;
2559 else if (strcmpic(ss, US"strict") == 0) strict = TRUE;
2560 else if (strcmpic(ss, US"noupdate") == 0) noupdate = TRUE;
2561 else if (strcmpic(ss, US"readonly") == 0) readonly = TRUE;
2562 else if (strcmpic(ss, US"per_cmd") == 0) RATE_SET(mode, PER_CMD);
2563 else if (strcmpic(ss, US"per_conn") == 0)
2565 RATE_SET(mode, PER_CONN);
2566 if (where == ACL_WHERE_NOTSMTP || where == ACL_WHERE_NOTSMTP_START)
2569 else if (strcmpic(ss, US"per_mail") == 0)
2571 RATE_SET(mode, PER_MAIL);
2572 if (where > ACL_WHERE_NOTSMTP) badacl = TRUE;
2574 else if (strcmpic(ss, US"per_rcpt") == 0)
2576 /* If we are running in the RCPT ACL, then we'll count the recipients
2577 one by one, but if we are running when we have accumulated the whole
2578 list then we'll add them all in one batch. */
2579 if (where == ACL_WHERE_RCPT)
2580 RATE_SET(mode, PER_RCPT);
2581 else if (where >= ACL_WHERE_PREDATA && where <= ACL_WHERE_NOTSMTP)
2582 RATE_SET(mode, PER_ALLRCPTS), count = (double)recipients_count;
2583 else if (where == ACL_WHERE_MAIL || where > ACL_WHERE_NOTSMTP)
2584 RATE_SET(mode, PER_RCPT), badacl = TRUE;
2586 else if (strcmpic(ss, US"per_byte") == 0)
2588 /* If we have not yet received the message data and there was no SIZE
2589 declaration on the MAIL command, then it's safe to just use a value of
2590 zero and let the recorded rate decay as if nothing happened. */
2591 RATE_SET(mode, PER_MAIL);
2592 if (where > ACL_WHERE_NOTSMTP) badacl = TRUE;
2593 else count = message_size < 0 ? 0.0 : (double)message_size;
2595 else if (strcmpic(ss, US"per_addr") == 0)
2597 RATE_SET(mode, PER_RCPT);
2598 if (where != ACL_WHERE_RCPT) badacl = TRUE, unique = US"*";
2599 else unique = string_sprintf("%s@%s", deliver_localpart, deliver_domain);
2601 else if (strncmpic(ss, US"count=", 6) == 0)
2604 count = Ustrtod(ss+6, &e);
2605 if (count < 0.0 || *e != '\0')
2606 return ratelimit_error(log_msgptr, "\"%s\" is not a positive number", ss);
2608 else if (strncmpic(ss, US"unique=", 7) == 0)
2609 unique = string_copy(ss + 7);
2611 key = string_copy(ss);
2613 key = string_sprintf("%s/%s", key, ss);
2616 /* Sanity check. When the badacl flag is set the update mode must either
2617 be readonly (which is the default if it is omitted) or, for backwards
2618 compatibility, a combination of noupdate and strict or leaky. */
2620 if (mode == RATE_PER_CLASH)
2621 return ratelimit_error(log_msgptr, "conflicting per_* options");
2622 if (leaky + strict + readonly > 1)
2623 return ratelimit_error(log_msgptr, "conflicting update modes");
2624 if (badacl && (leaky || strict) && !noupdate)
2625 return ratelimit_error(log_msgptr,
2626 "\"%s\" must not have /leaky or /strict option, or cannot be used in %s ACL",
2627 ratelimit_option_string[mode], acl_wherenames[where]);
2629 /* Set the default values of any unset options. In readonly mode we
2630 perform the rate computation without any increment so that its value
2631 decays to eventually allow over-limit senders through. */
2633 if (noupdate) readonly = TRUE, leaky = strict = FALSE;
2634 if (badacl) readonly = TRUE;
2635 if (readonly) count = 0.0;
2636 if (!strict && !readonly) leaky = TRUE;
2637 if (mode == RATE_PER_WHAT) mode = RATE_PER_MAIL;
2639 /* Create the lookup key. If there is no explicit key, use sender_host_address.
2640 If there is no sender_host_address (e.g. -bs or acl_not_smtp) then we simply
2641 omit it. The smoothing constant (sender_rate_period) and the per_xxx options
2642 are added to the key because they alter the meaning of the stored data. */
2645 key = !sender_host_address ? US"" : sender_host_address;
2647 key = string_sprintf("%s/%s/%s%s",
2649 ratelimit_option_string[mode],
2650 unique == NULL ? "" : "unique/",
2654 debug_printf_indent("ratelimit condition count=%.0f %.1f/%s\n", count, limit, key);
2656 /* See if we have already computed the rate by looking in the relevant tree.
2657 For per-connection rate limiting, store tree nodes and dbdata in the permanent
2658 pool so that they survive across resets. In readonly mode we only remember the
2659 result for the rest of this command in case a later command changes it. After
2660 this bit of logic the code is independent of the per_* mode. */
2662 old_pool = store_pool;
2665 anchor = &ratelimiters_cmd;
2669 anchor = &ratelimiters_conn;
2670 store_pool = POOL_PERM;
2674 case RATE_PER_ALLRCPTS:
2675 anchor = &ratelimiters_mail;
2680 anchor = &ratelimiters_cmd;
2683 anchor = NULL; /* silence an "unused" complaint */
2684 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
2685 "internal ACL error: unknown ratelimit mode %d", mode);
2690 if ((t = tree_search(*anchor, key)))
2693 /* The following few lines duplicate some of the code below. */
2694 rc = (dbd->rate < limit)? FAIL : OK;
2695 store_pool = old_pool;
2696 sender_rate = string_sprintf("%.1f", dbd->rate);
2698 debug_printf_indent("ratelimit found pre-computed rate %s\n", sender_rate);
2702 /* We aren't using a pre-computed rate, so get a previously recorded rate
2703 from the database, which will be updated and written back if required. */
2705 if (!(dbm = dbfn_open(US"ratelimit", O_RDWR|O_CREAT, &dbblock, TRUE, TRUE)))
2707 store_pool = old_pool;
2709 HDEBUG(D_acl) debug_printf_indent("ratelimit database not available\n");
2710 *log_msgptr = US"ratelimit database not available";
2713 dbdb = dbfn_read_with_length(dbm, key, &dbdb_size);
2716 gettimeofday(&tv, NULL);
2720 /* Locate the basic ratelimit block inside the DB data. */
2721 HDEBUG(D_acl) debug_printf_indent("ratelimit found key in database\n");
2724 /* Forget the old Bloom filter if it is too old, so that we count each
2725 repeating event once per period. We don't simply clear and re-use the old
2726 filter because we want its size to change if the limit changes. Note that
2727 we keep the dbd pointer for copying the rate into the new data block. */
2729 if(unique && tv.tv_sec > dbdb->bloom_epoch + period)
2731 HDEBUG(D_acl) debug_printf_indent("ratelimit discarding old Bloom filter\n");
2737 if(unique && dbdb_size < sizeof(*dbdb))
2739 HDEBUG(D_acl) debug_printf_indent("ratelimit discarding undersize Bloom filter\n");
2744 /* Allocate a new data block if the database lookup failed
2745 or the Bloom filter passed its age limit. */
2751 /* No Bloom filter. This basic ratelimit block is initialized below. */
2752 HDEBUG(D_acl) debug_printf_indent("ratelimit creating new rate data block\n");
2753 dbdb_size = sizeof(*dbd);
2754 dbdb = store_get(dbdb_size, GET_UNTAINTED);
2759 HDEBUG(D_acl) debug_printf_indent("ratelimit creating new Bloom filter\n");
2761 /* See the long comment below for an explanation of the magic number 2.
2762 The filter has a minimum size in case the rate limit is very small;
2763 this is determined by the definition of dbdata_ratelimit_unique. */
2765 extra = (int)limit * 2 - sizeof(dbdb->bloom);
2766 if (extra < 0) extra = 0;
2767 dbdb_size = sizeof(*dbdb) + extra;
2768 dbdb = store_get(dbdb_size, GET_UNTAINTED);
2769 dbdb->bloom_epoch = tv.tv_sec;
2770 dbdb->bloom_size = sizeof(dbdb->bloom) + extra;
2771 memset(dbdb->bloom, 0, dbdb->bloom_size);
2773 /* Preserve any basic ratelimit data (which is our longer-term memory)
2774 by copying it from the discarded block. */
2784 /* If we are counting unique events, find out if this event is new or not.
2785 If the client repeats the event during the current period then it should be
2786 counted. We skip this code in readonly mode for efficiency, because any
2787 changes to the filter will be discarded and because count is already set to
2790 if (unique && !readonly)
2792 /* We identify unique events using a Bloom filter. (You can find my
2793 notes on Bloom filters at http://fanf.livejournal.com/81696.html)
2794 With the per_addr option, an "event" is a recipient address, though the
2795 user can use the unique option to define their own events. We only count
2796 an event if we have not seen it before.
2798 We size the filter according to the rate limit, which (in leaky mode)
2799 is the limit on the population of the filter. We allow 16 bits of space
2800 per entry (see the construction code above) and we set (up to) 8 of them
2801 when inserting an element (see the loop below). The probability of a false
2802 positive (an event we have not seen before but which we fail to count) is
2806 allzero = exp(-numhash * pop / size)
2807 = exp(-0.5 * pop / limit)
2808 fpr = pow(1 - allzero, numhash)
2810 For senders at the limit the fpr is 0.06% or 1 in 1700
2811 and for senders at half the limit it is 0.0006% or 1 in 170000
2813 In strict mode the Bloom filter can fill up beyond the normal limit, in
2814 which case the false positive rate will rise. This means that the
2815 measured rate for very fast senders can bogusly drop off after a while.
2817 At twice the limit, the fpr is 2.5% or 1 in 40
2818 At four times the limit, it is 31% or 1 in 3.2
2820 It takes ln(pop/limit) periods for an over-limit burst of pop events to
2821 decay below the limit, and if this is more than one then the Bloom filter
2822 will be discarded before the decay gets that far. The false positive rate
2823 at this threshold is 9.3% or 1 in 10.7. */
2826 unsigned n, hash, hinc;
2830 /* Instead of using eight independent hash values, we combine two values
2831 using the formula h1 + n * h2. This does not harm the Bloom filter's
2832 performance, and means the amount of hash we need is independent of the
2833 number of bits we set in the filter. */
2835 md5_start(&md5info);
2836 md5_end(&md5info, unique, Ustrlen(unique), md5sum);
2837 hash = md5sum[0] | md5sum[1] << 8 | md5sum[2] << 16 | md5sum[3] << 24;
2838 hinc = md5sum[4] | md5sum[5] << 8 | md5sum[6] << 16 | md5sum[7] << 24;
2840 /* Scan the bits corresponding to this event. A zero bit means we have
2841 not seen it before. Ensure all bits are set to record this event. */
2843 HDEBUG(D_acl) debug_printf_indent("ratelimit checking uniqueness of %s\n", unique);
2846 for (n = 0; n < 8; n++, hash += hinc)
2848 int bit = 1 << (hash % 8);
2849 int byte = (hash / 8) % dbdb->bloom_size;
2850 if ((dbdb->bloom[byte] & bit) == 0)
2852 dbdb->bloom[byte] |= bit;
2857 /* If this event has occurred before, do not count it. */
2861 HDEBUG(D_acl) debug_printf_indent("ratelimit event found in Bloom filter\n");
2865 HDEBUG(D_acl) debug_printf_indent("ratelimit event added to Bloom filter\n");
2868 /* If there was no previous ratelimit data block for this key, initialize
2869 the new one, otherwise update the block from the database. The initial rate
2870 is what would be computed by the code below for an infinite interval. */
2874 HDEBUG(D_acl) debug_printf_indent("ratelimit initializing new key's rate data\n");
2876 dbd->time_stamp = tv.tv_sec;
2877 dbd->time_usec = tv.tv_usec;
2882 /* The smoothed rate is computed using an exponentially weighted moving
2883 average adjusted for variable sampling intervals. The standard EWMA for
2884 a fixed sampling interval is: f'(t) = (1 - a) * f(t) + a * f'(t - 1)
2885 where f() is the measured value and f'() is the smoothed value.
2887 Old data decays out of the smoothed value exponentially, such that data n
2888 samples old is multiplied by a^n. The exponential decay time constant p
2889 is defined such that data p samples old is multiplied by 1/e, which means
2890 that a = exp(-1/p). We can maintain the same time constant for a variable
2891 sampling interval i by using a = exp(-i/p).
2893 The rate we are measuring is messages per period, suitable for directly
2894 comparing with the limit. The average rate between now and the previous
2895 message is period / interval, which we feed into the EWMA as the sample.
2897 It turns out that the number of messages required for the smoothed rate
2898 to reach the limit when they are sent in a burst is equal to the limit.
2899 This can be seen by analysing the value of the smoothed rate after N
2900 messages sent at even intervals. Let k = (1 - a) * p/i
2902 rate_1 = (1 - a) * p/i + a * rate_0
2904 rate_2 = k + a * rate_1
2905 = k + a * k + a^2 * rate_0
2906 rate_3 = k + a * k + a^2 * k + a^3 * rate_0
2907 rate_N = rate_0 * a^N + k * SUM(x=0..N-1)(a^x)
2908 = rate_0 * a^N + k * (1 - a^N) / (1 - a)
2909 = rate_0 * a^N + p/i * (1 - a^N)
2911 When N is large, a^N -> 0 so rate_N -> p/i as desired.
2913 rate_N = p/i + (rate_0 - p/i) * a^N
2914 a^N = (rate_N - p/i) / (rate_0 - p/i)
2915 N * -i/p = log((rate_N - p/i) / (rate_0 - p/i))
2916 N = p/i * log((rate_0 - p/i) / (rate_N - p/i))
2918 Numerical analysis of the above equation, setting the computed rate to
2919 increase from rate_0 = 0 to rate_N = limit, shows that for large sending
2920 rates, p/i, the number of messages N = limit. So limit serves as both the
2921 maximum rate measured in messages per period, and the maximum number of
2922 messages that can be sent in a fast burst. */
2924 double this_time = (double)tv.tv_sec
2925 + (double)tv.tv_usec / 1000000.0;
2926 double prev_time = (double)dbd->time_stamp
2927 + (double)dbd->time_usec / 1000000.0;
2929 /* We must avoid division by zero, and deal gracefully with the clock going
2930 backwards. If we blunder ahead when time is in reverse then the computed
2931 rate will be bogus. To be safe we clamp interval to a very small number. */
2933 double interval = this_time - prev_time <= 0.0 ? 1e-9
2934 : this_time - prev_time;
2936 double i_over_p = interval / period;
2937 double a = exp(-i_over_p);
2939 /* Combine the instantaneous rate (period / interval) with the previous rate
2940 using the smoothing factor a. In order to measure sized events, multiply the
2941 instantaneous rate by the count of bytes or recipients etc. */
2943 dbd->time_stamp = tv.tv_sec;
2944 dbd->time_usec = tv.tv_usec;
2945 dbd->rate = (1 - a) * count / i_over_p + a * dbd->rate;
2947 /* When events are very widely spaced the computed rate tends towards zero.
2948 Although this is accurate it turns out not to be useful for our purposes,
2949 especially when the first event after a long silence is the start of a spam
2950 run. A more useful model is that the rate for an isolated event should be the
2951 size of the event per the period size, ignoring the lack of events outside
2952 the current period and regardless of where the event falls in the period. So,
2953 if the interval was so long that the calculated rate is unhelpfully small, we
2954 re-initialize the rate. In the absence of higher-rate bursts, the condition
2955 below is true if the interval is greater than the period. */
2957 if (dbd->rate < count) dbd->rate = count;
2960 /* Clients sending at the limit are considered to be over the limit.
2961 This matters for edge cases such as a limit of zero, when the client
2962 should be completely blocked. */
2964 rc = dbd->rate < limit ? FAIL : OK;
2966 /* Update the state if the rate is low or if we are being strict. If we
2967 are in leaky mode and the sender's rate is too high, we do not update
2968 the recorded rate in order to avoid an over-aggressive sender's retry
2969 rate preventing them from getting any email through. If readonly is set,
2970 neither leaky nor strict are set, so we do not do any updates. */
2972 if ((rc == FAIL && leaky) || strict)
2974 dbfn_write(dbm, key, dbdb, dbdb_size);
2975 HDEBUG(D_acl) debug_printf_indent("ratelimit db updated\n");
2979 HDEBUG(D_acl) debug_printf_indent("ratelimit db not updated: %s\n",
2980 readonly? "readonly mode" : "over the limit, but leaky");
2985 /* Store the result in the tree for future reference. Take the taint status
2986 from the key for consistency even though it's unlikely we'll ever expand this. */
2988 t = store_get(sizeof(tree_node) + Ustrlen(key), key);
2990 Ustrcpy(t->name, key);
2991 (void)tree_insertnode(anchor, t);
2993 /* We create the formatted version of the sender's rate very late in
2994 order to ensure that it is done using the correct storage pool. */
2996 store_pool = old_pool;
2997 sender_rate = string_sprintf("%.1f", dbd->rate);
3000 debug_printf_indent("ratelimit computed rate %s\n", sender_rate);
3007 /*************************************************
3008 * Handle a check for previously-seen *
3009 *************************************************/
3012 ACL clauses like: seen = -5m / key=$foo / readonly
3014 Return is true for condition-true - but the semantics
3015 depend heavily on the actual use-case.
3017 Negative times test for seen-before, positive for seen-more-recently-than
3018 (the given interval before current time).
3020 All are subject to history not having been cleaned from the DB.
3022 Default for seen-before is to create if not present, and to
3023 update if older than 10d (with the seen-test time).
3024 Default for seen-since is to always create or update.
3027 key=value. Default key is $sender_host_address
3030 refresh=<interval>: update an existing DB entry older than given
3031 amount. Default refresh lacking this option is 10d.
3032 The update sets the record timestamp to the seen-test time.
3034 XXX do we need separate nocreate, noupdate controls?
3037 arg the option string for seen=
3038 where ACL_WHERE_xxxx indicating which ACL this is
3039 log_msgptr for error messages
3041 Returns: OK - Condition is true
3042 FAIL - Condition is false
3043 DEFER - Problem opening history database
3044 ERROR - Syntax error in options
3048 acl_seen(const uschar * arg, int where, uschar ** log_msgptr)
3050 enum { SEEN_DEFAULT, SEEN_READONLY, SEEN_WRITE };
3052 const uschar * list = arg;
3053 int slash = '/', interval, mode = SEEN_DEFAULT, yield = FAIL;
3055 int refresh = 10 * 24 * 60 * 60; /* 10 days */
3056 const uschar * ele, * key = sender_host_address;
3057 open_db dbblock, * dbm;
3061 /* Parse the first element, the time-relation. */
3063 if (!(ele = string_nextinlist(&list, &slash, NULL, 0)))
3065 if ((before = *ele == '-'))
3067 if ((interval = readconf_readtime(ele, 0, FALSE)) < 0)
3070 /* Remaining elements are options */
3072 while ((ele = string_nextinlist(&list, &slash, NULL, 0)))
3073 if (Ustrncmp(ele, "key=", 4) == 0)
3075 else if (Ustrcmp(ele, "readonly") == 0)
3076 mode = SEEN_READONLY;
3077 else if (Ustrcmp(ele, "write") == 0)
3079 else if (Ustrncmp(ele, "refresh=", 8) == 0)
3081 if ((refresh = readconf_readtime(ele + 8, 0, FALSE)) < 0)
3087 if (!(dbm = dbfn_open(US"seen", O_RDWR|O_CREAT, &dbblock, TRUE, TRUE)))
3089 HDEBUG(D_acl) debug_printf_indent("database for 'seen' not available\n");
3090 *log_msgptr = US"database for 'seen' not available";
3094 dbd = dbfn_read_with_length(dbm, key, NULL);
3096 if (dbd) /* an existing record */
3098 time_t diff = now - dbd->time_stamp; /* time since the record was written */
3100 if (before ? diff >= interval : diff < interval)
3103 if (mode == SEEN_READONLY)
3104 { HDEBUG(D_acl) debug_printf_indent("seen db not written (readonly)\n"); }
3105 else if (mode == SEEN_WRITE || !before)
3107 dbd->time_stamp = now;
3108 dbfn_write(dbm, key, dbd, sizeof(*dbd));
3109 HDEBUG(D_acl) debug_printf_indent("seen db written (update)\n");
3111 else if (diff >= refresh)
3113 dbd->time_stamp = now - interval;
3114 dbfn_write(dbm, key, dbd, sizeof(*dbd));
3115 HDEBUG(D_acl) debug_printf_indent("seen db written (refresh)\n");
3119 { /* No record found, yield always FAIL */
3120 if (mode != SEEN_READONLY)
3122 dbdata_seen d = {.time_stamp = now};
3123 dbfn_write(dbm, key, &d, sizeof(*dbd));
3124 HDEBUG(D_acl) debug_printf_indent("seen db written (create)\n");
3127 HDEBUG(D_acl) debug_printf_indent("seen db not written (readonly)\n");
3135 *log_msgptr = string_sprintf("failed to parse '%s'", arg);
3138 *log_msgptr = string_sprintf("unrecognised option '%s' in '%s'", ele, arg);
3144 /*************************************************
3145 * The udpsend ACL modifier *
3146 *************************************************/
3148 /* Called by acl_check_condition() below.
3151 arg the option string for udpsend=
3152 log_msgptr for error messages
3154 Returns: OK - Completed.
3155 DEFER - Problem with DNS lookup.
3156 ERROR - Syntax error in options.
3160 acl_udpsend(const uschar *arg, uschar **log_msgptr)
3172 hostname = string_nextinlist(&arg, &sep, NULL, 0);
3173 portstr = string_nextinlist(&arg, &sep, NULL, 0);
3177 *log_msgptr = US"missing destination host in \"udpsend\" modifier";
3182 *log_msgptr = US"missing destination port in \"udpsend\" modifier";
3187 *log_msgptr = US"missing datagram payload in \"udpsend\" modifier";
3190 portnum = Ustrtol(portstr, &portend, 10);
3191 if (*portend != '\0')
3193 *log_msgptr = US"bad destination port in \"udpsend\" modifier";
3197 /* Make a single-item host list. */
3198 h = store_get(sizeof(host_item), GET_UNTAINTED);
3199 memset(h, 0, sizeof(host_item));
3204 if (string_is_ip_address(hostname, NULL))
3205 h->address = hostname, r = HOST_FOUND;
3207 r = host_find_byname(h, NULL, 0, NULL, FALSE);
3208 if (r == HOST_FIND_FAILED || r == HOST_FIND_AGAIN)
3210 *log_msgptr = US"DNS lookup failed in \"udpsend\" modifier";
3215 debug_printf_indent("udpsend [%s]:%d %s\n", h->address, portnum, arg);
3217 /*XXX this could better use sendto */
3218 r = s = ip_connectedsocket(SOCK_DGRAM, h->address, portnum, portnum,
3219 1, NULL, &errstr, NULL);
3220 if (r < 0) goto defer;
3222 r = send(s, arg, len, 0);
3225 errstr = US strerror(errno);
3233 string_sprintf("\"udpsend\" truncated from %d to %d octets", len, r);
3238 debug_printf_indent("udpsend %d bytes\n", r);
3243 *log_msgptr = string_sprintf("\"udpsend\" failed: %s", errstr);
3249 #ifndef DISABLE_WELLKNOWN
3250 /*************************************************
3251 * The "wellknown" ACL modifier *
3252 *************************************************/
3254 /* Called by acl_check_condition() below.
3256 Retrieve the given file and encode content as xtext.
3257 Prefix with a summary line giving the length of plaintext.
3258 Leave a global pointer to the whole, for output by
3259 the smtp verb handler code (smtp_in.c).
3262 arg the option string for wellknown=
3263 log_msgptr for error messages
3269 wellknown_process(const uschar * arg, uschar ** log_msgptr)
3271 struct stat statbuf;
3275 wellknown_response = NULL;
3276 if (f.no_multiline_responses) return FAIL;
3278 /* Check for file existence */
3280 if (!*arg) return FAIL;
3281 if (Ustat(arg, &statbuf) != 0)
3282 { *log_msgptr = US"stat"; goto fail; }
3284 /*XXX perhaps refuse to serve a group- or world-writeable file? */
3286 if (!(rf = Ufopen(arg, "r")))
3287 { *log_msgptr = US"open"; goto fail; }
3289 /* Set up summary line for output */
3291 g = string_fmt_append(NULL, "SIZE=%lu\n", (long) statbuf.st_size);
3294 for (int n = 0, ch; (ch = fgetc(rf)) != EOF; )
3296 /* Xtext-encode, adding output linebreaks for input linebreaks
3297 or when the line gets long enough */
3300 { g = string_fmt_append(g, "+%02X", ch); n = LINE_LIM; }
3301 else if (ch < 33 || ch > 126 || ch == '+' || ch == '=')
3302 { g = string_fmt_append(g, "+%02X", ch); n += 3; }
3304 { g = string_fmt_append(g, "%c", ch); n++; }
3307 { g = string_catn(g, US"\n", 1); n = 0; }
3311 gstring_release_unused(g);
3312 wellknown_response = string_from_gstring(g);
3316 *log_msgptr = string_sprintf("wellknown: failed to %s file \"%s\": %s",
3317 *log_msgptr, arg, strerror(errno));
3323 /*************************************************
3324 * Handle conditions/modifiers on an ACL item *
3325 *************************************************/
3327 /* Called from acl_check() below.
3331 cb ACL condition block - if NULL, result is OK
3332 where where called from
3333 addr the address being checked for RCPT, or NULL
3334 level the nesting level
3335 epp pointer to pass back TRUE if "endpass" encountered
3336 (applies only to "accept" and "discard")
3337 user_msgptr user message pointer
3338 log_msgptr log message pointer
3339 basic_errno pointer to where to put verify error
3341 Returns: OK - all conditions are met
3342 DISCARD - an "acl" condition returned DISCARD - only allowed
3343 for "accept" or "discard" verbs
3344 FAIL - at least one condition fails
3345 FAIL_DROP - an "acl" condition returned FAIL_DROP
3346 DEFER - can't tell at the moment (typically, lookup defer,
3347 but can be temporary callout problem)
3348 ERROR - ERROR from nested ACL or expansion failure or other
3353 acl_check_condition(int verb, acl_condition_block *cb, int where,
3354 address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
3355 uschar **log_msgptr, int *basic_errno)
3357 uschar * user_message = NULL;
3358 uschar * log_message = NULL;
3361 for (; cb; cb = cb->next)
3365 BOOL textonly = FALSE;
3367 /* The message and log_message items set up messages to be used in
3368 case of rejection. They are expanded later. */
3370 if (cb->type == ACLC_MESSAGE)
3372 HDEBUG(D_acl) debug_printf_indent(" message: %s\n", cb->arg);
3373 user_message = cb->arg;
3377 if (cb->type == ACLC_LOG_MESSAGE)
3379 HDEBUG(D_acl) debug_printf_indent("l_message: %s\n", cb->arg);
3380 log_message = cb->arg;
3384 /* The endpass "condition" just sets a flag to show it occurred. This is
3385 checked at compile time to be on an "accept" or "discard" item. */
3387 if (cb->type == ACLC_ENDPASS)
3393 /* For other conditions and modifiers, the argument is expanded now for some
3394 of them, but not for all, because expansion happens down in some lower level
3395 checking functions in some cases. */
3397 if (!(conditions[cb->type].flags & ACD_EXP))
3400 else if (!(arg = expand_string_2(cb->arg, &textonly)))
3402 if (f.expand_string_forcedfail) continue;
3403 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
3404 cb->arg, expand_string_message);
3405 return f.search_find_defer ? DEFER : ERROR;
3408 /* Show condition, and expanded condition if it's different */
3413 debug_printf_indent("check %s%s %n",
3414 (!(conditions[cb->type].flags & ACD_MOD) && cb->u.negated) ? "!":"",
3415 conditions[cb->type].name, &lhswidth);
3417 if (cb->type == ACLC_SET)
3419 #ifndef DISABLE_DKIM
3420 if ( Ustrcmp(cb->u.varname, "dkim_verify_status") == 0
3421 || Ustrcmp(cb->u.varname, "dkim_verify_reason") == 0)
3423 debug_printf("%s ", cb->u.varname);
3429 debug_printf("acl_%s ", cb->u.varname);
3430 lhswidth += 5 + Ustrlen(cb->u.varname);
3434 debug_printf("= %s\n", cb->arg);
3437 debug_printf("%.*s= %s\n", lhswidth,
3441 /* Check that this condition makes sense at this time */
3443 if ((conditions[cb->type].forbids & (1 << where)) != 0)
3445 *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
3446 conditions[cb->type].flags & ACD_MOD ? "use" : "test",
3447 conditions[cb->type].name, acl_wherenames[where]);
3451 /* Run the appropriate test for each condition, or take the appropriate
3452 action for the remaining modifiers. */
3456 /* A nested ACL that returns "discard" makes sense only for an "accept" or
3460 rc = acl_check_wargs(where, addr, arg, user_msgptr, log_msgptr);
3461 if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
3463 *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
3464 "\"%s\" command (only allowed with \"accept\" or \"discard\")",
3470 case ACLC_ADD_HEADER:
3474 case ACLC_ATRN_DOMAINS:
3475 if (is_tainted(arg))
3477 log_write(0, LOG_MAIN|LOG_PANIC,
3478 "attempt to used tainted value '%s' for atrn_domains%#s",
3481 ? string_sprintf(" (%s %d)", config_filename, config_lineno)
3483 *log_msgptr = US"internal configuration error";
3486 atrn_domains = string_copy(arg);
3488 rc = spool_has_one_undelivered_dom(arg);
3492 case ACLC_AUTHENTICATED:
3493 rc = sender_host_authenticated ? match_isinlist(sender_host_authenticated,
3494 &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL) : FAIL;
3497 #ifdef EXPERIMENTAL_BRIGHTMAIL
3498 case ACLC_BMI_OPTIN:
3500 int old_pool = store_pool;
3501 store_pool = POOL_PERM;
3502 bmi_current_optin = string_copy(arg);
3503 store_pool = old_pool;
3508 case ACLC_CONDITION:
3509 /* The true/false parsing here should be kept in sync with that used in
3510 expand.c when dealing with ECOND_BOOL so that we don't have too many
3511 different definitions of what can be a boolean. */
3513 ? Ustrspn(arg+1, "0123456789") == Ustrlen(arg+1) /* Negative number */
3514 : Ustrspn(arg, "0123456789") == Ustrlen(arg)) /* Digits, or empty */
3515 rc = (Uatoi(arg) == 0)? FAIL : OK;
3517 rc = (strcmpic(arg, US"no") == 0 ||
3518 strcmpic(arg, US"false") == 0)? FAIL :
3519 (strcmpic(arg, US"yes") == 0 ||
3520 strcmpic(arg, US"true") == 0)? OK : DEFER;
3522 *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
3525 case ACLC_CONTINUE: /* Always succeeds */
3530 const uschar * p = NULL;
3531 control_type = decode_control(arg, &p, where, log_msgptr);
3533 /* Check if this control makes sense at this time */
3535 if (controls_list[control_type].forbids & (1 << where))
3537 *log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
3538 controls_list[control_type].name, acl_wherenames[where]);
3542 /*XXX ought to sort these, just for sanity */
3543 switch(control_type)
3545 case CONTROL_AUTH_UNADVERTISED:
3546 f.allow_auth_unadvertised = TRUE;
3549 #ifdef EXPERIMENTAL_BRIGHTMAIL
3550 case CONTROL_BMI_RUN:
3555 #ifndef DISABLE_DKIM
3556 case CONTROL_DKIM_VERIFY:
3557 f.dkim_disable_verify = TRUE;
3558 # ifdef SUPPORT_DMARC
3559 /* Since DKIM was blocked, skip DMARC too */
3560 f.dmarc_disable_verify = TRUE;
3561 f.dmarc_enable_forensic = FALSE;
3566 #ifdef SUPPORT_DMARC
3567 case CONTROL_DMARC_VERIFY:
3568 f.dmarc_disable_verify = TRUE;
3571 case CONTROL_DMARC_FORENSIC:
3572 f.dmarc_enable_forensic = TRUE;
3579 int fd, af, level, optname, value;
3580 /* If we are acting on stdin, the setsockopt may fail if stdin is not
3581 a socket; we can accept that, we'll just debug-log failures anyway. */
3582 fd = fileno(smtp_in);
3583 if ((af = ip_get_address_family(fd)) < 0)
3586 debug_printf_indent("smtp input is probably not a socket [%s], not setting DSCP\n",
3590 if (dscp_lookup(p+1, af, &level, &optname, &value))
3591 if (setsockopt(fd, level, optname, &value, sizeof(value)) < 0)
3593 HDEBUG(D_acl) debug_printf_indent("failed to set input DSCP[%s]: %s\n",
3594 p+1, strerror(errno));
3598 HDEBUG(D_acl) debug_printf_indent("set input DSCP to \"%s\"\n", p+1);
3602 *log_msgptr = string_sprintf("unrecognised DSCP value in \"control=%s\"", arg);
3608 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
3616 case CONTROL_CASEFUL_LOCAL_PART:
3617 deliver_localpart = addr->cc_local_part;
3620 case CONTROL_CASELOWER_LOCAL_PART:
3621 deliver_localpart = addr->lc_local_part;
3624 case CONTROL_ENFORCE_SYNC:
3625 smtp_enforce_sync = TRUE;
3628 case CONTROL_NO_ENFORCE_SYNC:
3629 smtp_enforce_sync = FALSE;
3632 #ifdef WITH_CONTENT_SCAN
3633 case CONTROL_NO_MBOX_UNSPOOL:
3634 f.no_mbox_unspool = TRUE;
3638 case CONTROL_NO_MULTILINE:
3639 f.no_multiline_responses = TRUE;
3642 case CONTROL_NO_PIPELINING:
3643 f.pipelining_enable = FALSE;
3646 case CONTROL_NO_DELAY_FLUSH:
3647 f.disable_delay_flush = TRUE;
3650 case CONTROL_NO_CALLOUT_FLUSH:
3651 f.disable_callout_flush = TRUE;
3654 case CONTROL_FAKEREJECT:
3655 cancel_cutthrough_connection(TRUE, US"fakereject");
3656 case CONTROL_FAKEDEFER:
3657 fake_response = control_type == CONTROL_FAKEDEFER ? DEFER : FAIL;
3660 const uschar *pp = p + 1;
3662 /* The entire control= line was expanded at top so no need to expand
3663 the part after the / */
3664 fake_response_text = string_copyn(p+1, pp-p-1);
3667 else /* Explicitly reset to default string */
3668 fake_response_text = US"Your message has been rejected but is being kept for evaluation.\nIf it was a legitimate message, it may still be delivered to the target recipient(s).";
3671 case CONTROL_FREEZE:
3672 f.deliver_freeze = TRUE;
3673 deliver_frozen_at = time(NULL);
3674 freeze_tell = freeze_tell_config; /* Reset to configured value */
3675 if (Ustrncmp(p, "/no_tell", 8) == 0)
3682 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
3685 cancel_cutthrough_connection(TRUE, US"item frozen");
3689 f.queue_only_policy = TRUE;
3690 if (Ustrcmp(p, "_only") == 0)
3692 else while (*p == '/')
3693 if (Ustrncmp(p, "/only", 5) == 0)
3694 { p += 5; f.queue_smtp = FALSE; }
3695 else if (Ustrncmp(p, "/first_pass_route", 17) == 0)
3696 { p += 17; f.queue_smtp = TRUE; }
3699 cancel_cutthrough_connection(TRUE, US"queueing forced");
3702 case CONTROL_SUBMISSION:
3703 originator_name = US"";
3704 f.submission_mode = TRUE;
3707 if (Ustrncmp(p, "/sender_retain", 14) == 0)
3710 f.active_local_sender_retain = TRUE;
3711 f.active_local_from_check = FALSE;
3713 else if (Ustrncmp(p, "/domain=", 8) == 0)
3715 const uschar *pp = p + 8;
3716 while (*pp && *pp != '/') pp++;
3717 submission_domain = string_copyn(p+8, pp-p-8);
3720 /* The name= option must be last, because it swallows the rest of
3722 else if (Ustrncmp(p, "/name=", 6) == 0)
3724 const uschar *pp = p + 6;
3726 submission_name = parse_fix_phrase(p+6, pp-p-6);
3733 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
3740 uschar * debug_tag = NULL, * debug_opts = NULL;
3741 BOOL kill = FALSE, stop = FALSE;
3745 const uschar * pp = p+1;
3746 if (Ustrncmp(pp, "tag=", 4) == 0)
3748 for (pp += 4; *pp && *pp != '/';) pp++;
3749 debug_tag = string_copyn(p+5, pp-p-5);
3751 else if (Ustrncmp(pp, "opts=", 5) == 0)
3753 for (pp += 5; *pp && *pp != '/';) pp++;
3754 debug_opts = string_copyn(p+6, pp-p-6);
3756 else if (Ustrncmp(pp, "kill", 4) == 0)
3761 else if (Ustrncmp(pp, "stop", 4) == 0)
3766 else if (Ustrncmp(pp, "pretrigger=", 11) == 0)
3767 debug_pretrigger_setup(pp+11);
3768 else if (Ustrncmp(pp, "trigger=", 8) == 0)
3770 if (Ustrncmp(pp += 8, "now", 3) == 0)
3773 debug_trigger_fire();
3775 else if (Ustrncmp(pp, "paniclog", 8) == 0)
3778 dtrigger_selector |= BIT(DTi_panictrigger);
3781 while (*pp && *pp != '/') pp++;
3786 debug_logging_stop(TRUE);
3788 debug_logging_stop(FALSE);
3789 else if (debug_tag || debug_opts)
3790 debug_logging_activate(debug_tag, debug_opts);
3794 case CONTROL_SUPPRESS_LOCAL_FIXUPS:
3795 f.suppress_local_fixups = TRUE;
3798 case CONTROL_CUTTHROUGH_DELIVERY:
3800 uschar * ignored = NULL;
3801 #ifndef DISABLE_PRDR
3806 /* Too hard to think about for now. We might in future cutthrough
3807 the case where both sides handle prdr and this-node prdr acl
3809 ignored = US"PRDR active";
3810 else if (f.deliver_freeze)
3811 ignored = US"frozen";
3812 else if (f.queue_only_policy)
3813 ignored = US"queue-only";
3814 else if (fake_response == FAIL)
3815 ignored = US"fakereject";
3816 else if (rcpt_count != 1)
3817 ignored = US"nonfirst rcpt";
3818 else if (cutthrough.delivery)
3819 ignored = US"repeated";
3820 else if (cutthrough.callout_hold_only)
3823 debug_printf_indent(" cutthrough request upgrades callout hold\n");
3824 cutthrough.callout_hold_only = FALSE;
3825 cutthrough.delivery = TRUE; /* control accepted */
3829 cutthrough.delivery = TRUE; /* control accepted */
3832 const uschar * pp = p+1;
3833 if (Ustrncmp(pp, "defer=", 6) == 0)
3836 if (Ustrncmp(pp, "pass", 4) == 0) cutthrough.defer_pass = TRUE;
3837 /* else if (Ustrncmp(pp, "spool") == 0) ; default */
3840 while (*pp && *pp != '/') pp++;
3845 DEBUG(D_acl) if (ignored)
3846 debug_printf(" cutthrough request ignored on %s item\n", ignored);
3851 case CONTROL_UTF8_DOWNCONVERT:
3856 message_utf8_downconvert = 1;
3857 addr->prop.utf8_downcvt = TRUE;
3858 addr->prop.utf8_downcvt_maybe = FALSE;
3864 message_utf8_downconvert = 0;
3865 addr->prop.utf8_downcvt = FALSE;
3866 addr->prop.utf8_downcvt_maybe = FALSE;
3870 if (p[1] == '-' && p[2] == '1')
3872 message_utf8_downconvert = -1;
3873 addr->prop.utf8_downcvt = FALSE;
3874 addr->prop.utf8_downcvt_maybe = TRUE;
3878 *log_msgptr = US"bad option value for control=utf8_downconvert";
3882 message_utf8_downconvert = 1;
3883 addr->prop.utf8_downcvt = TRUE;
3884 addr->prop.utf8_downcvt_maybe = FALSE;
3890 #ifndef DISABLE_WELLKNOWN
3891 case CONTROL_WELLKNOWN:
3892 rc = *p == '/' ? wellknown_process(p+1, log_msgptr) : FAIL;
3899 #ifdef EXPERIMENTAL_DCC
3902 /* Separate the regular expression and any optional parameters. */
3903 const uschar * list = arg;
3905 uschar * ss = string_nextinlist(&list, &sep, NULL, 0);
3906 /* Run the dcc backend. */
3907 rc = dcc_process(&ss);
3908 /* Modify return code based upon the existence of options. */
3909 while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
3910 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3911 rc = FAIL; /* FAIL so that the message is passed to the next ACL */
3916 #ifdef WITH_CONTENT_SCAN
3918 rc = mime_decode(&arg);
3924 int delay = readconf_readtime(arg, 0, FALSE);
3927 *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
3928 "modifier: \"%s\" is not a time value", arg);
3933 HDEBUG(D_acl) debug_printf_indent("delay modifier requests %d-second delay\n",
3938 debug_printf_indent("delay skipped in -bh checking mode\n");
3941 /* NOTE 1: Remember that we may be
3942 dealing with stdin/stdout here, in addition to TCP/IP connections.
3943 Also, delays may be specified for non-SMTP input, where smtp_out and
3944 smtp_in will be NULL. Whatever is done must work in all cases.
3946 NOTE 2: The added feature of flushing the output before a delay must
3947 apply only to SMTP input. Hence the test for smtp_out being non-NULL.
3952 if (smtp_out && !f.disable_delay_flush)
3955 #if !defined(NO_POLL_H) && defined (POLLRDHUP)
3961 p.fd = fileno(smtp_out);
3962 p.events = POLLRDHUP;
3965 if (poll(&p, n, delay*1000) > 0)
3966 HDEBUG(D_acl) debug_printf_indent("delay cancelled by peer close\n");
3969 /* Lacking POLLRDHUP it appears to be impossible to detect that a
3970 TCP/IP connection has gone away without reading from it. This means
3971 that we cannot shorten the delay below if the client goes away,
3972 because we cannot discover that the client has closed its end of the
3973 connection. (The connection is actually in a half-closed state,
3974 waiting for the server to close its end.) It would be nice to be able
3975 to detect this state, so that the Exim process is not held up
3976 unnecessarily. However, it seems that we can't. The poll() function
3977 does not do the right thing, and in any case it is not always
3980 while (delay > 0) delay = sleep(delay);
3987 #ifndef DISABLE_DKIM
3988 case ACLC_DKIM_SIGNER:
3989 case ACLC_DKIM_STATUS:
3990 /* See comment on ACLC_SPF wrt. coding issues */
3992 misc_module_info * mi = misc_mod_find(US"dkim", &log_message);
3993 typedef int (*fn_t)(const uschar *);
3995 ? (((fn_t *) mi->functions)
3996 [cb->type == ACLC_DKIM_SIGNER
3997 ? DKIM_SIGNER_ISINLIST
3998 : DKIM_STATUS_LISTMATCH]) (arg)
4004 #ifdef SUPPORT_DMARC
4005 case ACLC_DMARC_STATUS:
4006 /* See comment on ACLC_SPF wrt. coding issues */
4008 misc_module_info * mi = misc_mod_find(US"dmarc", &log_message);
4009 typedef uschar * (*efn_t)(int);
4010 uschar * expanded_query;
4013 { rc = DEFER; break; } /* shouldn't happen */
4015 if (!f.dmarc_has_been_checked)
4017 typedef int (*pfn_t)(void);
4018 (void) (((pfn_t *) mi->functions)[DMARC_PROCESS]) ();
4019 f.dmarc_has_been_checked = TRUE;
4022 /* used long way of dmarc_exim_expand_query() in case we need more
4023 view into the process in the future. */
4025 /*XXX is this call used with any other arg? */
4026 expanded_query = (((efn_t *) mi->functions)[DMARC_EXPAND_QUERY])
4027 (DMARC_VERIFY_STATUS);
4028 rc = match_isinlist(expanded_query,
4029 &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
4035 rc = verify_check_dnsbl(where, &arg, log_msgptr);
4039 rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
4040 addr->domain_cache, MCL_DOMAIN, TRUE, CUSS &deliver_domain_data);
4043 /* The value in tls_cipher is the full cipher name, for example,
4044 TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
4045 cipher names such as DES-CBC3-SHA. But program defensively. We don't know
4046 what may in practice come out of the SSL library - which at the time of
4047 writing is poorly documented. */
4049 case ACLC_ENCRYPTED:
4050 if (!tls_in.cipher) rc = FAIL;
4053 uschar *endcipher = NULL;
4054 uschar *cipher = Ustrchr(tls_in.cipher, ':');
4055 if (!cipher) cipher = tls_in.cipher; else
4057 endcipher = Ustrchr(++cipher, ':');
4058 if (endcipher) *endcipher = 0;
4060 rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
4061 if (endcipher) *endcipher = ':';
4065 /* Use verify_check_this_host() instead of verify_check_host() so that
4066 we can pass over &host_data to catch any looked up data. Once it has been
4067 set, it retains its value so that it's still there if another ACL verb
4068 comes through here and uses the cache. However, we must put it into
4069 permanent store in case it is also expected to be used in a subsequent
4070 message in the same SMTP connection. */
4073 rc = verify_check_this_host(&arg, sender_host_cache, NULL,
4074 sender_host_address ? sender_host_address : US"", CUSS &host_data);
4075 if (rc == DEFER) *log_msgptr = search_error_message;
4076 if (host_data) host_data = string_copy_perm(host_data, TRUE);
4079 case ACLC_LOCAL_PARTS:
4080 rc = match_isinlist(addr->cc_local_part, &arg, 0,
4081 &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
4082 CUSS &deliver_localpart_data);
4085 case ACLC_LOG_REJECT_TARGET:
4087 int logbits = 0, sep = 0;
4088 const uschar * s = arg;
4090 for (uschar * ss; ss = string_nextinlist(&s, &sep, NULL, 0); )
4092 if (Ustrcmp(ss, "main") == 0) logbits |= LOG_MAIN;
4093 else if (Ustrcmp(ss, "panic") == 0) logbits |= LOG_PANIC;
4094 else if (Ustrcmp(ss, "reject") == 0) logbits |= LOG_REJECT;
4097 logbits |= LOG_MAIN|LOG_REJECT;
4098 log_write(0, LOG_MAIN|LOG_PANIC, "unknown log name \"%s\" in "
4099 "\"log_reject_target\" in %s ACL", ss, acl_wherenames[where]);
4102 log_reject_target = logbits;
4109 const uschar *s = arg;
4115 if (Ustrncmp(s, "main", 4) == 0)
4116 { logbits |= LOG_MAIN; s += 4; }
4117 else if (Ustrncmp(s, "panic", 5) == 0)
4118 { logbits |= LOG_PANIC; s += 5; }
4119 else if (Ustrncmp(s, "reject", 6) == 0)
4120 { logbits |= LOG_REJECT; s += 6; }
4123 logbits = LOG_MAIN|LOG_PANIC;
4124 s = string_sprintf(":unknown log name in \"%s\" in "
4125 "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
4131 Uskip_whitespace(&s);
4133 if (logbits == 0) logbits = LOG_MAIN;
4134 log_write(0, logbits, "%s", string_printing(s));
4138 #ifdef WITH_CONTENT_SCAN
4139 case ACLC_MALWARE: /* Run the malware backend. */
4141 /* Separate the regular expression and any optional parameters. */
4142 const uschar * list = arg;
4143 BOOL defer_ok = FALSE;
4144 int timeout = 0, sep = -'/';
4145 uschar * ss = string_nextinlist(&list, &sep, NULL, 0);
4147 for (uschar * opt; opt = string_nextinlist(&list, &sep, NULL, 0); )
4148 if (strcmpic(opt, US"defer_ok") == 0)
4150 else if ( strncmpic(opt, US"tmo=", 4) == 0
4151 && (timeout = readconf_readtime(opt+4, '\0', FALSE)) < 0
4154 *log_msgptr = string_sprintf("bad timeout value in '%s'", opt);
4158 rc = malware(ss, textonly, timeout);
4159 if (rc == DEFER && defer_ok)
4160 rc = FAIL; /* FAIL so that the message is passed to the next ACL */
4164 case ACLC_MIME_REGEX:
4165 rc = mime_regex(&arg, textonly);
4170 if (is_tainted(arg))
4172 *log_msgptr = string_sprintf("Tainted name '%s' for queue not permitted",
4176 if (Ustrchr(arg, '/'))
4178 *log_msgptr = string_sprintf(
4179 "Directory separator not permitted in queue name: '%s'", arg);
4182 queue_name = string_copy_perm(arg, FALSE);
4185 case ACLC_RATELIMIT:
4186 rc = acl_ratelimit(arg, where, log_msgptr);
4189 case ACLC_RECIPIENTS:
4190 rc = match_address_list(CUS addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
4191 CUSS &recipient_data);
4194 #ifdef WITH_CONTENT_SCAN
4196 rc = regex(&arg, textonly);
4200 case ACLC_REMOVE_HEADER:
4201 setup_remove_header(arg);
4205 rc = acl_seen(arg, where, log_msgptr);
4208 case ACLC_SENDER_DOMAINS:
4211 sdomain = Ustrrchr(sender_address, '@');
4212 sdomain = sdomain ? sdomain + 1 : US"";
4213 rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
4214 sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
4219 rc = match_address_list(CUS sender_address, TRUE, TRUE, &arg,
4220 sender_address_cache, -1, 0, CUSS &sender_data);
4223 /* Connection variables must persist forever; message variables not */
4227 int old_pool = store_pool;
4228 if ( cb->u.varname[0] != 'm'
4229 #ifndef DISABLE_EVENT
4230 || event_name /* An event is being delivered */
4233 store_pool = POOL_PERM;
4235 #ifndef DISABLE_DKIM /* Overwriteable dkim result variables */
4236 if ( Ustrcmp(cb->u.varname, "dkim_verify_status") == 0
4237 || Ustrcmp(cb->u.varname, "dkim_verify_reason") == 0
4240 misc_module_info * mi = misc_mod_findonly(US"dkim");
4241 typedef void (*fn_t)(const uschar *, void *);
4244 (((fn_t *) mi->functions)[DKIM_SETVAR])
4245 (cb->u.varname, string_copy(arg));
4249 acl_var_create(cb->u.varname)->data.ptr = string_copy(arg);
4250 store_pool = old_pool;
4254 #ifdef WITH_CONTENT_SCAN
4257 /* Separate the regular expression and any optional parameters. */
4258 const uschar * list = arg;
4260 uschar * ss = string_nextinlist(&list, &sep, NULL, 0);
4262 rc = spam(CUSS &ss);
4263 /* Modify return code based upon the existence of options. */
4264 while ((ss = string_nextinlist(&list, &sep, NULL, 0)))
4265 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
4266 rc = FAIL; /* FAIL so that the message is passed to the next ACL */
4273 case ACLC_SPF_GUESS:
4274 /* We have hardwired function-call numbers, and also prototypes for the
4275 functions. We could do a function name table search or (simpler)
4276 a module include file with defines for the numbers
4277 but I can't see how to deal with prototypes. Is a K&R non-prototyped
4278 function still usable with today's compilers (but we would lose on
4279 type-checking)? We could macroize the typedef, and even the function
4280 table access - but it obscures how it works rather. */
4282 misc_module_info * mi = misc_mod_find(US"spf", &log_message);
4283 typedef int (*fn_t)(const uschar **, const uschar *, int);
4287 { rc = DEFER; break; } /* shouldn't happen */
4289 fn = ((fn_t *) mi->functions)[SPF_PROCESS];
4291 rc = fn(&arg, sender_address,
4292 cb->type == ACLC_SPF ? SPF_PROCESS_NORMAL : SPF_PROCESS_GUESS);
4298 rc = acl_udpsend(arg, log_msgptr);
4301 /* If the verb is WARN, discard any user message from verification, because
4302 such messages are SMTP responses, not header additions. The latter come
4303 only from explicit "message" modifiers. However, put the user message into
4304 $acl_verify_message so it can be used in subsequent conditions or modifiers
4305 (until something changes it). */
4308 rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
4310 acl_verify_message = *user_msgptr;
4311 if (verb == ACL_WARN) *user_msgptr = NULL;
4315 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
4316 "condition %d", cb->type);
4320 /* If a condition was negated, invert OK/FAIL. */
4322 if (!(conditions[cb->type].flags & ACD_MOD) && cb->u.negated)
4323 if (rc == OK) rc = FAIL;
4324 else if (rc == FAIL || rc == FAIL_DROP) rc = OK;
4326 if (rc != OK) break; /* Conditions loop */
4330 /* If the result is the one for which "message" and/or "log_message" are used,
4331 handle the values of these modifiers. If there isn't a log message set, we make
4332 it the same as the user message.
4334 "message" is a user message that will be included in an SMTP response. Unless
4335 it is empty, it overrides any previously set user message.
4337 "log_message" is a non-user message, and it adds to any existing non-user
4338 message that is already set.
4340 Most verbs have but a single return for which the messages are relevant, but
4341 for "discard", it's useful to have the log message both when it succeeds and
4342 when it fails. For "accept", the message is used in the OK case if there is no
4343 "endpass", but (for backwards compatibility) in the FAIL case if "endpass" is
4346 if (*epp && rc == OK) user_message = NULL;
4348 if ((BIT(rc) & msgcond[verb]) != 0)
4351 uschar *old_user_msgptr = *user_msgptr;
4352 uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;
4354 /* If the verb is "warn", messages generated by conditions (verification or
4355 nested ACLs) are always discarded. This also happens for acceptance verbs
4356 when they actually do accept. Only messages specified at this level are used.
4357 However, the value of an existing message is available in $acl_verify_message
4358 during expansions. */
4360 if (verb == ACL_WARN ||
4361 (rc == OK && (verb == ACL_ACCEPT || verb == ACL_DISCARD)))
4362 *log_msgptr = *user_msgptr = NULL;
4366 acl_verify_message = old_user_msgptr;
4367 expmessage = expand_string(user_message);
4370 if (!f.expand_string_forcedfail)
4371 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
4372 user_message, expand_string_message);
4374 else if (expmessage[0] != 0) *user_msgptr = expmessage;
4379 acl_verify_message = old_log_msgptr;
4380 expmessage = expand_string(log_message);
4383 if (!f.expand_string_forcedfail)
4384 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
4385 log_message, expand_string_message);
4387 else if (expmessage[0] != 0)
4389 *log_msgptr = (*log_msgptr == NULL)? expmessage :
4390 string_sprintf("%s: %s", expmessage, *log_msgptr);
4394 /* If no log message, default it to the user message */
4396 if (!*log_msgptr) *log_msgptr = *user_msgptr;
4399 acl_verify_message = NULL;
4407 /*************************************************
4408 * Get line from a literal ACL *
4409 *************************************************/
4411 /* This function is passed to acl_read() in order to extract individual lines
4412 of a literal ACL, which we access via static pointers. We can destroy the
4413 contents because this is called only once (the compiled ACL is remembered).
4415 This code is intended to treat the data in the same way as lines in the main
4416 Exim configuration file. That is:
4418 . Leading spaces are ignored.
4420 . A \ at the end of a line is a continuation - trailing spaces after the \
4421 are permitted (this is because I don't believe in making invisible things
4422 significant). Leading spaces on the continued part of a line are ignored.
4424 . Physical lines starting (significantly) with # are totally ignored, and
4425 may appear within a sequence of backslash-continued lines.
4427 . Blank lines are ignored, but will end a sequence of continuations.
4430 Returns: a pointer to the next line
4434 static uschar *acl_text; /* Current pointer in the text */
4435 static uschar *acl_text_end; /* Points one past the terminating '0' */
4443 /* This loop handles leading blank lines and comments. */
4447 Uskip_whitespace(&acl_text); /* Leading spaces/empty lines */
4448 if (!*acl_text) return NULL; /* No more data */
4449 yield = acl_text; /* Potential data line */
4451 while (*acl_text && *acl_text != '\n') acl_text++;
4453 /* If we hit the end before a newline, we have the whole logical line. If
4454 it's a comment, there's no more data to be given. Otherwise, yield it. */
4456 if (!*acl_text) return *yield == '#' ? NULL : yield;
4458 /* After reaching a newline, end this loop if the physical line does not
4459 start with '#'. If it does, it's a comment, and the loop continues. */
4461 if (*yield != '#') break;
4464 /* This loop handles continuations. We know we have some real data, ending in
4465 newline. See if there is a continuation marker at the end (ignoring trailing
4466 white space). We know that *yield is not white space, so no need to test for
4467 cont > yield in the backwards scanning loop. */
4472 for (cont = acl_text - 1; isspace(*cont); cont--);
4474 /* If no continuation follows, we are done. Mark the end of the line and
4483 /* We have encountered a continuation. Skip over whitespace at the start of
4484 the next line, and indeed the whole of the next line or lines if they are
4489 while (*(++acl_text) == ' ' || *acl_text == '\t');
4490 if (*acl_text != '#') break;
4491 while (*(++acl_text) != 0 && *acl_text != '\n');
4494 /* We have the start of a continuation line. Move all the rest of the data
4495 to join onto the previous line, and then find its end. If the end is not a
4496 newline, we are done. Otherwise loop to look for another continuation. */
4498 memmove(cont, acl_text, acl_text_end - acl_text);
4499 acl_text_end -= acl_text - cont;
4501 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
4502 if (*acl_text == 0) return yield;
4505 /* Control does not reach here */
4512 /************************************************/
4513 /* For error messages, a string describing the config location
4514 associated with current processing. NULL if not in an ACL. */
4517 acl_current_verb(void)
4519 if (acl_current) return string_sprintf(" (ACL %s, %s %d)",
4520 verbs[acl_current->verb], acl_current->srcfile, acl_current->srcline);
4524 /*************************************************
4525 * Check access using an ACL *
4526 *************************************************/
4528 /* This function is called from address_check. It may recurse via
4529 acl_check_condition() - hence the use of a level to stop looping. The ACL is
4530 passed as a string which is expanded. A forced failure implies no access check
4531 is required. If the result is a single word, it is taken as the name of an ACL
4532 which is sought in the global ACL tree. Otherwise, it is taken as literal ACL
4533 text, complete with newlines, and parsed as such. In both cases, the ACL check
4534 is then run. This function uses an auxiliary function for acl_read() to call
4535 for reading individual lines of a literal ACL. This is acl_getline(), which
4536 appears immediately above.
4539 where where called from
4540 addr address item when called from RCPT; otherwise NULL
4541 s the input string; NULL is the same as an empty ACL => DENY
4542 user_msgptr where to put a user error (for SMTP response)
4543 log_msgptr where to put a logging message (not for SMTP response)
4545 Returns: OK access is granted
4546 DISCARD access is apparently granted...
4547 FAIL access is denied
4548 FAIL_DROP access is denied; drop the connection
4549 DEFER can't tell at the moment
4554 acl_check_internal(int where, address_item *addr, uschar *s,
4555 uschar **user_msgptr, uschar **log_msgptr)
4558 acl_block *acl = NULL;
4559 uschar *acl_name = US"inline ACL";
4562 /* Catch configuration loops */
4566 *log_msgptr = US"ACL nested too deep: possible loop";
4572 HDEBUG(D_acl) debug_printf_indent("ACL is NULL: implicit DENY\n");
4576 /* At top level, we expand the incoming string. At lower levels, it has already
4577 been expanded as part of condition processing. */
4581 else if (!(ss = expand_string(s)))
4583 if (f.expand_string_forcedfail) return OK;
4584 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s", s,
4585 expand_string_message);
4589 Uskip_whitespace(&ss);
4591 /* If we can't find a named ACL, the default is to parse it as an inline one.
4592 (Unless it begins with a slash; non-existent files give rise to an error.) */
4596 if (is_tainted(acl_text) && !f.running_in_test_harness)
4598 log_write(0, LOG_MAIN|LOG_PANIC,
4599 "attempt to use tainted ACL text \"%s\"", acl_text);
4600 /* Avoid leaking info to an attacker */
4601 *log_msgptr = US"internal configuration error";
4605 /* Handle the case of a string that does not contain any spaces. Look for a
4606 named ACL among those read from the configuration, or a previously read file.
4607 It is possible that the pointer to the ACL is NULL if the configuration
4608 contains a name with no data. If not found, and the text begins with '/',
4609 read an ACL from a file, and save it so it can be re-used. */
4611 if (Ustrchr(ss, ' ') == NULL)
4613 tree_node * t = tree_search(acl_anchor, ss);
4616 if (!(acl = (acl_block *)(t->data.ptr)))
4618 HDEBUG(D_acl) debug_printf_indent("ACL \"%s\" is empty: implicit DENY\n", ss);
4621 acl_name = string_sprintf("ACL %s", ss);
4622 HDEBUG(D_acl) debug_printf_indent("using ACL \"%s\"\n", ss);
4625 else if (*ss == '/')
4627 struct stat statbuf;
4628 if ((fd = Uopen(ss, O_RDONLY, 0)) < 0)
4630 *log_msgptr = string_sprintf("failed to open ACL file \"%s\": %s", ss,
4634 if (fstat(fd, &statbuf) != 0)
4636 *log_msgptr = string_sprintf("failed to fstat ACL file \"%s\": %s", ss,
4641 /* If the string being used as a filename is tainted, so is the file content */
4642 acl_text = store_get(statbuf.st_size + 1, ss);
4643 acl_text_end = acl_text + statbuf.st_size + 1;
4645 if (read(fd, acl_text, statbuf.st_size) != statbuf.st_size)
4647 *log_msgptr = string_sprintf("failed to read ACL file \"%s\": %s",
4648 ss, strerror(errno));
4651 acl_text[statbuf.st_size] = 0;
4654 acl_name = string_sprintf("ACL %s", ss);
4655 HDEBUG(D_acl) debug_printf_indent("read ACL from file %s\n", ss);
4659 /* Parse an ACL that is still in text form. If it came from a file, remember it
4660 in the ACL tree, having read it into the POOL_PERM store pool so that it
4661 persists between multiple messages. */
4665 int old_pool = store_pool;
4666 if (fd >= 0) store_pool = POOL_PERM;
4667 acl = acl_read(acl_getline, log_msgptr);
4668 store_pool = old_pool;
4669 if (!acl && *log_msgptr) return ERROR;
4672 tree_node * t = store_get_perm(sizeof(tree_node) + Ustrlen(ss), ss);
4673 Ustrcpy(t->name, ss);
4675 (void)tree_insertnode(&acl_anchor, t);
4679 /* Now we have an ACL to use. It's possible it may be NULL. */
4681 while ((acl_current = acl))
4684 int basic_errno = 0;
4685 BOOL endpass_seen = FALSE;
4686 BOOL acl_quit_check = acl_level == 0
4687 && (where == ACL_WHERE_QUIT || where == ACL_WHERE_NOTQUIT);
4689 *log_msgptr = *user_msgptr = NULL;
4690 f.acl_temp_details = FALSE;
4692 config_filename = acl->srcfile;
4693 config_lineno = acl->srcline;
4697 debug_printf_indent("processing %s \"%s\"", acl_name, verbs[acl->verb]);
4698 if (config_lineno) debug_printf(" (%s %d)", config_filename, config_lineno);
4702 /* Clear out any search error message from a previous check before testing
4705 search_error_message = NULL;
4706 cond = acl_check_condition(acl->verb, acl->condition, where, addr, acl_level,
4707 &endpass_seen, user_msgptr, log_msgptr, &basic_errno);
4709 /* Handle special returns: DEFER causes a return except on a WARN verb;
4710 ERROR always causes a return. */
4715 HDEBUG(D_acl) debug_printf_indent("%s: condition test deferred in %s\n",
4716 verbs[acl->verb], acl_name);
4717 if (basic_errno != ERRNO_CALLOUTDEFER)
4719 if (search_error_message && *search_error_message)
4720 *log_msgptr = search_error_message;
4721 if (smtp_return_error_details) f.acl_temp_details = TRUE;
4724 f.acl_temp_details = TRUE;
4725 if (acl->verb != ACL_WARN) return DEFER;
4728 default: /* Paranoia */
4730 HDEBUG(D_acl) debug_printf_indent("%s: condition test error in %s\n",
4731 verbs[acl->verb], acl_name);
4735 HDEBUG(D_acl) debug_printf_indent("%s: condition test succeeded in %s\n",
4736 verbs[acl->verb], acl_name);
4740 HDEBUG(D_acl) debug_printf_indent("%s: condition test failed in %s\n",
4741 verbs[acl->verb], acl_name);
4744 /* DISCARD and DROP can happen only from a nested ACL condition, and
4745 DISCARD can happen only for an "accept" or "discard" verb. */
4748 HDEBUG(D_acl) debug_printf_indent("%s: condition test yielded \"discard\" in %s\n",
4749 verbs[acl->verb], acl_name);
4753 HDEBUG(D_acl) debug_printf_indent("%s: condition test yielded \"drop\" in %s\n",
4754 verbs[acl->verb], acl_name);
4758 /* At this point, cond for most verbs is either OK or FAIL or (as a result of
4759 a nested ACL condition) FAIL_DROP. However, for WARN, cond may be DEFER, and
4760 for ACCEPT and DISCARD, it may be DISCARD after a nested ACL call. */
4765 if (cond == OK || cond == DISCARD)
4767 HDEBUG(D_acl) debug_printf_indent("end of %s: ACCEPT\n", acl_name);
4772 HDEBUG(D_acl) debug_printf_indent("accept: endpass encountered - denying access\n");
4780 HDEBUG(D_acl) debug_printf_indent("end of %s: DEFER\n", acl_name);
4781 if (acl_quit_check) goto badquit;
4782 f.acl_temp_details = TRUE;
4790 HDEBUG(D_acl) debug_printf_indent("end of %s: DENY\n", acl_name);
4791 if (acl_quit_check) goto badquit;
4797 if (cond == OK || cond == DISCARD)
4799 HDEBUG(D_acl) debug_printf_indent("end of %s: DISCARD\n", acl_name);
4800 if (acl_quit_check) goto badquit;
4806 debug_printf_indent("discard: endpass encountered - denying access\n");
4814 HDEBUG(D_acl) debug_printf_indent("end of %s: DROP\n", acl_name);
4815 if (acl_quit_check) goto badquit;
4823 HDEBUG(D_acl) debug_printf_indent("end of %s: not OK\n", acl_name);
4824 if (acl_quit_check) goto badquit;
4831 acl_warn(where, *user_msgptr, *log_msgptr);
4832 else if (cond == DEFER && LOGGING(acl_warn_skipped))
4833 if (config_lineno > 0)
4834 log_write(0, LOG_MAIN,
4835 "%s Warning: ACL 'warn' statement skipped (in %s at line %d of %s):"
4836 " condition test deferred%s%s",
4837 host_and_ident(TRUE), acl_name, config_lineno, config_filename,
4838 *log_msgptr ? US": " : US"", *log_msgptr ? *log_msgptr : US"");
4840 log_write(0, LOG_MAIN,
4841 "%s Warning: ACL 'warn' statement skipped (in %s):"
4842 " condition test deferred%s%s",
4843 host_and_ident(TRUE), acl_name,
4844 *log_msgptr ? US": " : US"", *log_msgptr ? *log_msgptr : US"");
4845 *log_msgptr = *user_msgptr = NULL; /* In case implicit DENY follows */
4849 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown verb %d",
4854 /* Pass to the next ACL item */
4859 /* We have reached the end of the ACL. This is an implicit DENY. */
4861 HDEBUG(D_acl) debug_printf_indent("end of %s: implicit DENY\n", acl_name);
4865 *log_msgptr = string_sprintf("QUIT or not-QUIT toplevel ACL may not fail "
4866 "('%s' verb used incorrectly)", verbs[acl->verb]);
4873 /* Same args as acl_check_internal() above, but the string s is
4874 the name of an ACL followed optionally by up to 9 space-separated arguments.
4875 The name and args are separately expanded. Args go into $acl_arg globals. */
4877 acl_check_wargs(int where, address_item *addr, const uschar *s,
4878 uschar **user_msgptr, uschar **log_msgptr)
4881 uschar * tmp_arg[9]; /* must match acl_arg[] */
4882 uschar * sav_arg[9]; /* must match acl_arg[] */
4888 if (!(tmp = string_dequote(&s)) || !(name = expand_string(tmp)))
4891 for (i = 0; i < 9; i++)
4893 if (!Uskip_whitespace(&s))
4895 if (!(tmp = string_dequote(&s)) || !(tmp_arg[i] = expand_string(tmp)))
4902 sav_narg = acl_narg;
4904 for (i = 0; i < acl_narg; i++)
4906 sav_arg[i] = acl_arg[i];
4907 acl_arg[i] = tmp_arg[i];
4911 sav_arg[i] = acl_arg[i];
4912 acl_arg[i++] = NULL;
4916 ret = acl_check_internal(where, addr, name, user_msgptr, log_msgptr);
4920 acl_narg = sav_narg;
4921 for (i = 0; i < 9; i++) acl_arg[i] = sav_arg[i];
4925 if (f.expand_string_forcedfail) return ERROR;
4926 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
4927 tmp, expand_string_message);
4928 return f.search_find_defer ? DEFER : ERROR;
4933 /*************************************************
4934 * Check access using an ACL *
4935 *************************************************/
4937 /* Alternate interface for ACL, used by expansions */
4939 acl_eval(int where, uschar *s, uschar **user_msgptr, uschar **log_msgptr)
4942 address_item *addr = NULL;
4945 *user_msgptr = *log_msgptr = NULL;
4946 sender_verified_failed = NULL;
4947 ratelimiters_cmd = NULL;
4948 log_reject_target = LOG_MAIN|LOG_REJECT;
4950 if (where == ACL_WHERE_RCPT)
4952 adb = address_defaults;
4954 addr->address = expand_string(US"$local_part@$domain");
4955 addr->domain = deliver_domain;
4956 addr->local_part = deliver_localpart;
4957 addr->cc_local_part = deliver_localpart;
4958 addr->lc_local_part = deliver_localpart;
4962 rc = acl_check_internal(where, addr, s, user_msgptr, log_msgptr);
4970 /* This is the external interface for ACL checks. It sets up an address and the
4971 expansions for $domain and $local_part when called after RCPT, then calls
4972 acl_check_internal() to do the actual work.
4975 where ACL_WHERE_xxxx indicating where called from
4976 recipient RCPT address for RCPT check, else NULL
4977 s the input string; NULL is the same as an empty ACL => DENY
4978 user_msgptr where to put a user error (for SMTP response)
4979 log_msgptr where to put a logging message (not for SMTP response)
4981 Returns: OK access is granted by an ACCEPT verb
4982 DISCARD access is granted by a DISCARD verb
4983 FAIL access is denied
4984 FAIL_DROP access is denied; drop the connection
4985 DEFER can't tell at the moment
4990 acl_check(int where, const uschar * recipient, uschar * s,
4991 uschar ** user_msgptr, uschar ** log_msgptr)
4995 address_item *addr = NULL;
4997 *user_msgptr = *log_msgptr = NULL;
4998 sender_verified_failed = NULL;
4999 ratelimiters_cmd = NULL;
5000 log_reject_target = LOG_MAIN|LOG_REJECT;
5002 #ifndef DISABLE_PRDR
5003 if (where==ACL_WHERE_RCPT || where==ACL_WHERE_VRFY || where==ACL_WHERE_PRDR)
5005 if (where==ACL_WHERE_RCPT || where==ACL_WHERE_VRFY)
5008 adb = address_defaults;
5010 addr->address = recipient;
5011 if (deliver_split_address(addr) == DEFER)
5013 *log_msgptr = US"defer in percent_hack_domains check";
5017 if ((addr->prop.utf8_msg = message_smtputf8))
5019 addr->prop.utf8_downcvt = message_utf8_downconvert == 1;
5020 addr->prop.utf8_downcvt_maybe = message_utf8_downconvert == -1;
5023 deliver_domain = addr->domain;
5024 deliver_localpart = addr->local_part;
5029 rc = acl_check_internal(where, addr, s, user_msgptr, log_msgptr);
5031 acl_where = ACL_WHERE_UNKNOWN;
5034 /* Cutthrough - if requested,
5035 and WHERE_RCPT and not yet opened conn as result of recipient-verify,
5036 and rcpt acl returned accept,
5037 and first recipient (cancel on any subsequents)
5038 open one now and run it up to RCPT acceptance.
5039 A failed verify should cancel cutthrough request,
5040 and will pass the fail to the originator.
5041 Initial implementation: dual-write to spool.
5042 Assume the rxd datastream is now being copied byte-for-byte to an open cutthrough connection.
5044 Cease cutthrough copy on rxd final dot; do not send one.
5046 On a data acl, if not accept and a cutthrough conn is open, hard-close it (no SMTP niceness).
5048 On data acl accept, terminate the dataphase on an open cutthrough conn. If accepted or
5049 perm-rejected, reflect that to the original sender - and dump the spooled copy.
5050 If temp-reject, close the conn (and keep the spooled copy).
5051 If conn-failure, no action (and keep the spooled copy).
5055 case ACL_WHERE_RCPT:
5056 #ifndef DISABLE_PRDR
5057 case ACL_WHERE_PRDR:
5060 if (f.host_checking_callout) /* -bhc mode */
5061 cancel_cutthrough_connection(TRUE, US"host-checking mode");
5064 && cutthrough.delivery
5065 && rcpt_count > cutthrough.nrcpt
5068 if ((rc = open_cutthrough_connection(addr)) == DEFER)
5069 if (cutthrough.defer_pass)
5071 uschar * s = addr->message;
5072 /* Horrid kludge to recover target's SMTP message */
5074 do --s; while (!isdigit(*s));
5075 if (*--s && isdigit(*s) && *--s && isdigit(*s)) *user_msgptr = s;
5076 f.acl_temp_details = TRUE;
5080 HDEBUG(D_acl) debug_printf_indent("cutthrough defer; will spool\n");
5084 else HDEBUG(D_acl) if (cutthrough.delivery)
5085 if (rcpt_count <= cutthrough.nrcpt)
5086 debug_printf_indent("ignore cutthrough request; nonfirst message\n");
5088 debug_printf_indent("ignore cutthrough request; ACL did not accept\n");
5091 case ACL_WHERE_PREDATA:
5093 cutthrough_predata();
5095 cancel_cutthrough_connection(TRUE, US"predata acl not ok");
5098 case ACL_WHERE_QUIT:
5099 case ACL_WHERE_NOTQUIT:
5100 /* Drop cutthrough conns, and drop heldopen verify conns if
5101 the previous was not DATA */
5104 smtp_connection_had[SMTP_HBUFF_PREV(SMTP_HBUFF_PREV(smtp_ch_index))];
5105 BOOL dropverify = !(prev == SCH_DATA || prev == SCH_BDAT);
5107 cancel_cutthrough_connection(dropverify, US"quit or conndrop");
5115 deliver_domain = deliver_localpart = deliver_address_data =
5116 deliver_domain_data = sender_address_data = NULL;
5118 /* A DISCARD response is permitted only for message ACLs, excluding the PREDATA
5119 ACL, which is really in the middle of an SMTP command. */
5123 if (where > ACL_WHERE_NOTSMTP || where == ACL_WHERE_PREDATA)
5125 log_write(0, LOG_MAIN|LOG_PANIC, "\"discard\" verb not allowed in %s "
5126 "ACL", acl_wherenames[where]);
5132 /* A DROP response is not permitted from MAILAUTH */
5134 if (rc == FAIL_DROP && where == ACL_WHERE_MAILAUTH)
5136 log_write(0, LOG_MAIN|LOG_PANIC, "\"drop\" verb not allowed in %s "
5137 "ACL", acl_wherenames[where]);
5141 /* Before giving a response, take a look at the length of any user message, and
5142 split it up into multiple lines if possible. */
5144 *user_msgptr = string_split_message(*user_msgptr);
5145 if (fake_response != OK)
5146 fake_response_text = string_split_message(fake_response_text);
5152 /*************************************************
5153 * Create ACL variable *
5154 *************************************************/
5156 /* Create an ACL variable or reuse an existing one. ACL variables are in a
5157 binary tree (see tree.c) with acl_var_c and acl_var_m as root nodes.
5160 name pointer to the variable's name, starting with c or m
5162 Returns the pointer to variable's tree node
5166 acl_var_create(uschar * name)
5168 tree_node * node, ** root = name[0] == 'c' ? &acl_var_c : &acl_var_m;
5169 if (!(node = tree_search(*root, name)))
5171 node = store_get(sizeof(tree_node) + Ustrlen(name), name);
5172 Ustrcpy(node->name, name);
5173 (void)tree_insertnode(root, node);
5175 node->data.ptr = NULL;
5181 /*************************************************
5182 * Write an ACL variable in spool format *
5183 *************************************************/
5185 /* This function is used as a callback for tree_walk when writing variables to
5186 the spool file. To retain spool file compatibility, what is written is -aclc or
5187 -aclm followed by the rest of the name and the data length, space separated,
5188 then the value itself, starting on a new line, and terminated by an additional
5189 newline. When we had only numbered ACL variables, the first line might look
5190 like this: "-aclc 5 20". Now it might be "-aclc foo 20" for the variable called
5194 name of the variable
5195 value of the variable
5196 ctx FILE pointer (as a void pointer)
5202 acl_var_write(uschar * name, uschar * value, void * ctx)
5204 FILE * f = (FILE *)ctx;
5206 if (is_tainted(value))
5208 const uschar * quoter_name;
5210 (void) quoter_for_address(value, "er_name);
5212 fprintf(f, "(%s)", quoter_name);
5214 fprintf(f, "acl%c %s %d\n%s\n", name[0], name+1, Ustrlen(value), value);
5221 acl_standalone_setvar(const uschar * s, BOOL taint)
5223 acl_condition_block * cond = store_get(sizeof(acl_condition_block), GET_UNTAINTED);
5224 uschar * errstr = NULL, * log_msg = NULL;
5229 cond->type = ACLC_SET;
5230 if (!acl_varname_to_cond(&s, cond, &errstr)) return errstr;
5231 if (!acl_data_to_cond(s, cond, US"'-be'", taint, &errstr)) return errstr;
5233 if (acl_check_condition(ACL_WARN, cond, ACL_WHERE_UNKNOWN,
5234 NULL, 0, &endpass_seen, &errstr, &log_msg, &e) != OK)
5235 return string_sprintf("oops: %s", errstr);
5236 return string_sprintf("variable %s set", cond->u.varname);
5240 #endif /* !MACRO_PREDEF */