1 /* $Cambridge: exim/src/src/acl.c,v 1.80 2007/09/28 12:21:57 tom 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
177 #ifdef EXPERIMENTAL_DKIM
181 CONTROL_CASEFUL_LOCAL_PART,
182 CONTROL_CASELOWER_LOCAL_PART,
183 CONTROL_ENFORCE_SYNC,
184 CONTROL_NO_ENFORCE_SYNC,
188 CONTROL_SUPPRESS_LOCAL_FIXUPS,
189 #ifdef WITH_CONTENT_SCAN
190 CONTROL_NO_MBOX_UNSPOOL,
194 CONTROL_NO_MULTILINE,
195 CONTROL_NO_PIPELINING,
196 CONTROL_NO_DELAY_FLUSH,
197 CONTROL_NO_CALLOUT_FLUSH
200 /* ACL control names; keep in step with the table above! This list is used for
201 turning ids into names. The actual list of recognized names is in the variable
202 control_def controls_list[] below. The fact that there are two lists is a mess
203 and should be tidied up. */
205 static uschar *controls[] = {
206 US"allow_auth_unadvertised",
207 #ifdef EXPERIMENTAL_BRIGHTMAIL
210 #ifdef EXPERIMENTAL_DOMAINKEYS
213 #ifdef EXPERIMENTAL_DKIM
217 US"caseful_local_part",
218 US"caselower_local_part",
224 US"suppress_local_fixups",
225 #ifdef WITH_CONTENT_SCAN
230 US"no_multiline_responses",
236 /* Flags to indicate for which conditions/modifiers a string expansion is done
237 at the outer level. In the other cases, expansion already occurs in the
238 checking functions. */
240 static uschar cond_expand_at_top[] = {
242 TRUE, /* add_header */
243 FALSE, /* authenticated */
244 #ifdef EXPERIMENTAL_BRIGHTMAIL
245 TRUE, /* bmi_optin */
247 TRUE, /* condition */
250 #ifdef WITH_CONTENT_SCAN
254 #ifdef WITH_OLD_DEMIME
257 #ifdef EXPERIMENTAL_DOMAINKEYS
258 TRUE, /* dk_domain_source */
259 TRUE, /* dk_policy */
260 TRUE, /* dk_sender_domains */
261 TRUE, /* dk_sender_local_parts */
262 TRUE, /* dk_senders */
263 TRUE, /* dk_status */
267 FALSE, /* encrypted */
270 FALSE, /* local_parts */
271 TRUE, /* log_message */
272 TRUE, /* log_reject_target */
274 #ifdef WITH_CONTENT_SCAN
278 #ifdef WITH_CONTENT_SCAN
279 TRUE, /* mime_regex */
281 TRUE, /* ratelimit */
282 FALSE, /* recipients */
283 #ifdef WITH_CONTENT_SCAN
286 FALSE, /* sender_domains */
289 #ifdef WITH_CONTENT_SCAN
292 #ifdef EXPERIMENTAL_SPF
298 /* Flags to identify the modifiers */
300 static uschar cond_modifiers[] = {
302 TRUE, /* add_header */
303 FALSE, /* authenticated */
304 #ifdef EXPERIMENTAL_BRIGHTMAIL
305 TRUE, /* bmi_optin */
307 FALSE, /* condition */
310 #ifdef WITH_CONTENT_SCAN
314 #ifdef WITH_OLD_DEMIME
317 #ifdef EXPERIMENTAL_DOMAINKEYS
318 FALSE, /* dk_domain_source */
319 FALSE, /* dk_policy */
320 FALSE, /* dk_sender_domains */
321 FALSE, /* dk_sender_local_parts */
322 FALSE, /* dk_senders */
323 FALSE, /* dk_status */
325 FALSE, /* dnslists */
327 FALSE, /* encrypted */
330 FALSE, /* local_parts */
331 TRUE, /* log_message */
332 TRUE, /* log_reject_target */
334 #ifdef WITH_CONTENT_SCAN
338 #ifdef WITH_CONTENT_SCAN
339 FALSE, /* mime_regex */
341 FALSE, /* ratelimit */
342 FALSE, /* recipients */
343 #ifdef WITH_CONTENT_SCAN
346 FALSE, /* sender_domains */
349 #ifdef WITH_CONTENT_SCAN
352 #ifdef EXPERIMENTAL_SPF
358 /* Bit map vector of which conditions and modifiers are not allowed at certain
359 times. For each condition and modifier, there's a bitmap of dis-allowed times.
360 For some, it is easier to specify the negation of a small number of allowed
363 static unsigned int cond_forbids[] = {
367 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* add_header */
368 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
369 (1<<ACL_WHERE_MIME)|(1<<ACL_WHERE_NOTSMTP)|
370 (1<<ACL_WHERE_NOTSMTP_START)),
372 (1<<ACL_WHERE_NOTSMTP)| /* authenticated */
373 (1<<ACL_WHERE_NOTSMTP_START)|
374 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO),
376 #ifdef EXPERIMENTAL_BRIGHTMAIL
377 (1<<ACL_WHERE_AUTH)| /* bmi_optin */
378 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
379 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_MIME)|
380 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
381 (1<<ACL_WHERE_MAILAUTH)|
382 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
383 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_PREDATA)|
384 (1<<ACL_WHERE_NOTSMTP_START),
391 /* Certain types of control are always allowed, so we let it through
392 always and check in the control processing itself. */
396 #ifdef WITH_CONTENT_SCAN
398 ~(1<<ACL_WHERE_MIME), /* decode */
401 (1<<ACL_WHERE_NOTQUIT), /* delay */
403 #ifdef WITH_OLD_DEMIME
405 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* demime */
408 #ifdef EXPERIMENTAL_DOMAINKEYS
409 (1<<ACL_WHERE_AUTH)| /* dk_domain_source */
410 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
411 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
412 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
413 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
414 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
415 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
417 (1<<ACL_WHERE_AUTH)| /* dk_policy */
418 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
419 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
420 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
421 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
422 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
423 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
425 (1<<ACL_WHERE_AUTH)| /* dk_sender_domains */
426 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
427 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
428 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
429 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
430 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
431 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
433 (1<<ACL_WHERE_AUTH)| /* dk_sender_local_parts */
434 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
435 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
436 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
437 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
438 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
439 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
441 (1<<ACL_WHERE_AUTH)| /* dk_senders */
442 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
443 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
444 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
445 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
446 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
447 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
449 (1<<ACL_WHERE_AUTH)| /* dk_status */
450 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
451 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
452 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
453 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
454 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
455 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
458 (1<<ACL_WHERE_NOTSMTP)| /* dnslists */
459 (1<<ACL_WHERE_NOTSMTP_START),
462 ~(1<<ACL_WHERE_RCPT), /* domains */
464 (1<<ACL_WHERE_NOTSMTP)| /* encrypted */
465 (1<<ACL_WHERE_CONNECT)|
466 (1<<ACL_WHERE_NOTSMTP_START)|
471 (1<<ACL_WHERE_NOTSMTP)| /* hosts */
472 (1<<ACL_WHERE_NOTSMTP_START),
475 ~(1<<ACL_WHERE_RCPT), /* local_parts */
479 0, /* log_reject_target */
483 #ifdef WITH_CONTENT_SCAN
485 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* malware */
490 #ifdef WITH_CONTENT_SCAN
492 ~(1<<ACL_WHERE_MIME), /* mime_regex */
498 ~(1<<ACL_WHERE_RCPT), /* recipients */
500 #ifdef WITH_CONTENT_SCAN
502 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* regex */
503 (1<<ACL_WHERE_MIME)),
506 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* sender_domains */
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),
512 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* senders */
514 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
515 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
516 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
520 #ifdef WITH_CONTENT_SCAN
522 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* spam */
525 #ifdef EXPERIMENTAL_SPF
526 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* spf */
528 (1<<ACL_WHERE_MAILAUTH)|
529 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
530 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY)|
531 (1<<ACL_WHERE_NOTSMTP)|
532 (1<<ACL_WHERE_NOTSMTP_START),
535 /* Certain types of verify are always allowed, so we let it through
536 always and check in the verify function itself */
542 /* Bit map vector of which controls are not allowed at certain times. For
543 each control, there's a bitmap of dis-allowed times. For some, it is easier to
544 specify the negation of a small number of allowed times. */
546 static unsigned int control_forbids[] = {
548 ~((1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)), /* allow_auth_unadvertised */
550 #ifdef EXPERIMENTAL_BRIGHTMAIL
554 #ifdef EXPERIMENTAL_DOMAINKEYS
555 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* dk_verify */
556 (1<<ACL_WHERE_NOTSMTP_START),
559 #ifdef EXPERIMENTAL_DKIM
560 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* dkim_verify */
561 (1<<ACL_WHERE_NOTSMTP_START),
567 ~(1<<ACL_WHERE_RCPT), /* caseful_local_part */
570 ~(1<<ACL_WHERE_RCPT), /* caselower_local_part */
572 (1<<ACL_WHERE_NOTSMTP)| /* enforce_sync */
573 (1<<ACL_WHERE_NOTSMTP_START),
575 (1<<ACL_WHERE_NOTSMTP)| /* no_enforce_sync */
576 (1<<ACL_WHERE_NOTSMTP_START),
579 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* freeze */
580 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
581 (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_MIME)),
584 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* queue_only */
585 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
586 (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_MIME)),
589 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* submission */
590 (1<<ACL_WHERE_PREDATA)),
593 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* suppress_local_fixups */
594 (1<<ACL_WHERE_PREDATA)|
595 (1<<ACL_WHERE_NOTSMTP_START)),
597 #ifdef WITH_CONTENT_SCAN
599 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* no_mbox_unspool */
600 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
601 (1<<ACL_WHERE_MIME)),
605 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* fakedefer */
606 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
607 (1<<ACL_WHERE_MIME)),
610 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* fakereject */
611 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
612 (1<<ACL_WHERE_MIME)),
614 (1<<ACL_WHERE_NOTSMTP)| /* no_multiline */
615 (1<<ACL_WHERE_NOTSMTP_START),
617 (1<<ACL_WHERE_NOTSMTP)| /* no_pipelining */
618 (1<<ACL_WHERE_NOTSMTP_START),
620 (1<<ACL_WHERE_NOTSMTP)| /* no_delay_flush */
621 (1<<ACL_WHERE_NOTSMTP_START),
623 (1<<ACL_WHERE_NOTSMTP)| /* no_callout_flush */
624 (1<<ACL_WHERE_NOTSMTP_START)
627 /* Structure listing various control arguments, with their characteristics. */
629 typedef struct control_def {
631 int value; /* CONTROL_xxx value */
632 BOOL has_option; /* Has /option(s) following */
635 static control_def controls_list[] = {
636 { US"allow_auth_unadvertised", CONTROL_AUTH_UNADVERTISED, FALSE },
637 #ifdef EXPERIMENTAL_BRIGHTMAIL
638 { US"bmi_run", CONTROL_BMI_RUN, FALSE },
640 #ifdef EXPERIMENTAL_DOMAINKEYS
641 { US"dk_verify", CONTROL_DK_VERIFY, FALSE },
643 #ifdef EXPERIMENTAL_DKIM
644 { US"dkim_verify", CONTROL_DKIM_VERIFY, FALSE },
646 { US"caseful_local_part", CONTROL_CASEFUL_LOCAL_PART, FALSE },
647 { US"caselower_local_part", CONTROL_CASELOWER_LOCAL_PART, FALSE },
648 { US"enforce_sync", CONTROL_ENFORCE_SYNC, FALSE },
649 { US"freeze", CONTROL_FREEZE, TRUE },
650 { US"no_callout_flush", CONTROL_NO_CALLOUT_FLUSH, FALSE },
651 { US"no_delay_flush", CONTROL_NO_DELAY_FLUSH, FALSE },
652 { US"no_enforce_sync", CONTROL_NO_ENFORCE_SYNC, FALSE },
653 { US"no_multiline_responses", CONTROL_NO_MULTILINE, FALSE },
654 { US"no_pipelining", CONTROL_NO_PIPELINING, FALSE },
655 { US"queue_only", CONTROL_QUEUE_ONLY, FALSE },
656 #ifdef WITH_CONTENT_SCAN
657 { US"no_mbox_unspool", CONTROL_NO_MBOX_UNSPOOL, FALSE },
659 { US"fakedefer", CONTROL_FAKEDEFER, TRUE },
660 { US"fakereject", CONTROL_FAKEREJECT, TRUE },
661 { US"submission", CONTROL_SUBMISSION, TRUE },
662 { US"suppress_local_fixups", CONTROL_SUPPRESS_LOCAL_FIXUPS, FALSE }
665 /* Support data structures for Client SMTP Authorization. acl_verify_csa()
666 caches its result in a tree to avoid repeated DNS queries. The result is an
667 integer code which is used as an index into the following tables of
668 explanatory strings and verification return codes. */
670 static tree_node *csa_cache = NULL;
672 enum { CSA_UNKNOWN, CSA_OK, CSA_DEFER_SRV, CSA_DEFER_ADDR,
673 CSA_FAIL_EXPLICIT, CSA_FAIL_DOMAIN, CSA_FAIL_NOADDR, CSA_FAIL_MISMATCH };
675 /* The acl_verify_csa() return code is translated into an acl_verify() return
676 code using the following table. It is OK unless the client is definitely not
677 authorized. This is because CSA is supposed to be optional for sending sites,
678 so recipients should not be too strict about checking it - especially because
679 DNS problems are quite likely to occur. It's possible to use $csa_status in
680 further ACL conditions to distinguish ok, unknown, and defer if required, but
681 the aim is to make the usual configuration simple. */
683 static int csa_return_code[] = {
685 FAIL, FAIL, FAIL, FAIL
688 static uschar *csa_status_string[] = {
689 US"unknown", US"ok", US"defer", US"defer",
690 US"fail", US"fail", US"fail", US"fail"
693 static uschar *csa_reason_string[] = {
696 US"deferred (SRV lookup failed)",
697 US"deferred (target address lookup failed)",
698 US"failed (explicit authorization required)",
699 US"failed (host name not authorized)",
700 US"failed (no authorized addresses)",
701 US"failed (client address mismatch)"
704 /* Enable recursion between acl_check_internal() and acl_check_condition() */
706 static int acl_check_internal(int, address_item *, uschar *, int, uschar **,
710 /*************************************************
711 * Pick out name from list *
712 *************************************************/
714 /* Use a binary chop method
721 Returns: offset in list, or -1 if not found
725 acl_checkname(uschar *name, uschar **list, int end)
731 int mid = (start + end)/2;
732 int c = Ustrcmp(name, list[mid]);
733 if (c == 0) return mid;
734 if (c < 0) end = mid; else start = mid + 1;
741 /*************************************************
742 * Read and parse one ACL *
743 *************************************************/
745 /* This function is called both from readconf in order to parse the ACLs in the
746 configuration file, and also when an ACL is encountered dynamically (e.g. as
747 the result of an expansion). It is given a function to call in order to
748 retrieve the lines of the ACL. This function handles skipping comments and
749 blank lines (where relevant).
752 func function to get next line of ACL
753 error where to put an error message
755 Returns: pointer to ACL, or NULL
756 NULL can be legal (empty ACL); in this case error will be NULL
760 acl_read(uschar *(*func)(void), uschar **error)
762 acl_block *yield = NULL;
763 acl_block **lastp = &yield;
764 acl_block *this = NULL;
765 acl_condition_block *cond;
766 acl_condition_block **condp = NULL;
771 while ((s = (*func)()) != NULL)
774 BOOL negated = FALSE;
775 uschar *saveline = s;
778 /* Conditions (but not verbs) are allowed to be negated by an initial
781 while (isspace(*s)) s++;
788 /* Read the name of a verb or a condition, or the start of a new ACL, which
789 can be started by a name, or by a macro definition. */
791 s = readconf_readname(name, sizeof(name), s);
792 if (*s == ':' || (isupper(name[0]) && *s == '=')) return yield;
794 /* If a verb is unrecognized, it may be another condition or modifier that
795 continues the previous verb. */
797 v = acl_checkname(name, verbs, sizeof(verbs)/sizeof(char *));
802 *error = string_sprintf("unknown ACL verb \"%s\" in \"%s\"", name,
814 *error = string_sprintf("malformed ACL line \"%s\"", saveline);
817 this = store_get(sizeof(acl_block));
819 lastp = &(this->next);
822 this->condition = NULL;
823 condp = &(this->condition);
824 if (*s == 0) continue; /* No condition on this line */
830 s = readconf_readname(name, sizeof(name), s); /* Condition name */
833 /* Handle a condition or modifier. */
835 c = acl_checkname(name, conditions, sizeof(conditions)/sizeof(char *));
838 *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
843 /* The modifiers may not be negated */
845 if (negated && cond_modifiers[c])
847 *error = string_sprintf("ACL error: negation is not allowed with "
848 "\"%s\"", conditions[c]);
852 /* ENDPASS may occur only with ACCEPT or DISCARD. */
854 if (c == ACLC_ENDPASS &&
855 this->verb != ACL_ACCEPT &&
856 this->verb != ACL_DISCARD)
858 *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
859 conditions[c], verbs[this->verb]);
863 cond = store_get(sizeof(acl_condition_block));
866 cond->u.negated = negated;
869 condp = &(cond->next);
871 /* The "set" modifier is different in that its argument is "name=value"
872 rather than just a value, and we can check the validity of the name, which
873 gives us a variable name to insert into the data block. The original ACL
874 variable names were acl_c0 ... acl_c9 and acl_m0 ... acl_m9. This was
875 extended to 20 of each type, but after that people successfully argued for
876 arbitrary names. In the new scheme, the names must start with acl_c or acl_m.
877 After that, we allow alphanumerics and underscores, but the first character
878 after c or m must be a digit or an underscore. This retains backwards
885 if (Ustrncmp(s, "acl_c", 5) != 0 &&
886 Ustrncmp(s, "acl_m", 5) != 0)
888 *error = string_sprintf("invalid variable name after \"set\" in ACL "
889 "modifier \"set %s\" (must start \"acl_c\" or \"acl_m\")", s);
894 if (!isdigit(*endptr) && *endptr != '_')
896 *error = string_sprintf("invalid variable name after \"set\" in ACL "
897 "modifier \"set %s\" (digit or underscore must follow acl_c or acl_m)",
902 while (*endptr != 0 && *endptr != '=' && !isspace(*endptr))
904 if (!isalnum(*endptr) && *endptr != '_')
906 *error = string_sprintf("invalid character \"%c\" in variable name "
907 "in ACL modifier \"set %s\"", *endptr, s);
913 cond->u.varname = string_copyn(s + 4, endptr - s - 4);
915 while (isspace(*s)) s++;
918 /* For "set", we are now positioned for the data. For the others, only
919 "endpass" has no data */
921 if (c != ACLC_ENDPASS)
925 *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
926 cond_modifiers[c]? US"modifier" : US"condition");
929 while (isspace(*s)) s++;
930 cond->arg = string_copy(s);
939 /*************************************************
940 * Set up added header line(s) *
941 *************************************************/
943 /* This function is called by the add_header modifier, and also from acl_warn()
944 to implement the now-deprecated way of adding header lines using "message" on a
945 "warn" verb. The argument is treated as a sequence of header lines which are
946 added to a chain, provided there isn't an identical one already there.
948 Argument: string of header lines
953 setup_header(uschar *hstring)
956 int hlen = Ustrlen(hstring);
958 /* An empty string does nothing; otherwise add a final newline if necessary. */
960 if (hlen <= 0) return;
961 if (hstring[hlen-1] != '\n') hstring = string_sprintf("%s\n", hstring);
963 /* Loop for multiple header lines, taking care about continuations */
965 for (p = q = hstring; *p != 0; )
968 int newtype = htype_add_bot;
969 header_line **hptr = &acl_added_headers;
971 /* Find next header line within the string */
975 q = Ustrchr(q, '\n');
976 if (*(++q) != ' ' && *q != '\t') break;
979 /* If the line starts with a colon, interpret the instruction for where to
980 add it. This temporarily sets up a new type. */
984 if (strncmpic(p, US":after_received:", 16) == 0)
986 newtype = htype_add_rec;
989 else if (strncmpic(p, US":at_start_rfc:", 14) == 0)
991 newtype = htype_add_rfc;
994 else if (strncmpic(p, US":at_start:", 10) == 0)
996 newtype = htype_add_top;
999 else if (strncmpic(p, US":at_end:", 8) == 0)
1001 newtype = htype_add_bot;
1004 while (*p == ' ' || *p == '\t') p++;
1007 /* See if this line starts with a header name, and if not, add X-ACL-Warn:
1008 to the front of it. */
1010 for (s = p; s < q - 1; s++)
1012 if (*s == ':' || !isgraph(*s)) break;
1015 s = string_sprintf("%s%.*s", (*s == ':')? "" : "X-ACL-Warn: ", q - p, p);
1018 /* See if this line has already been added */
1020 while (*hptr != NULL)
1022 if (Ustrncmp((*hptr)->text, s, hlen) == 0) break;
1023 hptr = &((*hptr)->next);
1026 /* Add if not previously present */
1030 header_line *h = store_get(sizeof(header_line));
1039 /* Advance for next header line within the string */
1048 /*************************************************
1050 *************************************************/
1052 /* This function is called when a WARN verb's conditions are true. It adds to
1053 the message's headers, and/or writes information to the log. In each case, this
1054 only happens once (per message for headers, per connection for log).
1056 ** NOTE: The header adding action using the "message" setting is historic, and
1057 its use is now deprecated. The new add_header modifier should be used instead.
1060 where ACL_WHERE_xxxx indicating which ACL this is
1061 user_message message for adding to headers
1062 log_message message for logging, if different
1068 acl_warn(int where, uschar *user_message, uschar *log_message)
1070 if (log_message != NULL && log_message != user_message)
1073 string_item *logged;
1075 text = string_sprintf("%s Warning: %s", host_and_ident(TRUE),
1076 string_printing(log_message));
1078 /* If a sender verification has failed, and the log message is "sender verify
1079 failed", add the failure message. */
1081 if (sender_verified_failed != NULL &&
1082 sender_verified_failed->message != NULL &&
1083 strcmpic(log_message, US"sender verify failed") == 0)
1084 text = string_sprintf("%s: %s", text, sender_verified_failed->message);
1086 /* Search previously logged warnings. They are kept in malloc
1087 store so they can be freed at the start of a new message. */
1089 for (logged = acl_warn_logged; logged != NULL; logged = logged->next)
1090 if (Ustrcmp(logged->text, text) == 0) break;
1094 int length = Ustrlen(text) + 1;
1095 log_write(0, LOG_MAIN, "%s", text);
1096 logged = store_malloc(sizeof(string_item) + length);
1097 logged->text = (uschar *)logged + sizeof(string_item);
1098 memcpy(logged->text, text, length);
1099 logged->next = acl_warn_logged;
1100 acl_warn_logged = logged;
1104 /* If there's no user message, we are done. */
1106 if (user_message == NULL) return;
1108 /* If this isn't a message ACL, we can't do anything with a user message.
1111 if (where > ACL_WHERE_NOTSMTP)
1113 log_write(0, LOG_MAIN|LOG_PANIC, "ACL \"warn\" with \"message\" setting "
1114 "found in a non-message (%s) ACL: cannot specify header lines here: "
1115 "message ignored", acl_wherenames[where]);
1119 /* The code for setting up header lines is now abstracted into a separate
1120 function so that it can be used for the add_header modifier as well. */
1122 setup_header(user_message);
1127 /*************************************************
1128 * Verify and check reverse DNS *
1129 *************************************************/
1131 /* Called from acl_verify() below. We look up the host name(s) of the client IP
1132 address if this has not yet been done. The host_name_lookup() function checks
1133 that one of these names resolves to an address list that contains the client IP
1134 address, so we don't actually have to do the check here.
1137 user_msgptr pointer for user message
1138 log_msgptr pointer for log message
1140 Returns: OK verification condition succeeded
1141 FAIL verification failed
1142 DEFER there was a problem verifying
1146 acl_verify_reverse(uschar **user_msgptr, uschar **log_msgptr)
1150 user_msgptr = user_msgptr; /* stop compiler warning */
1152 /* Previous success */
1154 if (sender_host_name != NULL) return OK;
1156 /* Previous failure */
1158 if (host_lookup_failed)
1160 *log_msgptr = string_sprintf("host lookup failed%s", host_lookup_msg);
1164 /* Need to do a lookup */
1167 debug_printf("looking up host name to force name/address consistency check\n");
1169 if ((rc = host_name_lookup()) != OK)
1171 *log_msgptr = (rc == DEFER)?
1172 US"host lookup deferred for reverse lookup check"
1174 string_sprintf("host lookup failed for reverse lookup check%s",
1176 return rc; /* DEFER or FAIL */
1179 host_build_sender_fullhost();
1185 /*************************************************
1186 * Check client IP address matches CSA target *
1187 *************************************************/
1189 /* Called from acl_verify_csa() below. This routine scans a section of a DNS
1190 response for address records belonging to the CSA target hostname. The section
1191 is specified by the reset argument, either RESET_ADDITIONAL or RESET_ANSWERS.
1192 If one of the addresses matches the client's IP address, then the client is
1193 authorized by CSA. If there are target IP addresses but none of them match
1194 then the client is using an unauthorized IP address. If there are no target IP
1195 addresses then the client cannot be using an authorized IP address. (This is
1196 an odd configuration - why didn't the SRV record have a weight of 1 instead?)
1199 dnsa the DNS answer block
1200 dnss a DNS scan block for us to use
1201 reset option specifing what portion to scan, as described above
1202 target the target hostname to use for matching RR names
1204 Returns: CSA_OK successfully authorized
1205 CSA_FAIL_MISMATCH addresses found but none matched
1206 CSA_FAIL_NOADDR no target addresses found
1210 acl_verify_csa_address(dns_answer *dnsa, dns_scan *dnss, int reset,
1216 BOOL target_found = FALSE;
1218 for (rr = dns_next_rr(dnsa, dnss, reset);
1220 rr = dns_next_rr(dnsa, dnss, RESET_NEXT))
1222 /* Check this is an address RR for the target hostname. */
1226 && rr->type != T_AAAA
1233 if (strcmpic(target, rr->name) != 0) continue;
1235 target_found = TRUE;
1237 /* Turn the target address RR into a list of textual IP addresses and scan
1238 the list. There may be more than one if it is an A6 RR. */
1240 for (da = dns_address_from_rr(dnsa, rr); da != NULL; da = da->next)
1242 /* If the client IP address matches the target IP address, it's good! */
1244 DEBUG(D_acl) debug_printf("CSA target address is %s\n", da->address);
1246 if (strcmpic(sender_host_address, da->address) == 0) return CSA_OK;
1250 /* If we found some target addresses but none of them matched, the client is
1251 using an unauthorized IP address, otherwise the target has no authorized IP
1254 if (target_found) return CSA_FAIL_MISMATCH;
1255 else return CSA_FAIL_NOADDR;
1260 /*************************************************
1261 * Verify Client SMTP Authorization *
1262 *************************************************/
1264 /* Called from acl_verify() below. This routine calls dns_lookup_special()
1265 to find the CSA SRV record corresponding to the domain argument, or
1266 $sender_helo_name if no argument is provided. It then checks that the
1267 client is authorized, and that its IP address corresponds to the SRV
1268 target's address by calling acl_verify_csa_address() above. The address
1269 should have been returned in the DNS response's ADDITIONAL section, but if
1270 not we perform another DNS lookup to get it.
1273 domain pointer to optional parameter following verify = csa
1275 Returns: CSA_UNKNOWN no valid CSA record found
1276 CSA_OK successfully authorized
1277 CSA_FAIL_* client is definitely not authorized
1278 CSA_DEFER_* there was a DNS problem
1282 acl_verify_csa(uschar *domain)
1286 int priority, weight, port;
1293 /* Work out the domain we are using for the CSA lookup. The default is the
1294 client's HELO domain. If the client has not said HELO, use its IP address
1295 instead. If it's a local client (exim -bs), CSA isn't applicable. */
1297 while (isspace(*domain) && *domain != '\0') ++domain;
1298 if (*domain == '\0') domain = sender_helo_name;
1299 if (domain == NULL) domain = sender_host_address;
1300 if (sender_host_address == NULL) return CSA_UNKNOWN;
1302 /* If we have an address literal, strip off the framing ready for turning it
1303 into a domain. The framing consists of matched square brackets possibly
1304 containing a keyword and a colon before the actual IP address. */
1306 if (domain[0] == '[')
1308 uschar *start = Ustrchr(domain, ':');
1309 if (start == NULL) start = domain;
1310 domain = string_copyn(start + 1, Ustrlen(start) - 2);
1313 /* Turn domains that look like bare IP addresses into domains in the reverse
1314 DNS. This code also deals with address literals and $sender_host_address. It's
1315 not quite kosher to treat bare domains such as EHLO 192.0.2.57 the same as
1316 address literals, but it's probably the most friendly thing to do. This is an
1317 extension to CSA, so we allow it to be turned off for proper conformance. */
1319 if (string_is_ip_address(domain, NULL) != 0)
1321 if (!dns_csa_use_reverse) return CSA_UNKNOWN;
1322 dns_build_reverse(domain, target);
1326 /* Find out if we've already done the CSA check for this domain. If we have,
1327 return the same result again. Otherwise build a new cached result structure
1328 for this domain. The name is filled in now, and the value is filled in when
1329 we return from this function. */
1331 t = tree_search(csa_cache, domain);
1332 if (t != NULL) return t->data.val;
1334 t = store_get_perm(sizeof(tree_node) + Ustrlen(domain));
1335 Ustrcpy(t->name, domain);
1336 (void)tree_insertnode(&csa_cache, t);
1338 /* Now we are ready to do the actual DNS lookup(s). */
1341 switch (dns_special_lookup(&dnsa, domain, T_CSA, &found))
1343 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1346 return t->data.val = CSA_DEFER_SRV;
1348 /* If we found nothing, the client's authorization is unknown. */
1352 return t->data.val = CSA_UNKNOWN;
1354 /* We got something! Go on to look at the reply in more detail. */
1360 /* Scan the reply for well-formed CSA SRV records. */
1362 for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
1364 rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
1366 if (rr->type != T_SRV) continue;
1368 /* Extract the numerical SRV fields (p is incremented) */
1371 GETSHORT(priority, p);
1372 GETSHORT(weight, p);
1376 debug_printf("CSA priority=%d weight=%d port=%d\n", priority, weight, port);
1378 /* Check the CSA version number */
1380 if (priority != 1) continue;
1382 /* If the domain does not have a CSA SRV record of its own (i.e. the domain
1383 found by dns_special_lookup() is a parent of the one we asked for), we check
1384 the subdomain assertions in the port field. At the moment there's only one
1385 assertion: legitimate SMTP clients are all explicitly authorized with CSA
1386 SRV records of their own. */
1388 if (found != domain)
1391 return t->data.val = CSA_FAIL_EXPLICIT;
1393 return t->data.val = CSA_UNKNOWN;
1396 /* This CSA SRV record refers directly to our domain, so we check the value
1397 in the weight field to work out the domain's authorization. 0 and 1 are
1398 unauthorized; 3 means the client is authorized but we can't check the IP
1399 address in order to authenticate it, so we treat it as unknown; values
1400 greater than 3 are undefined. */
1402 if (weight < 2) return t->data.val = CSA_FAIL_DOMAIN;
1404 if (weight > 2) continue;
1406 /* Weight == 2, which means the domain is authorized. We must check that the
1407 client's IP address is listed as one of the SRV target addresses. Save the
1408 target hostname then break to scan the additional data for its addresses. */
1410 (void)dn_expand(dnsa.answer, dnsa.answer + dnsa.answerlen, p,
1411 (DN_EXPAND_ARG4_TYPE)target, sizeof(target));
1413 DEBUG(D_acl) debug_printf("CSA target is %s\n", target);
1418 /* If we didn't break the loop then no appropriate records were found. */
1420 if (rr == NULL) return t->data.val = CSA_UNKNOWN;
1422 /* Do not check addresses if the target is ".", in accordance with RFC 2782.
1423 A target of "." indicates there are no valid addresses, so the client cannot
1424 be authorized. (This is an odd configuration because weight=2 target=. is
1425 equivalent to weight=1, but we check for it in order to keep load off the
1426 root name servers.) Note that dn_expand() turns "." into "". */
1428 if (Ustrcmp(target, "") == 0) return t->data.val = CSA_FAIL_NOADDR;
1430 /* Scan the additional section of the CSA SRV reply for addresses belonging
1431 to the target. If the name server didn't return any additional data (e.g.
1432 because it does not fully support SRV records), we need to do another lookup
1433 to obtain the target addresses; otherwise we have a definitive result. */
1435 rc = acl_verify_csa_address(&dnsa, &dnss, RESET_ADDITIONAL, target);
1436 if (rc != CSA_FAIL_NOADDR) return t->data.val = rc;
1438 /* The DNS lookup type corresponds to the IP version used by the client. */
1441 if (Ustrchr(sender_host_address, ':') != NULL)
1444 #endif /* HAVE_IPV6 */
1448 #if HAVE_IPV6 && defined(SUPPORT_A6)
1452 switch (dns_lookup(&dnsa, target, type, NULL))
1454 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1457 return t->data.val = CSA_DEFER_ADDR;
1459 /* If the query succeeded, scan the addresses and return the result. */
1462 rc = acl_verify_csa_address(&dnsa, &dnss, RESET_ANSWERS, target);
1463 if (rc != CSA_FAIL_NOADDR) return t->data.val = rc;
1464 /* else fall through */
1466 /* If the target has no IP addresses, the client cannot have an authorized
1467 IP address. However, if the target site uses A6 records (not AAAA records)
1468 we have to do yet another lookup in order to check them. */
1473 #if HAVE_IPV6 && defined(SUPPORT_A6)
1474 if (type == T_AAAA) { type = T_A6; goto DNS_LOOKUP_AGAIN; }
1477 return t->data.val = CSA_FAIL_NOADDR;
1483 /*************************************************
1484 * Handle verification (address & other) *
1485 *************************************************/
1487 /* This function implements the "verify" condition. It is called when
1488 encountered in any ACL, because some tests are almost always permitted. Some
1489 just don't make sense, and always fail (for example, an attempt to test a host
1490 lookup for a non-TCP/IP message). Others are restricted to certain ACLs.
1493 where where called from
1494 addr the recipient address that the ACL is handling, or NULL
1495 arg the argument of "verify"
1496 user_msgptr pointer for user message
1497 log_msgptr pointer for log message
1498 basic_errno where to put verify errno
1500 Returns: OK verification condition succeeded
1501 FAIL verification failed
1502 DEFER there was a problem verifying
1507 acl_verify(int where, address_item *addr, uschar *arg,
1508 uschar **user_msgptr, uschar **log_msgptr, int *basic_errno)
1512 int callout_overall = -1;
1513 int callout_connect = -1;
1514 int verify_options = 0;
1516 BOOL verify_header_sender = FALSE;
1517 BOOL defer_ok = FALSE;
1518 BOOL callout_defer_ok = FALSE;
1519 BOOL no_details = FALSE;
1520 BOOL success_on_redirect = FALSE;
1521 address_item *sender_vaddr = NULL;
1522 uschar *verify_sender_address = NULL;
1523 uschar *pm_mailfrom = NULL;
1524 uschar *se_mailfrom = NULL;
1526 /* Some of the verify items have slash-separated options; some do not. Diagnose
1527 an error if options are given for items that don't expect them. This code has
1528 now got very message. Refactoring to use a table would be a good idea one day.
1531 uschar *slash = Ustrchr(arg, '/');
1533 uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);
1535 if (ss == NULL) goto BAD_VERIFY;
1537 /* Handle name/address consistency verification in a separate function. */
1539 if (strcmpic(ss, US"reverse_host_lookup") == 0)
1541 if (slash != NULL) goto NO_OPTIONS;
1542 if (sender_host_address == NULL) return OK;
1543 return acl_verify_reverse(user_msgptr, log_msgptr);
1546 /* TLS certificate verification is done at STARTTLS time; here we just
1547 test whether it was successful or not. (This is for optional verification; for
1548 mandatory verification, the connection doesn't last this long.) */
1550 if (strcmpic(ss, US"certificate") == 0)
1552 if (slash != NULL) goto NO_OPTIONS;
1553 if (tls_certificate_verified) return OK;
1554 *user_msgptr = US"no verified certificate";
1558 /* We can test the result of optional HELO verification that might have
1559 occurred earlier. If not, we can attempt the verification now. */
1561 if (strcmpic(ss, US"helo") == 0)
1563 if (slash != NULL) goto NO_OPTIONS;
1564 if (!helo_verified && !helo_verify_failed) smtp_verify_helo();
1565 return helo_verified? OK : FAIL;
1568 /* Do Client SMTP Authorization checks in a separate function, and turn the
1569 result code into user-friendly strings. */
1571 if (strcmpic(ss, US"csa") == 0)
1573 rc = acl_verify_csa(list);
1574 *log_msgptr = *user_msgptr = string_sprintf("client SMTP authorization %s",
1575 csa_reason_string[rc]);
1576 csa_status = csa_status_string[rc];
1577 DEBUG(D_acl) debug_printf("CSA result %s\n", csa_status);
1578 return csa_return_code[rc];
1581 /* Check that all relevant header lines have the correct syntax. If there is
1582 a syntax error, we return details of the error to the sender if configured to
1583 send out full details. (But a "message" setting on the ACL can override, as
1586 if (strcmpic(ss, US"header_syntax") == 0)
1588 if (slash != NULL) goto NO_OPTIONS;
1589 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1590 rc = verify_check_headers(log_msgptr);
1591 if (rc != OK && smtp_return_error_details && *log_msgptr != NULL)
1592 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1596 /* Check that no recipient of this message is "blind", that is, every envelope
1597 recipient must be mentioned in either To: or Cc:. */
1599 if (strcmpic(ss, US"not_blind") == 0)
1601 if (slash != NULL) goto NO_OPTIONS;
1602 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1603 rc = verify_check_notblind();
1606 *log_msgptr = string_sprintf("bcc recipient detected");
1607 if (smtp_return_error_details)
1608 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1613 /* The remaining verification tests check recipient and sender addresses,
1614 either from the envelope or from the header. There are a number of
1615 slash-separated options that are common to all of them. */
1618 /* Check that there is at least one verifiable sender address in the relevant
1619 header lines. This can be followed by callout and defer options, just like
1620 sender and recipient. */
1622 if (strcmpic(ss, US"header_sender") == 0)
1624 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1625 verify_header_sender = TRUE;
1628 /* Otherwise, first item in verify argument must be "sender" or "recipient".
1629 In the case of a sender, this can optionally be followed by an address to use
1630 in place of the actual sender (rare special-case requirement). */
1632 else if (strncmpic(ss, US"sender", 6) == 0)
1635 if (where > ACL_WHERE_NOTSMTP)
1637 *log_msgptr = string_sprintf("cannot verify sender in ACL for %s "
1638 "(only possible for MAIL, RCPT, PREDATA, or DATA)",
1639 acl_wherenames[where]);
1643 verify_sender_address = sender_address;
1646 while (isspace(*s)) s++;
1647 if (*s++ != '=') goto BAD_VERIFY;
1648 while (isspace(*s)) s++;
1649 verify_sender_address = string_copy(s);
1654 if (strcmpic(ss, US"recipient") != 0) goto BAD_VERIFY;
1657 *log_msgptr = string_sprintf("cannot verify recipient in ACL for %s "
1658 "(only possible for RCPT)", acl_wherenames[where]);
1663 /* Remaining items are optional; they apply to sender and recipient
1664 verification, including "header sender" verification. */
1666 while ((ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))
1669 if (strcmpic(ss, US"defer_ok") == 0) defer_ok = TRUE;
1670 else if (strcmpic(ss, US"no_details") == 0) no_details = TRUE;
1671 else if (strcmpic(ss, US"success_on_redirect") == 0) success_on_redirect = TRUE;
1673 /* These two old options are left for backwards compatibility */
1675 else if (strcmpic(ss, US"callout_defer_ok") == 0)
1677 callout_defer_ok = TRUE;
1678 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1681 else if (strcmpic(ss, US"check_postmaster") == 0)
1684 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1687 /* The callout option has a number of sub-options, comma separated */
1689 else if (strncmpic(ss, US"callout", 7) == 0)
1691 callout = CALLOUT_TIMEOUT_DEFAULT;
1695 while (isspace(*ss)) ss++;
1701 while (isspace(*ss)) ss++;
1703 /* This callout option handling code has become a mess as new options
1704 have been added in an ad hoc manner. It should be tidied up into some
1705 kind of table-driven thing. */
1707 while ((opt = string_nextinlist(&ss, &optsep, buffer, sizeof(buffer)))
1710 if (strcmpic(opt, US"defer_ok") == 0) callout_defer_ok = TRUE;
1711 else if (strcmpic(opt, US"no_cache") == 0)
1712 verify_options |= vopt_callout_no_cache;
1713 else if (strcmpic(opt, US"random") == 0)
1714 verify_options |= vopt_callout_random;
1715 else if (strcmpic(opt, US"use_sender") == 0)
1716 verify_options |= vopt_callout_recipsender;
1717 else if (strcmpic(opt, US"use_postmaster") == 0)
1718 verify_options |= vopt_callout_recippmaster;
1719 else if (strcmpic(opt, US"postmaster") == 0) pm_mailfrom = US"";
1720 else if (strcmpic(opt, US"fullpostmaster") == 0)
1723 verify_options |= vopt_callout_fullpm;
1726 else if (strncmpic(opt, US"mailfrom", 8) == 0)
1728 if (!verify_header_sender)
1730 *log_msgptr = string_sprintf("\"mailfrom\" is allowed as a "
1731 "callout option only for verify=header_sender (detected in ACL "
1732 "condition \"%s\")", arg);
1736 while (isspace(*opt)) opt++;
1739 *log_msgptr = string_sprintf("'=' expected after "
1740 "\"mailfrom\" in ACL condition \"%s\"", arg);
1743 while (isspace(*opt)) opt++;
1744 se_mailfrom = string_copy(opt);
1747 else if (strncmpic(opt, US"postmaster_mailfrom", 19) == 0)
1750 while (isspace(*opt)) opt++;
1753 *log_msgptr = string_sprintf("'=' expected after "
1754 "\"postmaster_mailfrom\" in ACL condition \"%s\"", arg);
1757 while (isspace(*opt)) opt++;
1758 pm_mailfrom = string_copy(opt);
1761 else if (strncmpic(opt, US"maxwait", 7) == 0)
1764 while (isspace(*opt)) opt++;
1767 *log_msgptr = string_sprintf("'=' expected after \"maxwait\" in "
1768 "ACL condition \"%s\"", arg);
1771 while (isspace(*opt)) opt++;
1772 callout_overall = readconf_readtime(opt, 0, FALSE);
1773 if (callout_overall < 0)
1775 *log_msgptr = string_sprintf("bad time value in ACL condition "
1776 "\"verify %s\"", arg);
1780 else if (strncmpic(opt, US"connect", 7) == 0)
1783 while (isspace(*opt)) opt++;
1786 *log_msgptr = string_sprintf("'=' expected after "
1787 "\"callout_overaall\" in ACL condition \"%s\"", arg);
1790 while (isspace(*opt)) opt++;
1791 callout_connect = readconf_readtime(opt, 0, FALSE);
1792 if (callout_connect < 0)
1794 *log_msgptr = string_sprintf("bad time value in ACL condition "
1795 "\"verify %s\"", arg);
1799 else /* Plain time is callout connect/command timeout */
1801 callout = readconf_readtime(opt, 0, FALSE);
1804 *log_msgptr = string_sprintf("bad time value in ACL condition "
1805 "\"verify %s\"", arg);
1813 *log_msgptr = string_sprintf("'=' expected after \"callout\" in "
1814 "ACL condition \"%s\"", arg);
1820 /* Option not recognized */
1824 *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1825 "condition \"verify %s\"", ss, arg);
1830 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)) ==
1831 (vopt_callout_recipsender|vopt_callout_recippmaster))
1833 *log_msgptr = US"only one of use_sender and use_postmaster can be set "
1834 "for a recipient callout";
1838 /* Handle sender-in-header verification. Default the user message to the log
1839 message if giving out verification details. */
1841 if (verify_header_sender)
1844 rc = verify_check_header_address(user_msgptr, log_msgptr, callout,
1845 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, verify_options,
1849 *basic_errno = verrno;
1850 if (smtp_return_error_details)
1852 if (*user_msgptr == NULL && *log_msgptr != NULL)
1853 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1854 if (rc == DEFER) acl_temp_details = TRUE;
1859 /* Handle a sender address. The default is to verify *the* sender address, but
1860 optionally a different address can be given, for special requirements. If the
1861 address is empty, we are dealing with a bounce message that has no sender, so
1862 we cannot do any checking. If the real sender address gets rewritten during
1863 verification (e.g. DNS widening), set the flag to stop it being rewritten again
1864 during message reception.
1866 A list of verified "sender" addresses is kept to try to avoid doing to much
1867 work repetitively when there are multiple recipients in a message and they all
1868 require sender verification. However, when callouts are involved, it gets too
1869 complicated because different recipients may require different callout options.
1870 Therefore, we always do a full sender verify when any kind of callout is
1871 specified. Caching elsewhere, for instance in the DNS resolver and in the
1872 callout handling, should ensure that this is not terribly inefficient. */
1874 else if (verify_sender_address != NULL)
1876 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster))
1879 *log_msgptr = US"use_sender or use_postmaster cannot be used for a "
1880 "sender verify callout";
1884 sender_vaddr = verify_checked_sender(verify_sender_address);
1885 if (sender_vaddr != NULL && /* Previously checked */
1886 callout <= 0) /* No callout needed this time */
1888 /* If the "routed" flag is set, it means that routing worked before, so
1889 this check can give OK (the saved return code value, if set, belongs to a
1890 callout that was done previously). If the "routed" flag is not set, routing
1891 must have failed, so we use the saved return code. */
1893 if (testflag(sender_vaddr, af_verify_routed)) rc = OK; else
1895 rc = sender_vaddr->special_action;
1896 *basic_errno = sender_vaddr->basic_errno;
1898 HDEBUG(D_acl) debug_printf("using cached sender verify result\n");
1901 /* Do a new verification, and cache the result. The cache is used to avoid
1902 verifying the sender multiple times for multiple RCPTs when callouts are not
1903 specified (see comments above).
1905 The cache is also used on failure to give details in response to the first
1906 RCPT that gets bounced for this reason. However, this can be suppressed by
1907 the no_details option, which sets the flag that says "this detail has already
1908 been sent". The cache normally contains just one address, but there may be
1909 more in esoteric circumstances. */
1914 uschar *save_address_data = deliver_address_data;
1916 sender_vaddr = deliver_make_addr(verify_sender_address, TRUE);
1917 if (no_details) setflag(sender_vaddr, af_sverify_told);
1918 if (verify_sender_address[0] != 0)
1920 /* If this is the real sender address, save the unrewritten version
1921 for use later in receive. Otherwise, set a flag so that rewriting the
1922 sender in verify_address() does not update sender_address. */
1924 if (verify_sender_address == sender_address)
1925 sender_address_unrewritten = sender_address;
1927 verify_options |= vopt_fake_sender;
1929 if (success_on_redirect)
1930 verify_options |= vopt_success_on_redirect;
1932 /* The recipient, qualify, and expn options are never set in
1935 rc = verify_address(sender_vaddr, NULL, verify_options, callout,
1936 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, &routed);
1938 HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1942 if (Ustrcmp(sender_vaddr->address, verify_sender_address) != 0)
1944 DEBUG(D_acl) debug_printf("sender %s verified ok as %s\n",
1945 verify_sender_address, sender_vaddr->address);
1949 DEBUG(D_acl) debug_printf("sender %s verified ok\n",
1950 verify_sender_address);
1953 else *basic_errno = sender_vaddr->basic_errno;
1955 else rc = OK; /* Null sender */
1957 /* Cache the result code */
1959 if (routed) setflag(sender_vaddr, af_verify_routed);
1960 if (callout > 0) setflag(sender_vaddr, af_verify_callout);
1961 sender_vaddr->special_action = rc;
1962 sender_vaddr->next = sender_verified_list;
1963 sender_verified_list = sender_vaddr;
1965 /* Restore the recipient address data, which might have been clobbered by
1966 the sender verification. */
1968 deliver_address_data = save_address_data;
1971 /* Put the sender address_data value into $sender_address_data */
1973 sender_address_data = sender_vaddr->p.address_data;
1976 /* A recipient address just gets a straightforward verify; again we must handle
1977 the DEFER overrides. */
1983 if (success_on_redirect)
1984 verify_options |= vopt_success_on_redirect;
1986 /* We must use a copy of the address for verification, because it might
1990 rc = verify_address(&addr2, NULL, verify_options|vopt_is_recipient, callout,
1991 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, NULL);
1992 HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1994 *basic_errno = addr2.basic_errno;
1995 *log_msgptr = addr2.message;
1996 *user_msgptr = (addr2.user_message != NULL)?
1997 addr2.user_message : addr2.message;
1999 /* Allow details for temporary error if the address is so flagged. */
2000 if (testflag((&addr2), af_pass_message)) acl_temp_details = TRUE;
2002 /* Make $address_data visible */
2003 deliver_address_data = addr2.p.address_data;
2006 /* We have a result from the relevant test. Handle defer overrides first. */
2008 if (rc == DEFER && (defer_ok ||
2009 (callout_defer_ok && *basic_errno == ERRNO_CALLOUTDEFER)))
2011 HDEBUG(D_acl) debug_printf("verify defer overridden by %s\n",
2012 defer_ok? "defer_ok" : "callout_defer_ok");
2016 /* If we've failed a sender, set up a recipient message, and point
2017 sender_verified_failed to the address item that actually failed. */
2019 if (rc != OK && verify_sender_address != NULL)
2023 *log_msgptr = *user_msgptr = US"Sender verify failed";
2025 else if (*basic_errno != ERRNO_CALLOUTDEFER)
2027 *log_msgptr = *user_msgptr = US"Could not complete sender verify";
2031 *log_msgptr = US"Could not complete sender verify callout";
2032 *user_msgptr = smtp_return_error_details? sender_vaddr->user_message :
2036 sender_verified_failed = sender_vaddr;
2039 /* Verifying an address messes up the values of $domain and $local_part,
2040 so reset them before returning if this is a RCPT ACL. */
2044 deliver_domain = addr->domain;
2045 deliver_localpart = addr->local_part;
2049 /* Syntax errors in the verify argument come here. */
2052 *log_msgptr = string_sprintf("expected \"sender[=address]\", \"recipient\", "
2053 "\"helo\", \"header_syntax\", \"header_sender\" or "
2054 "\"reverse_host_lookup\" at start of ACL condition "
2055 "\"verify %s\"", arg);
2058 /* Options supplied when not allowed come here */
2061 *log_msgptr = string_sprintf("unexpected '/' found in \"%s\" "
2062 "(this verify item has no options)", arg);
2065 /* Calls in the wrong ACL come here */
2068 *log_msgptr = string_sprintf("cannot check header contents in ACL for %s "
2069 "(only possible in ACL for DATA)", acl_wherenames[where]);
2076 /*************************************************
2077 * Check argument for control= modifier *
2078 *************************************************/
2080 /* Called from acl_check_condition() below
2083 arg the argument string for control=
2084 pptr set to point to the terminating character
2085 where which ACL we are in
2086 log_msgptr for error messages
2088 Returns: CONTROL_xxx value
2092 decode_control(uschar *arg, uschar **pptr, int where, uschar **log_msgptr)
2097 for (d = controls_list;
2098 d < controls_list + sizeof(controls_list)/sizeof(control_def);
2101 len = Ustrlen(d->name);
2102 if (Ustrncmp(d->name, arg, len) == 0) break;
2105 if (d >= controls_list + sizeof(controls_list)/sizeof(control_def) ||
2106 (arg[len] != 0 && (!d->has_option || arg[len] != '/')))
2108 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2109 return CONTROL_ERROR;
2118 /*************************************************
2119 * Handle rate limiting *
2120 *************************************************/
2122 /* Called by acl_check_condition() below to calculate the result
2123 of the ACL ratelimit condition.
2125 Note that the return value might be slightly unexpected: if the
2126 sender's rate is above the limit then the result is OK. This is
2127 similar to the dnslists condition, and is so that you can write
2128 ACL clauses like: defer ratelimit = 15 / 1h
2131 arg the option string for ratelimit=
2132 where ACL_WHERE_xxxx indicating which ACL this is
2133 log_msgptr for error messages
2135 Returns: OK - Sender's rate is above limit
2136 FAIL - Sender's rate is below limit
2137 DEFER - Problem opening ratelimit database
2138 ERROR - Syntax error in options.
2142 acl_ratelimit(uschar *arg, int where, uschar **log_msgptr)
2144 double limit, period;
2148 BOOL leaky = FALSE, strict = FALSE, noupdate = FALSE;
2149 BOOL per_byte = FALSE, per_cmd = FALSE, per_conn = FALSE, per_mail = FALSE;
2151 tree_node **anchor, *t;
2152 open_db dbblock, *dbm;
2153 dbdata_ratelimit *dbd;
2156 /* Parse the first two options and record their values in expansion
2157 variables. These variables allow the configuration to have informative
2158 error messages based on rate limits obtained from a table lookup. */
2160 /* First is the maximum number of messages per period and maximum burst
2161 size, which must be greater than or equal to zero. Zero is useful for
2162 rate measurement as opposed to rate limiting. */
2164 sender_rate_limit = string_nextinlist(&arg, &sep, NULL, 0);
2165 if (sender_rate_limit == NULL)
2169 limit = Ustrtod(sender_rate_limit, &ss);
2170 if (tolower(*ss) == 'k') { limit *= 1024.0; ss++; }
2171 else if (tolower(*ss) == 'm') { limit *= 1024.0*1024.0; ss++; }
2172 else if (tolower(*ss) == 'g') { limit *= 1024.0*1024.0*1024.0; ss++; }
2174 if (limit < 0.0 || *ss != 0)
2176 *log_msgptr = string_sprintf("syntax error in argument for "
2177 "\"ratelimit\" condition: \"%s\" is not a positive number",
2182 /* Second is the rate measurement period and exponential smoothing time
2183 constant. This must be strictly greater than zero, because zero leads to
2184 run-time division errors. */
2186 sender_rate_period = string_nextinlist(&arg, &sep, NULL, 0);
2187 if (sender_rate_period == NULL) period = -1.0;
2188 else period = readconf_readtime(sender_rate_period, 0, FALSE);
2191 *log_msgptr = string_sprintf("syntax error in argument for "
2192 "\"ratelimit\" condition: \"%s\" is not a time value",
2193 sender_rate_period);
2197 /* Parse the other options. Should we check if the per_* options are being
2198 used in ACLs where they don't make sense, e.g. per_mail in the connect ACL? */
2200 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
2203 if (strcmpic(ss, US"leaky") == 0) leaky = TRUE;
2204 else if (strcmpic(ss, US"strict") == 0) strict = TRUE;
2205 else if (strcmpic(ss, US"noupdate") == 0) noupdate = TRUE;
2206 else if (strcmpic(ss, US"per_byte") == 0) per_byte = TRUE;
2207 else if (strcmpic(ss, US"per_cmd") == 0) per_cmd = TRUE;
2208 else if (strcmpic(ss, US"per_rcpt") == 0) per_cmd = TRUE; /* alias */
2209 else if (strcmpic(ss, US"per_conn") == 0) per_conn = TRUE;
2210 else if (strcmpic(ss, US"per_mail") == 0) per_mail = TRUE;
2211 else key = string_sprintf("%s", ss);
2214 if (leaky + strict > 1 || per_byte + per_cmd + per_conn + per_mail > 1)
2216 *log_msgptr = US"conflicting options for \"ratelimit\" condition";
2220 /* Default option values */
2222 if (!strict) leaky = TRUE;
2223 if (!per_byte && !per_cmd && !per_conn) per_mail = TRUE;
2225 /* Create the lookup key. If there is no explicit key, use sender_host_address.
2226 If there is no sender_host_address (e.g. -bs or acl_not_smtp) then we simply
2227 omit it. The smoothing constant (sender_rate_period) and the per_xxx options
2228 are added to the key because they alter the meaning of the stored data. */
2231 key = (sender_host_address == NULL)? US"" : sender_host_address;
2233 key = string_sprintf("%s/%s/%s/%s",
2235 per_byte? US"per_byte" :
2236 per_cmd? US"per_cmd" :
2237 per_mail? US"per_mail" : US"per_conn",
2238 strict? US"strict" : US"leaky",
2241 HDEBUG(D_acl) debug_printf("ratelimit condition limit=%.0f period=%.0f key=%s\n",
2242 limit, period, key);
2244 /* See if we have already computed the rate by looking in the relevant tree.
2245 For per-connection rate limiting, store tree nodes and dbdata in the permanent
2246 pool so that they survive across resets. */
2249 old_pool = store_pool;
2253 anchor = &ratelimiters_conn;
2254 store_pool = POOL_PERM;
2256 else if (per_mail || per_byte)
2257 anchor = &ratelimiters_mail;
2259 anchor = &ratelimiters_cmd;
2261 if (anchor != NULL && (t = tree_search(*anchor, key)) != NULL)
2264 /* The following few lines duplicate some of the code below. */
2265 rc = (dbd->rate < limit)? FAIL : OK;
2266 store_pool = old_pool;
2267 sender_rate = string_sprintf("%.1f", dbd->rate);
2269 debug_printf("ratelimit found pre-computed rate %s\n", sender_rate);
2273 /* We aren't using a pre-computed rate, so get a previously recorded
2274 rate from the database, update it, and write it back when required. If there's
2275 no previous rate for this key, create one. */
2277 dbm = dbfn_open(US"ratelimit", O_RDWR, &dbblock, TRUE);
2280 store_pool = old_pool;
2282 HDEBUG(D_acl) debug_printf("ratelimit database not available\n");
2283 *log_msgptr = US"ratelimit database not available";
2286 dbd = dbfn_read(dbm, key);
2288 gettimeofday(&tv, NULL);
2292 HDEBUG(D_acl) debug_printf("ratelimit initializing new key's data\n");
2293 dbd = store_get(sizeof(dbdata_ratelimit));
2294 dbd->time_stamp = tv.tv_sec;
2295 dbd->time_usec = tv.tv_usec;
2300 /* The smoothed rate is computed using an exponentially weighted moving
2301 average adjusted for variable sampling intervals. The standard EWMA for
2302 a fixed sampling interval is: f'(t) = (1 - a) * f(t) + a * f'(t - 1)
2303 where f() is the measured value and f'() is the smoothed value.
2305 Old data decays out of the smoothed value exponentially, such that data n
2306 samples old is multiplied by a^n. The exponential decay time constant p
2307 is defined such that data p samples old is multiplied by 1/e, which means
2308 that a = exp(-1/p). We can maintain the same time constant for a variable
2309 sampling interval i by using a = exp(-i/p).
2311 The rate we are measuring is messages per period, suitable for directly
2312 comparing with the limit. The average rate between now and the previous
2313 message is period / interval, which we feed into the EWMA as the sample.
2315 It turns out that the number of messages required for the smoothed rate
2316 to reach the limit when they are sent in a burst is equal to the limit.
2317 This can be seen by analysing the value of the smoothed rate after N
2318 messages sent at even intervals. Let k = (1 - a) * p/i
2320 rate_1 = (1 - a) * p/i + a * rate_0
2322 rate_2 = k + a * rate_1
2323 = k + a * k + a^2 * rate_0
2324 rate_3 = k + a * k + a^2 * k + a^3 * rate_0
2325 rate_N = rate_0 * a^N + k * SUM(x=0..N-1)(a^x)
2326 = rate_0 * a^N + k * (1 - a^N) / (1 - a)
2327 = rate_0 * a^N + p/i * (1 - a^N)
2329 When N is large, a^N -> 0 so rate_N -> p/i as desired.
2331 rate_N = p/i + (rate_0 - p/i) * a^N
2332 a^N = (rate_N - p/i) / (rate_0 - p/i)
2333 N * -i/p = log((rate_N - p/i) / (rate_0 - p/i))
2334 N = p/i * log((rate_0 - p/i) / (rate_N - p/i))
2336 Numerical analysis of the above equation, setting the computed rate to
2337 increase from rate_0 = 0 to rate_N = limit, shows that for large sending
2338 rates, p/i, the number of messages N = limit. So limit serves as both the
2339 maximum rate measured in messages per period, and the maximum number of
2340 messages that can be sent in a fast burst. */
2342 double this_time = (double)tv.tv_sec
2343 + (double)tv.tv_usec / 1000000.0;
2344 double prev_time = (double)dbd->time_stamp
2345 + (double)dbd->time_usec / 1000000.0;
2347 /* We must avoid division by zero, and deal gracefully with the clock going
2348 backwards. If we blunder ahead when time is in reverse then the computed
2349 rate will be bogus. To be safe we clamp interval to a very small number. */
2351 double interval = this_time - prev_time <= 0.0 ? 1e-9
2352 : this_time - prev_time;
2354 double i_over_p = interval / period;
2355 double a = exp(-i_over_p);
2357 dbd->time_stamp = tv.tv_sec;
2358 dbd->time_usec = tv.tv_usec;
2360 /* If we are measuring the rate in bytes per period, multiply the
2361 measured rate by the message size. If we don't know the message size
2362 then it's safe to just use a value of zero and let the recorded rate
2363 decay as if nothing happened. */
2366 dbd->rate = (message_size < 0 ? 0.0 : (double)message_size)
2367 * (1 - a) / i_over_p + a * dbd->rate;
2368 else if (per_cmd && where == ACL_WHERE_NOTSMTP)
2369 dbd->rate = (double)recipients_count
2370 * (1 - a) / i_over_p + a * dbd->rate;
2372 dbd->rate = (1 - a) / i_over_p + a * dbd->rate;
2375 /* Clients sending at the limit are considered to be over the limit. This
2376 matters for edge cases such the first message sent by a client (which gets
2377 the initial rate of 0.0) when the rate limit is zero (i.e. the client should
2378 be completely blocked). */
2380 rc = (dbd->rate < limit)? FAIL : OK;
2382 /* Update the state if the rate is low or if we are being strict. If we
2383 are in leaky mode and the sender's rate is too high, we do not update
2384 the recorded rate in order to avoid an over-aggressive sender's retry
2385 rate preventing them from getting any email through. If noupdate is set,
2386 do not do any updates. */
2388 if ((rc == FAIL || !leaky) && !noupdate)
2390 dbfn_write(dbm, key, dbd, sizeof(dbdata_ratelimit));
2391 HDEBUG(D_acl) debug_printf("ratelimit db updated\n");
2395 HDEBUG(D_acl) debug_printf("ratelimit db not updated: %s\n",
2396 noupdate? "noupdate set" : "over the limit, but leaky");
2401 /* Store the result in the tree for future reference, if necessary. */
2403 if (anchor != NULL && !noupdate)
2405 t = store_get(sizeof(tree_node) + Ustrlen(key));
2407 Ustrcpy(t->name, key);
2408 (void)tree_insertnode(anchor, t);
2411 /* We create the formatted version of the sender's rate very late in
2412 order to ensure that it is done using the correct storage pool. */
2414 store_pool = old_pool;
2415 sender_rate = string_sprintf("%.1f", dbd->rate);
2418 debug_printf("ratelimit computed rate %s\n", sender_rate);
2425 /*************************************************
2426 * Handle conditions/modifiers on an ACL item *
2427 *************************************************/
2429 /* Called from acl_check() below.
2433 cb ACL condition block - if NULL, result is OK
2434 where where called from
2435 addr the address being checked for RCPT, or NULL
2436 level the nesting level
2437 epp pointer to pass back TRUE if "endpass" encountered
2438 (applies only to "accept" and "discard")
2439 user_msgptr user message pointer
2440 log_msgptr log message pointer
2441 basic_errno pointer to where to put verify error
2443 Returns: OK - all conditions are met
2444 DISCARD - an "acl" condition returned DISCARD - only allowed
2445 for "accept" or "discard" verbs
2446 FAIL - at least one condition fails
2447 FAIL_DROP - an "acl" condition returned FAIL_DROP
2448 DEFER - can't tell at the moment (typically, lookup defer,
2449 but can be temporary callout problem)
2450 ERROR - ERROR from nested ACL or expansion failure or other
2455 acl_check_condition(int verb, acl_condition_block *cb, int where,
2456 address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
2457 uschar **log_msgptr, int *basic_errno)
2459 uschar *user_message = NULL;
2460 uschar *log_message = NULL;
2463 #ifdef WITH_CONTENT_SCAN
2467 for (; cb != NULL; cb = cb->next)
2472 /* The message and log_message items set up messages to be used in
2473 case of rejection. They are expanded later. */
2475 if (cb->type == ACLC_MESSAGE)
2477 user_message = cb->arg;
2481 if (cb->type == ACLC_LOG_MESSAGE)
2483 log_message = cb->arg;
2487 /* The endpass "condition" just sets a flag to show it occurred. This is
2488 checked at compile time to be on an "accept" or "discard" item. */
2490 if (cb->type == ACLC_ENDPASS)
2496 /* For other conditions and modifiers, the argument is expanded now for some
2497 of them, but not for all, because expansion happens down in some lower level
2498 checking functions in some cases. */
2500 if (cond_expand_at_top[cb->type])
2502 arg = expand_string(cb->arg);
2505 if (expand_string_forcedfail) continue;
2506 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
2507 cb->arg, expand_string_message);
2508 return search_find_defer? DEFER : ERROR;
2513 /* Show condition, and expanded condition if it's different */
2518 debug_printf("check %s%s %n",
2519 (!cond_modifiers[cb->type] && cb->u.negated)? "!":"",
2520 conditions[cb->type], &lhswidth);
2522 if (cb->type == ACLC_SET)
2524 debug_printf("acl_%s ", cb->u.varname);
2525 lhswidth += 5 + Ustrlen(cb->u.varname);
2528 debug_printf("= %s\n", cb->arg);
2531 debug_printf("%.*s= %s\n", lhswidth,
2535 /* Check that this condition makes sense at this time */
2537 if ((cond_forbids[cb->type] & (1 << where)) != 0)
2539 *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
2540 cond_modifiers[cb->type]? "use" : "test",
2541 conditions[cb->type], acl_wherenames[where]);
2545 /* Run the appropriate test for each condition, or take the appropriate
2546 action for the remaining modifiers. */
2550 case ACLC_ADD_HEADER:
2554 /* A nested ACL that returns "discard" makes sense only for an "accept" or
2558 rc = acl_check_internal(where, addr, arg, level+1, user_msgptr, log_msgptr);
2559 if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
2561 *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
2562 "\"%s\" command (only allowed with \"accept\" or \"discard\")",
2568 case ACLC_AUTHENTICATED:
2569 rc = (sender_host_authenticated == NULL)? FAIL :
2570 match_isinlist(sender_host_authenticated, &arg, 0, NULL, NULL, MCL_STRING,
2574 #ifdef EXPERIMENTAL_BRIGHTMAIL
2575 case ACLC_BMI_OPTIN:
2577 int old_pool = store_pool;
2578 store_pool = POOL_PERM;
2579 bmi_current_optin = string_copy(arg);
2580 store_pool = old_pool;
2585 case ACLC_CONDITION:
2586 if (Ustrspn(arg, "0123456789") == Ustrlen(arg)) /* Digits, or empty */
2587 rc = (Uatoi(arg) == 0)? FAIL : OK;
2589 rc = (strcmpic(arg, US"no") == 0 ||
2590 strcmpic(arg, US"false") == 0)? FAIL :
2591 (strcmpic(arg, US"yes") == 0 ||
2592 strcmpic(arg, US"true") == 0)? OK : DEFER;
2594 *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
2597 case ACLC_CONTINUE: /* Always succeeds */
2601 control_type = decode_control(arg, &p, where, log_msgptr);
2603 /* Check if this control makes sense at this time */
2605 if ((control_forbids[control_type] & (1 << where)) != 0)
2607 *log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
2608 controls[control_type], acl_wherenames[where]);
2612 switch(control_type)
2614 case CONTROL_AUTH_UNADVERTISED:
2615 allow_auth_unadvertised = TRUE;
2618 #ifdef EXPERIMENTAL_BRIGHTMAIL
2619 case CONTROL_BMI_RUN:
2624 #ifdef EXPERIMENTAL_DOMAINKEYS
2625 case CONTROL_DK_VERIFY:
2630 #ifdef EXPERIMENTAL_DKIM
2631 case CONTROL_DKIM_VERIFY:
2639 case CONTROL_CASEFUL_LOCAL_PART:
2640 deliver_localpart = addr->cc_local_part;
2643 case CONTROL_CASELOWER_LOCAL_PART:
2644 deliver_localpart = addr->lc_local_part;
2647 case CONTROL_ENFORCE_SYNC:
2648 smtp_enforce_sync = TRUE;
2651 case CONTROL_NO_ENFORCE_SYNC:
2652 smtp_enforce_sync = FALSE;
2655 #ifdef WITH_CONTENT_SCAN
2656 case CONTROL_NO_MBOX_UNSPOOL:
2657 no_mbox_unspool = TRUE;
2661 case CONTROL_NO_MULTILINE:
2662 no_multiline_responses = TRUE;
2665 case CONTROL_NO_PIPELINING:
2666 pipelining_enable = FALSE;
2669 case CONTROL_NO_DELAY_FLUSH:
2670 disable_delay_flush = TRUE;
2673 case CONTROL_NO_CALLOUT_FLUSH:
2674 disable_callout_flush = TRUE;
2677 case CONTROL_FAKEDEFER:
2678 case CONTROL_FAKEREJECT:
2679 fake_response = (control_type == CONTROL_FAKEDEFER) ? DEFER : FAIL;
2683 while (*pp != 0) pp++;
2684 fake_response_text = expand_string(string_copyn(p+1, pp-p-1));
2689 /* Explicitly reset to default string */
2690 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).";
2694 case CONTROL_FREEZE:
2695 deliver_freeze = TRUE;
2696 deliver_frozen_at = time(NULL);
2697 freeze_tell = freeze_tell_config; /* Reset to configured value */
2698 if (Ustrncmp(p, "/no_tell", 8) == 0)
2705 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2710 case CONTROL_QUEUE_ONLY:
2711 queue_only_policy = TRUE;
2714 case CONTROL_SUBMISSION:
2715 originator_name = US"";
2716 submission_mode = TRUE;
2719 if (Ustrncmp(p, "/sender_retain", 14) == 0)
2722 active_local_sender_retain = TRUE;
2723 active_local_from_check = FALSE;
2725 else if (Ustrncmp(p, "/domain=", 8) == 0)
2728 while (*pp != 0 && *pp != '/') pp++;
2729 submission_domain = string_copyn(p+8, pp-p-8);
2732 /* The name= option must be last, because it swallows the rest of
2734 else if (Ustrncmp(p, "/name=", 6) == 0)
2737 while (*pp != 0) pp++;
2738 submission_name = string_copy(parse_fix_phrase(p+6, pp-p-6,
2739 big_buffer, big_buffer_size));
2746 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2751 case CONTROL_SUPPRESS_LOCAL_FIXUPS:
2752 suppress_local_fixups = TRUE;
2757 #ifdef WITH_CONTENT_SCAN
2759 rc = mime_decode(&arg);
2765 int delay = readconf_readtime(arg, 0, FALSE);
2768 *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
2769 "modifier: \"%s\" is not a time value", arg);
2774 HDEBUG(D_acl) debug_printf("delay modifier requests %d-second delay\n",
2779 debug_printf("delay skipped in -bh checking mode\n");
2782 /* It appears to be impossible to detect that a TCP/IP connection has
2783 gone away without reading from it. This means that we cannot shorten
2784 the delay below if the client goes away, because we cannot discover
2785 that the client has closed its end of the connection. (The connection
2786 is actually in a half-closed state, waiting for the server to close its
2787 end.) It would be nice to be able to detect this state, so that the
2788 Exim process is not held up unnecessarily. However, it seems that we
2789 can't. The poll() function does not do the right thing, and in any case
2790 it is not always available.
2792 NOTE 1: If ever this state of affairs changes, remember that we may be
2793 dealing with stdin/stdout here, in addition to TCP/IP connections.
2794 Also, delays may be specified for non-SMTP input, where smtp_out and
2795 smtp_in will be NULL. Whatever is done must work in all cases.
2797 NOTE 2: The added feature of flushing the output before a delay must
2798 apply only to SMTP input. Hence the test for smtp_out being non-NULL.
2803 if (smtp_out != NULL && !disable_delay_flush) mac_smtp_fflush();
2804 while (delay > 0) delay = sleep(delay);
2810 #ifdef WITH_OLD_DEMIME
2816 #ifdef EXPERIMENTAL_DOMAINKEYS
2817 case ACLC_DK_DOMAIN_SOURCE:
2818 if (dk_verify_block == NULL) { rc = FAIL; break; };
2819 /* check header source of domain against given string */
2820 switch (dk_verify_block->address_source) {
2821 case DK_EXIM_ADDRESS_FROM_FROM:
2822 rc = match_isinlist(US"from", &arg, 0, NULL,
2823 NULL, MCL_STRING, TRUE, NULL);
2825 case DK_EXIM_ADDRESS_FROM_SENDER:
2826 rc = match_isinlist(US"sender", &arg, 0, NULL,
2827 NULL, MCL_STRING, TRUE, NULL);
2829 case DK_EXIM_ADDRESS_NONE:
2830 rc = match_isinlist(US"none", &arg, 0, NULL,
2831 NULL, MCL_STRING, TRUE, NULL);
2836 case ACLC_DK_POLICY:
2837 if (dk_verify_block == NULL) { rc = FAIL; break; };
2838 /* check policy against given string, default FAIL */
2840 if (dk_verify_block->signsall)
2841 rc = match_isinlist(US"signsall", &arg, 0, NULL,
2842 NULL, MCL_STRING, TRUE, NULL);
2843 if (dk_verify_block->testing)
2844 rc = match_isinlist(US"testing", &arg, 0, NULL,
2845 NULL, MCL_STRING, TRUE, NULL);
2848 case ACLC_DK_SENDER_DOMAINS:
2849 if (dk_verify_block == NULL) { rc = FAIL; break; };
2850 if (dk_verify_block->domain != NULL)
2851 rc = match_isinlist(dk_verify_block->domain, &arg, 0, &domainlist_anchor,
2852 NULL, MCL_DOMAIN, TRUE, NULL);
2856 case ACLC_DK_SENDER_LOCAL_PARTS:
2857 if (dk_verify_block == NULL) { rc = FAIL; break; };
2858 if (dk_verify_block->local_part != NULL)
2859 rc = match_isinlist(dk_verify_block->local_part, &arg, 0, &localpartlist_anchor,
2860 NULL, MCL_LOCALPART, TRUE, NULL);
2864 case ACLC_DK_SENDERS:
2865 if (dk_verify_block == NULL) { rc = FAIL; break; };
2866 if (dk_verify_block->address != NULL)
2867 rc = match_address_list(dk_verify_block->address, TRUE, TRUE, &arg, NULL, -1, 0, NULL);
2871 case ACLC_DK_STATUS:
2872 if (dk_verify_block == NULL) { rc = FAIL; break; };
2873 if (dk_verify_block->result > 0) {
2874 switch(dk_verify_block->result) {
2875 case DK_EXIM_RESULT_BAD_FORMAT:
2876 rc = match_isinlist(US"bad format", &arg, 0, NULL,
2877 NULL, MCL_STRING, TRUE, NULL);
2879 case DK_EXIM_RESULT_NO_KEY:
2880 rc = match_isinlist(US"no key", &arg, 0, NULL,
2881 NULL, MCL_STRING, TRUE, NULL);
2883 case DK_EXIM_RESULT_NO_SIGNATURE:
2884 rc = match_isinlist(US"no signature", &arg, 0, NULL,
2885 NULL, MCL_STRING, TRUE, NULL);
2887 case DK_EXIM_RESULT_REVOKED:
2888 rc = match_isinlist(US"revoked", &arg, 0, NULL,
2889 NULL, MCL_STRING, TRUE, NULL);
2891 case DK_EXIM_RESULT_NON_PARTICIPANT:
2892 rc = match_isinlist(US"non-participant", &arg, 0, NULL,
2893 NULL, MCL_STRING, TRUE, NULL);
2895 case DK_EXIM_RESULT_GOOD:
2896 rc = match_isinlist(US"good", &arg, 0, NULL,
2897 NULL, MCL_STRING, TRUE, NULL);
2899 case DK_EXIM_RESULT_BAD:
2900 rc = match_isinlist(US"bad", &arg, 0, NULL,
2901 NULL, MCL_STRING, TRUE, NULL);
2909 rc = verify_check_dnsbl(&arg);
2913 rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
2914 addr->domain_cache, MCL_DOMAIN, TRUE, &deliver_domain_data);
2917 /* The value in tls_cipher is the full cipher name, for example,
2918 TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
2919 cipher names such as DES-CBC3-SHA. But program defensively. We don't know
2920 what may in practice come out of the SSL library - which at the time of
2921 writing is poorly documented. */
2923 case ACLC_ENCRYPTED:
2924 if (tls_cipher == NULL) rc = FAIL; else
2926 uschar *endcipher = NULL;
2927 uschar *cipher = Ustrchr(tls_cipher, ':');
2928 if (cipher == NULL) cipher = tls_cipher; else
2930 endcipher = Ustrchr(++cipher, ':');
2931 if (endcipher != NULL) *endcipher = 0;
2933 rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
2934 if (endcipher != NULL) *endcipher = ':';
2938 /* Use verify_check_this_host() instead of verify_check_host() so that
2939 we can pass over &host_data to catch any looked up data. Once it has been
2940 set, it retains its value so that it's still there if another ACL verb
2941 comes through here and uses the cache. However, we must put it into
2942 permanent store in case it is also expected to be used in a subsequent
2943 message in the same SMTP connection. */
2946 rc = verify_check_this_host(&arg, sender_host_cache, NULL,
2947 (sender_host_address == NULL)? US"" : sender_host_address, &host_data);
2948 if (host_data != NULL) host_data = string_copy_malloc(host_data);
2951 case ACLC_LOCAL_PARTS:
2952 rc = match_isinlist(addr->cc_local_part, &arg, 0,
2953 &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
2954 &deliver_localpart_data);
2957 case ACLC_LOG_REJECT_TARGET:
2963 while ((ss = string_nextinlist(&s, &sep, big_buffer, big_buffer_size))
2966 if (Ustrcmp(ss, "main") == 0) logbits |= LOG_MAIN;
2967 else if (Ustrcmp(ss, "panic") == 0) logbits |= LOG_PANIC;
2968 else if (Ustrcmp(ss, "reject") == 0) logbits |= LOG_REJECT;
2971 logbits |= LOG_MAIN|LOG_REJECT;
2972 log_write(0, LOG_MAIN|LOG_PANIC, "unknown log name \"%s\" in "
2973 "\"log_reject_target\" in %s ACL", ss, acl_wherenames[where]);
2976 log_reject_target = logbits;
2989 if (Ustrncmp(s, "main", 4) == 0)
2990 { logbits |= LOG_MAIN; s += 4; }
2991 else if (Ustrncmp(s, "panic", 5) == 0)
2992 { logbits |= LOG_PANIC; s += 5; }
2993 else if (Ustrncmp(s, "reject", 6) == 0)
2994 { logbits |= LOG_REJECT; s += 6; }
2997 logbits = LOG_MAIN|LOG_PANIC;
2998 s = string_sprintf(":unknown log name in \"%s\" in "
2999 "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
3005 while (isspace(*s)) s++;
3008 if (logbits == 0) logbits = LOG_MAIN;
3009 log_write(0, logbits, "%s", string_printing(s));
3013 #ifdef WITH_CONTENT_SCAN
3016 /* Separate the regular expression and any optional parameters. */
3017 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
3018 /* Run the malware backend. */
3020 /* Modify return code based upon the existance of options. */
3021 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
3023 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3025 /* FAIL so that the message is passed to the next ACL */
3032 case ACLC_MIME_REGEX:
3033 rc = mime_regex(&arg);
3037 case ACLC_RATELIMIT:
3038 rc = acl_ratelimit(arg, where, log_msgptr);
3041 case ACLC_RECIPIENTS:
3042 rc = match_address_list(addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
3046 #ifdef WITH_CONTENT_SCAN
3052 case ACLC_SENDER_DOMAINS:
3055 sdomain = Ustrrchr(sender_address, '@');
3056 sdomain = (sdomain == NULL)? US"" : sdomain + 1;
3057 rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
3058 sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
3063 rc = match_address_list(sender_address, TRUE, TRUE, &arg,
3064 sender_address_cache, -1, 0, &sender_data);
3067 /* Connection variables must persist forever */
3071 int old_pool = store_pool;
3072 if (cb->u.varname[0] == 'c') store_pool = POOL_PERM;
3073 acl_var_create(cb->u.varname)->data.ptr = string_copy(arg);
3074 store_pool = old_pool;
3078 #ifdef WITH_CONTENT_SCAN
3081 /* Seperate the regular expression and any optional parameters. */
3082 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
3083 /* Run the spam backend. */
3085 /* Modify return code based upon the existance of options. */
3086 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
3088 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3090 /* FAIL so that the message is passed to the next ACL */
3098 #ifdef EXPERIMENTAL_SPF
3100 rc = spf_process(&arg, sender_address);
3104 /* If the verb is WARN, discard any user message from verification, because
3105 such messages are SMTP responses, not header additions. The latter come
3106 only from explicit "message" modifiers. However, put the user message into
3107 $acl_verify_message so it can be used in subsequent conditions or modifiers
3108 (until something changes it). */
3111 rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
3112 acl_verify_message = *user_msgptr;
3113 if (verb == ACL_WARN) *user_msgptr = NULL;
3117 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
3118 "condition %d", cb->type);
3122 /* If a condition was negated, invert OK/FAIL. */
3124 if (!cond_modifiers[cb->type] && cb->u.negated)
3126 if (rc == OK) rc = FAIL;
3127 else if (rc == FAIL || rc == FAIL_DROP) rc = OK;
3130 if (rc != OK) break; /* Conditions loop */
3134 /* If the result is the one for which "message" and/or "log_message" are used,
3135 handle the values of these modifiers. If there isn't a log message set, we make
3136 it the same as the user message.
3138 "message" is a user message that will be included in an SMTP response. Unless
3139 it is empty, it overrides any previously set user message.
3141 "log_message" is a non-user message, and it adds to any existing non-user
3142 message that is already set.
3144 Most verbs have but a single return for which the messages are relevant, but
3145 for "discard", it's useful to have the log message both when it succeeds and
3146 when it fails. For "accept", the message is used in the OK case if there is no
3147 "endpass", but (for backwards compatibility) in the FAIL case if "endpass" is
3150 if (*epp && rc == OK) user_message = NULL;
3152 if (((1<<rc) & msgcond[verb]) != 0)
3155 uschar *old_user_msgptr = *user_msgptr;
3156 uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;
3158 /* If the verb is "warn", messages generated by conditions (verification or
3159 nested ACLs) are always discarded. This also happens for acceptance verbs
3160 when they actually do accept. Only messages specified at this level are used.
3161 However, the value of an existing message is available in $acl_verify_message
3162 during expansions. */
3164 if (verb == ACL_WARN ||
3165 (rc == OK && (verb == ACL_ACCEPT || verb == ACL_DISCARD)))
3166 *log_msgptr = *user_msgptr = NULL;
3168 if (user_message != NULL)
3170 acl_verify_message = old_user_msgptr;
3171 expmessage = expand_string(user_message);
3172 if (expmessage == NULL)
3174 if (!expand_string_forcedfail)
3175 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
3176 user_message, expand_string_message);
3178 else if (expmessage[0] != 0) *user_msgptr = expmessage;
3181 if (log_message != NULL)
3183 acl_verify_message = old_log_msgptr;
3184 expmessage = expand_string(log_message);
3185 if (expmessage == NULL)
3187 if (!expand_string_forcedfail)
3188 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
3189 log_message, expand_string_message);
3191 else if (expmessage[0] != 0)
3193 *log_msgptr = (*log_msgptr == NULL)? expmessage :
3194 string_sprintf("%s: %s", expmessage, *log_msgptr);
3198 /* If no log message, default it to the user message */
3200 if (*log_msgptr == NULL) *log_msgptr = *user_msgptr;
3203 acl_verify_message = NULL;
3211 /*************************************************
3212 * Get line from a literal ACL *
3213 *************************************************/
3215 /* This function is passed to acl_read() in order to extract individual lines
3216 of a literal ACL, which we access via static pointers. We can destroy the
3217 contents because this is called only once (the compiled ACL is remembered).
3219 This code is intended to treat the data in the same way as lines in the main
3220 Exim configuration file. That is:
3222 . Leading spaces are ignored.
3224 . A \ at the end of a line is a continuation - trailing spaces after the \
3225 are permitted (this is because I don't believe in making invisible things
3226 significant). Leading spaces on the continued part of a line are ignored.
3228 . Physical lines starting (significantly) with # are totally ignored, and
3229 may appear within a sequence of backslash-continued lines.
3231 . Blank lines are ignored, but will end a sequence of continuations.
3234 Returns: a pointer to the next line
3238 static uschar *acl_text; /* Current pointer in the text */
3239 static uschar *acl_text_end; /* Points one past the terminating '0' */
3247 /* This loop handles leading blank lines and comments. */
3251 while (isspace(*acl_text)) acl_text++; /* Leading spaces/empty lines */
3252 if (*acl_text == 0) return NULL; /* No more data */
3253 yield = acl_text; /* Potential data line */
3255 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
3257 /* If we hit the end before a newline, we have the whole logical line. If
3258 it's a comment, there's no more data to be given. Otherwise, yield it. */
3260 if (*acl_text == 0) return (*yield == '#')? NULL : yield;
3262 /* After reaching a newline, end this loop if the physical line does not
3263 start with '#'. If it does, it's a comment, and the loop continues. */
3265 if (*yield != '#') break;
3268 /* This loop handles continuations. We know we have some real data, ending in
3269 newline. See if there is a continuation marker at the end (ignoring trailing
3270 white space). We know that *yield is not white space, so no need to test for
3271 cont > yield in the backwards scanning loop. */
3276 for (cont = acl_text - 1; isspace(*cont); cont--);
3278 /* If no continuation follows, we are done. Mark the end of the line and
3287 /* We have encountered a continuation. Skip over whitespace at the start of
3288 the next line, and indeed the whole of the next line or lines if they are
3293 while (*(++acl_text) == ' ' || *acl_text == '\t');
3294 if (*acl_text != '#') break;
3295 while (*(++acl_text) != 0 && *acl_text != '\n');
3298 /* We have the start of a continuation line. Move all the rest of the data
3299 to join onto the previous line, and then find its end. If the end is not a
3300 newline, we are done. Otherwise loop to look for another continuation. */
3302 memmove(cont, acl_text, acl_text_end - acl_text);
3303 acl_text_end -= acl_text - cont;
3305 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
3306 if (*acl_text == 0) return yield;
3309 /* Control does not reach here */
3316 /*************************************************
3317 * Check access using an ACL *
3318 *************************************************/
3320 /* This function is called from address_check. It may recurse via
3321 acl_check_condition() - hence the use of a level to stop looping. The ACL is
3322 passed as a string which is expanded. A forced failure implies no access check
3323 is required. If the result is a single word, it is taken as the name of an ACL
3324 which is sought in the global ACL tree. Otherwise, it is taken as literal ACL
3325 text, complete with newlines, and parsed as such. In both cases, the ACL check
3326 is then run. This function uses an auxiliary function for acl_read() to call
3327 for reading individual lines of a literal ACL. This is acl_getline(), which
3328 appears immediately above.
3331 where where called from
3332 addr address item when called from RCPT; otherwise NULL
3333 s the input string; NULL is the same as an empty ACL => DENY
3334 level the nesting level
3335 user_msgptr where to put a user error (for SMTP response)
3336 log_msgptr where to put a logging message (not for SMTP response)
3338 Returns: OK access is granted
3339 DISCARD access is apparently granted...
3340 FAIL access is denied
3341 FAIL_DROP access is denied; drop the connection
3342 DEFER can't tell at the moment
3347 acl_check_internal(int where, address_item *addr, uschar *s, int level,
3348 uschar **user_msgptr, uschar **log_msgptr)
3351 acl_block *acl = NULL;
3352 uschar *acl_name = US"inline ACL";
3355 /* Catch configuration loops */
3359 *log_msgptr = US"ACL nested too deep: possible loop";
3365 HDEBUG(D_acl) debug_printf("ACL is NULL: implicit DENY\n");
3369 /* At top level, we expand the incoming string. At lower levels, it has already
3370 been expanded as part of condition processing. */
3374 ss = expand_string(s);
3377 if (expand_string_forcedfail) return OK;
3378 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s", s,
3379 expand_string_message);
3385 while (isspace(*ss))ss++;
3387 /* If we can't find a named ACL, the default is to parse it as an inline one.
3388 (Unless it begins with a slash; non-existent files give rise to an error.) */
3392 /* Handle the case of a string that does not contain any spaces. Look for a
3393 named ACL among those read from the configuration, or a previously read file.
3394 It is possible that the pointer to the ACL is NULL if the configuration
3395 contains a name with no data. If not found, and the text begins with '/',
3396 read an ACL from a file, and save it so it can be re-used. */
3398 if (Ustrchr(ss, ' ') == NULL)
3400 tree_node *t = tree_search(acl_anchor, ss);
3403 acl = (acl_block *)(t->data.ptr);
3406 HDEBUG(D_acl) debug_printf("ACL \"%s\" is empty: implicit DENY\n", ss);
3409 acl_name = string_sprintf("ACL \"%s\"", ss);
3410 HDEBUG(D_acl) debug_printf("using ACL \"%s\"\n", ss);
3413 else if (*ss == '/')
3415 struct stat statbuf;
3416 fd = Uopen(ss, O_RDONLY, 0);
3419 *log_msgptr = string_sprintf("failed to open ACL file \"%s\": %s", ss,
3424 if (fstat(fd, &statbuf) != 0)
3426 *log_msgptr = string_sprintf("failed to fstat ACL file \"%s\": %s", ss,
3431 acl_text = store_get(statbuf.st_size + 1);
3432 acl_text_end = acl_text + statbuf.st_size + 1;
3434 if (read(fd, acl_text, statbuf.st_size) != statbuf.st_size)
3436 *log_msgptr = string_sprintf("failed to read ACL file \"%s\": %s",
3437 ss, strerror(errno));
3440 acl_text[statbuf.st_size] = 0;
3443 acl_name = string_sprintf("ACL \"%s\"", ss);
3444 HDEBUG(D_acl) debug_printf("read ACL from file %s\n", ss);
3448 /* Parse an ACL that is still in text form. If it came from a file, remember it
3449 in the ACL tree, having read it into the POOL_PERM store pool so that it
3450 persists between multiple messages. */
3454 int old_pool = store_pool;
3455 if (fd >= 0) store_pool = POOL_PERM;
3456 acl = acl_read(acl_getline, log_msgptr);
3457 store_pool = old_pool;
3458 if (acl == NULL && *log_msgptr != NULL) return ERROR;
3461 tree_node *t = store_get_perm(sizeof(tree_node) + Ustrlen(ss));
3462 Ustrcpy(t->name, ss);
3464 (void)tree_insertnode(&acl_anchor, t);
3468 /* Now we have an ACL to use. It's possible it may be NULL. */
3473 int basic_errno = 0;
3474 BOOL endpass_seen = FALSE;
3476 *log_msgptr = *user_msgptr = NULL;
3477 acl_temp_details = FALSE;
3479 if ((where == ACL_WHERE_QUIT || where == ACL_WHERE_NOTQUIT) &&
3480 acl->verb != ACL_ACCEPT &&
3481 acl->verb != ACL_WARN)
3483 *log_msgptr = string_sprintf("\"%s\" is not allowed in a QUIT or not-QUIT ACL",
3488 HDEBUG(D_acl) debug_printf("processing \"%s\"\n", verbs[acl->verb]);
3490 /* Clear out any search error message from a previous check before testing
3493 search_error_message = NULL;
3494 cond = acl_check_condition(acl->verb, acl->condition, where, addr, level,
3495 &endpass_seen, user_msgptr, log_msgptr, &basic_errno);
3497 /* Handle special returns: DEFER causes a return except on a WARN verb;
3498 ERROR always causes a return. */
3503 HDEBUG(D_acl) debug_printf("%s: condition test deferred\n", verbs[acl->verb]);
3504 if (basic_errno != ERRNO_CALLOUTDEFER)
3506 if (search_error_message != NULL && *search_error_message != 0)
3507 *log_msgptr = search_error_message;
3508 if (smtp_return_error_details) acl_temp_details = TRUE;
3512 acl_temp_details = TRUE;
3514 if (acl->verb != ACL_WARN) return DEFER;
3517 default: /* Paranoia */
3519 HDEBUG(D_acl) debug_printf("%s: condition test error\n", verbs[acl->verb]);
3523 HDEBUG(D_acl) debug_printf("%s: condition test succeeded\n",
3528 HDEBUG(D_acl) debug_printf("%s: condition test failed\n", verbs[acl->verb]);
3531 /* DISCARD and DROP can happen only from a nested ACL condition, and
3532 DISCARD can happen only for an "accept" or "discard" verb. */
3535 HDEBUG(D_acl) debug_printf("%s: condition test yielded \"discard\"\n",
3540 HDEBUG(D_acl) debug_printf("%s: condition test yielded \"drop\"\n",
3545 /* At this point, cond for most verbs is either OK or FAIL or (as a result of
3546 a nested ACL condition) FAIL_DROP. However, for WARN, cond may be DEFER, and
3547 for ACCEPT and DISCARD, it may be DISCARD after a nested ACL call. */
3552 if (cond == OK || cond == DISCARD) return cond;
3555 HDEBUG(D_acl) debug_printf("accept: endpass encountered - denying access\n");
3563 acl_temp_details = TRUE;
3569 if (cond == OK) return FAIL;
3573 if (cond == OK || cond == DISCARD) return DISCARD;
3576 HDEBUG(D_acl) debug_printf("discard: endpass encountered - denying access\n");
3582 if (cond == OK) return FAIL_DROP;
3586 if (cond != OK) return cond;
3591 acl_warn(where, *user_msgptr, *log_msgptr);
3592 else if (cond == DEFER && (log_extra_selector & LX_acl_warn_skipped) != 0)
3593 log_write(0, LOG_MAIN, "%s Warning: ACL \"warn\" statement skipped: "
3594 "condition test deferred%s%s", host_and_ident(TRUE),
3595 (*log_msgptr == NULL)? US"" : US": ",
3596 (*log_msgptr == NULL)? US"" : *log_msgptr);
3597 *log_msgptr = *user_msgptr = NULL; /* In case implicit DENY follows */
3601 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown verb %d",
3606 /* Pass to the next ACL item */
3611 /* We have reached the end of the ACL. This is an implicit DENY. */
3613 HDEBUG(D_acl) debug_printf("end of %s: implicit DENY\n", acl_name);
3618 /*************************************************
3619 * Check access using an ACL *
3620 *************************************************/
3622 /* This is the external interface for ACL checks. It sets up an address and the
3623 expansions for $domain and $local_part when called after RCPT, then calls
3624 acl_check_internal() to do the actual work.
3627 where ACL_WHERE_xxxx indicating where called from
3628 recipient RCPT address for RCPT check, else NULL
3629 s the input string; NULL is the same as an empty ACL => DENY
3630 user_msgptr where to put a user error (for SMTP response)
3631 log_msgptr where to put a logging message (not for SMTP response)
3633 Returns: OK access is granted by an ACCEPT verb
3634 DISCARD access is granted by a DISCARD verb
3635 FAIL access is denied
3636 FAIL_DROP access is denied; drop the connection
3637 DEFER can't tell at the moment
3642 acl_check(int where, uschar *recipient, uschar *s, uschar **user_msgptr,
3643 uschar **log_msgptr)
3647 address_item *addr = NULL;
3649 *user_msgptr = *log_msgptr = NULL;
3650 sender_verified_failed = NULL;
3651 ratelimiters_cmd = NULL;
3652 log_reject_target = LOG_MAIN|LOG_REJECT;
3654 if (where == ACL_WHERE_RCPT)
3656 adb = address_defaults;
3658 addr->address = recipient;
3659 if (deliver_split_address(addr) == DEFER)
3661 *log_msgptr = US"defer in percent_hack_domains check";
3664 deliver_domain = addr->domain;
3665 deliver_localpart = addr->local_part;
3668 rc = acl_check_internal(where, addr, s, 0, user_msgptr, log_msgptr);
3670 deliver_domain = deliver_localpart = deliver_address_data =
3671 sender_address_data = NULL;
3673 /* A DISCARD response is permitted only for message ACLs, excluding the PREDATA
3674 ACL, which is really in the middle of an SMTP command. */
3678 if (where > ACL_WHERE_NOTSMTP || where == ACL_WHERE_PREDATA)
3680 log_write(0, LOG_MAIN|LOG_PANIC, "\"discard\" verb not allowed in %s "
3681 "ACL", acl_wherenames[where]);
3687 /* A DROP response is not permitted from MAILAUTH */
3689 if (rc == FAIL_DROP && where == ACL_WHERE_MAILAUTH)
3691 log_write(0, LOG_MAIN|LOG_PANIC, "\"drop\" verb not allowed in %s "
3692 "ACL", acl_wherenames[where]);
3696 /* Before giving a response, take a look at the length of any user message, and
3697 split it up into multiple lines if possible. */
3699 *user_msgptr = string_split_message(*user_msgptr);
3700 if (fake_response != OK)
3701 fake_response_text = string_split_message(fake_response_text);
3708 /*************************************************
3709 * Create ACL variable *
3710 *************************************************/
3712 /* Create an ACL variable or reuse an existing one. ACL variables are in a
3713 binary tree (see tree.c) with acl_var_c and acl_var_m as root nodes.
3716 name pointer to the variable's name, starting with c or m
3718 Returns the pointer to variable's tree node
3722 acl_var_create(uschar *name)
3724 tree_node *node, **root;
3725 root = (name[0] == 'c')? &acl_var_c : &acl_var_m;
3726 node = tree_search(*root, name);
3729 node = store_get(sizeof(tree_node) + Ustrlen(name));
3730 Ustrcpy(node->name, name);
3731 (void)tree_insertnode(root, node);
3733 node->data.ptr = NULL;
3739 /*************************************************
3740 * Write an ACL variable in spool format *
3741 *************************************************/
3743 /* This function is used as a callback for tree_walk when writing variables to
3744 the spool file. To retain spool file compatibility, what is written is -aclc or
3745 -aclm followed by the rest of the name and the data length, space separated,
3746 then the value itself, starting on a new line, and terminated by an additional
3747 newline. When we had only numbered ACL variables, the first line might look
3748 like this: "-aclc 5 20". Now it might be "-aclc foo 20" for the variable called
3752 name of the variable
3753 value of the variable
3754 ctx FILE pointer (as a void pointer)
3760 acl_var_write(uschar *name, uschar *value, void *ctx)
3762 FILE *f = (FILE *)ctx;
3763 fprintf(f, "-acl%c %s %d\n%s\n", name[0], name+1, Ustrlen(value), value);