1 /* $Cambridge: exim/src/src/acl.c,v 1.79 2007/08/29 13:58:25 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) University of Cambridge 1995 - 2007 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* Code for handling Access Control Lists (ACLs) */
15 /* Default callout timeout */
17 #define CALLOUT_TIMEOUT_DEFAULT 30
19 /* ACL verb codes - keep in step with the table of verbs that follows */
21 enum { ACL_ACCEPT, ACL_DEFER, ACL_DENY, ACL_DISCARD, ACL_DROP, ACL_REQUIRE,
26 static uschar *verbs[] =
27 { US"accept", US"defer", US"deny", US"discard", US"drop", US"require",
30 /* For each verb, the conditions for which "message" or "log_message" are used
31 are held as a bitmap. This is to avoid expanding the strings unnecessarily. For
32 "accept", the FAIL case is used only after "endpass", but that is selected in
35 static int msgcond[] = {
36 (1<<OK) | (1<<FAIL) | (1<<FAIL_DROP), /* accept */
39 (1<<OK) | (1<<FAIL) | (1<<FAIL_DROP), /* discard */
41 (1<<FAIL) | (1<<FAIL_DROP), /* require */
45 /* ACL condition and modifier codes - keep in step with the table that
46 follows, and the cond_expand_at_top and uschar cond_modifiers tables lower
52 #ifdef EXPERIMENTAL_BRIGHTMAIL
58 #ifdef WITH_CONTENT_SCAN
62 #ifdef WITH_OLD_DEMIME
65 #ifdef EXPERIMENTAL_DOMAINKEYS
66 ACLC_DK_DOMAIN_SOURCE,
68 ACLC_DK_SENDER_DOMAINS,
69 ACLC_DK_SENDER_LOCAL_PARTS,
80 ACLC_LOG_REJECT_TARGET,
82 #ifdef WITH_CONTENT_SCAN
86 #ifdef WITH_CONTENT_SCAN
91 #ifdef WITH_CONTENT_SCAN
97 #ifdef WITH_CONTENT_SCAN
100 #ifdef EXPERIMENTAL_SPF
105 /* ACL conditions/modifiers: "delay", "control", "continue", "endpass",
106 "message", "log_message", "log_reject_target", "logwrite", and "set" are
107 modifiers that look like conditions but always return TRUE. They are used for
108 their side effects. */
110 static uschar *conditions[] = {
114 #ifdef EXPERIMENTAL_BRIGHTMAIL
120 #ifdef WITH_CONTENT_SCAN
124 #ifdef WITH_OLD_DEMIME
127 #ifdef EXPERIMENTAL_DOMAINKEYS
128 US"dk_domain_source",
130 US"dk_sender_domains",
131 US"dk_sender_local_parts",
142 US"log_reject_target",
144 #ifdef WITH_CONTENT_SCAN
148 #ifdef WITH_CONTENT_SCAN
153 #ifdef WITH_CONTENT_SCAN
156 US"sender_domains", US"senders", US"set",
157 #ifdef WITH_CONTENT_SCAN
160 #ifdef EXPERIMENTAL_SPF
166 /* Return values from decode_control(); keep in step with the table of names
170 CONTROL_AUTH_UNADVERTISED,
171 #ifdef EXPERIMENTAL_BRIGHTMAIL
174 #ifdef EXPERIMENTAL_DOMAINKEYS
178 CONTROL_CASEFUL_LOCAL_PART,
179 CONTROL_CASELOWER_LOCAL_PART,
180 CONTROL_ENFORCE_SYNC,
181 CONTROL_NO_ENFORCE_SYNC,
185 CONTROL_SUPPRESS_LOCAL_FIXUPS,
186 #ifdef WITH_CONTENT_SCAN
187 CONTROL_NO_MBOX_UNSPOOL,
191 CONTROL_NO_MULTILINE,
192 CONTROL_NO_PIPELINING,
193 CONTROL_NO_DELAY_FLUSH,
194 CONTROL_NO_CALLOUT_FLUSH
197 /* ACL control names; keep in step with the table above! This list is used for
198 turning ids into names. The actual list of recognized names is in the variable
199 control_def controls_list[] below. The fact that there are two lists is a mess
200 and should be tidied up. */
202 static uschar *controls[] = {
203 US"allow_auth_unadvertised",
204 #ifdef EXPERIMENTAL_BRIGHTMAIL
207 #ifdef EXPERIMENTAL_DOMAINKEYS
211 US"caseful_local_part",
212 US"caselower_local_part",
218 US"suppress_local_fixups",
219 #ifdef WITH_CONTENT_SCAN
224 US"no_multiline_responses",
230 /* Flags to indicate for which conditions/modifiers a string expansion is done
231 at the outer level. In the other cases, expansion already occurs in the
232 checking functions. */
234 static uschar cond_expand_at_top[] = {
236 TRUE, /* add_header */
237 FALSE, /* authenticated */
238 #ifdef EXPERIMENTAL_BRIGHTMAIL
239 TRUE, /* bmi_optin */
241 TRUE, /* condition */
244 #ifdef WITH_CONTENT_SCAN
248 #ifdef WITH_OLD_DEMIME
251 #ifdef EXPERIMENTAL_DOMAINKEYS
252 TRUE, /* dk_domain_source */
253 TRUE, /* dk_policy */
254 TRUE, /* dk_sender_domains */
255 TRUE, /* dk_sender_local_parts */
256 TRUE, /* dk_senders */
257 TRUE, /* dk_status */
261 FALSE, /* encrypted */
264 FALSE, /* local_parts */
265 TRUE, /* log_message */
266 TRUE, /* log_reject_target */
268 #ifdef WITH_CONTENT_SCAN
272 #ifdef WITH_CONTENT_SCAN
273 TRUE, /* mime_regex */
275 TRUE, /* ratelimit */
276 FALSE, /* recipients */
277 #ifdef WITH_CONTENT_SCAN
280 FALSE, /* sender_domains */
283 #ifdef WITH_CONTENT_SCAN
286 #ifdef EXPERIMENTAL_SPF
292 /* Flags to identify the modifiers */
294 static uschar cond_modifiers[] = {
296 TRUE, /* add_header */
297 FALSE, /* authenticated */
298 #ifdef EXPERIMENTAL_BRIGHTMAIL
299 TRUE, /* bmi_optin */
301 FALSE, /* condition */
304 #ifdef WITH_CONTENT_SCAN
308 #ifdef WITH_OLD_DEMIME
311 #ifdef EXPERIMENTAL_DOMAINKEYS
312 FALSE, /* dk_domain_source */
313 FALSE, /* dk_policy */
314 FALSE, /* dk_sender_domains */
315 FALSE, /* dk_sender_local_parts */
316 FALSE, /* dk_senders */
317 FALSE, /* dk_status */
319 FALSE, /* dnslists */
321 FALSE, /* encrypted */
324 FALSE, /* local_parts */
325 TRUE, /* log_message */
326 TRUE, /* log_reject_target */
328 #ifdef WITH_CONTENT_SCAN
332 #ifdef WITH_CONTENT_SCAN
333 FALSE, /* mime_regex */
335 FALSE, /* ratelimit */
336 FALSE, /* recipients */
337 #ifdef WITH_CONTENT_SCAN
340 FALSE, /* sender_domains */
343 #ifdef WITH_CONTENT_SCAN
346 #ifdef EXPERIMENTAL_SPF
352 /* Bit map vector of which conditions and modifiers are not allowed at certain
353 times. For each condition and modifier, there's a bitmap of dis-allowed times.
354 For some, it is easier to specify the negation of a small number of allowed
357 static unsigned int cond_forbids[] = {
361 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* add_header */
362 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
363 (1<<ACL_WHERE_MIME)|(1<<ACL_WHERE_NOTSMTP)|
364 (1<<ACL_WHERE_NOTSMTP_START)),
366 (1<<ACL_WHERE_NOTSMTP)| /* authenticated */
367 (1<<ACL_WHERE_NOTSMTP_START)|
368 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO),
370 #ifdef EXPERIMENTAL_BRIGHTMAIL
371 (1<<ACL_WHERE_AUTH)| /* bmi_optin */
372 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
373 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_MIME)|
374 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
375 (1<<ACL_WHERE_MAILAUTH)|
376 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
377 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_PREDATA)|
378 (1<<ACL_WHERE_NOTSMTP_START),
385 /* Certain types of control are always allowed, so we let it through
386 always and check in the control processing itself. */
390 #ifdef WITH_CONTENT_SCAN
392 ~(1<<ACL_WHERE_MIME), /* decode */
395 (1<<ACL_WHERE_NOTQUIT), /* delay */
397 #ifdef WITH_OLD_DEMIME
399 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* demime */
402 #ifdef EXPERIMENTAL_DOMAINKEYS
403 (1<<ACL_WHERE_AUTH)| /* dk_domain_source */
404 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
405 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
406 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
407 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
408 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
409 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
411 (1<<ACL_WHERE_AUTH)| /* dk_policy */
412 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
413 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
414 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
415 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
416 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
417 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
419 (1<<ACL_WHERE_AUTH)| /* dk_sender_domains */
420 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
421 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
422 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
423 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
424 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
425 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
427 (1<<ACL_WHERE_AUTH)| /* dk_sender_local_parts */
428 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
429 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
430 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
431 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
432 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
433 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
435 (1<<ACL_WHERE_AUTH)| /* dk_senders */
436 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
437 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
438 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
439 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
440 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
441 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
443 (1<<ACL_WHERE_AUTH)| /* dk_status */
444 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
445 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
446 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
447 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
448 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
449 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
452 (1<<ACL_WHERE_NOTSMTP)| /* dnslists */
453 (1<<ACL_WHERE_NOTSMTP_START),
456 ~(1<<ACL_WHERE_RCPT), /* domains */
458 (1<<ACL_WHERE_NOTSMTP)| /* encrypted */
459 (1<<ACL_WHERE_CONNECT)|
460 (1<<ACL_WHERE_NOTSMTP_START)|
465 (1<<ACL_WHERE_NOTSMTP)| /* hosts */
466 (1<<ACL_WHERE_NOTSMTP_START),
469 ~(1<<ACL_WHERE_RCPT), /* local_parts */
473 0, /* log_reject_target */
477 #ifdef WITH_CONTENT_SCAN
479 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* malware */
484 #ifdef WITH_CONTENT_SCAN
486 ~(1<<ACL_WHERE_MIME), /* mime_regex */
492 ~(1<<ACL_WHERE_RCPT), /* recipients */
494 #ifdef WITH_CONTENT_SCAN
496 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* regex */
497 (1<<ACL_WHERE_MIME)),
500 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* sender_domains */
502 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
503 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
504 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
506 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* senders */
508 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
509 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
510 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
514 #ifdef WITH_CONTENT_SCAN
516 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* spam */
519 #ifdef EXPERIMENTAL_SPF
520 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* spf */
522 (1<<ACL_WHERE_MAILAUTH)|
523 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
524 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY)|
525 (1<<ACL_WHERE_NOTSMTP)|
526 (1<<ACL_WHERE_NOTSMTP_START),
529 /* Certain types of verify are always allowed, so we let it through
530 always and check in the verify function itself */
536 /* Bit map vector of which controls are not allowed at certain times. For
537 each control, there's a bitmap of dis-allowed times. For some, it is easier to
538 specify the negation of a small number of allowed times. */
540 static unsigned int control_forbids[] = {
542 ~((1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)), /* allow_auth_unadvertised */
544 #ifdef EXPERIMENTAL_BRIGHTMAIL
548 #ifdef EXPERIMENTAL_DOMAINKEYS
549 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* dk_verify */
550 (1<<ACL_WHERE_NOTSMTP_START),
556 ~(1<<ACL_WHERE_RCPT), /* caseful_local_part */
559 ~(1<<ACL_WHERE_RCPT), /* caselower_local_part */
561 (1<<ACL_WHERE_NOTSMTP)| /* enforce_sync */
562 (1<<ACL_WHERE_NOTSMTP_START),
564 (1<<ACL_WHERE_NOTSMTP)| /* no_enforce_sync */
565 (1<<ACL_WHERE_NOTSMTP_START),
568 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* freeze */
569 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
570 (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_MIME)),
573 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* queue_only */
574 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
575 (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_MIME)),
578 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* submission */
579 (1<<ACL_WHERE_PREDATA)),
582 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* suppress_local_fixups */
583 (1<<ACL_WHERE_PREDATA)|
584 (1<<ACL_WHERE_NOTSMTP_START)),
586 #ifdef WITH_CONTENT_SCAN
588 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* no_mbox_unspool */
589 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
590 (1<<ACL_WHERE_MIME)),
594 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* fakedefer */
595 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
596 (1<<ACL_WHERE_MIME)),
599 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* fakereject */
600 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
601 (1<<ACL_WHERE_MIME)),
603 (1<<ACL_WHERE_NOTSMTP)| /* no_multiline */
604 (1<<ACL_WHERE_NOTSMTP_START),
606 (1<<ACL_WHERE_NOTSMTP)| /* no_pipelining */
607 (1<<ACL_WHERE_NOTSMTP_START),
609 (1<<ACL_WHERE_NOTSMTP)| /* no_delay_flush */
610 (1<<ACL_WHERE_NOTSMTP_START),
612 (1<<ACL_WHERE_NOTSMTP)| /* no_callout_flush */
613 (1<<ACL_WHERE_NOTSMTP_START)
616 /* Structure listing various control arguments, with their characteristics. */
618 typedef struct control_def {
620 int value; /* CONTROL_xxx value */
621 BOOL has_option; /* Has /option(s) following */
624 static control_def controls_list[] = {
625 { US"allow_auth_unadvertised", CONTROL_AUTH_UNADVERTISED, FALSE },
626 #ifdef EXPERIMENTAL_BRIGHTMAIL
627 { US"bmi_run", CONTROL_BMI_RUN, FALSE },
629 #ifdef EXPERIMENTAL_DOMAINKEYS
630 { US"dk_verify", CONTROL_DK_VERIFY, FALSE },
632 { US"caseful_local_part", CONTROL_CASEFUL_LOCAL_PART, FALSE },
633 { US"caselower_local_part", CONTROL_CASELOWER_LOCAL_PART, FALSE },
634 { US"enforce_sync", CONTROL_ENFORCE_SYNC, FALSE },
635 { US"freeze", CONTROL_FREEZE, TRUE },
636 { US"no_callout_flush", CONTROL_NO_CALLOUT_FLUSH, FALSE },
637 { US"no_delay_flush", CONTROL_NO_DELAY_FLUSH, FALSE },
638 { US"no_enforce_sync", CONTROL_NO_ENFORCE_SYNC, FALSE },
639 { US"no_multiline_responses", CONTROL_NO_MULTILINE, FALSE },
640 { US"no_pipelining", CONTROL_NO_PIPELINING, FALSE },
641 { US"queue_only", CONTROL_QUEUE_ONLY, FALSE },
642 #ifdef WITH_CONTENT_SCAN
643 { US"no_mbox_unspool", CONTROL_NO_MBOX_UNSPOOL, FALSE },
645 { US"fakedefer", CONTROL_FAKEDEFER, TRUE },
646 { US"fakereject", CONTROL_FAKEREJECT, TRUE },
647 { US"submission", CONTROL_SUBMISSION, TRUE },
648 { US"suppress_local_fixups", CONTROL_SUPPRESS_LOCAL_FIXUPS, FALSE }
651 /* Support data structures for Client SMTP Authorization. acl_verify_csa()
652 caches its result in a tree to avoid repeated DNS queries. The result is an
653 integer code which is used as an index into the following tables of
654 explanatory strings and verification return codes. */
656 static tree_node *csa_cache = NULL;
658 enum { CSA_UNKNOWN, CSA_OK, CSA_DEFER_SRV, CSA_DEFER_ADDR,
659 CSA_FAIL_EXPLICIT, CSA_FAIL_DOMAIN, CSA_FAIL_NOADDR, CSA_FAIL_MISMATCH };
661 /* The acl_verify_csa() return code is translated into an acl_verify() return
662 code using the following table. It is OK unless the client is definitely not
663 authorized. This is because CSA is supposed to be optional for sending sites,
664 so recipients should not be too strict about checking it - especially because
665 DNS problems are quite likely to occur. It's possible to use $csa_status in
666 further ACL conditions to distinguish ok, unknown, and defer if required, but
667 the aim is to make the usual configuration simple. */
669 static int csa_return_code[] = {
671 FAIL, FAIL, FAIL, FAIL
674 static uschar *csa_status_string[] = {
675 US"unknown", US"ok", US"defer", US"defer",
676 US"fail", US"fail", US"fail", US"fail"
679 static uschar *csa_reason_string[] = {
682 US"deferred (SRV lookup failed)",
683 US"deferred (target address lookup failed)",
684 US"failed (explicit authorization required)",
685 US"failed (host name not authorized)",
686 US"failed (no authorized addresses)",
687 US"failed (client address mismatch)"
690 /* Enable recursion between acl_check_internal() and acl_check_condition() */
692 static int acl_check_internal(int, address_item *, uschar *, int, uschar **,
696 /*************************************************
697 * Pick out name from list *
698 *************************************************/
700 /* Use a binary chop method
707 Returns: offset in list, or -1 if not found
711 acl_checkname(uschar *name, uschar **list, int end)
717 int mid = (start + end)/2;
718 int c = Ustrcmp(name, list[mid]);
719 if (c == 0) return mid;
720 if (c < 0) end = mid; else start = mid + 1;
727 /*************************************************
728 * Read and parse one ACL *
729 *************************************************/
731 /* This function is called both from readconf in order to parse the ACLs in the
732 configuration file, and also when an ACL is encountered dynamically (e.g. as
733 the result of an expansion). It is given a function to call in order to
734 retrieve the lines of the ACL. This function handles skipping comments and
735 blank lines (where relevant).
738 func function to get next line of ACL
739 error where to put an error message
741 Returns: pointer to ACL, or NULL
742 NULL can be legal (empty ACL); in this case error will be NULL
746 acl_read(uschar *(*func)(void), uschar **error)
748 acl_block *yield = NULL;
749 acl_block **lastp = &yield;
750 acl_block *this = NULL;
751 acl_condition_block *cond;
752 acl_condition_block **condp = NULL;
757 while ((s = (*func)()) != NULL)
760 BOOL negated = FALSE;
761 uschar *saveline = s;
764 /* Conditions (but not verbs) are allowed to be negated by an initial
767 while (isspace(*s)) s++;
774 /* Read the name of a verb or a condition, or the start of a new ACL, which
775 can be started by a name, or by a macro definition. */
777 s = readconf_readname(name, sizeof(name), s);
778 if (*s == ':' || (isupper(name[0]) && *s == '=')) return yield;
780 /* If a verb is unrecognized, it may be another condition or modifier that
781 continues the previous verb. */
783 v = acl_checkname(name, verbs, sizeof(verbs)/sizeof(char *));
788 *error = string_sprintf("unknown ACL verb \"%s\" in \"%s\"", name,
800 *error = string_sprintf("malformed ACL line \"%s\"", saveline);
803 this = store_get(sizeof(acl_block));
805 lastp = &(this->next);
808 this->condition = NULL;
809 condp = &(this->condition);
810 if (*s == 0) continue; /* No condition on this line */
816 s = readconf_readname(name, sizeof(name), s); /* Condition name */
819 /* Handle a condition or modifier. */
821 c = acl_checkname(name, conditions, sizeof(conditions)/sizeof(char *));
824 *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
829 /* The modifiers may not be negated */
831 if (negated && cond_modifiers[c])
833 *error = string_sprintf("ACL error: negation is not allowed with "
834 "\"%s\"", conditions[c]);
838 /* ENDPASS may occur only with ACCEPT or DISCARD. */
840 if (c == ACLC_ENDPASS &&
841 this->verb != ACL_ACCEPT &&
842 this->verb != ACL_DISCARD)
844 *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
845 conditions[c], verbs[this->verb]);
849 cond = store_get(sizeof(acl_condition_block));
852 cond->u.negated = negated;
855 condp = &(cond->next);
857 /* The "set" modifier is different in that its argument is "name=value"
858 rather than just a value, and we can check the validity of the name, which
859 gives us a variable name to insert into the data block. The original ACL
860 variable names were acl_c0 ... acl_c9 and acl_m0 ... acl_m9. This was
861 extended to 20 of each type, but after that people successfully argued for
862 arbitrary names. In the new scheme, the names must start with acl_c or acl_m.
863 After that, we allow alphanumerics and underscores, but the first character
864 after c or m must be a digit or an underscore. This retains backwards
871 if (Ustrncmp(s, "acl_c", 5) != 0 &&
872 Ustrncmp(s, "acl_m", 5) != 0)
874 *error = string_sprintf("invalid variable name after \"set\" in ACL "
875 "modifier \"set %s\" (must start \"acl_c\" or \"acl_m\")", s);
880 if (!isdigit(*endptr) && *endptr != '_')
882 *error = string_sprintf("invalid variable name after \"set\" in ACL "
883 "modifier \"set %s\" (digit or underscore must follow acl_c or acl_m)",
888 while (*endptr != 0 && *endptr != '=' && !isspace(*endptr))
890 if (!isalnum(*endptr) && *endptr != '_')
892 *error = string_sprintf("invalid character \"%c\" in variable name "
893 "in ACL modifier \"set %s\"", *endptr, s);
899 cond->u.varname = string_copyn(s + 4, endptr - s - 4);
901 while (isspace(*s)) s++;
904 /* For "set", we are now positioned for the data. For the others, only
905 "endpass" has no data */
907 if (c != ACLC_ENDPASS)
911 *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
912 cond_modifiers[c]? US"modifier" : US"condition");
915 while (isspace(*s)) s++;
916 cond->arg = string_copy(s);
925 /*************************************************
926 * Set up added header line(s) *
927 *************************************************/
929 /* This function is called by the add_header modifier, and also from acl_warn()
930 to implement the now-deprecated way of adding header lines using "message" on a
931 "warn" verb. The argument is treated as a sequence of header lines which are
932 added to a chain, provided there isn't an identical one already there.
934 Argument: string of header lines
939 setup_header(uschar *hstring)
942 int hlen = Ustrlen(hstring);
944 /* An empty string does nothing; otherwise add a final newline if necessary. */
946 if (hlen <= 0) return;
947 if (hstring[hlen-1] != '\n') hstring = string_sprintf("%s\n", hstring);
949 /* Loop for multiple header lines, taking care about continuations */
951 for (p = q = hstring; *p != 0; )
954 int newtype = htype_add_bot;
955 header_line **hptr = &acl_added_headers;
957 /* Find next header line within the string */
961 q = Ustrchr(q, '\n');
962 if (*(++q) != ' ' && *q != '\t') break;
965 /* If the line starts with a colon, interpret the instruction for where to
966 add it. This temporarily sets up a new type. */
970 if (strncmpic(p, US":after_received:", 16) == 0)
972 newtype = htype_add_rec;
975 else if (strncmpic(p, US":at_start_rfc:", 14) == 0)
977 newtype = htype_add_rfc;
980 else if (strncmpic(p, US":at_start:", 10) == 0)
982 newtype = htype_add_top;
985 else if (strncmpic(p, US":at_end:", 8) == 0)
987 newtype = htype_add_bot;
990 while (*p == ' ' || *p == '\t') p++;
993 /* See if this line starts with a header name, and if not, add X-ACL-Warn:
994 to the front of it. */
996 for (s = p; s < q - 1; s++)
998 if (*s == ':' || !isgraph(*s)) break;
1001 s = string_sprintf("%s%.*s", (*s == ':')? "" : "X-ACL-Warn: ", q - p, p);
1004 /* See if this line has already been added */
1006 while (*hptr != NULL)
1008 if (Ustrncmp((*hptr)->text, s, hlen) == 0) break;
1009 hptr = &((*hptr)->next);
1012 /* Add if not previously present */
1016 header_line *h = store_get(sizeof(header_line));
1025 /* Advance for next header line within the string */
1034 /*************************************************
1036 *************************************************/
1038 /* This function is called when a WARN verb's conditions are true. It adds to
1039 the message's headers, and/or writes information to the log. In each case, this
1040 only happens once (per message for headers, per connection for log).
1042 ** NOTE: The header adding action using the "message" setting is historic, and
1043 its use is now deprecated. The new add_header modifier should be used instead.
1046 where ACL_WHERE_xxxx indicating which ACL this is
1047 user_message message for adding to headers
1048 log_message message for logging, if different
1054 acl_warn(int where, uschar *user_message, uschar *log_message)
1056 if (log_message != NULL && log_message != user_message)
1059 string_item *logged;
1061 text = string_sprintf("%s Warning: %s", host_and_ident(TRUE),
1062 string_printing(log_message));
1064 /* If a sender verification has failed, and the log message is "sender verify
1065 failed", add the failure message. */
1067 if (sender_verified_failed != NULL &&
1068 sender_verified_failed->message != NULL &&
1069 strcmpic(log_message, US"sender verify failed") == 0)
1070 text = string_sprintf("%s: %s", text, sender_verified_failed->message);
1072 /* Search previously logged warnings. They are kept in malloc
1073 store so they can be freed at the start of a new message. */
1075 for (logged = acl_warn_logged; logged != NULL; logged = logged->next)
1076 if (Ustrcmp(logged->text, text) == 0) break;
1080 int length = Ustrlen(text) + 1;
1081 log_write(0, LOG_MAIN, "%s", text);
1082 logged = store_malloc(sizeof(string_item) + length);
1083 logged->text = (uschar *)logged + sizeof(string_item);
1084 memcpy(logged->text, text, length);
1085 logged->next = acl_warn_logged;
1086 acl_warn_logged = logged;
1090 /* If there's no user message, we are done. */
1092 if (user_message == NULL) return;
1094 /* If this isn't a message ACL, we can't do anything with a user message.
1097 if (where > ACL_WHERE_NOTSMTP)
1099 log_write(0, LOG_MAIN|LOG_PANIC, "ACL \"warn\" with \"message\" setting "
1100 "found in a non-message (%s) ACL: cannot specify header lines here: "
1101 "message ignored", acl_wherenames[where]);
1105 /* The code for setting up header lines is now abstracted into a separate
1106 function so that it can be used for the add_header modifier as well. */
1108 setup_header(user_message);
1113 /*************************************************
1114 * Verify and check reverse DNS *
1115 *************************************************/
1117 /* Called from acl_verify() below. We look up the host name(s) of the client IP
1118 address if this has not yet been done. The host_name_lookup() function checks
1119 that one of these names resolves to an address list that contains the client IP
1120 address, so we don't actually have to do the check here.
1123 user_msgptr pointer for user message
1124 log_msgptr pointer for log message
1126 Returns: OK verification condition succeeded
1127 FAIL verification failed
1128 DEFER there was a problem verifying
1132 acl_verify_reverse(uschar **user_msgptr, uschar **log_msgptr)
1136 user_msgptr = user_msgptr; /* stop compiler warning */
1138 /* Previous success */
1140 if (sender_host_name != NULL) return OK;
1142 /* Previous failure */
1144 if (host_lookup_failed)
1146 *log_msgptr = string_sprintf("host lookup failed%s", host_lookup_msg);
1150 /* Need to do a lookup */
1153 debug_printf("looking up host name to force name/address consistency check\n");
1155 if ((rc = host_name_lookup()) != OK)
1157 *log_msgptr = (rc == DEFER)?
1158 US"host lookup deferred for reverse lookup check"
1160 string_sprintf("host lookup failed for reverse lookup check%s",
1162 return rc; /* DEFER or FAIL */
1165 host_build_sender_fullhost();
1171 /*************************************************
1172 * Check client IP address matches CSA target *
1173 *************************************************/
1175 /* Called from acl_verify_csa() below. This routine scans a section of a DNS
1176 response for address records belonging to the CSA target hostname. The section
1177 is specified by the reset argument, either RESET_ADDITIONAL or RESET_ANSWERS.
1178 If one of the addresses matches the client's IP address, then the client is
1179 authorized by CSA. If there are target IP addresses but none of them match
1180 then the client is using an unauthorized IP address. If there are no target IP
1181 addresses then the client cannot be using an authorized IP address. (This is
1182 an odd configuration - why didn't the SRV record have a weight of 1 instead?)
1185 dnsa the DNS answer block
1186 dnss a DNS scan block for us to use
1187 reset option specifing what portion to scan, as described above
1188 target the target hostname to use for matching RR names
1190 Returns: CSA_OK successfully authorized
1191 CSA_FAIL_MISMATCH addresses found but none matched
1192 CSA_FAIL_NOADDR no target addresses found
1196 acl_verify_csa_address(dns_answer *dnsa, dns_scan *dnss, int reset,
1202 BOOL target_found = FALSE;
1204 for (rr = dns_next_rr(dnsa, dnss, reset);
1206 rr = dns_next_rr(dnsa, dnss, RESET_NEXT))
1208 /* Check this is an address RR for the target hostname. */
1212 && rr->type != T_AAAA
1219 if (strcmpic(target, rr->name) != 0) continue;
1221 target_found = TRUE;
1223 /* Turn the target address RR into a list of textual IP addresses and scan
1224 the list. There may be more than one if it is an A6 RR. */
1226 for (da = dns_address_from_rr(dnsa, rr); da != NULL; da = da->next)
1228 /* If the client IP address matches the target IP address, it's good! */
1230 DEBUG(D_acl) debug_printf("CSA target address is %s\n", da->address);
1232 if (strcmpic(sender_host_address, da->address) == 0) return CSA_OK;
1236 /* If we found some target addresses but none of them matched, the client is
1237 using an unauthorized IP address, otherwise the target has no authorized IP
1240 if (target_found) return CSA_FAIL_MISMATCH;
1241 else return CSA_FAIL_NOADDR;
1246 /*************************************************
1247 * Verify Client SMTP Authorization *
1248 *************************************************/
1250 /* Called from acl_verify() below. This routine calls dns_lookup_special()
1251 to find the CSA SRV record corresponding to the domain argument, or
1252 $sender_helo_name if no argument is provided. It then checks that the
1253 client is authorized, and that its IP address corresponds to the SRV
1254 target's address by calling acl_verify_csa_address() above. The address
1255 should have been returned in the DNS response's ADDITIONAL section, but if
1256 not we perform another DNS lookup to get it.
1259 domain pointer to optional parameter following verify = csa
1261 Returns: CSA_UNKNOWN no valid CSA record found
1262 CSA_OK successfully authorized
1263 CSA_FAIL_* client is definitely not authorized
1264 CSA_DEFER_* there was a DNS problem
1268 acl_verify_csa(uschar *domain)
1272 int priority, weight, port;
1279 /* Work out the domain we are using for the CSA lookup. The default is the
1280 client's HELO domain. If the client has not said HELO, use its IP address
1281 instead. If it's a local client (exim -bs), CSA isn't applicable. */
1283 while (isspace(*domain) && *domain != '\0') ++domain;
1284 if (*domain == '\0') domain = sender_helo_name;
1285 if (domain == NULL) domain = sender_host_address;
1286 if (sender_host_address == NULL) return CSA_UNKNOWN;
1288 /* If we have an address literal, strip off the framing ready for turning it
1289 into a domain. The framing consists of matched square brackets possibly
1290 containing a keyword and a colon before the actual IP address. */
1292 if (domain[0] == '[')
1294 uschar *start = Ustrchr(domain, ':');
1295 if (start == NULL) start = domain;
1296 domain = string_copyn(start + 1, Ustrlen(start) - 2);
1299 /* Turn domains that look like bare IP addresses into domains in the reverse
1300 DNS. This code also deals with address literals and $sender_host_address. It's
1301 not quite kosher to treat bare domains such as EHLO 192.0.2.57 the same as
1302 address literals, but it's probably the most friendly thing to do. This is an
1303 extension to CSA, so we allow it to be turned off for proper conformance. */
1305 if (string_is_ip_address(domain, NULL) != 0)
1307 if (!dns_csa_use_reverse) return CSA_UNKNOWN;
1308 dns_build_reverse(domain, target);
1312 /* Find out if we've already done the CSA check for this domain. If we have,
1313 return the same result again. Otherwise build a new cached result structure
1314 for this domain. The name is filled in now, and the value is filled in when
1315 we return from this function. */
1317 t = tree_search(csa_cache, domain);
1318 if (t != NULL) return t->data.val;
1320 t = store_get_perm(sizeof(tree_node) + Ustrlen(domain));
1321 Ustrcpy(t->name, domain);
1322 (void)tree_insertnode(&csa_cache, t);
1324 /* Now we are ready to do the actual DNS lookup(s). */
1327 switch (dns_special_lookup(&dnsa, domain, T_CSA, &found))
1329 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1332 return t->data.val = CSA_DEFER_SRV;
1334 /* If we found nothing, the client's authorization is unknown. */
1338 return t->data.val = CSA_UNKNOWN;
1340 /* We got something! Go on to look at the reply in more detail. */
1346 /* Scan the reply for well-formed CSA SRV records. */
1348 for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
1350 rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
1352 if (rr->type != T_SRV) continue;
1354 /* Extract the numerical SRV fields (p is incremented) */
1357 GETSHORT(priority, p);
1358 GETSHORT(weight, p);
1362 debug_printf("CSA priority=%d weight=%d port=%d\n", priority, weight, port);
1364 /* Check the CSA version number */
1366 if (priority != 1) continue;
1368 /* If the domain does not have a CSA SRV record of its own (i.e. the domain
1369 found by dns_special_lookup() is a parent of the one we asked for), we check
1370 the subdomain assertions in the port field. At the moment there's only one
1371 assertion: legitimate SMTP clients are all explicitly authorized with CSA
1372 SRV records of their own. */
1374 if (found != domain)
1377 return t->data.val = CSA_FAIL_EXPLICIT;
1379 return t->data.val = CSA_UNKNOWN;
1382 /* This CSA SRV record refers directly to our domain, so we check the value
1383 in the weight field to work out the domain's authorization. 0 and 1 are
1384 unauthorized; 3 means the client is authorized but we can't check the IP
1385 address in order to authenticate it, so we treat it as unknown; values
1386 greater than 3 are undefined. */
1388 if (weight < 2) return t->data.val = CSA_FAIL_DOMAIN;
1390 if (weight > 2) continue;
1392 /* Weight == 2, which means the domain is authorized. We must check that the
1393 client's IP address is listed as one of the SRV target addresses. Save the
1394 target hostname then break to scan the additional data for its addresses. */
1396 (void)dn_expand(dnsa.answer, dnsa.answer + dnsa.answerlen, p,
1397 (DN_EXPAND_ARG4_TYPE)target, sizeof(target));
1399 DEBUG(D_acl) debug_printf("CSA target is %s\n", target);
1404 /* If we didn't break the loop then no appropriate records were found. */
1406 if (rr == NULL) return t->data.val = CSA_UNKNOWN;
1408 /* Do not check addresses if the target is ".", in accordance with RFC 2782.
1409 A target of "." indicates there are no valid addresses, so the client cannot
1410 be authorized. (This is an odd configuration because weight=2 target=. is
1411 equivalent to weight=1, but we check for it in order to keep load off the
1412 root name servers.) Note that dn_expand() turns "." into "". */
1414 if (Ustrcmp(target, "") == 0) return t->data.val = CSA_FAIL_NOADDR;
1416 /* Scan the additional section of the CSA SRV reply for addresses belonging
1417 to the target. If the name server didn't return any additional data (e.g.
1418 because it does not fully support SRV records), we need to do another lookup
1419 to obtain the target addresses; otherwise we have a definitive result. */
1421 rc = acl_verify_csa_address(&dnsa, &dnss, RESET_ADDITIONAL, target);
1422 if (rc != CSA_FAIL_NOADDR) return t->data.val = rc;
1424 /* The DNS lookup type corresponds to the IP version used by the client. */
1427 if (Ustrchr(sender_host_address, ':') != NULL)
1430 #endif /* HAVE_IPV6 */
1434 #if HAVE_IPV6 && defined(SUPPORT_A6)
1438 switch (dns_lookup(&dnsa, target, type, NULL))
1440 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1443 return t->data.val = CSA_DEFER_ADDR;
1445 /* If the query succeeded, scan the addresses and return the result. */
1448 rc = acl_verify_csa_address(&dnsa, &dnss, RESET_ANSWERS, target);
1449 if (rc != CSA_FAIL_NOADDR) return t->data.val = rc;
1450 /* else fall through */
1452 /* If the target has no IP addresses, the client cannot have an authorized
1453 IP address. However, if the target site uses A6 records (not AAAA records)
1454 we have to do yet another lookup in order to check them. */
1459 #if HAVE_IPV6 && defined(SUPPORT_A6)
1460 if (type == T_AAAA) { type = T_A6; goto DNS_LOOKUP_AGAIN; }
1463 return t->data.val = CSA_FAIL_NOADDR;
1469 /*************************************************
1470 * Handle verification (address & other) *
1471 *************************************************/
1473 /* This function implements the "verify" condition. It is called when
1474 encountered in any ACL, because some tests are almost always permitted. Some
1475 just don't make sense, and always fail (for example, an attempt to test a host
1476 lookup for a non-TCP/IP message). Others are restricted to certain ACLs.
1479 where where called from
1480 addr the recipient address that the ACL is handling, or NULL
1481 arg the argument of "verify"
1482 user_msgptr pointer for user message
1483 log_msgptr pointer for log message
1484 basic_errno where to put verify errno
1486 Returns: OK verification condition succeeded
1487 FAIL verification failed
1488 DEFER there was a problem verifying
1493 acl_verify(int where, address_item *addr, uschar *arg,
1494 uschar **user_msgptr, uschar **log_msgptr, int *basic_errno)
1498 int callout_overall = -1;
1499 int callout_connect = -1;
1500 int verify_options = 0;
1502 BOOL verify_header_sender = FALSE;
1503 BOOL defer_ok = FALSE;
1504 BOOL callout_defer_ok = FALSE;
1505 BOOL no_details = FALSE;
1506 BOOL success_on_redirect = FALSE;
1507 address_item *sender_vaddr = NULL;
1508 uschar *verify_sender_address = NULL;
1509 uschar *pm_mailfrom = NULL;
1510 uschar *se_mailfrom = NULL;
1512 /* Some of the verify items have slash-separated options; some do not. Diagnose
1513 an error if options are given for items that don't expect them. This code has
1514 now got very message. Refactoring to use a table would be a good idea one day.
1517 uschar *slash = Ustrchr(arg, '/');
1519 uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);
1521 if (ss == NULL) goto BAD_VERIFY;
1523 /* Handle name/address consistency verification in a separate function. */
1525 if (strcmpic(ss, US"reverse_host_lookup") == 0)
1527 if (slash != NULL) goto NO_OPTIONS;
1528 if (sender_host_address == NULL) return OK;
1529 return acl_verify_reverse(user_msgptr, log_msgptr);
1532 /* TLS certificate verification is done at STARTTLS time; here we just
1533 test whether it was successful or not. (This is for optional verification; for
1534 mandatory verification, the connection doesn't last this long.) */
1536 if (strcmpic(ss, US"certificate") == 0)
1538 if (slash != NULL) goto NO_OPTIONS;
1539 if (tls_certificate_verified) return OK;
1540 *user_msgptr = US"no verified certificate";
1544 /* We can test the result of optional HELO verification that might have
1545 occurred earlier. If not, we can attempt the verification now. */
1547 if (strcmpic(ss, US"helo") == 0)
1549 if (slash != NULL) goto NO_OPTIONS;
1550 if (!helo_verified && !helo_verify_failed) smtp_verify_helo();
1551 return helo_verified? OK : FAIL;
1554 /* Do Client SMTP Authorization checks in a separate function, and turn the
1555 result code into user-friendly strings. */
1557 if (strcmpic(ss, US"csa") == 0)
1559 rc = acl_verify_csa(list);
1560 *log_msgptr = *user_msgptr = string_sprintf("client SMTP authorization %s",
1561 csa_reason_string[rc]);
1562 csa_status = csa_status_string[rc];
1563 DEBUG(D_acl) debug_printf("CSA result %s\n", csa_status);
1564 return csa_return_code[rc];
1567 /* Check that all relevant header lines have the correct syntax. If there is
1568 a syntax error, we return details of the error to the sender if configured to
1569 send out full details. (But a "message" setting on the ACL can override, as
1572 if (strcmpic(ss, US"header_syntax") == 0)
1574 if (slash != NULL) goto NO_OPTIONS;
1575 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1576 rc = verify_check_headers(log_msgptr);
1577 if (rc != OK && smtp_return_error_details && *log_msgptr != NULL)
1578 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1582 /* Check that no recipient of this message is "blind", that is, every envelope
1583 recipient must be mentioned in either To: or Cc:. */
1585 if (strcmpic(ss, US"not_blind") == 0)
1587 if (slash != NULL) goto NO_OPTIONS;
1588 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1589 rc = verify_check_notblind();
1592 *log_msgptr = string_sprintf("bcc recipient detected");
1593 if (smtp_return_error_details)
1594 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1599 /* The remaining verification tests check recipient and sender addresses,
1600 either from the envelope or from the header. There are a number of
1601 slash-separated options that are common to all of them. */
1604 /* Check that there is at least one verifiable sender address in the relevant
1605 header lines. This can be followed by callout and defer options, just like
1606 sender and recipient. */
1608 if (strcmpic(ss, US"header_sender") == 0)
1610 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1611 verify_header_sender = TRUE;
1614 /* Otherwise, first item in verify argument must be "sender" or "recipient".
1615 In the case of a sender, this can optionally be followed by an address to use
1616 in place of the actual sender (rare special-case requirement). */
1618 else if (strncmpic(ss, US"sender", 6) == 0)
1621 if (where > ACL_WHERE_NOTSMTP)
1623 *log_msgptr = string_sprintf("cannot verify sender in ACL for %s "
1624 "(only possible for MAIL, RCPT, PREDATA, or DATA)",
1625 acl_wherenames[where]);
1629 verify_sender_address = sender_address;
1632 while (isspace(*s)) s++;
1633 if (*s++ != '=') goto BAD_VERIFY;
1634 while (isspace(*s)) s++;
1635 verify_sender_address = string_copy(s);
1640 if (strcmpic(ss, US"recipient") != 0) goto BAD_VERIFY;
1643 *log_msgptr = string_sprintf("cannot verify recipient in ACL for %s "
1644 "(only possible for RCPT)", acl_wherenames[where]);
1649 /* Remaining items are optional; they apply to sender and recipient
1650 verification, including "header sender" verification. */
1652 while ((ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))
1655 if (strcmpic(ss, US"defer_ok") == 0) defer_ok = TRUE;
1656 else if (strcmpic(ss, US"no_details") == 0) no_details = TRUE;
1657 else if (strcmpic(ss, US"success_on_redirect") == 0) success_on_redirect = TRUE;
1659 /* These two old options are left for backwards compatibility */
1661 else if (strcmpic(ss, US"callout_defer_ok") == 0)
1663 callout_defer_ok = TRUE;
1664 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1667 else if (strcmpic(ss, US"check_postmaster") == 0)
1670 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1673 /* The callout option has a number of sub-options, comma separated */
1675 else if (strncmpic(ss, US"callout", 7) == 0)
1677 callout = CALLOUT_TIMEOUT_DEFAULT;
1681 while (isspace(*ss)) ss++;
1687 while (isspace(*ss)) ss++;
1689 /* This callout option handling code has become a mess as new options
1690 have been added in an ad hoc manner. It should be tidied up into some
1691 kind of table-driven thing. */
1693 while ((opt = string_nextinlist(&ss, &optsep, buffer, sizeof(buffer)))
1696 if (strcmpic(opt, US"defer_ok") == 0) callout_defer_ok = TRUE;
1697 else if (strcmpic(opt, US"no_cache") == 0)
1698 verify_options |= vopt_callout_no_cache;
1699 else if (strcmpic(opt, US"random") == 0)
1700 verify_options |= vopt_callout_random;
1701 else if (strcmpic(opt, US"use_sender") == 0)
1702 verify_options |= vopt_callout_recipsender;
1703 else if (strcmpic(opt, US"use_postmaster") == 0)
1704 verify_options |= vopt_callout_recippmaster;
1705 else if (strcmpic(opt, US"postmaster") == 0) pm_mailfrom = US"";
1706 else if (strcmpic(opt, US"fullpostmaster") == 0)
1709 verify_options |= vopt_callout_fullpm;
1712 else if (strncmpic(opt, US"mailfrom", 8) == 0)
1714 if (!verify_header_sender)
1716 *log_msgptr = string_sprintf("\"mailfrom\" is allowed as a "
1717 "callout option only for verify=header_sender (detected in ACL "
1718 "condition \"%s\")", arg);
1722 while (isspace(*opt)) opt++;
1725 *log_msgptr = string_sprintf("'=' expected after "
1726 "\"mailfrom\" in ACL condition \"%s\"", arg);
1729 while (isspace(*opt)) opt++;
1730 se_mailfrom = string_copy(opt);
1733 else if (strncmpic(opt, US"postmaster_mailfrom", 19) == 0)
1736 while (isspace(*opt)) opt++;
1739 *log_msgptr = string_sprintf("'=' expected after "
1740 "\"postmaster_mailfrom\" in ACL condition \"%s\"", arg);
1743 while (isspace(*opt)) opt++;
1744 pm_mailfrom = string_copy(opt);
1747 else if (strncmpic(opt, US"maxwait", 7) == 0)
1750 while (isspace(*opt)) opt++;
1753 *log_msgptr = string_sprintf("'=' expected after \"maxwait\" in "
1754 "ACL condition \"%s\"", arg);
1757 while (isspace(*opt)) opt++;
1758 callout_overall = readconf_readtime(opt, 0, FALSE);
1759 if (callout_overall < 0)
1761 *log_msgptr = string_sprintf("bad time value in ACL condition "
1762 "\"verify %s\"", arg);
1766 else if (strncmpic(opt, US"connect", 7) == 0)
1769 while (isspace(*opt)) opt++;
1772 *log_msgptr = string_sprintf("'=' expected after "
1773 "\"callout_overaall\" in ACL condition \"%s\"", arg);
1776 while (isspace(*opt)) opt++;
1777 callout_connect = readconf_readtime(opt, 0, FALSE);
1778 if (callout_connect < 0)
1780 *log_msgptr = string_sprintf("bad time value in ACL condition "
1781 "\"verify %s\"", arg);
1785 else /* Plain time is callout connect/command timeout */
1787 callout = readconf_readtime(opt, 0, FALSE);
1790 *log_msgptr = string_sprintf("bad time value in ACL condition "
1791 "\"verify %s\"", arg);
1799 *log_msgptr = string_sprintf("'=' expected after \"callout\" in "
1800 "ACL condition \"%s\"", arg);
1806 /* Option not recognized */
1810 *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1811 "condition \"verify %s\"", ss, arg);
1816 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)) ==
1817 (vopt_callout_recipsender|vopt_callout_recippmaster))
1819 *log_msgptr = US"only one of use_sender and use_postmaster can be set "
1820 "for a recipient callout";
1824 /* Handle sender-in-header verification. Default the user message to the log
1825 message if giving out verification details. */
1827 if (verify_header_sender)
1830 rc = verify_check_header_address(user_msgptr, log_msgptr, callout,
1831 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, verify_options,
1835 *basic_errno = verrno;
1836 if (smtp_return_error_details)
1838 if (*user_msgptr == NULL && *log_msgptr != NULL)
1839 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1840 if (rc == DEFER) acl_temp_details = TRUE;
1845 /* Handle a sender address. The default is to verify *the* sender address, but
1846 optionally a different address can be given, for special requirements. If the
1847 address is empty, we are dealing with a bounce message that has no sender, so
1848 we cannot do any checking. If the real sender address gets rewritten during
1849 verification (e.g. DNS widening), set the flag to stop it being rewritten again
1850 during message reception.
1852 A list of verified "sender" addresses is kept to try to avoid doing to much
1853 work repetitively when there are multiple recipients in a message and they all
1854 require sender verification. However, when callouts are involved, it gets too
1855 complicated because different recipients may require different callout options.
1856 Therefore, we always do a full sender verify when any kind of callout is
1857 specified. Caching elsewhere, for instance in the DNS resolver and in the
1858 callout handling, should ensure that this is not terribly inefficient. */
1860 else if (verify_sender_address != NULL)
1862 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster))
1865 *log_msgptr = US"use_sender or use_postmaster cannot be used for a "
1866 "sender verify callout";
1870 sender_vaddr = verify_checked_sender(verify_sender_address);
1871 if (sender_vaddr != NULL && /* Previously checked */
1872 callout <= 0) /* No callout needed this time */
1874 /* If the "routed" flag is set, it means that routing worked before, so
1875 this check can give OK (the saved return code value, if set, belongs to a
1876 callout that was done previously). If the "routed" flag is not set, routing
1877 must have failed, so we use the saved return code. */
1879 if (testflag(sender_vaddr, af_verify_routed)) rc = OK; else
1881 rc = sender_vaddr->special_action;
1882 *basic_errno = sender_vaddr->basic_errno;
1884 HDEBUG(D_acl) debug_printf("using cached sender verify result\n");
1887 /* Do a new verification, and cache the result. The cache is used to avoid
1888 verifying the sender multiple times for multiple RCPTs when callouts are not
1889 specified (see comments above).
1891 The cache is also used on failure to give details in response to the first
1892 RCPT that gets bounced for this reason. However, this can be suppressed by
1893 the no_details option, which sets the flag that says "this detail has already
1894 been sent". The cache normally contains just one address, but there may be
1895 more in esoteric circumstances. */
1900 uschar *save_address_data = deliver_address_data;
1902 sender_vaddr = deliver_make_addr(verify_sender_address, TRUE);
1903 if (no_details) setflag(sender_vaddr, af_sverify_told);
1904 if (verify_sender_address[0] != 0)
1906 /* If this is the real sender address, save the unrewritten version
1907 for use later in receive. Otherwise, set a flag so that rewriting the
1908 sender in verify_address() does not update sender_address. */
1910 if (verify_sender_address == sender_address)
1911 sender_address_unrewritten = sender_address;
1913 verify_options |= vopt_fake_sender;
1915 if (success_on_redirect)
1916 verify_options |= vopt_success_on_redirect;
1918 /* The recipient, qualify, and expn options are never set in
1921 rc = verify_address(sender_vaddr, NULL, verify_options, callout,
1922 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, &routed);
1924 HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1928 if (Ustrcmp(sender_vaddr->address, verify_sender_address) != 0)
1930 DEBUG(D_acl) debug_printf("sender %s verified ok as %s\n",
1931 verify_sender_address, sender_vaddr->address);
1935 DEBUG(D_acl) debug_printf("sender %s verified ok\n",
1936 verify_sender_address);
1939 else *basic_errno = sender_vaddr->basic_errno;
1941 else rc = OK; /* Null sender */
1943 /* Cache the result code */
1945 if (routed) setflag(sender_vaddr, af_verify_routed);
1946 if (callout > 0) setflag(sender_vaddr, af_verify_callout);
1947 sender_vaddr->special_action = rc;
1948 sender_vaddr->next = sender_verified_list;
1949 sender_verified_list = sender_vaddr;
1951 /* Restore the recipient address data, which might have been clobbered by
1952 the sender verification. */
1954 deliver_address_data = save_address_data;
1957 /* Put the sender address_data value into $sender_address_data */
1959 sender_address_data = sender_vaddr->p.address_data;
1962 /* A recipient address just gets a straightforward verify; again we must handle
1963 the DEFER overrides. */
1969 if (success_on_redirect)
1970 verify_options |= vopt_success_on_redirect;
1972 /* We must use a copy of the address for verification, because it might
1976 rc = verify_address(&addr2, NULL, verify_options|vopt_is_recipient, callout,
1977 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, NULL);
1978 HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1980 *basic_errno = addr2.basic_errno;
1981 *log_msgptr = addr2.message;
1982 *user_msgptr = (addr2.user_message != NULL)?
1983 addr2.user_message : addr2.message;
1985 /* Allow details for temporary error if the address is so flagged. */
1986 if (testflag((&addr2), af_pass_message)) acl_temp_details = TRUE;
1988 /* Make $address_data visible */
1989 deliver_address_data = addr2.p.address_data;
1992 /* We have a result from the relevant test. Handle defer overrides first. */
1994 if (rc == DEFER && (defer_ok ||
1995 (callout_defer_ok && *basic_errno == ERRNO_CALLOUTDEFER)))
1997 HDEBUG(D_acl) debug_printf("verify defer overridden by %s\n",
1998 defer_ok? "defer_ok" : "callout_defer_ok");
2002 /* If we've failed a sender, set up a recipient message, and point
2003 sender_verified_failed to the address item that actually failed. */
2005 if (rc != OK && verify_sender_address != NULL)
2009 *log_msgptr = *user_msgptr = US"Sender verify failed";
2011 else if (*basic_errno != ERRNO_CALLOUTDEFER)
2013 *log_msgptr = *user_msgptr = US"Could not complete sender verify";
2017 *log_msgptr = US"Could not complete sender verify callout";
2018 *user_msgptr = smtp_return_error_details? sender_vaddr->user_message :
2022 sender_verified_failed = sender_vaddr;
2025 /* Verifying an address messes up the values of $domain and $local_part,
2026 so reset them before returning if this is a RCPT ACL. */
2030 deliver_domain = addr->domain;
2031 deliver_localpart = addr->local_part;
2035 /* Syntax errors in the verify argument come here. */
2038 *log_msgptr = string_sprintf("expected \"sender[=address]\", \"recipient\", "
2039 "\"helo\", \"header_syntax\", \"header_sender\" or "
2040 "\"reverse_host_lookup\" at start of ACL condition "
2041 "\"verify %s\"", arg);
2044 /* Options supplied when not allowed come here */
2047 *log_msgptr = string_sprintf("unexpected '/' found in \"%s\" "
2048 "(this verify item has no options)", arg);
2051 /* Calls in the wrong ACL come here */
2054 *log_msgptr = string_sprintf("cannot check header contents in ACL for %s "
2055 "(only possible in ACL for DATA)", acl_wherenames[where]);
2062 /*************************************************
2063 * Check argument for control= modifier *
2064 *************************************************/
2066 /* Called from acl_check_condition() below
2069 arg the argument string for control=
2070 pptr set to point to the terminating character
2071 where which ACL we are in
2072 log_msgptr for error messages
2074 Returns: CONTROL_xxx value
2078 decode_control(uschar *arg, uschar **pptr, int where, uschar **log_msgptr)
2083 for (d = controls_list;
2084 d < controls_list + sizeof(controls_list)/sizeof(control_def);
2087 len = Ustrlen(d->name);
2088 if (Ustrncmp(d->name, arg, len) == 0) break;
2091 if (d >= controls_list + sizeof(controls_list)/sizeof(control_def) ||
2092 (arg[len] != 0 && (!d->has_option || arg[len] != '/')))
2094 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2095 return CONTROL_ERROR;
2104 /*************************************************
2105 * Handle rate limiting *
2106 *************************************************/
2108 /* Called by acl_check_condition() below to calculate the result
2109 of the ACL ratelimit condition.
2111 Note that the return value might be slightly unexpected: if the
2112 sender's rate is above the limit then the result is OK. This is
2113 similar to the dnslists condition, and is so that you can write
2114 ACL clauses like: defer ratelimit = 15 / 1h
2117 arg the option string for ratelimit=
2118 where ACL_WHERE_xxxx indicating which ACL this is
2119 log_msgptr for error messages
2121 Returns: OK - Sender's rate is above limit
2122 FAIL - Sender's rate is below limit
2123 DEFER - Problem opening ratelimit database
2124 ERROR - Syntax error in options.
2128 acl_ratelimit(uschar *arg, int where, uschar **log_msgptr)
2130 double limit, period;
2134 BOOL leaky = FALSE, strict = FALSE, noupdate = FALSE;
2135 BOOL per_byte = FALSE, per_cmd = FALSE, per_conn = FALSE, per_mail = FALSE;
2137 tree_node **anchor, *t;
2138 open_db dbblock, *dbm;
2139 dbdata_ratelimit *dbd;
2142 /* Parse the first two options and record their values in expansion
2143 variables. These variables allow the configuration to have informative
2144 error messages based on rate limits obtained from a table lookup. */
2146 /* First is the maximum number of messages per period and maximum burst
2147 size, which must be greater than or equal to zero. Zero is useful for
2148 rate measurement as opposed to rate limiting. */
2150 sender_rate_limit = string_nextinlist(&arg, &sep, NULL, 0);
2151 if (sender_rate_limit == NULL)
2155 limit = Ustrtod(sender_rate_limit, &ss);
2156 if (tolower(*ss) == 'k') { limit *= 1024.0; ss++; }
2157 else if (tolower(*ss) == 'm') { limit *= 1024.0*1024.0; ss++; }
2158 else if (tolower(*ss) == 'g') { limit *= 1024.0*1024.0*1024.0; ss++; }
2160 if (limit < 0.0 || *ss != 0)
2162 *log_msgptr = string_sprintf("syntax error in argument for "
2163 "\"ratelimit\" condition: \"%s\" is not a positive number",
2168 /* Second is the rate measurement period and exponential smoothing time
2169 constant. This must be strictly greater than zero, because zero leads to
2170 run-time division errors. */
2172 sender_rate_period = string_nextinlist(&arg, &sep, NULL, 0);
2173 if (sender_rate_period == NULL) period = -1.0;
2174 else period = readconf_readtime(sender_rate_period, 0, FALSE);
2177 *log_msgptr = string_sprintf("syntax error in argument for "
2178 "\"ratelimit\" condition: \"%s\" is not a time value",
2179 sender_rate_period);
2183 /* Parse the other options. Should we check if the per_* options are being
2184 used in ACLs where they don't make sense, e.g. per_mail in the connect ACL? */
2186 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
2189 if (strcmpic(ss, US"leaky") == 0) leaky = TRUE;
2190 else if (strcmpic(ss, US"strict") == 0) strict = TRUE;
2191 else if (strcmpic(ss, US"noupdate") == 0) noupdate = TRUE;
2192 else if (strcmpic(ss, US"per_byte") == 0) per_byte = TRUE;
2193 else if (strcmpic(ss, US"per_cmd") == 0) per_cmd = TRUE;
2194 else if (strcmpic(ss, US"per_rcpt") == 0) per_cmd = TRUE; /* alias */
2195 else if (strcmpic(ss, US"per_conn") == 0) per_conn = TRUE;
2196 else if (strcmpic(ss, US"per_mail") == 0) per_mail = TRUE;
2197 else key = string_sprintf("%s", ss);
2200 if (leaky + strict > 1 || per_byte + per_cmd + per_conn + per_mail > 1)
2202 *log_msgptr = US"conflicting options for \"ratelimit\" condition";
2206 /* Default option values */
2208 if (!strict) leaky = TRUE;
2209 if (!per_byte && !per_cmd && !per_conn) per_mail = TRUE;
2211 /* Create the lookup key. If there is no explicit key, use sender_host_address.
2212 If there is no sender_host_address (e.g. -bs or acl_not_smtp) then we simply
2213 omit it. The smoothing constant (sender_rate_period) and the per_xxx options
2214 are added to the key because they alter the meaning of the stored data. */
2217 key = (sender_host_address == NULL)? US"" : sender_host_address;
2219 key = string_sprintf("%s/%s/%s/%s",
2221 per_byte? US"per_byte" :
2222 per_cmd? US"per_cmd" :
2223 per_mail? US"per_mail" : US"per_conn",
2224 strict? US"strict" : US"leaky",
2227 HDEBUG(D_acl) debug_printf("ratelimit condition limit=%.0f period=%.0f key=%s\n",
2228 limit, period, key);
2230 /* See if we have already computed the rate by looking in the relevant tree.
2231 For per-connection rate limiting, store tree nodes and dbdata in the permanent
2232 pool so that they survive across resets. */
2235 old_pool = store_pool;
2239 anchor = &ratelimiters_conn;
2240 store_pool = POOL_PERM;
2242 else if (per_mail || per_byte)
2243 anchor = &ratelimiters_mail;
2245 anchor = &ratelimiters_cmd;
2247 if (anchor != NULL && (t = tree_search(*anchor, key)) != NULL)
2250 /* The following few lines duplicate some of the code below. */
2251 rc = (dbd->rate < limit)? FAIL : OK;
2252 store_pool = old_pool;
2253 sender_rate = string_sprintf("%.1f", dbd->rate);
2255 debug_printf("ratelimit found pre-computed rate %s\n", sender_rate);
2259 /* We aren't using a pre-computed rate, so get a previously recorded
2260 rate from the database, update it, and write it back when required. If there's
2261 no previous rate for this key, create one. */
2263 dbm = dbfn_open(US"ratelimit", O_RDWR, &dbblock, TRUE);
2266 store_pool = old_pool;
2268 HDEBUG(D_acl) debug_printf("ratelimit database not available\n");
2269 *log_msgptr = US"ratelimit database not available";
2272 dbd = dbfn_read(dbm, key);
2274 gettimeofday(&tv, NULL);
2278 HDEBUG(D_acl) debug_printf("ratelimit initializing new key's data\n");
2279 dbd = store_get(sizeof(dbdata_ratelimit));
2280 dbd->time_stamp = tv.tv_sec;
2281 dbd->time_usec = tv.tv_usec;
2286 /* The smoothed rate is computed using an exponentially weighted moving
2287 average adjusted for variable sampling intervals. The standard EWMA for
2288 a fixed sampling interval is: f'(t) = (1 - a) * f(t) + a * f'(t - 1)
2289 where f() is the measured value and f'() is the smoothed value.
2291 Old data decays out of the smoothed value exponentially, such that data n
2292 samples old is multiplied by a^n. The exponential decay time constant p
2293 is defined such that data p samples old is multiplied by 1/e, which means
2294 that a = exp(-1/p). We can maintain the same time constant for a variable
2295 sampling interval i by using a = exp(-i/p).
2297 The rate we are measuring is messages per period, suitable for directly
2298 comparing with the limit. The average rate between now and the previous
2299 message is period / interval, which we feed into the EWMA as the sample.
2301 It turns out that the number of messages required for the smoothed rate
2302 to reach the limit when they are sent in a burst is equal to the limit.
2303 This can be seen by analysing the value of the smoothed rate after N
2304 messages sent at even intervals. Let k = (1 - a) * p/i
2306 rate_1 = (1 - a) * p/i + a * rate_0
2308 rate_2 = k + a * rate_1
2309 = k + a * k + a^2 * rate_0
2310 rate_3 = k + a * k + a^2 * k + a^3 * rate_0
2311 rate_N = rate_0 * a^N + k * SUM(x=0..N-1)(a^x)
2312 = rate_0 * a^N + k * (1 - a^N) / (1 - a)
2313 = rate_0 * a^N + p/i * (1 - a^N)
2315 When N is large, a^N -> 0 so rate_N -> p/i as desired.
2317 rate_N = p/i + (rate_0 - p/i) * a^N
2318 a^N = (rate_N - p/i) / (rate_0 - p/i)
2319 N * -i/p = log((rate_N - p/i) / (rate_0 - p/i))
2320 N = p/i * log((rate_0 - p/i) / (rate_N - p/i))
2322 Numerical analysis of the above equation, setting the computed rate to
2323 increase from rate_0 = 0 to rate_N = limit, shows that for large sending
2324 rates, p/i, the number of messages N = limit. So limit serves as both the
2325 maximum rate measured in messages per period, and the maximum number of
2326 messages that can be sent in a fast burst. */
2328 double this_time = (double)tv.tv_sec
2329 + (double)tv.tv_usec / 1000000.0;
2330 double prev_time = (double)dbd->time_stamp
2331 + (double)dbd->time_usec / 1000000.0;
2333 /* We must avoid division by zero, and deal gracefully with the clock going
2334 backwards. If we blunder ahead when time is in reverse then the computed
2335 rate will be bogus. To be safe we clamp interval to a very small number. */
2337 double interval = this_time - prev_time <= 0.0 ? 1e-9
2338 : this_time - prev_time;
2340 double i_over_p = interval / period;
2341 double a = exp(-i_over_p);
2343 dbd->time_stamp = tv.tv_sec;
2344 dbd->time_usec = tv.tv_usec;
2346 /* If we are measuring the rate in bytes per period, multiply the
2347 measured rate by the message size. If we don't know the message size
2348 then it's safe to just use a value of zero and let the recorded rate
2349 decay as if nothing happened. */
2352 dbd->rate = (message_size < 0 ? 0.0 : (double)message_size)
2353 * (1 - a) / i_over_p + a * dbd->rate;
2354 else if (per_cmd && where == ACL_WHERE_NOTSMTP)
2355 dbd->rate = (double)recipients_count
2356 * (1 - a) / i_over_p + a * dbd->rate;
2358 dbd->rate = (1 - a) / i_over_p + a * dbd->rate;
2361 /* Clients sending at the limit are considered to be over the limit. This
2362 matters for edge cases such the first message sent by a client (which gets
2363 the initial rate of 0.0) when the rate limit is zero (i.e. the client should
2364 be completely blocked). */
2366 rc = (dbd->rate < limit)? FAIL : OK;
2368 /* Update the state if the rate is low or if we are being strict. If we
2369 are in leaky mode and the sender's rate is too high, we do not update
2370 the recorded rate in order to avoid an over-aggressive sender's retry
2371 rate preventing them from getting any email through. If noupdate is set,
2372 do not do any updates. */
2374 if ((rc == FAIL || !leaky) && !noupdate)
2376 dbfn_write(dbm, key, dbd, sizeof(dbdata_ratelimit));
2377 HDEBUG(D_acl) debug_printf("ratelimit db updated\n");
2381 HDEBUG(D_acl) debug_printf("ratelimit db not updated: %s\n",
2382 noupdate? "noupdate set" : "over the limit, but leaky");
2387 /* Store the result in the tree for future reference, if necessary. */
2389 if (anchor != NULL && !noupdate)
2391 t = store_get(sizeof(tree_node) + Ustrlen(key));
2393 Ustrcpy(t->name, key);
2394 (void)tree_insertnode(anchor, t);
2397 /* We create the formatted version of the sender's rate very late in
2398 order to ensure that it is done using the correct storage pool. */
2400 store_pool = old_pool;
2401 sender_rate = string_sprintf("%.1f", dbd->rate);
2404 debug_printf("ratelimit computed rate %s\n", sender_rate);
2411 /*************************************************
2412 * Handle conditions/modifiers on an ACL item *
2413 *************************************************/
2415 /* Called from acl_check() below.
2419 cb ACL condition block - if NULL, result is OK
2420 where where called from
2421 addr the address being checked for RCPT, or NULL
2422 level the nesting level
2423 epp pointer to pass back TRUE if "endpass" encountered
2424 (applies only to "accept" and "discard")
2425 user_msgptr user message pointer
2426 log_msgptr log message pointer
2427 basic_errno pointer to where to put verify error
2429 Returns: OK - all conditions are met
2430 DISCARD - an "acl" condition returned DISCARD - only allowed
2431 for "accept" or "discard" verbs
2432 FAIL - at least one condition fails
2433 FAIL_DROP - an "acl" condition returned FAIL_DROP
2434 DEFER - can't tell at the moment (typically, lookup defer,
2435 but can be temporary callout problem)
2436 ERROR - ERROR from nested ACL or expansion failure or other
2441 acl_check_condition(int verb, acl_condition_block *cb, int where,
2442 address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
2443 uschar **log_msgptr, int *basic_errno)
2445 uschar *user_message = NULL;
2446 uschar *log_message = NULL;
2449 #ifdef WITH_CONTENT_SCAN
2453 for (; cb != NULL; cb = cb->next)
2458 /* The message and log_message items set up messages to be used in
2459 case of rejection. They are expanded later. */
2461 if (cb->type == ACLC_MESSAGE)
2463 user_message = cb->arg;
2467 if (cb->type == ACLC_LOG_MESSAGE)
2469 log_message = cb->arg;
2473 /* The endpass "condition" just sets a flag to show it occurred. This is
2474 checked at compile time to be on an "accept" or "discard" item. */
2476 if (cb->type == ACLC_ENDPASS)
2482 /* For other conditions and modifiers, the argument is expanded now for some
2483 of them, but not for all, because expansion happens down in some lower level
2484 checking functions in some cases. */
2486 if (cond_expand_at_top[cb->type])
2488 arg = expand_string(cb->arg);
2491 if (expand_string_forcedfail) continue;
2492 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
2493 cb->arg, expand_string_message);
2494 return search_find_defer? DEFER : ERROR;
2499 /* Show condition, and expanded condition if it's different */
2504 debug_printf("check %s%s %n",
2505 (!cond_modifiers[cb->type] && cb->u.negated)? "!":"",
2506 conditions[cb->type], &lhswidth);
2508 if (cb->type == ACLC_SET)
2510 debug_printf("acl_%s ", cb->u.varname);
2511 lhswidth += 5 + Ustrlen(cb->u.varname);
2514 debug_printf("= %s\n", cb->arg);
2517 debug_printf("%.*s= %s\n", lhswidth,
2521 /* Check that this condition makes sense at this time */
2523 if ((cond_forbids[cb->type] & (1 << where)) != 0)
2525 *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
2526 cond_modifiers[cb->type]? "use" : "test",
2527 conditions[cb->type], acl_wherenames[where]);
2531 /* Run the appropriate test for each condition, or take the appropriate
2532 action for the remaining modifiers. */
2536 case ACLC_ADD_HEADER:
2540 /* A nested ACL that returns "discard" makes sense only for an "accept" or
2544 rc = acl_check_internal(where, addr, arg, level+1, user_msgptr, log_msgptr);
2545 if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
2547 *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
2548 "\"%s\" command (only allowed with \"accept\" or \"discard\")",
2554 case ACLC_AUTHENTICATED:
2555 rc = (sender_host_authenticated == NULL)? FAIL :
2556 match_isinlist(sender_host_authenticated, &arg, 0, NULL, NULL, MCL_STRING,
2560 #ifdef EXPERIMENTAL_BRIGHTMAIL
2561 case ACLC_BMI_OPTIN:
2563 int old_pool = store_pool;
2564 store_pool = POOL_PERM;
2565 bmi_current_optin = string_copy(arg);
2566 store_pool = old_pool;
2571 case ACLC_CONDITION:
2572 if (Ustrspn(arg, "0123456789") == Ustrlen(arg)) /* Digits, or empty */
2573 rc = (Uatoi(arg) == 0)? FAIL : OK;
2575 rc = (strcmpic(arg, US"no") == 0 ||
2576 strcmpic(arg, US"false") == 0)? FAIL :
2577 (strcmpic(arg, US"yes") == 0 ||
2578 strcmpic(arg, US"true") == 0)? OK : DEFER;
2580 *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
2583 case ACLC_CONTINUE: /* Always succeeds */
2587 control_type = decode_control(arg, &p, where, log_msgptr);
2589 /* Check if this control makes sense at this time */
2591 if ((control_forbids[control_type] & (1 << where)) != 0)
2593 *log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
2594 controls[control_type], acl_wherenames[where]);
2598 switch(control_type)
2600 case CONTROL_AUTH_UNADVERTISED:
2601 allow_auth_unadvertised = TRUE;
2604 #ifdef EXPERIMENTAL_BRIGHTMAIL
2605 case CONTROL_BMI_RUN:
2610 #ifdef EXPERIMENTAL_DOMAINKEYS
2611 case CONTROL_DK_VERIFY:
2619 case CONTROL_CASEFUL_LOCAL_PART:
2620 deliver_localpart = addr->cc_local_part;
2623 case CONTROL_CASELOWER_LOCAL_PART:
2624 deliver_localpart = addr->lc_local_part;
2627 case CONTROL_ENFORCE_SYNC:
2628 smtp_enforce_sync = TRUE;
2631 case CONTROL_NO_ENFORCE_SYNC:
2632 smtp_enforce_sync = FALSE;
2635 #ifdef WITH_CONTENT_SCAN
2636 case CONTROL_NO_MBOX_UNSPOOL:
2637 no_mbox_unspool = TRUE;
2641 case CONTROL_NO_MULTILINE:
2642 no_multiline_responses = TRUE;
2645 case CONTROL_NO_PIPELINING:
2646 pipelining_enable = FALSE;
2649 case CONTROL_NO_DELAY_FLUSH:
2650 disable_delay_flush = TRUE;
2653 case CONTROL_NO_CALLOUT_FLUSH:
2654 disable_callout_flush = TRUE;
2657 case CONTROL_FAKEDEFER:
2658 case CONTROL_FAKEREJECT:
2659 fake_response = (control_type == CONTROL_FAKEDEFER) ? DEFER : FAIL;
2663 while (*pp != 0) pp++;
2664 fake_response_text = expand_string(string_copyn(p+1, pp-p-1));
2669 /* Explicitly reset to default string */
2670 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).";
2674 case CONTROL_FREEZE:
2675 deliver_freeze = TRUE;
2676 deliver_frozen_at = time(NULL);
2677 freeze_tell = freeze_tell_config; /* Reset to configured value */
2678 if (Ustrncmp(p, "/no_tell", 8) == 0)
2685 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2690 case CONTROL_QUEUE_ONLY:
2691 queue_only_policy = TRUE;
2694 case CONTROL_SUBMISSION:
2695 originator_name = US"";
2696 submission_mode = TRUE;
2699 if (Ustrncmp(p, "/sender_retain", 14) == 0)
2702 active_local_sender_retain = TRUE;
2703 active_local_from_check = FALSE;
2705 else if (Ustrncmp(p, "/domain=", 8) == 0)
2708 while (*pp != 0 && *pp != '/') pp++;
2709 submission_domain = string_copyn(p+8, pp-p-8);
2712 /* The name= option must be last, because it swallows the rest of
2714 else if (Ustrncmp(p, "/name=", 6) == 0)
2717 while (*pp != 0) pp++;
2718 submission_name = string_copy(parse_fix_phrase(p+6, pp-p-6,
2719 big_buffer, big_buffer_size));
2726 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2731 case CONTROL_SUPPRESS_LOCAL_FIXUPS:
2732 suppress_local_fixups = TRUE;
2737 #ifdef WITH_CONTENT_SCAN
2739 rc = mime_decode(&arg);
2745 int delay = readconf_readtime(arg, 0, FALSE);
2748 *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
2749 "modifier: \"%s\" is not a time value", arg);
2754 HDEBUG(D_acl) debug_printf("delay modifier requests %d-second delay\n",
2759 debug_printf("delay skipped in -bh checking mode\n");
2762 /* It appears to be impossible to detect that a TCP/IP connection has
2763 gone away without reading from it. This means that we cannot shorten
2764 the delay below if the client goes away, because we cannot discover
2765 that the client has closed its end of the connection. (The connection
2766 is actually in a half-closed state, waiting for the server to close its
2767 end.) It would be nice to be able to detect this state, so that the
2768 Exim process is not held up unnecessarily. However, it seems that we
2769 can't. The poll() function does not do the right thing, and in any case
2770 it is not always available.
2772 NOTE 1: If ever this state of affairs changes, remember that we may be
2773 dealing with stdin/stdout here, in addition to TCP/IP connections.
2774 Also, delays may be specified for non-SMTP input, where smtp_out and
2775 smtp_in will be NULL. Whatever is done must work in all cases.
2777 NOTE 2: The added feature of flushing the output before a delay must
2778 apply only to SMTP input. Hence the test for smtp_out being non-NULL.
2783 if (smtp_out != NULL && !disable_delay_flush) mac_smtp_fflush();
2784 while (delay > 0) delay = sleep(delay);
2790 #ifdef WITH_OLD_DEMIME
2796 #ifdef EXPERIMENTAL_DOMAINKEYS
2797 case ACLC_DK_DOMAIN_SOURCE:
2798 if (dk_verify_block == NULL) { rc = FAIL; break; };
2799 /* check header source of domain against given string */
2800 switch (dk_verify_block->address_source) {
2801 case DK_EXIM_ADDRESS_FROM_FROM:
2802 rc = match_isinlist(US"from", &arg, 0, NULL,
2803 NULL, MCL_STRING, TRUE, NULL);
2805 case DK_EXIM_ADDRESS_FROM_SENDER:
2806 rc = match_isinlist(US"sender", &arg, 0, NULL,
2807 NULL, MCL_STRING, TRUE, NULL);
2809 case DK_EXIM_ADDRESS_NONE:
2810 rc = match_isinlist(US"none", &arg, 0, NULL,
2811 NULL, MCL_STRING, TRUE, NULL);
2816 case ACLC_DK_POLICY:
2817 if (dk_verify_block == NULL) { rc = FAIL; break; };
2818 /* check policy against given string, default FAIL */
2820 if (dk_verify_block->signsall)
2821 rc = match_isinlist(US"signsall", &arg, 0, NULL,
2822 NULL, MCL_STRING, TRUE, NULL);
2823 if (dk_verify_block->testing)
2824 rc = match_isinlist(US"testing", &arg, 0, NULL,
2825 NULL, MCL_STRING, TRUE, NULL);
2828 case ACLC_DK_SENDER_DOMAINS:
2829 if (dk_verify_block == NULL) { rc = FAIL; break; };
2830 if (dk_verify_block->domain != NULL)
2831 rc = match_isinlist(dk_verify_block->domain, &arg, 0, &domainlist_anchor,
2832 NULL, MCL_DOMAIN, TRUE, NULL);
2836 case ACLC_DK_SENDER_LOCAL_PARTS:
2837 if (dk_verify_block == NULL) { rc = FAIL; break; };
2838 if (dk_verify_block->local_part != NULL)
2839 rc = match_isinlist(dk_verify_block->local_part, &arg, 0, &localpartlist_anchor,
2840 NULL, MCL_LOCALPART, TRUE, NULL);
2844 case ACLC_DK_SENDERS:
2845 if (dk_verify_block == NULL) { rc = FAIL; break; };
2846 if (dk_verify_block->address != NULL)
2847 rc = match_address_list(dk_verify_block->address, TRUE, TRUE, &arg, NULL, -1, 0, NULL);
2851 case ACLC_DK_STATUS:
2852 if (dk_verify_block == NULL) { rc = FAIL; break; };
2853 if (dk_verify_block->result > 0) {
2854 switch(dk_verify_block->result) {
2855 case DK_EXIM_RESULT_BAD_FORMAT:
2856 rc = match_isinlist(US"bad format", &arg, 0, NULL,
2857 NULL, MCL_STRING, TRUE, NULL);
2859 case DK_EXIM_RESULT_NO_KEY:
2860 rc = match_isinlist(US"no key", &arg, 0, NULL,
2861 NULL, MCL_STRING, TRUE, NULL);
2863 case DK_EXIM_RESULT_NO_SIGNATURE:
2864 rc = match_isinlist(US"no signature", &arg, 0, NULL,
2865 NULL, MCL_STRING, TRUE, NULL);
2867 case DK_EXIM_RESULT_REVOKED:
2868 rc = match_isinlist(US"revoked", &arg, 0, NULL,
2869 NULL, MCL_STRING, TRUE, NULL);
2871 case DK_EXIM_RESULT_NON_PARTICIPANT:
2872 rc = match_isinlist(US"non-participant", &arg, 0, NULL,
2873 NULL, MCL_STRING, TRUE, NULL);
2875 case DK_EXIM_RESULT_GOOD:
2876 rc = match_isinlist(US"good", &arg, 0, NULL,
2877 NULL, MCL_STRING, TRUE, NULL);
2879 case DK_EXIM_RESULT_BAD:
2880 rc = match_isinlist(US"bad", &arg, 0, NULL,
2881 NULL, MCL_STRING, TRUE, NULL);
2889 rc = verify_check_dnsbl(&arg);
2893 rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
2894 addr->domain_cache, MCL_DOMAIN, TRUE, &deliver_domain_data);
2897 /* The value in tls_cipher is the full cipher name, for example,
2898 TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
2899 cipher names such as DES-CBC3-SHA. But program defensively. We don't know
2900 what may in practice come out of the SSL library - which at the time of
2901 writing is poorly documented. */
2903 case ACLC_ENCRYPTED:
2904 if (tls_cipher == NULL) rc = FAIL; else
2906 uschar *endcipher = NULL;
2907 uschar *cipher = Ustrchr(tls_cipher, ':');
2908 if (cipher == NULL) cipher = tls_cipher; else
2910 endcipher = Ustrchr(++cipher, ':');
2911 if (endcipher != NULL) *endcipher = 0;
2913 rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
2914 if (endcipher != NULL) *endcipher = ':';
2918 /* Use verify_check_this_host() instead of verify_check_host() so that
2919 we can pass over &host_data to catch any looked up data. Once it has been
2920 set, it retains its value so that it's still there if another ACL verb
2921 comes through here and uses the cache. However, we must put it into
2922 permanent store in case it is also expected to be used in a subsequent
2923 message in the same SMTP connection. */
2926 rc = verify_check_this_host(&arg, sender_host_cache, NULL,
2927 (sender_host_address == NULL)? US"" : sender_host_address, &host_data);
2928 if (host_data != NULL) host_data = string_copy_malloc(host_data);
2931 case ACLC_LOCAL_PARTS:
2932 rc = match_isinlist(addr->cc_local_part, &arg, 0,
2933 &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
2934 &deliver_localpart_data);
2937 case ACLC_LOG_REJECT_TARGET:
2943 while ((ss = string_nextinlist(&s, &sep, big_buffer, big_buffer_size))
2946 if (Ustrcmp(ss, "main") == 0) logbits |= LOG_MAIN;
2947 else if (Ustrcmp(ss, "panic") == 0) logbits |= LOG_PANIC;
2948 else if (Ustrcmp(ss, "reject") == 0) logbits |= LOG_REJECT;
2951 logbits |= LOG_MAIN|LOG_REJECT;
2952 log_write(0, LOG_MAIN|LOG_PANIC, "unknown log name \"%s\" in "
2953 "\"log_reject_target\" in %s ACL", ss, acl_wherenames[where]);
2956 log_reject_target = logbits;
2969 if (Ustrncmp(s, "main", 4) == 0)
2970 { logbits |= LOG_MAIN; s += 4; }
2971 else if (Ustrncmp(s, "panic", 5) == 0)
2972 { logbits |= LOG_PANIC; s += 5; }
2973 else if (Ustrncmp(s, "reject", 6) == 0)
2974 { logbits |= LOG_REJECT; s += 6; }
2977 logbits = LOG_MAIN|LOG_PANIC;
2978 s = string_sprintf(":unknown log name in \"%s\" in "
2979 "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
2985 while (isspace(*s)) s++;
2988 if (logbits == 0) logbits = LOG_MAIN;
2989 log_write(0, logbits, "%s", string_printing(s));
2993 #ifdef WITH_CONTENT_SCAN
2996 /* Separate the regular expression and any optional parameters. */
2997 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
2998 /* Run the malware backend. */
3000 /* Modify return code based upon the existance of options. */
3001 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
3003 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3005 /* FAIL so that the message is passed to the next ACL */
3012 case ACLC_MIME_REGEX:
3013 rc = mime_regex(&arg);
3017 case ACLC_RATELIMIT:
3018 rc = acl_ratelimit(arg, where, log_msgptr);
3021 case ACLC_RECIPIENTS:
3022 rc = match_address_list(addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
3026 #ifdef WITH_CONTENT_SCAN
3032 case ACLC_SENDER_DOMAINS:
3035 sdomain = Ustrrchr(sender_address, '@');
3036 sdomain = (sdomain == NULL)? US"" : sdomain + 1;
3037 rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
3038 sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
3043 rc = match_address_list(sender_address, TRUE, TRUE, &arg,
3044 sender_address_cache, -1, 0, &sender_data);
3047 /* Connection variables must persist forever */
3051 int old_pool = store_pool;
3052 if (cb->u.varname[0] == 'c') store_pool = POOL_PERM;
3053 acl_var_create(cb->u.varname)->data.ptr = string_copy(arg);
3054 store_pool = old_pool;
3058 #ifdef WITH_CONTENT_SCAN
3061 /* Seperate the regular expression and any optional parameters. */
3062 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
3063 /* Run the spam backend. */
3065 /* Modify return code based upon the existance of options. */
3066 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
3068 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3070 /* FAIL so that the message is passed to the next ACL */
3078 #ifdef EXPERIMENTAL_SPF
3080 rc = spf_process(&arg, sender_address);
3084 /* If the verb is WARN, discard any user message from verification, because
3085 such messages are SMTP responses, not header additions. The latter come
3086 only from explicit "message" modifiers. However, put the user message into
3087 $acl_verify_message so it can be used in subsequent conditions or modifiers
3088 (until something changes it). */
3091 rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
3092 acl_verify_message = *user_msgptr;
3093 if (verb == ACL_WARN) *user_msgptr = NULL;
3097 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
3098 "condition %d", cb->type);
3102 /* If a condition was negated, invert OK/FAIL. */
3104 if (!cond_modifiers[cb->type] && cb->u.negated)
3106 if (rc == OK) rc = FAIL;
3107 else if (rc == FAIL || rc == FAIL_DROP) rc = OK;
3110 if (rc != OK) break; /* Conditions loop */
3114 /* If the result is the one for which "message" and/or "log_message" are used,
3115 handle the values of these modifiers. If there isn't a log message set, we make
3116 it the same as the user message.
3118 "message" is a user message that will be included in an SMTP response. Unless
3119 it is empty, it overrides any previously set user message.
3121 "log_message" is a non-user message, and it adds to any existing non-user
3122 message that is already set.
3124 Most verbs have but a single return for which the messages are relevant, but
3125 for "discard", it's useful to have the log message both when it succeeds and
3126 when it fails. For "accept", the message is used in the OK case if there is no
3127 "endpass", but (for backwards compatibility) in the FAIL case if "endpass" is
3130 if (*epp && rc == OK) user_message = NULL;
3132 if (((1<<rc) & msgcond[verb]) != 0)
3135 uschar *old_user_msgptr = *user_msgptr;
3136 uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;
3138 /* If the verb is "warn", messages generated by conditions (verification or
3139 nested ACLs) are always discarded. This also happens for acceptance verbs
3140 when they actually do accept. Only messages specified at this level are used.
3141 However, the value of an existing message is available in $acl_verify_message
3142 during expansions. */
3144 if (verb == ACL_WARN ||
3145 (rc == OK && (verb == ACL_ACCEPT || verb == ACL_DISCARD)))
3146 *log_msgptr = *user_msgptr = NULL;
3148 if (user_message != NULL)
3150 acl_verify_message = old_user_msgptr;
3151 expmessage = expand_string(user_message);
3152 if (expmessage == NULL)
3154 if (!expand_string_forcedfail)
3155 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
3156 user_message, expand_string_message);
3158 else if (expmessage[0] != 0) *user_msgptr = expmessage;
3161 if (log_message != NULL)
3163 acl_verify_message = old_log_msgptr;
3164 expmessage = expand_string(log_message);
3165 if (expmessage == NULL)
3167 if (!expand_string_forcedfail)
3168 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
3169 log_message, expand_string_message);
3171 else if (expmessage[0] != 0)
3173 *log_msgptr = (*log_msgptr == NULL)? expmessage :
3174 string_sprintf("%s: %s", expmessage, *log_msgptr);
3178 /* If no log message, default it to the user message */
3180 if (*log_msgptr == NULL) *log_msgptr = *user_msgptr;
3183 acl_verify_message = NULL;
3191 /*************************************************
3192 * Get line from a literal ACL *
3193 *************************************************/
3195 /* This function is passed to acl_read() in order to extract individual lines
3196 of a literal ACL, which we access via static pointers. We can destroy the
3197 contents because this is called only once (the compiled ACL is remembered).
3199 This code is intended to treat the data in the same way as lines in the main
3200 Exim configuration file. That is:
3202 . Leading spaces are ignored.
3204 . A \ at the end of a line is a continuation - trailing spaces after the \
3205 are permitted (this is because I don't believe in making invisible things
3206 significant). Leading spaces on the continued part of a line are ignored.
3208 . Physical lines starting (significantly) with # are totally ignored, and
3209 may appear within a sequence of backslash-continued lines.
3211 . Blank lines are ignored, but will end a sequence of continuations.
3214 Returns: a pointer to the next line
3218 static uschar *acl_text; /* Current pointer in the text */
3219 static uschar *acl_text_end; /* Points one past the terminating '0' */
3227 /* This loop handles leading blank lines and comments. */
3231 while (isspace(*acl_text)) acl_text++; /* Leading spaces/empty lines */
3232 if (*acl_text == 0) return NULL; /* No more data */
3233 yield = acl_text; /* Potential data line */
3235 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
3237 /* If we hit the end before a newline, we have the whole logical line. If
3238 it's a comment, there's no more data to be given. Otherwise, yield it. */
3240 if (*acl_text == 0) return (*yield == '#')? NULL : yield;
3242 /* After reaching a newline, end this loop if the physical line does not
3243 start with '#'. If it does, it's a comment, and the loop continues. */
3245 if (*yield != '#') break;
3248 /* This loop handles continuations. We know we have some real data, ending in
3249 newline. See if there is a continuation marker at the end (ignoring trailing
3250 white space). We know that *yield is not white space, so no need to test for
3251 cont > yield in the backwards scanning loop. */
3256 for (cont = acl_text - 1; isspace(*cont); cont--);
3258 /* If no continuation follows, we are done. Mark the end of the line and
3267 /* We have encountered a continuation. Skip over whitespace at the start of
3268 the next line, and indeed the whole of the next line or lines if they are
3273 while (*(++acl_text) == ' ' || *acl_text == '\t');
3274 if (*acl_text != '#') break;
3275 while (*(++acl_text) != 0 && *acl_text != '\n');
3278 /* We have the start of a continuation line. Move all the rest of the data
3279 to join onto the previous line, and then find its end. If the end is not a
3280 newline, we are done. Otherwise loop to look for another continuation. */
3282 memmove(cont, acl_text, acl_text_end - acl_text);
3283 acl_text_end -= acl_text - cont;
3285 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
3286 if (*acl_text == 0) return yield;
3289 /* Control does not reach here */
3296 /*************************************************
3297 * Check access using an ACL *
3298 *************************************************/
3300 /* This function is called from address_check. It may recurse via
3301 acl_check_condition() - hence the use of a level to stop looping. The ACL is
3302 passed as a string which is expanded. A forced failure implies no access check
3303 is required. If the result is a single word, it is taken as the name of an ACL
3304 which is sought in the global ACL tree. Otherwise, it is taken as literal ACL
3305 text, complete with newlines, and parsed as such. In both cases, the ACL check
3306 is then run. This function uses an auxiliary function for acl_read() to call
3307 for reading individual lines of a literal ACL. This is acl_getline(), which
3308 appears immediately above.
3311 where where called from
3312 addr address item when called from RCPT; otherwise NULL
3313 s the input string; NULL is the same as an empty ACL => DENY
3314 level the nesting level
3315 user_msgptr where to put a user error (for SMTP response)
3316 log_msgptr where to put a logging message (not for SMTP response)
3318 Returns: OK access is granted
3319 DISCARD access is apparently granted...
3320 FAIL access is denied
3321 FAIL_DROP access is denied; drop the connection
3322 DEFER can't tell at the moment
3327 acl_check_internal(int where, address_item *addr, uschar *s, int level,
3328 uschar **user_msgptr, uschar **log_msgptr)
3331 acl_block *acl = NULL;
3332 uschar *acl_name = US"inline ACL";
3335 /* Catch configuration loops */
3339 *log_msgptr = US"ACL nested too deep: possible loop";
3345 HDEBUG(D_acl) debug_printf("ACL is NULL: implicit DENY\n");
3349 /* At top level, we expand the incoming string. At lower levels, it has already
3350 been expanded as part of condition processing. */
3354 ss = expand_string(s);
3357 if (expand_string_forcedfail) return OK;
3358 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s", s,
3359 expand_string_message);
3365 while (isspace(*ss))ss++;
3367 /* If we can't find a named ACL, the default is to parse it as an inline one.
3368 (Unless it begins with a slash; non-existent files give rise to an error.) */
3372 /* Handle the case of a string that does not contain any spaces. Look for a
3373 named ACL among those read from the configuration, or a previously read file.
3374 It is possible that the pointer to the ACL is NULL if the configuration
3375 contains a name with no data. If not found, and the text begins with '/',
3376 read an ACL from a file, and save it so it can be re-used. */
3378 if (Ustrchr(ss, ' ') == NULL)
3380 tree_node *t = tree_search(acl_anchor, ss);
3383 acl = (acl_block *)(t->data.ptr);
3386 HDEBUG(D_acl) debug_printf("ACL \"%s\" is empty: implicit DENY\n", ss);
3389 acl_name = string_sprintf("ACL \"%s\"", ss);
3390 HDEBUG(D_acl) debug_printf("using ACL \"%s\"\n", ss);
3393 else if (*ss == '/')
3395 struct stat statbuf;
3396 fd = Uopen(ss, O_RDONLY, 0);
3399 *log_msgptr = string_sprintf("failed to open ACL file \"%s\": %s", ss,
3404 if (fstat(fd, &statbuf) != 0)
3406 *log_msgptr = string_sprintf("failed to fstat ACL file \"%s\": %s", ss,
3411 acl_text = store_get(statbuf.st_size + 1);
3412 acl_text_end = acl_text + statbuf.st_size + 1;
3414 if (read(fd, acl_text, statbuf.st_size) != statbuf.st_size)
3416 *log_msgptr = string_sprintf("failed to read ACL file \"%s\": %s",
3417 ss, strerror(errno));
3420 acl_text[statbuf.st_size] = 0;
3423 acl_name = string_sprintf("ACL \"%s\"", ss);
3424 HDEBUG(D_acl) debug_printf("read ACL from file %s\n", ss);
3428 /* Parse an ACL that is still in text form. If it came from a file, remember it
3429 in the ACL tree, having read it into the POOL_PERM store pool so that it
3430 persists between multiple messages. */
3434 int old_pool = store_pool;
3435 if (fd >= 0) store_pool = POOL_PERM;
3436 acl = acl_read(acl_getline, log_msgptr);
3437 store_pool = old_pool;
3438 if (acl == NULL && *log_msgptr != NULL) return ERROR;
3441 tree_node *t = store_get_perm(sizeof(tree_node) + Ustrlen(ss));
3442 Ustrcpy(t->name, ss);
3444 (void)tree_insertnode(&acl_anchor, t);
3448 /* Now we have an ACL to use. It's possible it may be NULL. */
3453 int basic_errno = 0;
3454 BOOL endpass_seen = FALSE;
3456 *log_msgptr = *user_msgptr = NULL;
3457 acl_temp_details = FALSE;
3459 if ((where == ACL_WHERE_QUIT || where == ACL_WHERE_NOTQUIT) &&
3460 acl->verb != ACL_ACCEPT &&
3461 acl->verb != ACL_WARN)
3463 *log_msgptr = string_sprintf("\"%s\" is not allowed in a QUIT or not-QUIT ACL",
3468 HDEBUG(D_acl) debug_printf("processing \"%s\"\n", verbs[acl->verb]);
3470 /* Clear out any search error message from a previous check before testing
3473 search_error_message = NULL;
3474 cond = acl_check_condition(acl->verb, acl->condition, where, addr, level,
3475 &endpass_seen, user_msgptr, log_msgptr, &basic_errno);
3477 /* Handle special returns: DEFER causes a return except on a WARN verb;
3478 ERROR always causes a return. */
3483 HDEBUG(D_acl) debug_printf("%s: condition test deferred\n", verbs[acl->verb]);
3484 if (basic_errno != ERRNO_CALLOUTDEFER)
3486 if (search_error_message != NULL && *search_error_message != 0)
3487 *log_msgptr = search_error_message;
3488 if (smtp_return_error_details) acl_temp_details = TRUE;
3492 acl_temp_details = TRUE;
3494 if (acl->verb != ACL_WARN) return DEFER;
3497 default: /* Paranoia */
3499 HDEBUG(D_acl) debug_printf("%s: condition test error\n", verbs[acl->verb]);
3503 HDEBUG(D_acl) debug_printf("%s: condition test succeeded\n",
3508 HDEBUG(D_acl) debug_printf("%s: condition test failed\n", verbs[acl->verb]);
3511 /* DISCARD and DROP can happen only from a nested ACL condition, and
3512 DISCARD can happen only for an "accept" or "discard" verb. */
3515 HDEBUG(D_acl) debug_printf("%s: condition test yielded \"discard\"\n",
3520 HDEBUG(D_acl) debug_printf("%s: condition test yielded \"drop\"\n",
3525 /* At this point, cond for most verbs is either OK or FAIL or (as a result of
3526 a nested ACL condition) FAIL_DROP. However, for WARN, cond may be DEFER, and
3527 for ACCEPT and DISCARD, it may be DISCARD after a nested ACL call. */
3532 if (cond == OK || cond == DISCARD) return cond;
3535 HDEBUG(D_acl) debug_printf("accept: endpass encountered - denying access\n");
3543 acl_temp_details = TRUE;
3549 if (cond == OK) return FAIL;
3553 if (cond == OK || cond == DISCARD) return DISCARD;
3556 HDEBUG(D_acl) debug_printf("discard: endpass encountered - denying access\n");
3562 if (cond == OK) return FAIL_DROP;
3566 if (cond != OK) return cond;
3571 acl_warn(where, *user_msgptr, *log_msgptr);
3572 else if (cond == DEFER && (log_extra_selector & LX_acl_warn_skipped) != 0)
3573 log_write(0, LOG_MAIN, "%s Warning: ACL \"warn\" statement skipped: "
3574 "condition test deferred%s%s", host_and_ident(TRUE),
3575 (*log_msgptr == NULL)? US"" : US": ",
3576 (*log_msgptr == NULL)? US"" : *log_msgptr);
3577 *log_msgptr = *user_msgptr = NULL; /* In case implicit DENY follows */
3581 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown verb %d",
3586 /* Pass to the next ACL item */
3591 /* We have reached the end of the ACL. This is an implicit DENY. */
3593 HDEBUG(D_acl) debug_printf("end of %s: implicit DENY\n", acl_name);
3598 /*************************************************
3599 * Check access using an ACL *
3600 *************************************************/
3602 /* This is the external interface for ACL checks. It sets up an address and the
3603 expansions for $domain and $local_part when called after RCPT, then calls
3604 acl_check_internal() to do the actual work.
3607 where ACL_WHERE_xxxx indicating where called from
3608 recipient RCPT address for RCPT check, else NULL
3609 s the input string; NULL is the same as an empty ACL => DENY
3610 user_msgptr where to put a user error (for SMTP response)
3611 log_msgptr where to put a logging message (not for SMTP response)
3613 Returns: OK access is granted by an ACCEPT verb
3614 DISCARD access is granted by a DISCARD verb
3615 FAIL access is denied
3616 FAIL_DROP access is denied; drop the connection
3617 DEFER can't tell at the moment
3622 acl_check(int where, uschar *recipient, uschar *s, uschar **user_msgptr,
3623 uschar **log_msgptr)
3627 address_item *addr = NULL;
3629 *user_msgptr = *log_msgptr = NULL;
3630 sender_verified_failed = NULL;
3631 ratelimiters_cmd = NULL;
3632 log_reject_target = LOG_MAIN|LOG_REJECT;
3634 if (where == ACL_WHERE_RCPT)
3636 adb = address_defaults;
3638 addr->address = recipient;
3639 if (deliver_split_address(addr) == DEFER)
3641 *log_msgptr = US"defer in percent_hack_domains check";
3644 deliver_domain = addr->domain;
3645 deliver_localpart = addr->local_part;
3648 rc = acl_check_internal(where, addr, s, 0, user_msgptr, log_msgptr);
3650 deliver_domain = deliver_localpart = deliver_address_data =
3651 sender_address_data = NULL;
3653 /* A DISCARD response is permitted only for message ACLs, excluding the PREDATA
3654 ACL, which is really in the middle of an SMTP command. */
3658 if (where > ACL_WHERE_NOTSMTP || where == ACL_WHERE_PREDATA)
3660 log_write(0, LOG_MAIN|LOG_PANIC, "\"discard\" verb not allowed in %s "
3661 "ACL", acl_wherenames[where]);
3667 /* A DROP response is not permitted from MAILAUTH */
3669 if (rc == FAIL_DROP && where == ACL_WHERE_MAILAUTH)
3671 log_write(0, LOG_MAIN|LOG_PANIC, "\"drop\" verb not allowed in %s "
3672 "ACL", acl_wherenames[where]);
3676 /* Before giving a response, take a look at the length of any user message, and
3677 split it up into multiple lines if possible. */
3679 *user_msgptr = string_split_message(*user_msgptr);
3680 if (fake_response != OK)
3681 fake_response_text = string_split_message(fake_response_text);
3688 /*************************************************
3689 * Create ACL variable *
3690 *************************************************/
3692 /* Create an ACL variable or reuse an existing one. ACL variables are in a
3693 binary tree (see tree.c) with acl_var_c and acl_var_m as root nodes.
3696 name pointer to the variable's name, starting with c or m
3698 Returns the pointer to variable's tree node
3702 acl_var_create(uschar *name)
3704 tree_node *node, **root;
3705 root = (name[0] == 'c')? &acl_var_c : &acl_var_m;
3706 node = tree_search(*root, name);
3709 node = store_get(sizeof(tree_node) + Ustrlen(name));
3710 Ustrcpy(node->name, name);
3711 (void)tree_insertnode(root, node);
3713 node->data.ptr = NULL;
3719 /*************************************************
3720 * Write an ACL variable in spool format *
3721 *************************************************/
3723 /* This function is used as a callback for tree_walk when writing variables to
3724 the spool file. To retain spool file compatibility, what is written is -aclc or
3725 -aclm followed by the rest of the name and the data length, space separated,
3726 then the value itself, starting on a new line, and terminated by an additional
3727 newline. When we had only numbered ACL variables, the first line might look
3728 like this: "-aclc 5 20". Now it might be "-aclc foo 20" for the variable called
3732 name of the variable
3733 value of the variable
3734 ctx FILE pointer (as a void pointer)
3740 acl_var_write(uschar *name, uschar *value, void *ctx)
3742 FILE *f = (FILE *)ctx;
3743 fprintf(f, "-acl%c %s %d\n%s\n", name[0], name+1, Ustrlen(value), value);