1 /* $Cambridge: exim/src/src/acl.c,v 1.81 2008/01/17 13:03:35 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 EXPERIMENTAL_DCC
61 #ifdef WITH_CONTENT_SCAN
65 #ifdef WITH_OLD_DEMIME
68 #ifdef EXPERIMENTAL_DOMAINKEYS
69 ACLC_DK_DOMAIN_SOURCE,
71 ACLC_DK_SENDER_DOMAINS,
72 ACLC_DK_SENDER_LOCAL_PARTS,
83 ACLC_LOG_REJECT_TARGET,
85 #ifdef WITH_CONTENT_SCAN
89 #ifdef WITH_CONTENT_SCAN
94 #ifdef WITH_CONTENT_SCAN
100 #ifdef WITH_CONTENT_SCAN
103 #ifdef EXPERIMENTAL_SPF
108 /* ACL conditions/modifiers: "delay", "control", "continue", "endpass",
109 "message", "log_message", "log_reject_target", "logwrite", and "set" are
110 modifiers that look like conditions but always return TRUE. They are used for
111 their side effects. */
113 static uschar *conditions[] = {
117 #ifdef EXPERIMENTAL_BRIGHTMAIL
123 #ifdef EXPERIMENTAL_DCC
126 #ifdef WITH_CONTENT_SCAN
130 #ifdef WITH_OLD_DEMIME
133 #ifdef EXPERIMENTAL_DOMAINKEYS
134 US"dk_domain_source",
136 US"dk_sender_domains",
137 US"dk_sender_local_parts",
148 US"log_reject_target",
150 #ifdef WITH_CONTENT_SCAN
154 #ifdef WITH_CONTENT_SCAN
159 #ifdef WITH_CONTENT_SCAN
162 US"sender_domains", US"senders", US"set",
163 #ifdef WITH_CONTENT_SCAN
166 #ifdef EXPERIMENTAL_SPF
172 /* Return values from decode_control(); keep in step with the table of names
176 CONTROL_AUTH_UNADVERTISED,
177 #ifdef EXPERIMENTAL_BRIGHTMAIL
180 #ifdef EXPERIMENTAL_DOMAINKEYS
183 #ifdef EXPERIMENTAL_DKIM
187 CONTROL_CASEFUL_LOCAL_PART,
188 CONTROL_CASELOWER_LOCAL_PART,
189 CONTROL_ENFORCE_SYNC,
190 CONTROL_NO_ENFORCE_SYNC,
194 CONTROL_SUPPRESS_LOCAL_FIXUPS,
195 #ifdef WITH_CONTENT_SCAN
196 CONTROL_NO_MBOX_UNSPOOL,
200 CONTROL_NO_MULTILINE,
201 CONTROL_NO_PIPELINING,
202 CONTROL_NO_DELAY_FLUSH,
203 CONTROL_NO_CALLOUT_FLUSH
206 /* ACL control names; keep in step with the table above! This list is used for
207 turning ids into names. The actual list of recognized names is in the variable
208 control_def controls_list[] below. The fact that there are two lists is a mess
209 and should be tidied up. */
211 static uschar *controls[] = {
212 US"allow_auth_unadvertised",
213 #ifdef EXPERIMENTAL_BRIGHTMAIL
216 #ifdef EXPERIMENTAL_DOMAINKEYS
219 #ifdef EXPERIMENTAL_DKIM
223 US"caseful_local_part",
224 US"caselower_local_part",
230 US"suppress_local_fixups",
231 #ifdef WITH_CONTENT_SCAN
236 US"no_multiline_responses",
242 /* Flags to indicate for which conditions/modifiers a string expansion is done
243 at the outer level. In the other cases, expansion already occurs in the
244 checking functions. */
246 static uschar cond_expand_at_top[] = {
248 TRUE, /* add_header */
249 FALSE, /* authenticated */
250 #ifdef EXPERIMENTAL_BRIGHTMAIL
251 TRUE, /* bmi_optin */
253 TRUE, /* condition */
256 #ifdef EXPERIMENTAL_DCC
259 #ifdef WITH_CONTENT_SCAN
263 #ifdef WITH_OLD_DEMIME
266 #ifdef EXPERIMENTAL_DOMAINKEYS
267 TRUE, /* dk_domain_source */
268 TRUE, /* dk_policy */
269 TRUE, /* dk_sender_domains */
270 TRUE, /* dk_sender_local_parts */
271 TRUE, /* dk_senders */
272 TRUE, /* dk_status */
276 FALSE, /* encrypted */
279 FALSE, /* local_parts */
280 TRUE, /* log_message */
281 TRUE, /* log_reject_target */
283 #ifdef WITH_CONTENT_SCAN
287 #ifdef WITH_CONTENT_SCAN
288 TRUE, /* mime_regex */
290 TRUE, /* ratelimit */
291 FALSE, /* recipients */
292 #ifdef WITH_CONTENT_SCAN
295 FALSE, /* sender_domains */
298 #ifdef WITH_CONTENT_SCAN
301 #ifdef EXPERIMENTAL_SPF
307 /* Flags to identify the modifiers */
309 static uschar cond_modifiers[] = {
311 TRUE, /* add_header */
312 FALSE, /* authenticated */
313 #ifdef EXPERIMENTAL_BRIGHTMAIL
314 TRUE, /* bmi_optin */
316 FALSE, /* condition */
319 #ifdef EXPERIMENTAL_DCC
322 #ifdef WITH_CONTENT_SCAN
326 #ifdef WITH_OLD_DEMIME
329 #ifdef EXPERIMENTAL_DOMAINKEYS
330 FALSE, /* dk_domain_source */
331 FALSE, /* dk_policy */
332 FALSE, /* dk_sender_domains */
333 FALSE, /* dk_sender_local_parts */
334 FALSE, /* dk_senders */
335 FALSE, /* dk_status */
337 FALSE, /* dnslists */
339 FALSE, /* encrypted */
342 FALSE, /* local_parts */
343 TRUE, /* log_message */
344 TRUE, /* log_reject_target */
346 #ifdef WITH_CONTENT_SCAN
350 #ifdef WITH_CONTENT_SCAN
351 FALSE, /* mime_regex */
353 FALSE, /* ratelimit */
354 FALSE, /* recipients */
355 #ifdef WITH_CONTENT_SCAN
358 FALSE, /* sender_domains */
361 #ifdef WITH_CONTENT_SCAN
364 #ifdef EXPERIMENTAL_SPF
370 /* Bit map vector of which conditions and modifiers are not allowed at certain
371 times. For each condition and modifier, there's a bitmap of dis-allowed times.
372 For some, it is easier to specify the negation of a small number of allowed
375 static unsigned int cond_forbids[] = {
379 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* add_header */
380 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
381 (1<<ACL_WHERE_MIME)|(1<<ACL_WHERE_NOTSMTP)|
382 (1<<ACL_WHERE_NOTSMTP_START)),
384 (1<<ACL_WHERE_NOTSMTP)| /* authenticated */
385 (1<<ACL_WHERE_NOTSMTP_START)|
386 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO),
388 #ifdef EXPERIMENTAL_BRIGHTMAIL
389 (1<<ACL_WHERE_AUTH)| /* bmi_optin */
390 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
391 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_MIME)|
392 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
393 (1<<ACL_WHERE_MAILAUTH)|
394 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
395 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_PREDATA)|
396 (1<<ACL_WHERE_NOTSMTP_START),
403 /* Certain types of control are always allowed, so we let it through
404 always and check in the control processing itself. */
408 #ifdef EXPERIMENTAL_DCC
410 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* dcc */
413 #ifdef WITH_CONTENT_SCAN
415 ~(1<<ACL_WHERE_MIME), /* decode */
418 (1<<ACL_WHERE_NOTQUIT), /* delay */
420 #ifdef WITH_OLD_DEMIME
422 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* demime */
425 #ifdef EXPERIMENTAL_DOMAINKEYS
426 (1<<ACL_WHERE_AUTH)| /* dk_domain_source */
427 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
428 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
429 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
430 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
431 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
432 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
434 (1<<ACL_WHERE_AUTH)| /* dk_policy */
435 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
436 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
437 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
438 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
439 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
440 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
442 (1<<ACL_WHERE_AUTH)| /* dk_sender_domains */
443 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
444 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
445 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
446 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
447 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
448 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
450 (1<<ACL_WHERE_AUTH)| /* dk_sender_local_parts */
451 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
452 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
453 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
454 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
455 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
456 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
458 (1<<ACL_WHERE_AUTH)| /* dk_senders */
459 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
460 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
461 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
462 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
463 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
464 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
466 (1<<ACL_WHERE_AUTH)| /* dk_status */
467 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
468 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
469 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
470 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
471 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
472 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
475 (1<<ACL_WHERE_NOTSMTP)| /* dnslists */
476 (1<<ACL_WHERE_NOTSMTP_START),
479 ~(1<<ACL_WHERE_RCPT), /* domains */
481 (1<<ACL_WHERE_NOTSMTP)| /* encrypted */
482 (1<<ACL_WHERE_CONNECT)|
483 (1<<ACL_WHERE_NOTSMTP_START)|
488 (1<<ACL_WHERE_NOTSMTP)| /* hosts */
489 (1<<ACL_WHERE_NOTSMTP_START),
492 ~(1<<ACL_WHERE_RCPT), /* local_parts */
496 0, /* log_reject_target */
500 #ifdef WITH_CONTENT_SCAN
502 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* malware */
507 #ifdef WITH_CONTENT_SCAN
509 ~(1<<ACL_WHERE_MIME), /* mime_regex */
515 ~(1<<ACL_WHERE_RCPT), /* recipients */
517 #ifdef WITH_CONTENT_SCAN
519 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* regex */
520 (1<<ACL_WHERE_MIME)),
523 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* sender_domains */
525 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
526 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
527 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
529 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* senders */
531 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
532 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
533 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
537 #ifdef WITH_CONTENT_SCAN
539 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* spam */
542 #ifdef EXPERIMENTAL_SPF
543 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* spf */
545 (1<<ACL_WHERE_MAILAUTH)|
546 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
547 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY)|
548 (1<<ACL_WHERE_NOTSMTP)|
549 (1<<ACL_WHERE_NOTSMTP_START),
552 /* Certain types of verify are always allowed, so we let it through
553 always and check in the verify function itself */
559 /* Bit map vector of which controls are not allowed at certain times. For
560 each control, there's a bitmap of dis-allowed times. For some, it is easier to
561 specify the negation of a small number of allowed times. */
563 static unsigned int control_forbids[] = {
565 ~((1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)), /* allow_auth_unadvertised */
567 #ifdef EXPERIMENTAL_BRIGHTMAIL
571 #ifdef EXPERIMENTAL_DOMAINKEYS
572 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* dk_verify */
573 (1<<ACL_WHERE_NOTSMTP_START),
576 #ifdef EXPERIMENTAL_DKIM
577 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* dkim_verify */
578 (1<<ACL_WHERE_NOTSMTP_START),
584 ~(1<<ACL_WHERE_RCPT), /* caseful_local_part */
587 ~(1<<ACL_WHERE_RCPT), /* caselower_local_part */
589 (1<<ACL_WHERE_NOTSMTP)| /* enforce_sync */
590 (1<<ACL_WHERE_NOTSMTP_START),
592 (1<<ACL_WHERE_NOTSMTP)| /* no_enforce_sync */
593 (1<<ACL_WHERE_NOTSMTP_START),
596 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* freeze */
597 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
598 (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_MIME)),
601 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* queue_only */
602 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
603 (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_MIME)),
606 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* submission */
607 (1<<ACL_WHERE_PREDATA)),
610 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* suppress_local_fixups */
611 (1<<ACL_WHERE_PREDATA)|
612 (1<<ACL_WHERE_NOTSMTP_START)),
614 #ifdef WITH_CONTENT_SCAN
616 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* no_mbox_unspool */
617 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
618 (1<<ACL_WHERE_MIME)),
622 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* fakedefer */
623 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
624 (1<<ACL_WHERE_MIME)),
627 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* fakereject */
628 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
629 (1<<ACL_WHERE_MIME)),
631 (1<<ACL_WHERE_NOTSMTP)| /* no_multiline */
632 (1<<ACL_WHERE_NOTSMTP_START),
634 (1<<ACL_WHERE_NOTSMTP)| /* no_pipelining */
635 (1<<ACL_WHERE_NOTSMTP_START),
637 (1<<ACL_WHERE_NOTSMTP)| /* no_delay_flush */
638 (1<<ACL_WHERE_NOTSMTP_START),
640 (1<<ACL_WHERE_NOTSMTP)| /* no_callout_flush */
641 (1<<ACL_WHERE_NOTSMTP_START)
644 /* Structure listing various control arguments, with their characteristics. */
646 typedef struct control_def {
648 int value; /* CONTROL_xxx value */
649 BOOL has_option; /* Has /option(s) following */
652 static control_def controls_list[] = {
653 { US"allow_auth_unadvertised", CONTROL_AUTH_UNADVERTISED, FALSE },
654 #ifdef EXPERIMENTAL_BRIGHTMAIL
655 { US"bmi_run", CONTROL_BMI_RUN, FALSE },
657 #ifdef EXPERIMENTAL_DOMAINKEYS
658 { US"dk_verify", CONTROL_DK_VERIFY, FALSE },
660 #ifdef EXPERIMENTAL_DKIM
661 { US"dkim_verify", CONTROL_DKIM_VERIFY, FALSE },
663 { US"caseful_local_part", CONTROL_CASEFUL_LOCAL_PART, FALSE },
664 { US"caselower_local_part", CONTROL_CASELOWER_LOCAL_PART, FALSE },
665 { US"enforce_sync", CONTROL_ENFORCE_SYNC, FALSE },
666 { US"freeze", CONTROL_FREEZE, TRUE },
667 { US"no_callout_flush", CONTROL_NO_CALLOUT_FLUSH, FALSE },
668 { US"no_delay_flush", CONTROL_NO_DELAY_FLUSH, FALSE },
669 { US"no_enforce_sync", CONTROL_NO_ENFORCE_SYNC, FALSE },
670 { US"no_multiline_responses", CONTROL_NO_MULTILINE, FALSE },
671 { US"no_pipelining", CONTROL_NO_PIPELINING, FALSE },
672 { US"queue_only", CONTROL_QUEUE_ONLY, FALSE },
673 #ifdef WITH_CONTENT_SCAN
674 { US"no_mbox_unspool", CONTROL_NO_MBOX_UNSPOOL, FALSE },
676 { US"fakedefer", CONTROL_FAKEDEFER, TRUE },
677 { US"fakereject", CONTROL_FAKEREJECT, TRUE },
678 { US"submission", CONTROL_SUBMISSION, TRUE },
679 { US"suppress_local_fixups", CONTROL_SUPPRESS_LOCAL_FIXUPS, FALSE }
682 /* Support data structures for Client SMTP Authorization. acl_verify_csa()
683 caches its result in a tree to avoid repeated DNS queries. The result is an
684 integer code which is used as an index into the following tables of
685 explanatory strings and verification return codes. */
687 static tree_node *csa_cache = NULL;
689 enum { CSA_UNKNOWN, CSA_OK, CSA_DEFER_SRV, CSA_DEFER_ADDR,
690 CSA_FAIL_EXPLICIT, CSA_FAIL_DOMAIN, CSA_FAIL_NOADDR, CSA_FAIL_MISMATCH };
692 /* The acl_verify_csa() return code is translated into an acl_verify() return
693 code using the following table. It is OK unless the client is definitely not
694 authorized. This is because CSA is supposed to be optional for sending sites,
695 so recipients should not be too strict about checking it - especially because
696 DNS problems are quite likely to occur. It's possible to use $csa_status in
697 further ACL conditions to distinguish ok, unknown, and defer if required, but
698 the aim is to make the usual configuration simple. */
700 static int csa_return_code[] = {
702 FAIL, FAIL, FAIL, FAIL
705 static uschar *csa_status_string[] = {
706 US"unknown", US"ok", US"defer", US"defer",
707 US"fail", US"fail", US"fail", US"fail"
710 static uschar *csa_reason_string[] = {
713 US"deferred (SRV lookup failed)",
714 US"deferred (target address lookup failed)",
715 US"failed (explicit authorization required)",
716 US"failed (host name not authorized)",
717 US"failed (no authorized addresses)",
718 US"failed (client address mismatch)"
721 /* Enable recursion between acl_check_internal() and acl_check_condition() */
723 static int acl_check_internal(int, address_item *, uschar *, int, uschar **,
727 /*************************************************
728 * Pick out name from list *
729 *************************************************/
731 /* Use a binary chop method
738 Returns: offset in list, or -1 if not found
742 acl_checkname(uschar *name, uschar **list, int end)
748 int mid = (start + end)/2;
749 int c = Ustrcmp(name, list[mid]);
750 if (c == 0) return mid;
751 if (c < 0) end = mid; else start = mid + 1;
758 /*************************************************
759 * Read and parse one ACL *
760 *************************************************/
762 /* This function is called both from readconf in order to parse the ACLs in the
763 configuration file, and also when an ACL is encountered dynamically (e.g. as
764 the result of an expansion). It is given a function to call in order to
765 retrieve the lines of the ACL. This function handles skipping comments and
766 blank lines (where relevant).
769 func function to get next line of ACL
770 error where to put an error message
772 Returns: pointer to ACL, or NULL
773 NULL can be legal (empty ACL); in this case error will be NULL
777 acl_read(uschar *(*func)(void), uschar **error)
779 acl_block *yield = NULL;
780 acl_block **lastp = &yield;
781 acl_block *this = NULL;
782 acl_condition_block *cond;
783 acl_condition_block **condp = NULL;
788 while ((s = (*func)()) != NULL)
791 BOOL negated = FALSE;
792 uschar *saveline = s;
795 /* Conditions (but not verbs) are allowed to be negated by an initial
798 while (isspace(*s)) s++;
805 /* Read the name of a verb or a condition, or the start of a new ACL, which
806 can be started by a name, or by a macro definition. */
808 s = readconf_readname(name, sizeof(name), s);
809 if (*s == ':' || (isupper(name[0]) && *s == '=')) return yield;
811 /* If a verb is unrecognized, it may be another condition or modifier that
812 continues the previous verb. */
814 v = acl_checkname(name, verbs, sizeof(verbs)/sizeof(char *));
819 *error = string_sprintf("unknown ACL verb \"%s\" in \"%s\"", name,
831 *error = string_sprintf("malformed ACL line \"%s\"", saveline);
834 this = store_get(sizeof(acl_block));
836 lastp = &(this->next);
839 this->condition = NULL;
840 condp = &(this->condition);
841 if (*s == 0) continue; /* No condition on this line */
847 s = readconf_readname(name, sizeof(name), s); /* Condition name */
850 /* Handle a condition or modifier. */
852 c = acl_checkname(name, conditions, sizeof(conditions)/sizeof(char *));
855 *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
860 /* The modifiers may not be negated */
862 if (negated && cond_modifiers[c])
864 *error = string_sprintf("ACL error: negation is not allowed with "
865 "\"%s\"", conditions[c]);
869 /* ENDPASS may occur only with ACCEPT or DISCARD. */
871 if (c == ACLC_ENDPASS &&
872 this->verb != ACL_ACCEPT &&
873 this->verb != ACL_DISCARD)
875 *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
876 conditions[c], verbs[this->verb]);
880 cond = store_get(sizeof(acl_condition_block));
883 cond->u.negated = negated;
886 condp = &(cond->next);
888 /* The "set" modifier is different in that its argument is "name=value"
889 rather than just a value, and we can check the validity of the name, which
890 gives us a variable name to insert into the data block. The original ACL
891 variable names were acl_c0 ... acl_c9 and acl_m0 ... acl_m9. This was
892 extended to 20 of each type, but after that people successfully argued for
893 arbitrary names. In the new scheme, the names must start with acl_c or acl_m.
894 After that, we allow alphanumerics and underscores, but the first character
895 after c or m must be a digit or an underscore. This retains backwards
902 if (Ustrncmp(s, "acl_c", 5) != 0 &&
903 Ustrncmp(s, "acl_m", 5) != 0)
905 *error = string_sprintf("invalid variable name after \"set\" in ACL "
906 "modifier \"set %s\" (must start \"acl_c\" or \"acl_m\")", s);
911 if (!isdigit(*endptr) && *endptr != '_')
913 *error = string_sprintf("invalid variable name after \"set\" in ACL "
914 "modifier \"set %s\" (digit or underscore must follow acl_c or acl_m)",
919 while (*endptr != 0 && *endptr != '=' && !isspace(*endptr))
921 if (!isalnum(*endptr) && *endptr != '_')
923 *error = string_sprintf("invalid character \"%c\" in variable name "
924 "in ACL modifier \"set %s\"", *endptr, s);
930 cond->u.varname = string_copyn(s + 4, endptr - s - 4);
932 while (isspace(*s)) s++;
935 /* For "set", we are now positioned for the data. For the others, only
936 "endpass" has no data */
938 if (c != ACLC_ENDPASS)
942 *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
943 cond_modifiers[c]? US"modifier" : US"condition");
946 while (isspace(*s)) s++;
947 cond->arg = string_copy(s);
956 /*************************************************
957 * Set up added header line(s) *
958 *************************************************/
960 /* This function is called by the add_header modifier, and also from acl_warn()
961 to implement the now-deprecated way of adding header lines using "message" on a
962 "warn" verb. The argument is treated as a sequence of header lines which are
963 added to a chain, provided there isn't an identical one already there.
965 Argument: string of header lines
970 setup_header(uschar *hstring)
973 int hlen = Ustrlen(hstring);
975 /* An empty string does nothing; otherwise add a final newline if necessary. */
977 if (hlen <= 0) return;
978 if (hstring[hlen-1] != '\n') hstring = string_sprintf("%s\n", hstring);
980 /* Loop for multiple header lines, taking care about continuations */
982 for (p = q = hstring; *p != 0; )
985 int newtype = htype_add_bot;
986 header_line **hptr = &acl_added_headers;
988 /* Find next header line within the string */
992 q = Ustrchr(q, '\n');
993 if (*(++q) != ' ' && *q != '\t') break;
996 /* If the line starts with a colon, interpret the instruction for where to
997 add it. This temporarily sets up a new type. */
1001 if (strncmpic(p, US":after_received:", 16) == 0)
1003 newtype = htype_add_rec;
1006 else if (strncmpic(p, US":at_start_rfc:", 14) == 0)
1008 newtype = htype_add_rfc;
1011 else if (strncmpic(p, US":at_start:", 10) == 0)
1013 newtype = htype_add_top;
1016 else if (strncmpic(p, US":at_end:", 8) == 0)
1018 newtype = htype_add_bot;
1021 while (*p == ' ' || *p == '\t') p++;
1024 /* See if this line starts with a header name, and if not, add X-ACL-Warn:
1025 to the front of it. */
1027 for (s = p; s < q - 1; s++)
1029 if (*s == ':' || !isgraph(*s)) break;
1032 s = string_sprintf("%s%.*s", (*s == ':')? "" : "X-ACL-Warn: ", q - p, p);
1035 /* See if this line has already been added */
1037 while (*hptr != NULL)
1039 if (Ustrncmp((*hptr)->text, s, hlen) == 0) break;
1040 hptr = &((*hptr)->next);
1043 /* Add if not previously present */
1047 header_line *h = store_get(sizeof(header_line));
1056 /* Advance for next header line within the string */
1065 /*************************************************
1067 *************************************************/
1069 /* This function is called when a WARN verb's conditions are true. It adds to
1070 the message's headers, and/or writes information to the log. In each case, this
1071 only happens once (per message for headers, per connection for log).
1073 ** NOTE: The header adding action using the "message" setting is historic, and
1074 its use is now deprecated. The new add_header modifier should be used instead.
1077 where ACL_WHERE_xxxx indicating which ACL this is
1078 user_message message for adding to headers
1079 log_message message for logging, if different
1085 acl_warn(int where, uschar *user_message, uschar *log_message)
1087 if (log_message != NULL && log_message != user_message)
1090 string_item *logged;
1092 text = string_sprintf("%s Warning: %s", host_and_ident(TRUE),
1093 string_printing(log_message));
1095 /* If a sender verification has failed, and the log message is "sender verify
1096 failed", add the failure message. */
1098 if (sender_verified_failed != NULL &&
1099 sender_verified_failed->message != NULL &&
1100 strcmpic(log_message, US"sender verify failed") == 0)
1101 text = string_sprintf("%s: %s", text, sender_verified_failed->message);
1103 /* Search previously logged warnings. They are kept in malloc
1104 store so they can be freed at the start of a new message. */
1106 for (logged = acl_warn_logged; logged != NULL; logged = logged->next)
1107 if (Ustrcmp(logged->text, text) == 0) break;
1111 int length = Ustrlen(text) + 1;
1112 log_write(0, LOG_MAIN, "%s", text);
1113 logged = store_malloc(sizeof(string_item) + length);
1114 logged->text = (uschar *)logged + sizeof(string_item);
1115 memcpy(logged->text, text, length);
1116 logged->next = acl_warn_logged;
1117 acl_warn_logged = logged;
1121 /* If there's no user message, we are done. */
1123 if (user_message == NULL) return;
1125 /* If this isn't a message ACL, we can't do anything with a user message.
1128 if (where > ACL_WHERE_NOTSMTP)
1130 log_write(0, LOG_MAIN|LOG_PANIC, "ACL \"warn\" with \"message\" setting "
1131 "found in a non-message (%s) ACL: cannot specify header lines here: "
1132 "message ignored", acl_wherenames[where]);
1136 /* The code for setting up header lines is now abstracted into a separate
1137 function so that it can be used for the add_header modifier as well. */
1139 setup_header(user_message);
1144 /*************************************************
1145 * Verify and check reverse DNS *
1146 *************************************************/
1148 /* Called from acl_verify() below. We look up the host name(s) of the client IP
1149 address if this has not yet been done. The host_name_lookup() function checks
1150 that one of these names resolves to an address list that contains the client IP
1151 address, so we don't actually have to do the check here.
1154 user_msgptr pointer for user message
1155 log_msgptr pointer for log message
1157 Returns: OK verification condition succeeded
1158 FAIL verification failed
1159 DEFER there was a problem verifying
1163 acl_verify_reverse(uschar **user_msgptr, uschar **log_msgptr)
1167 user_msgptr = user_msgptr; /* stop compiler warning */
1169 /* Previous success */
1171 if (sender_host_name != NULL) return OK;
1173 /* Previous failure */
1175 if (host_lookup_failed)
1177 *log_msgptr = string_sprintf("host lookup failed%s", host_lookup_msg);
1181 /* Need to do a lookup */
1184 debug_printf("looking up host name to force name/address consistency check\n");
1186 if ((rc = host_name_lookup()) != OK)
1188 *log_msgptr = (rc == DEFER)?
1189 US"host lookup deferred for reverse lookup check"
1191 string_sprintf("host lookup failed for reverse lookup check%s",
1193 return rc; /* DEFER or FAIL */
1196 host_build_sender_fullhost();
1202 /*************************************************
1203 * Check client IP address matches CSA target *
1204 *************************************************/
1206 /* Called from acl_verify_csa() below. This routine scans a section of a DNS
1207 response for address records belonging to the CSA target hostname. The section
1208 is specified by the reset argument, either RESET_ADDITIONAL or RESET_ANSWERS.
1209 If one of the addresses matches the client's IP address, then the client is
1210 authorized by CSA. If there are target IP addresses but none of them match
1211 then the client is using an unauthorized IP address. If there are no target IP
1212 addresses then the client cannot be using an authorized IP address. (This is
1213 an odd configuration - why didn't the SRV record have a weight of 1 instead?)
1216 dnsa the DNS answer block
1217 dnss a DNS scan block for us to use
1218 reset option specifing what portion to scan, as described above
1219 target the target hostname to use for matching RR names
1221 Returns: CSA_OK successfully authorized
1222 CSA_FAIL_MISMATCH addresses found but none matched
1223 CSA_FAIL_NOADDR no target addresses found
1227 acl_verify_csa_address(dns_answer *dnsa, dns_scan *dnss, int reset,
1233 BOOL target_found = FALSE;
1235 for (rr = dns_next_rr(dnsa, dnss, reset);
1237 rr = dns_next_rr(dnsa, dnss, RESET_NEXT))
1239 /* Check this is an address RR for the target hostname. */
1243 && rr->type != T_AAAA
1250 if (strcmpic(target, rr->name) != 0) continue;
1252 target_found = TRUE;
1254 /* Turn the target address RR into a list of textual IP addresses and scan
1255 the list. There may be more than one if it is an A6 RR. */
1257 for (da = dns_address_from_rr(dnsa, rr); da != NULL; da = da->next)
1259 /* If the client IP address matches the target IP address, it's good! */
1261 DEBUG(D_acl) debug_printf("CSA target address is %s\n", da->address);
1263 if (strcmpic(sender_host_address, da->address) == 0) return CSA_OK;
1267 /* If we found some target addresses but none of them matched, the client is
1268 using an unauthorized IP address, otherwise the target has no authorized IP
1271 if (target_found) return CSA_FAIL_MISMATCH;
1272 else return CSA_FAIL_NOADDR;
1277 /*************************************************
1278 * Verify Client SMTP Authorization *
1279 *************************************************/
1281 /* Called from acl_verify() below. This routine calls dns_lookup_special()
1282 to find the CSA SRV record corresponding to the domain argument, or
1283 $sender_helo_name if no argument is provided. It then checks that the
1284 client is authorized, and that its IP address corresponds to the SRV
1285 target's address by calling acl_verify_csa_address() above. The address
1286 should have been returned in the DNS response's ADDITIONAL section, but if
1287 not we perform another DNS lookup to get it.
1290 domain pointer to optional parameter following verify = csa
1292 Returns: CSA_UNKNOWN no valid CSA record found
1293 CSA_OK successfully authorized
1294 CSA_FAIL_* client is definitely not authorized
1295 CSA_DEFER_* there was a DNS problem
1299 acl_verify_csa(uschar *domain)
1303 int priority, weight, port;
1310 /* Work out the domain we are using for the CSA lookup. The default is the
1311 client's HELO domain. If the client has not said HELO, use its IP address
1312 instead. If it's a local client (exim -bs), CSA isn't applicable. */
1314 while (isspace(*domain) && *domain != '\0') ++domain;
1315 if (*domain == '\0') domain = sender_helo_name;
1316 if (domain == NULL) domain = sender_host_address;
1317 if (sender_host_address == NULL) return CSA_UNKNOWN;
1319 /* If we have an address literal, strip off the framing ready for turning it
1320 into a domain. The framing consists of matched square brackets possibly
1321 containing a keyword and a colon before the actual IP address. */
1323 if (domain[0] == '[')
1325 uschar *start = Ustrchr(domain, ':');
1326 if (start == NULL) start = domain;
1327 domain = string_copyn(start + 1, Ustrlen(start) - 2);
1330 /* Turn domains that look like bare IP addresses into domains in the reverse
1331 DNS. This code also deals with address literals and $sender_host_address. It's
1332 not quite kosher to treat bare domains such as EHLO 192.0.2.57 the same as
1333 address literals, but it's probably the most friendly thing to do. This is an
1334 extension to CSA, so we allow it to be turned off for proper conformance. */
1336 if (string_is_ip_address(domain, NULL) != 0)
1338 if (!dns_csa_use_reverse) return CSA_UNKNOWN;
1339 dns_build_reverse(domain, target);
1343 /* Find out if we've already done the CSA check for this domain. If we have,
1344 return the same result again. Otherwise build a new cached result structure
1345 for this domain. The name is filled in now, and the value is filled in when
1346 we return from this function. */
1348 t = tree_search(csa_cache, domain);
1349 if (t != NULL) return t->data.val;
1351 t = store_get_perm(sizeof(tree_node) + Ustrlen(domain));
1352 Ustrcpy(t->name, domain);
1353 (void)tree_insertnode(&csa_cache, t);
1355 /* Now we are ready to do the actual DNS lookup(s). */
1358 switch (dns_special_lookup(&dnsa, domain, T_CSA, &found))
1360 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1363 return t->data.val = CSA_DEFER_SRV;
1365 /* If we found nothing, the client's authorization is unknown. */
1369 return t->data.val = CSA_UNKNOWN;
1371 /* We got something! Go on to look at the reply in more detail. */
1377 /* Scan the reply for well-formed CSA SRV records. */
1379 for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
1381 rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
1383 if (rr->type != T_SRV) continue;
1385 /* Extract the numerical SRV fields (p is incremented) */
1388 GETSHORT(priority, p);
1389 GETSHORT(weight, p);
1393 debug_printf("CSA priority=%d weight=%d port=%d\n", priority, weight, port);
1395 /* Check the CSA version number */
1397 if (priority != 1) continue;
1399 /* If the domain does not have a CSA SRV record of its own (i.e. the domain
1400 found by dns_special_lookup() is a parent of the one we asked for), we check
1401 the subdomain assertions in the port field. At the moment there's only one
1402 assertion: legitimate SMTP clients are all explicitly authorized with CSA
1403 SRV records of their own. */
1405 if (found != domain)
1408 return t->data.val = CSA_FAIL_EXPLICIT;
1410 return t->data.val = CSA_UNKNOWN;
1413 /* This CSA SRV record refers directly to our domain, so we check the value
1414 in the weight field to work out the domain's authorization. 0 and 1 are
1415 unauthorized; 3 means the client is authorized but we can't check the IP
1416 address in order to authenticate it, so we treat it as unknown; values
1417 greater than 3 are undefined. */
1419 if (weight < 2) return t->data.val = CSA_FAIL_DOMAIN;
1421 if (weight > 2) continue;
1423 /* Weight == 2, which means the domain is authorized. We must check that the
1424 client's IP address is listed as one of the SRV target addresses. Save the
1425 target hostname then break to scan the additional data for its addresses. */
1427 (void)dn_expand(dnsa.answer, dnsa.answer + dnsa.answerlen, p,
1428 (DN_EXPAND_ARG4_TYPE)target, sizeof(target));
1430 DEBUG(D_acl) debug_printf("CSA target is %s\n", target);
1435 /* If we didn't break the loop then no appropriate records were found. */
1437 if (rr == NULL) return t->data.val = CSA_UNKNOWN;
1439 /* Do not check addresses if the target is ".", in accordance with RFC 2782.
1440 A target of "." indicates there are no valid addresses, so the client cannot
1441 be authorized. (This is an odd configuration because weight=2 target=. is
1442 equivalent to weight=1, but we check for it in order to keep load off the
1443 root name servers.) Note that dn_expand() turns "." into "". */
1445 if (Ustrcmp(target, "") == 0) return t->data.val = CSA_FAIL_NOADDR;
1447 /* Scan the additional section of the CSA SRV reply for addresses belonging
1448 to the target. If the name server didn't return any additional data (e.g.
1449 because it does not fully support SRV records), we need to do another lookup
1450 to obtain the target addresses; otherwise we have a definitive result. */
1452 rc = acl_verify_csa_address(&dnsa, &dnss, RESET_ADDITIONAL, target);
1453 if (rc != CSA_FAIL_NOADDR) return t->data.val = rc;
1455 /* The DNS lookup type corresponds to the IP version used by the client. */
1458 if (Ustrchr(sender_host_address, ':') != NULL)
1461 #endif /* HAVE_IPV6 */
1465 #if HAVE_IPV6 && defined(SUPPORT_A6)
1469 switch (dns_lookup(&dnsa, target, type, NULL))
1471 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1474 return t->data.val = CSA_DEFER_ADDR;
1476 /* If the query succeeded, scan the addresses and return the result. */
1479 rc = acl_verify_csa_address(&dnsa, &dnss, RESET_ANSWERS, target);
1480 if (rc != CSA_FAIL_NOADDR) return t->data.val = rc;
1481 /* else fall through */
1483 /* If the target has no IP addresses, the client cannot have an authorized
1484 IP address. However, if the target site uses A6 records (not AAAA records)
1485 we have to do yet another lookup in order to check them. */
1490 #if HAVE_IPV6 && defined(SUPPORT_A6)
1491 if (type == T_AAAA) { type = T_A6; goto DNS_LOOKUP_AGAIN; }
1494 return t->data.val = CSA_FAIL_NOADDR;
1500 /*************************************************
1501 * Handle verification (address & other) *
1502 *************************************************/
1504 /* This function implements the "verify" condition. It is called when
1505 encountered in any ACL, because some tests are almost always permitted. Some
1506 just don't make sense, and always fail (for example, an attempt to test a host
1507 lookup for a non-TCP/IP message). Others are restricted to certain ACLs.
1510 where where called from
1511 addr the recipient address that the ACL is handling, or NULL
1512 arg the argument of "verify"
1513 user_msgptr pointer for user message
1514 log_msgptr pointer for log message
1515 basic_errno where to put verify errno
1517 Returns: OK verification condition succeeded
1518 FAIL verification failed
1519 DEFER there was a problem verifying
1524 acl_verify(int where, address_item *addr, uschar *arg,
1525 uschar **user_msgptr, uschar **log_msgptr, int *basic_errno)
1529 int callout_overall = -1;
1530 int callout_connect = -1;
1531 int verify_options = 0;
1533 BOOL verify_header_sender = FALSE;
1534 BOOL defer_ok = FALSE;
1535 BOOL callout_defer_ok = FALSE;
1536 BOOL no_details = FALSE;
1537 BOOL success_on_redirect = FALSE;
1538 address_item *sender_vaddr = NULL;
1539 uschar *verify_sender_address = NULL;
1540 uschar *pm_mailfrom = NULL;
1541 uschar *se_mailfrom = NULL;
1543 /* Some of the verify items have slash-separated options; some do not. Diagnose
1544 an error if options are given for items that don't expect them. This code has
1545 now got very message. Refactoring to use a table would be a good idea one day.
1548 uschar *slash = Ustrchr(arg, '/');
1550 uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);
1552 if (ss == NULL) goto BAD_VERIFY;
1554 /* Handle name/address consistency verification in a separate function. */
1556 if (strcmpic(ss, US"reverse_host_lookup") == 0)
1558 if (slash != NULL) goto NO_OPTIONS;
1559 if (sender_host_address == NULL) return OK;
1560 return acl_verify_reverse(user_msgptr, log_msgptr);
1563 /* TLS certificate verification is done at STARTTLS time; here we just
1564 test whether it was successful or not. (This is for optional verification; for
1565 mandatory verification, the connection doesn't last this long.) */
1567 if (strcmpic(ss, US"certificate") == 0)
1569 if (slash != NULL) goto NO_OPTIONS;
1570 if (tls_certificate_verified) return OK;
1571 *user_msgptr = US"no verified certificate";
1575 /* We can test the result of optional HELO verification that might have
1576 occurred earlier. If not, we can attempt the verification now. */
1578 if (strcmpic(ss, US"helo") == 0)
1580 if (slash != NULL) goto NO_OPTIONS;
1581 if (!helo_verified && !helo_verify_failed) smtp_verify_helo();
1582 return helo_verified? OK : FAIL;
1585 /* Do Client SMTP Authorization checks in a separate function, and turn the
1586 result code into user-friendly strings. */
1588 if (strcmpic(ss, US"csa") == 0)
1590 rc = acl_verify_csa(list);
1591 *log_msgptr = *user_msgptr = string_sprintf("client SMTP authorization %s",
1592 csa_reason_string[rc]);
1593 csa_status = csa_status_string[rc];
1594 DEBUG(D_acl) debug_printf("CSA result %s\n", csa_status);
1595 return csa_return_code[rc];
1598 /* Check that all relevant header lines have the correct syntax. If there is
1599 a syntax error, we return details of the error to the sender if configured to
1600 send out full details. (But a "message" setting on the ACL can override, as
1603 if (strcmpic(ss, US"header_syntax") == 0)
1605 if (slash != NULL) goto NO_OPTIONS;
1606 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1607 rc = verify_check_headers(log_msgptr);
1608 if (rc != OK && smtp_return_error_details && *log_msgptr != NULL)
1609 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1613 /* Check that no recipient of this message is "blind", that is, every envelope
1614 recipient must be mentioned in either To: or Cc:. */
1616 if (strcmpic(ss, US"not_blind") == 0)
1618 if (slash != NULL) goto NO_OPTIONS;
1619 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1620 rc = verify_check_notblind();
1623 *log_msgptr = string_sprintf("bcc recipient detected");
1624 if (smtp_return_error_details)
1625 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1630 /* The remaining verification tests check recipient and sender addresses,
1631 either from the envelope or from the header. There are a number of
1632 slash-separated options that are common to all of them. */
1635 /* Check that there is at least one verifiable sender address in the relevant
1636 header lines. This can be followed by callout and defer options, just like
1637 sender and recipient. */
1639 if (strcmpic(ss, US"header_sender") == 0)
1641 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1642 verify_header_sender = TRUE;
1645 /* Otherwise, first item in verify argument must be "sender" or "recipient".
1646 In the case of a sender, this can optionally be followed by an address to use
1647 in place of the actual sender (rare special-case requirement). */
1649 else if (strncmpic(ss, US"sender", 6) == 0)
1652 if (where > ACL_WHERE_NOTSMTP)
1654 *log_msgptr = string_sprintf("cannot verify sender in ACL for %s "
1655 "(only possible for MAIL, RCPT, PREDATA, or DATA)",
1656 acl_wherenames[where]);
1660 verify_sender_address = sender_address;
1663 while (isspace(*s)) s++;
1664 if (*s++ != '=') goto BAD_VERIFY;
1665 while (isspace(*s)) s++;
1666 verify_sender_address = string_copy(s);
1671 if (strcmpic(ss, US"recipient") != 0) goto BAD_VERIFY;
1674 *log_msgptr = string_sprintf("cannot verify recipient in ACL for %s "
1675 "(only possible for RCPT)", acl_wherenames[where]);
1680 /* Remaining items are optional; they apply to sender and recipient
1681 verification, including "header sender" verification. */
1683 while ((ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))
1686 if (strcmpic(ss, US"defer_ok") == 0) defer_ok = TRUE;
1687 else if (strcmpic(ss, US"no_details") == 0) no_details = TRUE;
1688 else if (strcmpic(ss, US"success_on_redirect") == 0) success_on_redirect = TRUE;
1690 /* These two old options are left for backwards compatibility */
1692 else if (strcmpic(ss, US"callout_defer_ok") == 0)
1694 callout_defer_ok = TRUE;
1695 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1698 else if (strcmpic(ss, US"check_postmaster") == 0)
1701 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1704 /* The callout option has a number of sub-options, comma separated */
1706 else if (strncmpic(ss, US"callout", 7) == 0)
1708 callout = CALLOUT_TIMEOUT_DEFAULT;
1712 while (isspace(*ss)) ss++;
1718 while (isspace(*ss)) ss++;
1720 /* This callout option handling code has become a mess as new options
1721 have been added in an ad hoc manner. It should be tidied up into some
1722 kind of table-driven thing. */
1724 while ((opt = string_nextinlist(&ss, &optsep, buffer, sizeof(buffer)))
1727 if (strcmpic(opt, US"defer_ok") == 0) callout_defer_ok = TRUE;
1728 else if (strcmpic(opt, US"no_cache") == 0)
1729 verify_options |= vopt_callout_no_cache;
1730 else if (strcmpic(opt, US"random") == 0)
1731 verify_options |= vopt_callout_random;
1732 else if (strcmpic(opt, US"use_sender") == 0)
1733 verify_options |= vopt_callout_recipsender;
1734 else if (strcmpic(opt, US"use_postmaster") == 0)
1735 verify_options |= vopt_callout_recippmaster;
1736 else if (strcmpic(opt, US"postmaster") == 0) pm_mailfrom = US"";
1737 else if (strcmpic(opt, US"fullpostmaster") == 0)
1740 verify_options |= vopt_callout_fullpm;
1743 else if (strncmpic(opt, US"mailfrom", 8) == 0)
1745 if (!verify_header_sender)
1747 *log_msgptr = string_sprintf("\"mailfrom\" is allowed as a "
1748 "callout option only for verify=header_sender (detected in ACL "
1749 "condition \"%s\")", arg);
1753 while (isspace(*opt)) opt++;
1756 *log_msgptr = string_sprintf("'=' expected after "
1757 "\"mailfrom\" in ACL condition \"%s\"", arg);
1760 while (isspace(*opt)) opt++;
1761 se_mailfrom = string_copy(opt);
1764 else if (strncmpic(opt, US"postmaster_mailfrom", 19) == 0)
1767 while (isspace(*opt)) opt++;
1770 *log_msgptr = string_sprintf("'=' expected after "
1771 "\"postmaster_mailfrom\" in ACL condition \"%s\"", arg);
1774 while (isspace(*opt)) opt++;
1775 pm_mailfrom = string_copy(opt);
1778 else if (strncmpic(opt, US"maxwait", 7) == 0)
1781 while (isspace(*opt)) opt++;
1784 *log_msgptr = string_sprintf("'=' expected after \"maxwait\" in "
1785 "ACL condition \"%s\"", arg);
1788 while (isspace(*opt)) opt++;
1789 callout_overall = readconf_readtime(opt, 0, FALSE);
1790 if (callout_overall < 0)
1792 *log_msgptr = string_sprintf("bad time value in ACL condition "
1793 "\"verify %s\"", arg);
1797 else if (strncmpic(opt, US"connect", 7) == 0)
1800 while (isspace(*opt)) opt++;
1803 *log_msgptr = string_sprintf("'=' expected after "
1804 "\"callout_overaall\" in ACL condition \"%s\"", arg);
1807 while (isspace(*opt)) opt++;
1808 callout_connect = readconf_readtime(opt, 0, FALSE);
1809 if (callout_connect < 0)
1811 *log_msgptr = string_sprintf("bad time value in ACL condition "
1812 "\"verify %s\"", arg);
1816 else /* Plain time is callout connect/command timeout */
1818 callout = readconf_readtime(opt, 0, FALSE);
1821 *log_msgptr = string_sprintf("bad time value in ACL condition "
1822 "\"verify %s\"", arg);
1830 *log_msgptr = string_sprintf("'=' expected after \"callout\" in "
1831 "ACL condition \"%s\"", arg);
1837 /* Option not recognized */
1841 *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1842 "condition \"verify %s\"", ss, arg);
1847 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)) ==
1848 (vopt_callout_recipsender|vopt_callout_recippmaster))
1850 *log_msgptr = US"only one of use_sender and use_postmaster can be set "
1851 "for a recipient callout";
1855 /* Handle sender-in-header verification. Default the user message to the log
1856 message if giving out verification details. */
1858 if (verify_header_sender)
1861 rc = verify_check_header_address(user_msgptr, log_msgptr, callout,
1862 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, verify_options,
1866 *basic_errno = verrno;
1867 if (smtp_return_error_details)
1869 if (*user_msgptr == NULL && *log_msgptr != NULL)
1870 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1871 if (rc == DEFER) acl_temp_details = TRUE;
1876 /* Handle a sender address. The default is to verify *the* sender address, but
1877 optionally a different address can be given, for special requirements. If the
1878 address is empty, we are dealing with a bounce message that has no sender, so
1879 we cannot do any checking. If the real sender address gets rewritten during
1880 verification (e.g. DNS widening), set the flag to stop it being rewritten again
1881 during message reception.
1883 A list of verified "sender" addresses is kept to try to avoid doing to much
1884 work repetitively when there are multiple recipients in a message and they all
1885 require sender verification. However, when callouts are involved, it gets too
1886 complicated because different recipients may require different callout options.
1887 Therefore, we always do a full sender verify when any kind of callout is
1888 specified. Caching elsewhere, for instance in the DNS resolver and in the
1889 callout handling, should ensure that this is not terribly inefficient. */
1891 else if (verify_sender_address != NULL)
1893 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster))
1896 *log_msgptr = US"use_sender or use_postmaster cannot be used for a "
1897 "sender verify callout";
1901 sender_vaddr = verify_checked_sender(verify_sender_address);
1902 if (sender_vaddr != NULL && /* Previously checked */
1903 callout <= 0) /* No callout needed this time */
1905 /* If the "routed" flag is set, it means that routing worked before, so
1906 this check can give OK (the saved return code value, if set, belongs to a
1907 callout that was done previously). If the "routed" flag is not set, routing
1908 must have failed, so we use the saved return code. */
1910 if (testflag(sender_vaddr, af_verify_routed)) rc = OK; else
1912 rc = sender_vaddr->special_action;
1913 *basic_errno = sender_vaddr->basic_errno;
1915 HDEBUG(D_acl) debug_printf("using cached sender verify result\n");
1918 /* Do a new verification, and cache the result. The cache is used to avoid
1919 verifying the sender multiple times for multiple RCPTs when callouts are not
1920 specified (see comments above).
1922 The cache is also used on failure to give details in response to the first
1923 RCPT that gets bounced for this reason. However, this can be suppressed by
1924 the no_details option, which sets the flag that says "this detail has already
1925 been sent". The cache normally contains just one address, but there may be
1926 more in esoteric circumstances. */
1931 uschar *save_address_data = deliver_address_data;
1933 sender_vaddr = deliver_make_addr(verify_sender_address, TRUE);
1934 if (no_details) setflag(sender_vaddr, af_sverify_told);
1935 if (verify_sender_address[0] != 0)
1937 /* If this is the real sender address, save the unrewritten version
1938 for use later in receive. Otherwise, set a flag so that rewriting the
1939 sender in verify_address() does not update sender_address. */
1941 if (verify_sender_address == sender_address)
1942 sender_address_unrewritten = sender_address;
1944 verify_options |= vopt_fake_sender;
1946 if (success_on_redirect)
1947 verify_options |= vopt_success_on_redirect;
1949 /* The recipient, qualify, and expn options are never set in
1952 rc = verify_address(sender_vaddr, NULL, verify_options, callout,
1953 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, &routed);
1955 HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1959 if (Ustrcmp(sender_vaddr->address, verify_sender_address) != 0)
1961 DEBUG(D_acl) debug_printf("sender %s verified ok as %s\n",
1962 verify_sender_address, sender_vaddr->address);
1966 DEBUG(D_acl) debug_printf("sender %s verified ok\n",
1967 verify_sender_address);
1970 else *basic_errno = sender_vaddr->basic_errno;
1972 else rc = OK; /* Null sender */
1974 /* Cache the result code */
1976 if (routed) setflag(sender_vaddr, af_verify_routed);
1977 if (callout > 0) setflag(sender_vaddr, af_verify_callout);
1978 sender_vaddr->special_action = rc;
1979 sender_vaddr->next = sender_verified_list;
1980 sender_verified_list = sender_vaddr;
1982 /* Restore the recipient address data, which might have been clobbered by
1983 the sender verification. */
1985 deliver_address_data = save_address_data;
1988 /* Put the sender address_data value into $sender_address_data */
1990 sender_address_data = sender_vaddr->p.address_data;
1993 /* A recipient address just gets a straightforward verify; again we must handle
1994 the DEFER overrides. */
2000 if (success_on_redirect)
2001 verify_options |= vopt_success_on_redirect;
2003 /* We must use a copy of the address for verification, because it might
2007 rc = verify_address(&addr2, NULL, verify_options|vopt_is_recipient, callout,
2008 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, NULL);
2009 HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
2011 *basic_errno = addr2.basic_errno;
2012 *log_msgptr = addr2.message;
2013 *user_msgptr = (addr2.user_message != NULL)?
2014 addr2.user_message : addr2.message;
2016 /* Allow details for temporary error if the address is so flagged. */
2017 if (testflag((&addr2), af_pass_message)) acl_temp_details = TRUE;
2019 /* Make $address_data visible */
2020 deliver_address_data = addr2.p.address_data;
2023 /* We have a result from the relevant test. Handle defer overrides first. */
2025 if (rc == DEFER && (defer_ok ||
2026 (callout_defer_ok && *basic_errno == ERRNO_CALLOUTDEFER)))
2028 HDEBUG(D_acl) debug_printf("verify defer overridden by %s\n",
2029 defer_ok? "defer_ok" : "callout_defer_ok");
2033 /* If we've failed a sender, set up a recipient message, and point
2034 sender_verified_failed to the address item that actually failed. */
2036 if (rc != OK && verify_sender_address != NULL)
2040 *log_msgptr = *user_msgptr = US"Sender verify failed";
2042 else if (*basic_errno != ERRNO_CALLOUTDEFER)
2044 *log_msgptr = *user_msgptr = US"Could not complete sender verify";
2048 *log_msgptr = US"Could not complete sender verify callout";
2049 *user_msgptr = smtp_return_error_details? sender_vaddr->user_message :
2053 sender_verified_failed = sender_vaddr;
2056 /* Verifying an address messes up the values of $domain and $local_part,
2057 so reset them before returning if this is a RCPT ACL. */
2061 deliver_domain = addr->domain;
2062 deliver_localpart = addr->local_part;
2066 /* Syntax errors in the verify argument come here. */
2069 *log_msgptr = string_sprintf("expected \"sender[=address]\", \"recipient\", "
2070 "\"helo\", \"header_syntax\", \"header_sender\" or "
2071 "\"reverse_host_lookup\" at start of ACL condition "
2072 "\"verify %s\"", arg);
2075 /* Options supplied when not allowed come here */
2078 *log_msgptr = string_sprintf("unexpected '/' found in \"%s\" "
2079 "(this verify item has no options)", arg);
2082 /* Calls in the wrong ACL come here */
2085 *log_msgptr = string_sprintf("cannot check header contents in ACL for %s "
2086 "(only possible in ACL for DATA)", acl_wherenames[where]);
2093 /*************************************************
2094 * Check argument for control= modifier *
2095 *************************************************/
2097 /* Called from acl_check_condition() below
2100 arg the argument string for control=
2101 pptr set to point to the terminating character
2102 where which ACL we are in
2103 log_msgptr for error messages
2105 Returns: CONTROL_xxx value
2109 decode_control(uschar *arg, uschar **pptr, int where, uschar **log_msgptr)
2114 for (d = controls_list;
2115 d < controls_list + sizeof(controls_list)/sizeof(control_def);
2118 len = Ustrlen(d->name);
2119 if (Ustrncmp(d->name, arg, len) == 0) break;
2122 if (d >= controls_list + sizeof(controls_list)/sizeof(control_def) ||
2123 (arg[len] != 0 && (!d->has_option || arg[len] != '/')))
2125 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2126 return CONTROL_ERROR;
2135 /*************************************************
2136 * Handle rate limiting *
2137 *************************************************/
2139 /* Called by acl_check_condition() below to calculate the result
2140 of the ACL ratelimit condition.
2142 Note that the return value might be slightly unexpected: if the
2143 sender's rate is above the limit then the result is OK. This is
2144 similar to the dnslists condition, and is so that you can write
2145 ACL clauses like: defer ratelimit = 15 / 1h
2148 arg the option string for ratelimit=
2149 where ACL_WHERE_xxxx indicating which ACL this is
2150 log_msgptr for error messages
2152 Returns: OK - Sender's rate is above limit
2153 FAIL - Sender's rate is below limit
2154 DEFER - Problem opening ratelimit database
2155 ERROR - Syntax error in options.
2159 acl_ratelimit(uschar *arg, int where, uschar **log_msgptr)
2161 double limit, period;
2165 BOOL leaky = FALSE, strict = FALSE, noupdate = FALSE;
2166 BOOL per_byte = FALSE, per_cmd = FALSE, per_conn = FALSE, per_mail = FALSE;
2168 tree_node **anchor, *t;
2169 open_db dbblock, *dbm;
2170 dbdata_ratelimit *dbd;
2173 /* Parse the first two options and record their values in expansion
2174 variables. These variables allow the configuration to have informative
2175 error messages based on rate limits obtained from a table lookup. */
2177 /* First is the maximum number of messages per period and maximum burst
2178 size, which must be greater than or equal to zero. Zero is useful for
2179 rate measurement as opposed to rate limiting. */
2181 sender_rate_limit = string_nextinlist(&arg, &sep, NULL, 0);
2182 if (sender_rate_limit == NULL)
2186 limit = Ustrtod(sender_rate_limit, &ss);
2187 if (tolower(*ss) == 'k') { limit *= 1024.0; ss++; }
2188 else if (tolower(*ss) == 'm') { limit *= 1024.0*1024.0; ss++; }
2189 else if (tolower(*ss) == 'g') { limit *= 1024.0*1024.0*1024.0; ss++; }
2191 if (limit < 0.0 || *ss != 0)
2193 *log_msgptr = string_sprintf("syntax error in argument for "
2194 "\"ratelimit\" condition: \"%s\" is not a positive number",
2199 /* Second is the rate measurement period and exponential smoothing time
2200 constant. This must be strictly greater than zero, because zero leads to
2201 run-time division errors. */
2203 sender_rate_period = string_nextinlist(&arg, &sep, NULL, 0);
2204 if (sender_rate_period == NULL) period = -1.0;
2205 else period = readconf_readtime(sender_rate_period, 0, FALSE);
2208 *log_msgptr = string_sprintf("syntax error in argument for "
2209 "\"ratelimit\" condition: \"%s\" is not a time value",
2210 sender_rate_period);
2214 /* Parse the other options. Should we check if the per_* options are being
2215 used in ACLs where they don't make sense, e.g. per_mail in the connect ACL? */
2217 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
2220 if (strcmpic(ss, US"leaky") == 0) leaky = TRUE;
2221 else if (strcmpic(ss, US"strict") == 0) strict = TRUE;
2222 else if (strcmpic(ss, US"noupdate") == 0) noupdate = TRUE;
2223 else if (strcmpic(ss, US"per_byte") == 0) per_byte = TRUE;
2224 else if (strcmpic(ss, US"per_cmd") == 0) per_cmd = TRUE;
2225 else if (strcmpic(ss, US"per_rcpt") == 0) per_cmd = TRUE; /* alias */
2226 else if (strcmpic(ss, US"per_conn") == 0) per_conn = TRUE;
2227 else if (strcmpic(ss, US"per_mail") == 0) per_mail = TRUE;
2228 else key = string_sprintf("%s", ss);
2231 if (leaky + strict > 1 || per_byte + per_cmd + per_conn + per_mail > 1)
2233 *log_msgptr = US"conflicting options for \"ratelimit\" condition";
2237 /* Default option values */
2239 if (!strict) leaky = TRUE;
2240 if (!per_byte && !per_cmd && !per_conn) per_mail = TRUE;
2242 /* Create the lookup key. If there is no explicit key, use sender_host_address.
2243 If there is no sender_host_address (e.g. -bs or acl_not_smtp) then we simply
2244 omit it. The smoothing constant (sender_rate_period) and the per_xxx options
2245 are added to the key because they alter the meaning of the stored data. */
2248 key = (sender_host_address == NULL)? US"" : sender_host_address;
2250 key = string_sprintf("%s/%s/%s/%s",
2252 per_byte? US"per_byte" :
2253 per_cmd? US"per_cmd" :
2254 per_mail? US"per_mail" : US"per_conn",
2255 strict? US"strict" : US"leaky",
2258 HDEBUG(D_acl) debug_printf("ratelimit condition limit=%.0f period=%.0f key=%s\n",
2259 limit, period, key);
2261 /* See if we have already computed the rate by looking in the relevant tree.
2262 For per-connection rate limiting, store tree nodes and dbdata in the permanent
2263 pool so that they survive across resets. */
2266 old_pool = store_pool;
2270 anchor = &ratelimiters_conn;
2271 store_pool = POOL_PERM;
2273 else if (per_mail || per_byte)
2274 anchor = &ratelimiters_mail;
2276 anchor = &ratelimiters_cmd;
2278 if (anchor != NULL && (t = tree_search(*anchor, key)) != NULL)
2281 /* The following few lines duplicate some of the code below. */
2282 rc = (dbd->rate < limit)? FAIL : OK;
2283 store_pool = old_pool;
2284 sender_rate = string_sprintf("%.1f", dbd->rate);
2286 debug_printf("ratelimit found pre-computed rate %s\n", sender_rate);
2290 /* We aren't using a pre-computed rate, so get a previously recorded
2291 rate from the database, update it, and write it back when required. If there's
2292 no previous rate for this key, create one. */
2294 dbm = dbfn_open(US"ratelimit", O_RDWR, &dbblock, TRUE);
2297 store_pool = old_pool;
2299 HDEBUG(D_acl) debug_printf("ratelimit database not available\n");
2300 *log_msgptr = US"ratelimit database not available";
2303 dbd = dbfn_read(dbm, key);
2305 gettimeofday(&tv, NULL);
2309 HDEBUG(D_acl) debug_printf("ratelimit initializing new key's data\n");
2310 dbd = store_get(sizeof(dbdata_ratelimit));
2311 dbd->time_stamp = tv.tv_sec;
2312 dbd->time_usec = tv.tv_usec;
2317 /* The smoothed rate is computed using an exponentially weighted moving
2318 average adjusted for variable sampling intervals. The standard EWMA for
2319 a fixed sampling interval is: f'(t) = (1 - a) * f(t) + a * f'(t - 1)
2320 where f() is the measured value and f'() is the smoothed value.
2322 Old data decays out of the smoothed value exponentially, such that data n
2323 samples old is multiplied by a^n. The exponential decay time constant p
2324 is defined such that data p samples old is multiplied by 1/e, which means
2325 that a = exp(-1/p). We can maintain the same time constant for a variable
2326 sampling interval i by using a = exp(-i/p).
2328 The rate we are measuring is messages per period, suitable for directly
2329 comparing with the limit. The average rate between now and the previous
2330 message is period / interval, which we feed into the EWMA as the sample.
2332 It turns out that the number of messages required for the smoothed rate
2333 to reach the limit when they are sent in a burst is equal to the limit.
2334 This can be seen by analysing the value of the smoothed rate after N
2335 messages sent at even intervals. Let k = (1 - a) * p/i
2337 rate_1 = (1 - a) * p/i + a * rate_0
2339 rate_2 = k + a * rate_1
2340 = k + a * k + a^2 * rate_0
2341 rate_3 = k + a * k + a^2 * k + a^3 * rate_0
2342 rate_N = rate_0 * a^N + k * SUM(x=0..N-1)(a^x)
2343 = rate_0 * a^N + k * (1 - a^N) / (1 - a)
2344 = rate_0 * a^N + p/i * (1 - a^N)
2346 When N is large, a^N -> 0 so rate_N -> p/i as desired.
2348 rate_N = p/i + (rate_0 - p/i) * a^N
2349 a^N = (rate_N - p/i) / (rate_0 - p/i)
2350 N * -i/p = log((rate_N - p/i) / (rate_0 - p/i))
2351 N = p/i * log((rate_0 - p/i) / (rate_N - p/i))
2353 Numerical analysis of the above equation, setting the computed rate to
2354 increase from rate_0 = 0 to rate_N = limit, shows that for large sending
2355 rates, p/i, the number of messages N = limit. So limit serves as both the
2356 maximum rate measured in messages per period, and the maximum number of
2357 messages that can be sent in a fast burst. */
2359 double this_time = (double)tv.tv_sec
2360 + (double)tv.tv_usec / 1000000.0;
2361 double prev_time = (double)dbd->time_stamp
2362 + (double)dbd->time_usec / 1000000.0;
2364 /* We must avoid division by zero, and deal gracefully with the clock going
2365 backwards. If we blunder ahead when time is in reverse then the computed
2366 rate will be bogus. To be safe we clamp interval to a very small number. */
2368 double interval = this_time - prev_time <= 0.0 ? 1e-9
2369 : this_time - prev_time;
2371 double i_over_p = interval / period;
2372 double a = exp(-i_over_p);
2374 dbd->time_stamp = tv.tv_sec;
2375 dbd->time_usec = tv.tv_usec;
2377 /* If we are measuring the rate in bytes per period, multiply the
2378 measured rate by the message size. If we don't know the message size
2379 then it's safe to just use a value of zero and let the recorded rate
2380 decay as if nothing happened. */
2383 dbd->rate = (message_size < 0 ? 0.0 : (double)message_size)
2384 * (1 - a) / i_over_p + a * dbd->rate;
2385 else if (per_cmd && where == ACL_WHERE_NOTSMTP)
2386 dbd->rate = (double)recipients_count
2387 * (1 - a) / i_over_p + a * dbd->rate;
2389 dbd->rate = (1 - a) / i_over_p + a * dbd->rate;
2392 /* Clients sending at the limit are considered to be over the limit. This
2393 matters for edge cases such the first message sent by a client (which gets
2394 the initial rate of 0.0) when the rate limit is zero (i.e. the client should
2395 be completely blocked). */
2397 rc = (dbd->rate < limit)? FAIL : OK;
2399 /* Update the state if the rate is low or if we are being strict. If we
2400 are in leaky mode and the sender's rate is too high, we do not update
2401 the recorded rate in order to avoid an over-aggressive sender's retry
2402 rate preventing them from getting any email through. If noupdate is set,
2403 do not do any updates. */
2405 if ((rc == FAIL || !leaky) && !noupdate)
2407 dbfn_write(dbm, key, dbd, sizeof(dbdata_ratelimit));
2408 HDEBUG(D_acl) debug_printf("ratelimit db updated\n");
2412 HDEBUG(D_acl) debug_printf("ratelimit db not updated: %s\n",
2413 noupdate? "noupdate set" : "over the limit, but leaky");
2418 /* Store the result in the tree for future reference, if necessary. */
2420 if (anchor != NULL && !noupdate)
2422 t = store_get(sizeof(tree_node) + Ustrlen(key));
2424 Ustrcpy(t->name, key);
2425 (void)tree_insertnode(anchor, t);
2428 /* We create the formatted version of the sender's rate very late in
2429 order to ensure that it is done using the correct storage pool. */
2431 store_pool = old_pool;
2432 sender_rate = string_sprintf("%.1f", dbd->rate);
2435 debug_printf("ratelimit computed rate %s\n", sender_rate);
2442 /*************************************************
2443 * Handle conditions/modifiers on an ACL item *
2444 *************************************************/
2446 /* Called from acl_check() below.
2450 cb ACL condition block - if NULL, result is OK
2451 where where called from
2452 addr the address being checked for RCPT, or NULL
2453 level the nesting level
2454 epp pointer to pass back TRUE if "endpass" encountered
2455 (applies only to "accept" and "discard")
2456 user_msgptr user message pointer
2457 log_msgptr log message pointer
2458 basic_errno pointer to where to put verify error
2460 Returns: OK - all conditions are met
2461 DISCARD - an "acl" condition returned DISCARD - only allowed
2462 for "accept" or "discard" verbs
2463 FAIL - at least one condition fails
2464 FAIL_DROP - an "acl" condition returned FAIL_DROP
2465 DEFER - can't tell at the moment (typically, lookup defer,
2466 but can be temporary callout problem)
2467 ERROR - ERROR from nested ACL or expansion failure or other
2472 acl_check_condition(int verb, acl_condition_block *cb, int where,
2473 address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
2474 uschar **log_msgptr, int *basic_errno)
2476 uschar *user_message = NULL;
2477 uschar *log_message = NULL;
2480 #ifdef WITH_CONTENT_SCAN
2484 for (; cb != NULL; cb = cb->next)
2489 /* The message and log_message items set up messages to be used in
2490 case of rejection. They are expanded later. */
2492 if (cb->type == ACLC_MESSAGE)
2494 user_message = cb->arg;
2498 if (cb->type == ACLC_LOG_MESSAGE)
2500 log_message = cb->arg;
2504 /* The endpass "condition" just sets a flag to show it occurred. This is
2505 checked at compile time to be on an "accept" or "discard" item. */
2507 if (cb->type == ACLC_ENDPASS)
2513 /* For other conditions and modifiers, the argument is expanded now for some
2514 of them, but not for all, because expansion happens down in some lower level
2515 checking functions in some cases. */
2517 if (cond_expand_at_top[cb->type])
2519 arg = expand_string(cb->arg);
2522 if (expand_string_forcedfail) continue;
2523 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
2524 cb->arg, expand_string_message);
2525 return search_find_defer? DEFER : ERROR;
2530 /* Show condition, and expanded condition if it's different */
2535 debug_printf("check %s%s %n",
2536 (!cond_modifiers[cb->type] && cb->u.negated)? "!":"",
2537 conditions[cb->type], &lhswidth);
2539 if (cb->type == ACLC_SET)
2541 debug_printf("acl_%s ", cb->u.varname);
2542 lhswidth += 5 + Ustrlen(cb->u.varname);
2545 debug_printf("= %s\n", cb->arg);
2548 debug_printf("%.*s= %s\n", lhswidth,
2552 /* Check that this condition makes sense at this time */
2554 if ((cond_forbids[cb->type] & (1 << where)) != 0)
2556 *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
2557 cond_modifiers[cb->type]? "use" : "test",
2558 conditions[cb->type], acl_wherenames[where]);
2562 /* Run the appropriate test for each condition, or take the appropriate
2563 action for the remaining modifiers. */
2567 case ACLC_ADD_HEADER:
2571 /* A nested ACL that returns "discard" makes sense only for an "accept" or
2575 rc = acl_check_internal(where, addr, arg, level+1, user_msgptr, log_msgptr);
2576 if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
2578 *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
2579 "\"%s\" command (only allowed with \"accept\" or \"discard\")",
2585 case ACLC_AUTHENTICATED:
2586 rc = (sender_host_authenticated == NULL)? FAIL :
2587 match_isinlist(sender_host_authenticated, &arg, 0, NULL, NULL, MCL_STRING,
2591 #ifdef EXPERIMENTAL_BRIGHTMAIL
2592 case ACLC_BMI_OPTIN:
2594 int old_pool = store_pool;
2595 store_pool = POOL_PERM;
2596 bmi_current_optin = string_copy(arg);
2597 store_pool = old_pool;
2602 case ACLC_CONDITION:
2603 if (Ustrspn(arg, "0123456789") == Ustrlen(arg)) /* Digits, or empty */
2604 rc = (Uatoi(arg) == 0)? FAIL : OK;
2606 rc = (strcmpic(arg, US"no") == 0 ||
2607 strcmpic(arg, US"false") == 0)? FAIL :
2608 (strcmpic(arg, US"yes") == 0 ||
2609 strcmpic(arg, US"true") == 0)? OK : DEFER;
2611 *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
2614 case ACLC_CONTINUE: /* Always succeeds */
2618 control_type = decode_control(arg, &p, where, log_msgptr);
2620 /* Check if this control makes sense at this time */
2622 if ((control_forbids[control_type] & (1 << where)) != 0)
2624 *log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
2625 controls[control_type], acl_wherenames[where]);
2629 switch(control_type)
2631 case CONTROL_AUTH_UNADVERTISED:
2632 allow_auth_unadvertised = TRUE;
2635 #ifdef EXPERIMENTAL_BRIGHTMAIL
2636 case CONTROL_BMI_RUN:
2641 #ifdef EXPERIMENTAL_DOMAINKEYS
2642 case CONTROL_DK_VERIFY:
2647 #ifdef EXPERIMENTAL_DKIM
2648 case CONTROL_DKIM_VERIFY:
2656 case CONTROL_CASEFUL_LOCAL_PART:
2657 deliver_localpart = addr->cc_local_part;
2660 case CONTROL_CASELOWER_LOCAL_PART:
2661 deliver_localpart = addr->lc_local_part;
2664 case CONTROL_ENFORCE_SYNC:
2665 smtp_enforce_sync = TRUE;
2668 case CONTROL_NO_ENFORCE_SYNC:
2669 smtp_enforce_sync = FALSE;
2672 #ifdef WITH_CONTENT_SCAN
2673 case CONTROL_NO_MBOX_UNSPOOL:
2674 no_mbox_unspool = TRUE;
2678 case CONTROL_NO_MULTILINE:
2679 no_multiline_responses = TRUE;
2682 case CONTROL_NO_PIPELINING:
2683 pipelining_enable = FALSE;
2686 case CONTROL_NO_DELAY_FLUSH:
2687 disable_delay_flush = TRUE;
2690 case CONTROL_NO_CALLOUT_FLUSH:
2691 disable_callout_flush = TRUE;
2694 case CONTROL_FAKEDEFER:
2695 case CONTROL_FAKEREJECT:
2696 fake_response = (control_type == CONTROL_FAKEDEFER) ? DEFER : FAIL;
2700 while (*pp != 0) pp++;
2701 fake_response_text = expand_string(string_copyn(p+1, pp-p-1));
2706 /* Explicitly reset to default string */
2707 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).";
2711 case CONTROL_FREEZE:
2712 deliver_freeze = TRUE;
2713 deliver_frozen_at = time(NULL);
2714 freeze_tell = freeze_tell_config; /* Reset to configured value */
2715 if (Ustrncmp(p, "/no_tell", 8) == 0)
2722 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2727 case CONTROL_QUEUE_ONLY:
2728 queue_only_policy = TRUE;
2731 case CONTROL_SUBMISSION:
2732 originator_name = US"";
2733 submission_mode = TRUE;
2736 if (Ustrncmp(p, "/sender_retain", 14) == 0)
2739 active_local_sender_retain = TRUE;
2740 active_local_from_check = FALSE;
2742 else if (Ustrncmp(p, "/domain=", 8) == 0)
2745 while (*pp != 0 && *pp != '/') pp++;
2746 submission_domain = string_copyn(p+8, pp-p-8);
2749 /* The name= option must be last, because it swallows the rest of
2751 else if (Ustrncmp(p, "/name=", 6) == 0)
2754 while (*pp != 0) pp++;
2755 submission_name = string_copy(parse_fix_phrase(p+6, pp-p-6,
2756 big_buffer, big_buffer_size));
2763 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2768 case CONTROL_SUPPRESS_LOCAL_FIXUPS:
2769 suppress_local_fixups = TRUE;
2774 #ifdef EXPERIMENTAL_DCC
2777 /* Seperate the regular expression and any optional parameters. */
2778 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
2779 /* Run the dcc backend. */
2780 rc = dcc_process(&ss);
2781 /* Modify return code based upon the existance of options. */
2782 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
2784 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
2786 /* FAIL so that the message is passed to the next ACL */
2794 #ifdef WITH_CONTENT_SCAN
2796 rc = mime_decode(&arg);
2802 int delay = readconf_readtime(arg, 0, FALSE);
2805 *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
2806 "modifier: \"%s\" is not a time value", arg);
2811 HDEBUG(D_acl) debug_printf("delay modifier requests %d-second delay\n",
2816 debug_printf("delay skipped in -bh checking mode\n");
2819 /* It appears to be impossible to detect that a TCP/IP connection has
2820 gone away without reading from it. This means that we cannot shorten
2821 the delay below if the client goes away, because we cannot discover
2822 that the client has closed its end of the connection. (The connection
2823 is actually in a half-closed state, waiting for the server to close its
2824 end.) It would be nice to be able to detect this state, so that the
2825 Exim process is not held up unnecessarily. However, it seems that we
2826 can't. The poll() function does not do the right thing, and in any case
2827 it is not always available.
2829 NOTE 1: If ever this state of affairs changes, remember that we may be
2830 dealing with stdin/stdout here, in addition to TCP/IP connections.
2831 Also, delays may be specified for non-SMTP input, where smtp_out and
2832 smtp_in will be NULL. Whatever is done must work in all cases.
2834 NOTE 2: The added feature of flushing the output before a delay must
2835 apply only to SMTP input. Hence the test for smtp_out being non-NULL.
2840 if (smtp_out != NULL && !disable_delay_flush) mac_smtp_fflush();
2841 while (delay > 0) delay = sleep(delay);
2847 #ifdef WITH_OLD_DEMIME
2853 #ifdef EXPERIMENTAL_DOMAINKEYS
2854 case ACLC_DK_DOMAIN_SOURCE:
2855 if (dk_verify_block == NULL) { rc = FAIL; break; };
2856 /* check header source of domain against given string */
2857 switch (dk_verify_block->address_source) {
2858 case DK_EXIM_ADDRESS_FROM_FROM:
2859 rc = match_isinlist(US"from", &arg, 0, NULL,
2860 NULL, MCL_STRING, TRUE, NULL);
2862 case DK_EXIM_ADDRESS_FROM_SENDER:
2863 rc = match_isinlist(US"sender", &arg, 0, NULL,
2864 NULL, MCL_STRING, TRUE, NULL);
2866 case DK_EXIM_ADDRESS_NONE:
2867 rc = match_isinlist(US"none", &arg, 0, NULL,
2868 NULL, MCL_STRING, TRUE, NULL);
2873 case ACLC_DK_POLICY:
2874 if (dk_verify_block == NULL) { rc = FAIL; break; };
2875 /* check policy against given string, default FAIL */
2877 if (dk_verify_block->signsall)
2878 rc = match_isinlist(US"signsall", &arg, 0, NULL,
2879 NULL, MCL_STRING, TRUE, NULL);
2880 if (dk_verify_block->testing)
2881 rc = match_isinlist(US"testing", &arg, 0, NULL,
2882 NULL, MCL_STRING, TRUE, NULL);
2885 case ACLC_DK_SENDER_DOMAINS:
2886 if (dk_verify_block == NULL) { rc = FAIL; break; };
2887 if (dk_verify_block->domain != NULL)
2888 rc = match_isinlist(dk_verify_block->domain, &arg, 0, &domainlist_anchor,
2889 NULL, MCL_DOMAIN, TRUE, NULL);
2893 case ACLC_DK_SENDER_LOCAL_PARTS:
2894 if (dk_verify_block == NULL) { rc = FAIL; break; };
2895 if (dk_verify_block->local_part != NULL)
2896 rc = match_isinlist(dk_verify_block->local_part, &arg, 0, &localpartlist_anchor,
2897 NULL, MCL_LOCALPART, TRUE, NULL);
2901 case ACLC_DK_SENDERS:
2902 if (dk_verify_block == NULL) { rc = FAIL; break; };
2903 if (dk_verify_block->address != NULL)
2904 rc = match_address_list(dk_verify_block->address, TRUE, TRUE, &arg, NULL, -1, 0, NULL);
2908 case ACLC_DK_STATUS:
2909 if (dk_verify_block == NULL) { rc = FAIL; break; };
2910 if (dk_verify_block->result > 0) {
2911 switch(dk_verify_block->result) {
2912 case DK_EXIM_RESULT_BAD_FORMAT:
2913 rc = match_isinlist(US"bad format", &arg, 0, NULL,
2914 NULL, MCL_STRING, TRUE, NULL);
2916 case DK_EXIM_RESULT_NO_KEY:
2917 rc = match_isinlist(US"no key", &arg, 0, NULL,
2918 NULL, MCL_STRING, TRUE, NULL);
2920 case DK_EXIM_RESULT_NO_SIGNATURE:
2921 rc = match_isinlist(US"no signature", &arg, 0, NULL,
2922 NULL, MCL_STRING, TRUE, NULL);
2924 case DK_EXIM_RESULT_REVOKED:
2925 rc = match_isinlist(US"revoked", &arg, 0, NULL,
2926 NULL, MCL_STRING, TRUE, NULL);
2928 case DK_EXIM_RESULT_NON_PARTICIPANT:
2929 rc = match_isinlist(US"non-participant", &arg, 0, NULL,
2930 NULL, MCL_STRING, TRUE, NULL);
2932 case DK_EXIM_RESULT_GOOD:
2933 rc = match_isinlist(US"good", &arg, 0, NULL,
2934 NULL, MCL_STRING, TRUE, NULL);
2936 case DK_EXIM_RESULT_BAD:
2937 rc = match_isinlist(US"bad", &arg, 0, NULL,
2938 NULL, MCL_STRING, TRUE, NULL);
2946 rc = verify_check_dnsbl(&arg);
2950 rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
2951 addr->domain_cache, MCL_DOMAIN, TRUE, &deliver_domain_data);
2954 /* The value in tls_cipher is the full cipher name, for example,
2955 TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
2956 cipher names such as DES-CBC3-SHA. But program defensively. We don't know
2957 what may in practice come out of the SSL library - which at the time of
2958 writing is poorly documented. */
2960 case ACLC_ENCRYPTED:
2961 if (tls_cipher == NULL) rc = FAIL; else
2963 uschar *endcipher = NULL;
2964 uschar *cipher = Ustrchr(tls_cipher, ':');
2965 if (cipher == NULL) cipher = tls_cipher; else
2967 endcipher = Ustrchr(++cipher, ':');
2968 if (endcipher != NULL) *endcipher = 0;
2970 rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
2971 if (endcipher != NULL) *endcipher = ':';
2975 /* Use verify_check_this_host() instead of verify_check_host() so that
2976 we can pass over &host_data to catch any looked up data. Once it has been
2977 set, it retains its value so that it's still there if another ACL verb
2978 comes through here and uses the cache. However, we must put it into
2979 permanent store in case it is also expected to be used in a subsequent
2980 message in the same SMTP connection. */
2983 rc = verify_check_this_host(&arg, sender_host_cache, NULL,
2984 (sender_host_address == NULL)? US"" : sender_host_address, &host_data);
2985 if (host_data != NULL) host_data = string_copy_malloc(host_data);
2988 case ACLC_LOCAL_PARTS:
2989 rc = match_isinlist(addr->cc_local_part, &arg, 0,
2990 &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
2991 &deliver_localpart_data);
2994 case ACLC_LOG_REJECT_TARGET:
3000 while ((ss = string_nextinlist(&s, &sep, big_buffer, big_buffer_size))
3003 if (Ustrcmp(ss, "main") == 0) logbits |= LOG_MAIN;
3004 else if (Ustrcmp(ss, "panic") == 0) logbits |= LOG_PANIC;
3005 else if (Ustrcmp(ss, "reject") == 0) logbits |= LOG_REJECT;
3008 logbits |= LOG_MAIN|LOG_REJECT;
3009 log_write(0, LOG_MAIN|LOG_PANIC, "unknown log name \"%s\" in "
3010 "\"log_reject_target\" in %s ACL", ss, acl_wherenames[where]);
3013 log_reject_target = logbits;
3026 if (Ustrncmp(s, "main", 4) == 0)
3027 { logbits |= LOG_MAIN; s += 4; }
3028 else if (Ustrncmp(s, "panic", 5) == 0)
3029 { logbits |= LOG_PANIC; s += 5; }
3030 else if (Ustrncmp(s, "reject", 6) == 0)
3031 { logbits |= LOG_REJECT; s += 6; }
3034 logbits = LOG_MAIN|LOG_PANIC;
3035 s = string_sprintf(":unknown log name in \"%s\" in "
3036 "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
3042 while (isspace(*s)) s++;
3045 if (logbits == 0) logbits = LOG_MAIN;
3046 log_write(0, logbits, "%s", string_printing(s));
3050 #ifdef WITH_CONTENT_SCAN
3053 /* Separate the regular expression and any optional parameters. */
3054 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
3055 /* Run the malware backend. */
3057 /* Modify return code based upon the existance of options. */
3058 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
3060 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3062 /* FAIL so that the message is passed to the next ACL */
3069 case ACLC_MIME_REGEX:
3070 rc = mime_regex(&arg);
3074 case ACLC_RATELIMIT:
3075 rc = acl_ratelimit(arg, where, log_msgptr);
3078 case ACLC_RECIPIENTS:
3079 rc = match_address_list(addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
3083 #ifdef WITH_CONTENT_SCAN
3089 case ACLC_SENDER_DOMAINS:
3092 sdomain = Ustrrchr(sender_address, '@');
3093 sdomain = (sdomain == NULL)? US"" : sdomain + 1;
3094 rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
3095 sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
3100 rc = match_address_list(sender_address, TRUE, TRUE, &arg,
3101 sender_address_cache, -1, 0, &sender_data);
3104 /* Connection variables must persist forever */
3108 int old_pool = store_pool;
3109 if (cb->u.varname[0] == 'c') store_pool = POOL_PERM;
3110 acl_var_create(cb->u.varname)->data.ptr = string_copy(arg);
3111 store_pool = old_pool;
3115 #ifdef WITH_CONTENT_SCAN
3118 /* Seperate the regular expression and any optional parameters. */
3119 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
3120 /* Run the spam backend. */
3122 /* Modify return code based upon the existance of options. */
3123 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
3125 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3127 /* FAIL so that the message is passed to the next ACL */
3135 #ifdef EXPERIMENTAL_SPF
3137 rc = spf_process(&arg, sender_address);
3141 /* If the verb is WARN, discard any user message from verification, because
3142 such messages are SMTP responses, not header additions. The latter come
3143 only from explicit "message" modifiers. However, put the user message into
3144 $acl_verify_message so it can be used in subsequent conditions or modifiers
3145 (until something changes it). */
3148 rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
3149 acl_verify_message = *user_msgptr;
3150 if (verb == ACL_WARN) *user_msgptr = NULL;
3154 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
3155 "condition %d", cb->type);
3159 /* If a condition was negated, invert OK/FAIL. */
3161 if (!cond_modifiers[cb->type] && cb->u.negated)
3163 if (rc == OK) rc = FAIL;
3164 else if (rc == FAIL || rc == FAIL_DROP) rc = OK;
3167 if (rc != OK) break; /* Conditions loop */
3171 /* If the result is the one for which "message" and/or "log_message" are used,
3172 handle the values of these modifiers. If there isn't a log message set, we make
3173 it the same as the user message.
3175 "message" is a user message that will be included in an SMTP response. Unless
3176 it is empty, it overrides any previously set user message.
3178 "log_message" is a non-user message, and it adds to any existing non-user
3179 message that is already set.
3181 Most verbs have but a single return for which the messages are relevant, but
3182 for "discard", it's useful to have the log message both when it succeeds and
3183 when it fails. For "accept", the message is used in the OK case if there is no
3184 "endpass", but (for backwards compatibility) in the FAIL case if "endpass" is
3187 if (*epp && rc == OK) user_message = NULL;
3189 if (((1<<rc) & msgcond[verb]) != 0)
3192 uschar *old_user_msgptr = *user_msgptr;
3193 uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;
3195 /* If the verb is "warn", messages generated by conditions (verification or
3196 nested ACLs) are always discarded. This also happens for acceptance verbs
3197 when they actually do accept. Only messages specified at this level are used.
3198 However, the value of an existing message is available in $acl_verify_message
3199 during expansions. */
3201 if (verb == ACL_WARN ||
3202 (rc == OK && (verb == ACL_ACCEPT || verb == ACL_DISCARD)))
3203 *log_msgptr = *user_msgptr = NULL;
3205 if (user_message != NULL)
3207 acl_verify_message = old_user_msgptr;
3208 expmessage = expand_string(user_message);
3209 if (expmessage == NULL)
3211 if (!expand_string_forcedfail)
3212 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
3213 user_message, expand_string_message);
3215 else if (expmessage[0] != 0) *user_msgptr = expmessage;
3218 if (log_message != NULL)
3220 acl_verify_message = old_log_msgptr;
3221 expmessage = expand_string(log_message);
3222 if (expmessage == NULL)
3224 if (!expand_string_forcedfail)
3225 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
3226 log_message, expand_string_message);
3228 else if (expmessage[0] != 0)
3230 *log_msgptr = (*log_msgptr == NULL)? expmessage :
3231 string_sprintf("%s: %s", expmessage, *log_msgptr);
3235 /* If no log message, default it to the user message */
3237 if (*log_msgptr == NULL) *log_msgptr = *user_msgptr;
3240 acl_verify_message = NULL;
3248 /*************************************************
3249 * Get line from a literal ACL *
3250 *************************************************/
3252 /* This function is passed to acl_read() in order to extract individual lines
3253 of a literal ACL, which we access via static pointers. We can destroy the
3254 contents because this is called only once (the compiled ACL is remembered).
3256 This code is intended to treat the data in the same way as lines in the main
3257 Exim configuration file. That is:
3259 . Leading spaces are ignored.
3261 . A \ at the end of a line is a continuation - trailing spaces after the \
3262 are permitted (this is because I don't believe in making invisible things
3263 significant). Leading spaces on the continued part of a line are ignored.
3265 . Physical lines starting (significantly) with # are totally ignored, and
3266 may appear within a sequence of backslash-continued lines.
3268 . Blank lines are ignored, but will end a sequence of continuations.
3271 Returns: a pointer to the next line
3275 static uschar *acl_text; /* Current pointer in the text */
3276 static uschar *acl_text_end; /* Points one past the terminating '0' */
3284 /* This loop handles leading blank lines and comments. */
3288 while (isspace(*acl_text)) acl_text++; /* Leading spaces/empty lines */
3289 if (*acl_text == 0) return NULL; /* No more data */
3290 yield = acl_text; /* Potential data line */
3292 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
3294 /* If we hit the end before a newline, we have the whole logical line. If
3295 it's a comment, there's no more data to be given. Otherwise, yield it. */
3297 if (*acl_text == 0) return (*yield == '#')? NULL : yield;
3299 /* After reaching a newline, end this loop if the physical line does not
3300 start with '#'. If it does, it's a comment, and the loop continues. */
3302 if (*yield != '#') break;
3305 /* This loop handles continuations. We know we have some real data, ending in
3306 newline. See if there is a continuation marker at the end (ignoring trailing
3307 white space). We know that *yield is not white space, so no need to test for
3308 cont > yield in the backwards scanning loop. */
3313 for (cont = acl_text - 1; isspace(*cont); cont--);
3315 /* If no continuation follows, we are done. Mark the end of the line and
3324 /* We have encountered a continuation. Skip over whitespace at the start of
3325 the next line, and indeed the whole of the next line or lines if they are
3330 while (*(++acl_text) == ' ' || *acl_text == '\t');
3331 if (*acl_text != '#') break;
3332 while (*(++acl_text) != 0 && *acl_text != '\n');
3335 /* We have the start of a continuation line. Move all the rest of the data
3336 to join onto the previous line, and then find its end. If the end is not a
3337 newline, we are done. Otherwise loop to look for another continuation. */
3339 memmove(cont, acl_text, acl_text_end - acl_text);
3340 acl_text_end -= acl_text - cont;
3342 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
3343 if (*acl_text == 0) return yield;
3346 /* Control does not reach here */
3353 /*************************************************
3354 * Check access using an ACL *
3355 *************************************************/
3357 /* This function is called from address_check. It may recurse via
3358 acl_check_condition() - hence the use of a level to stop looping. The ACL is
3359 passed as a string which is expanded. A forced failure implies no access check
3360 is required. If the result is a single word, it is taken as the name of an ACL
3361 which is sought in the global ACL tree. Otherwise, it is taken as literal ACL
3362 text, complete with newlines, and parsed as such. In both cases, the ACL check
3363 is then run. This function uses an auxiliary function for acl_read() to call
3364 for reading individual lines of a literal ACL. This is acl_getline(), which
3365 appears immediately above.
3368 where where called from
3369 addr address item when called from RCPT; otherwise NULL
3370 s the input string; NULL is the same as an empty ACL => DENY
3371 level the nesting level
3372 user_msgptr where to put a user error (for SMTP response)
3373 log_msgptr where to put a logging message (not for SMTP response)
3375 Returns: OK access is granted
3376 DISCARD access is apparently granted...
3377 FAIL access is denied
3378 FAIL_DROP access is denied; drop the connection
3379 DEFER can't tell at the moment
3384 acl_check_internal(int where, address_item *addr, uschar *s, int level,
3385 uschar **user_msgptr, uschar **log_msgptr)
3388 acl_block *acl = NULL;
3389 uschar *acl_name = US"inline ACL";
3392 /* Catch configuration loops */
3396 *log_msgptr = US"ACL nested too deep: possible loop";
3402 HDEBUG(D_acl) debug_printf("ACL is NULL: implicit DENY\n");
3406 /* At top level, we expand the incoming string. At lower levels, it has already
3407 been expanded as part of condition processing. */
3411 ss = expand_string(s);
3414 if (expand_string_forcedfail) return OK;
3415 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s", s,
3416 expand_string_message);
3422 while (isspace(*ss))ss++;
3424 /* If we can't find a named ACL, the default is to parse it as an inline one.
3425 (Unless it begins with a slash; non-existent files give rise to an error.) */
3429 /* Handle the case of a string that does not contain any spaces. Look for a
3430 named ACL among those read from the configuration, or a previously read file.
3431 It is possible that the pointer to the ACL is NULL if the configuration
3432 contains a name with no data. If not found, and the text begins with '/',
3433 read an ACL from a file, and save it so it can be re-used. */
3435 if (Ustrchr(ss, ' ') == NULL)
3437 tree_node *t = tree_search(acl_anchor, ss);
3440 acl = (acl_block *)(t->data.ptr);
3443 HDEBUG(D_acl) debug_printf("ACL \"%s\" is empty: implicit DENY\n", ss);
3446 acl_name = string_sprintf("ACL \"%s\"", ss);
3447 HDEBUG(D_acl) debug_printf("using ACL \"%s\"\n", ss);
3450 else if (*ss == '/')
3452 struct stat statbuf;
3453 fd = Uopen(ss, O_RDONLY, 0);
3456 *log_msgptr = string_sprintf("failed to open ACL file \"%s\": %s", ss,
3461 if (fstat(fd, &statbuf) != 0)
3463 *log_msgptr = string_sprintf("failed to fstat ACL file \"%s\": %s", ss,
3468 acl_text = store_get(statbuf.st_size + 1);
3469 acl_text_end = acl_text + statbuf.st_size + 1;
3471 if (read(fd, acl_text, statbuf.st_size) != statbuf.st_size)
3473 *log_msgptr = string_sprintf("failed to read ACL file \"%s\": %s",
3474 ss, strerror(errno));
3477 acl_text[statbuf.st_size] = 0;
3480 acl_name = string_sprintf("ACL \"%s\"", ss);
3481 HDEBUG(D_acl) debug_printf("read ACL from file %s\n", ss);
3485 /* Parse an ACL that is still in text form. If it came from a file, remember it
3486 in the ACL tree, having read it into the POOL_PERM store pool so that it
3487 persists between multiple messages. */
3491 int old_pool = store_pool;
3492 if (fd >= 0) store_pool = POOL_PERM;
3493 acl = acl_read(acl_getline, log_msgptr);
3494 store_pool = old_pool;
3495 if (acl == NULL && *log_msgptr != NULL) return ERROR;
3498 tree_node *t = store_get_perm(sizeof(tree_node) + Ustrlen(ss));
3499 Ustrcpy(t->name, ss);
3501 (void)tree_insertnode(&acl_anchor, t);
3505 /* Now we have an ACL to use. It's possible it may be NULL. */
3510 int basic_errno = 0;
3511 BOOL endpass_seen = FALSE;
3513 *log_msgptr = *user_msgptr = NULL;
3514 acl_temp_details = FALSE;
3516 if ((where == ACL_WHERE_QUIT || where == ACL_WHERE_NOTQUIT) &&
3517 acl->verb != ACL_ACCEPT &&
3518 acl->verb != ACL_WARN)
3520 *log_msgptr = string_sprintf("\"%s\" is not allowed in a QUIT or not-QUIT ACL",
3525 HDEBUG(D_acl) debug_printf("processing \"%s\"\n", verbs[acl->verb]);
3527 /* Clear out any search error message from a previous check before testing
3530 search_error_message = NULL;
3531 cond = acl_check_condition(acl->verb, acl->condition, where, addr, level,
3532 &endpass_seen, user_msgptr, log_msgptr, &basic_errno);
3534 /* Handle special returns: DEFER causes a return except on a WARN verb;
3535 ERROR always causes a return. */
3540 HDEBUG(D_acl) debug_printf("%s: condition test deferred\n", verbs[acl->verb]);
3541 if (basic_errno != ERRNO_CALLOUTDEFER)
3543 if (search_error_message != NULL && *search_error_message != 0)
3544 *log_msgptr = search_error_message;
3545 if (smtp_return_error_details) acl_temp_details = TRUE;
3549 acl_temp_details = TRUE;
3551 if (acl->verb != ACL_WARN) return DEFER;
3554 default: /* Paranoia */
3556 HDEBUG(D_acl) debug_printf("%s: condition test error\n", verbs[acl->verb]);
3560 HDEBUG(D_acl) debug_printf("%s: condition test succeeded\n",
3565 HDEBUG(D_acl) debug_printf("%s: condition test failed\n", verbs[acl->verb]);
3568 /* DISCARD and DROP can happen only from a nested ACL condition, and
3569 DISCARD can happen only for an "accept" or "discard" verb. */
3572 HDEBUG(D_acl) debug_printf("%s: condition test yielded \"discard\"\n",
3577 HDEBUG(D_acl) debug_printf("%s: condition test yielded \"drop\"\n",
3582 /* At this point, cond for most verbs is either OK or FAIL or (as a result of
3583 a nested ACL condition) FAIL_DROP. However, for WARN, cond may be DEFER, and
3584 for ACCEPT and DISCARD, it may be DISCARD after a nested ACL call. */
3589 if (cond == OK || cond == DISCARD) return cond;
3592 HDEBUG(D_acl) debug_printf("accept: endpass encountered - denying access\n");
3600 acl_temp_details = TRUE;
3606 if (cond == OK) return FAIL;
3610 if (cond == OK || cond == DISCARD) return DISCARD;
3613 HDEBUG(D_acl) debug_printf("discard: endpass encountered - denying access\n");
3619 if (cond == OK) return FAIL_DROP;
3623 if (cond != OK) return cond;
3628 acl_warn(where, *user_msgptr, *log_msgptr);
3629 else if (cond == DEFER && (log_extra_selector & LX_acl_warn_skipped) != 0)
3630 log_write(0, LOG_MAIN, "%s Warning: ACL \"warn\" statement skipped: "
3631 "condition test deferred%s%s", host_and_ident(TRUE),
3632 (*log_msgptr == NULL)? US"" : US": ",
3633 (*log_msgptr == NULL)? US"" : *log_msgptr);
3634 *log_msgptr = *user_msgptr = NULL; /* In case implicit DENY follows */
3638 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown verb %d",
3643 /* Pass to the next ACL item */
3648 /* We have reached the end of the ACL. This is an implicit DENY. */
3650 HDEBUG(D_acl) debug_printf("end of %s: implicit DENY\n", acl_name);
3655 /*************************************************
3656 * Check access using an ACL *
3657 *************************************************/
3659 /* This is the external interface for ACL checks. It sets up an address and the
3660 expansions for $domain and $local_part when called after RCPT, then calls
3661 acl_check_internal() to do the actual work.
3664 where ACL_WHERE_xxxx indicating where called from
3665 recipient RCPT address for RCPT check, else NULL
3666 s the input string; NULL is the same as an empty ACL => DENY
3667 user_msgptr where to put a user error (for SMTP response)
3668 log_msgptr where to put a logging message (not for SMTP response)
3670 Returns: OK access is granted by an ACCEPT verb
3671 DISCARD access is granted by a DISCARD verb
3672 FAIL access is denied
3673 FAIL_DROP access is denied; drop the connection
3674 DEFER can't tell at the moment
3679 acl_check(int where, uschar *recipient, uschar *s, uschar **user_msgptr,
3680 uschar **log_msgptr)
3684 address_item *addr = NULL;
3686 *user_msgptr = *log_msgptr = NULL;
3687 sender_verified_failed = NULL;
3688 ratelimiters_cmd = NULL;
3689 log_reject_target = LOG_MAIN|LOG_REJECT;
3691 if (where == ACL_WHERE_RCPT)
3693 adb = address_defaults;
3695 addr->address = recipient;
3696 if (deliver_split_address(addr) == DEFER)
3698 *log_msgptr = US"defer in percent_hack_domains check";
3701 deliver_domain = addr->domain;
3702 deliver_localpart = addr->local_part;
3705 rc = acl_check_internal(where, addr, s, 0, user_msgptr, log_msgptr);
3707 deliver_domain = deliver_localpart = deliver_address_data =
3708 sender_address_data = NULL;
3710 /* A DISCARD response is permitted only for message ACLs, excluding the PREDATA
3711 ACL, which is really in the middle of an SMTP command. */
3715 if (where > ACL_WHERE_NOTSMTP || where == ACL_WHERE_PREDATA)
3717 log_write(0, LOG_MAIN|LOG_PANIC, "\"discard\" verb not allowed in %s "
3718 "ACL", acl_wherenames[where]);
3724 /* A DROP response is not permitted from MAILAUTH */
3726 if (rc == FAIL_DROP && where == ACL_WHERE_MAILAUTH)
3728 log_write(0, LOG_MAIN|LOG_PANIC, "\"drop\" verb not allowed in %s "
3729 "ACL", acl_wherenames[where]);
3733 /* Before giving a response, take a look at the length of any user message, and
3734 split it up into multiple lines if possible. */
3736 *user_msgptr = string_split_message(*user_msgptr);
3737 if (fake_response != OK)
3738 fake_response_text = string_split_message(fake_response_text);
3745 /*************************************************
3746 * Create ACL variable *
3747 *************************************************/
3749 /* Create an ACL variable or reuse an existing one. ACL variables are in a
3750 binary tree (see tree.c) with acl_var_c and acl_var_m as root nodes.
3753 name pointer to the variable's name, starting with c or m
3755 Returns the pointer to variable's tree node
3759 acl_var_create(uschar *name)
3761 tree_node *node, **root;
3762 root = (name[0] == 'c')? &acl_var_c : &acl_var_m;
3763 node = tree_search(*root, name);
3766 node = store_get(sizeof(tree_node) + Ustrlen(name));
3767 Ustrcpy(node->name, name);
3768 (void)tree_insertnode(root, node);
3770 node->data.ptr = NULL;
3776 /*************************************************
3777 * Write an ACL variable in spool format *
3778 *************************************************/
3780 /* This function is used as a callback for tree_walk when writing variables to
3781 the spool file. To retain spool file compatibility, what is written is -aclc or
3782 -aclm followed by the rest of the name and the data length, space separated,
3783 then the value itself, starting on a new line, and terminated by an additional
3784 newline. When we had only numbered ACL variables, the first line might look
3785 like this: "-aclc 5 20". Now it might be "-aclc foo 20" for the variable called
3789 name of the variable
3790 value of the variable
3791 ctx FILE pointer (as a void pointer)
3797 acl_var_write(uschar *name, uschar *value, void *ctx)
3799 FILE *f = (FILE *)ctx;
3800 fprintf(f, "-acl%c %s %d\n%s\n", name[0], name+1, Ustrlen(value), value);