1 /* $Cambridge: exim/src/src/acl.c,v 1.68 2007/01/08 10:50:17 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) University of Cambridge 1995 - 2007 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* Code for handling Access Control Lists (ACLs) */
15 /* Default callout timeout */
17 #define CALLOUT_TIMEOUT_DEFAULT 30
19 /* ACL verb codes - keep in step with the table of verbs that follows */
21 enum { ACL_ACCEPT, ACL_DEFER, ACL_DENY, ACL_DISCARD, ACL_DROP, ACL_REQUIRE,
26 static uschar *verbs[] =
27 { US"accept", US"defer", US"deny", US"discard", US"drop", US"require",
30 /* For each verb, the conditions for which "message" or "log_message" are used
31 are held as a bitmap. This is to avoid expanding the strings unnecessarily. For
32 "accept", the FAIL case is used only after "endpass", but that is selected in
35 static int msgcond[] = {
36 (1<<OK) | (1<<FAIL) | (1<<FAIL_DROP), /* accept */
39 (1<<OK) | (1<<FAIL) | (1<<FAIL_DROP), /* discard */
41 (1<<FAIL) | (1<<FAIL_DROP), /* require */
45 /* ACL condition and modifier codes - keep in step with the table that
46 follows, and the cond_expand_at_top and uschar cond_modifiers tables lower
52 #ifdef EXPERIMENTAL_BRIGHTMAIL
57 #ifdef WITH_CONTENT_SCAN
61 #ifdef WITH_OLD_DEMIME
64 #ifdef EXPERIMENTAL_DOMAINKEYS
65 ACLC_DK_DOMAIN_SOURCE,
67 ACLC_DK_SENDER_DOMAINS,
68 ACLC_DK_SENDER_LOCAL_PARTS,
79 ACLC_LOG_REJECT_TARGET,
81 #ifdef WITH_CONTENT_SCAN
85 #ifdef WITH_CONTENT_SCAN
90 #ifdef WITH_CONTENT_SCAN
96 #ifdef WITH_CONTENT_SCAN
99 #ifdef EXPERIMENTAL_SPF
104 /* ACL conditions/modifiers: "delay", "control", "endpass", "message",
105 "log_message", "log_reject_target", "logwrite", and "set" are modifiers that
106 look like conditions but always return TRUE. They are used for their side
109 static uschar *conditions[] = {
113 #ifdef EXPERIMENTAL_BRIGHTMAIL
118 #ifdef WITH_CONTENT_SCAN
122 #ifdef WITH_OLD_DEMIME
125 #ifdef EXPERIMENTAL_DOMAINKEYS
126 US"dk_domain_source",
128 US"dk_sender_domains",
129 US"dk_sender_local_parts",
140 US"log_reject_target",
142 #ifdef WITH_CONTENT_SCAN
146 #ifdef WITH_CONTENT_SCAN
151 #ifdef WITH_CONTENT_SCAN
154 US"sender_domains", US"senders", US"set",
155 #ifdef WITH_CONTENT_SCAN
158 #ifdef EXPERIMENTAL_SPF
164 /* Return values from decode_control(); keep in step with the table of names
168 CONTROL_AUTH_UNADVERTISED,
169 #ifdef EXPERIMENTAL_BRIGHTMAIL
172 #ifdef EXPERIMENTAL_DOMAINKEYS
176 CONTROL_CASEFUL_LOCAL_PART,
177 CONTROL_CASELOWER_LOCAL_PART,
178 CONTROL_ENFORCE_SYNC,
179 CONTROL_NO_ENFORCE_SYNC,
183 CONTROL_SUPPRESS_LOCAL_FIXUPS,
184 #ifdef WITH_CONTENT_SCAN
185 CONTROL_NO_MBOX_UNSPOOL,
192 /* ACL control names; keep in step with the table above! This list is used for
193 turning ids into names. The actual list of recognized names is in the variable
194 control_def controls_list[] below. The fact that there are two lists is a mess
195 and should be tidied up. */
197 static uschar *controls[] = {
198 US"allow_auth_unadvertised",
199 #ifdef EXPERIMENTAL_BRIGHTMAIL
202 #ifdef EXPERIMENTAL_DOMAINKEYS
206 US"caseful_local_part",
207 US"caselower_local_part",
213 US"suppress_local_fixups",
214 #ifdef WITH_CONTENT_SCAN
220 /* Flags to indicate for which conditions /modifiers a string expansion is done
221 at the outer level. In the other cases, expansion already occurs in the
222 checking functions. */
224 static uschar cond_expand_at_top[] = {
226 TRUE, /* add_header */
227 FALSE, /* authenticated */
228 #ifdef EXPERIMENTAL_BRIGHTMAIL
229 TRUE, /* bmi_optin */
231 TRUE, /* condition */
233 #ifdef WITH_CONTENT_SCAN
237 #ifdef WITH_OLD_DEMIME
240 #ifdef EXPERIMENTAL_DOMAINKEYS
241 TRUE, /* dk_domain_source */
242 TRUE, /* dk_policy */
243 TRUE, /* dk_sender_domains */
244 TRUE, /* dk_sender_local_parts */
245 TRUE, /* dk_senders */
246 TRUE, /* dk_status */
250 FALSE, /* encrypted */
253 FALSE, /* local_parts */
254 TRUE, /* log_message */
255 TRUE, /* log_reject_target */
257 #ifdef WITH_CONTENT_SCAN
261 #ifdef WITH_CONTENT_SCAN
262 TRUE, /* mime_regex */
264 TRUE, /* ratelimit */
265 FALSE, /* recipients */
266 #ifdef WITH_CONTENT_SCAN
269 FALSE, /* sender_domains */
272 #ifdef WITH_CONTENT_SCAN
275 #ifdef EXPERIMENTAL_SPF
281 /* Flags to identify the modifiers */
283 static uschar cond_modifiers[] = {
285 TRUE, /* add_header */
286 FALSE, /* authenticated */
287 #ifdef EXPERIMENTAL_BRIGHTMAIL
288 TRUE, /* bmi_optin */
290 FALSE, /* condition */
292 #ifdef WITH_CONTENT_SCAN
296 #ifdef WITH_OLD_DEMIME
299 #ifdef EXPERIMENTAL_DOMAINKEYS
300 FALSE, /* dk_domain_source */
301 FALSE, /* dk_policy */
302 FALSE, /* dk_sender_domains */
303 FALSE, /* dk_sender_local_parts */
304 FALSE, /* dk_senders */
305 FALSE, /* dk_status */
307 FALSE, /* dnslists */
309 FALSE, /* encrypted */
312 FALSE, /* local_parts */
313 TRUE, /* log_message */
314 TRUE, /* log_reject_target */
316 #ifdef WITH_CONTENT_SCAN
320 #ifdef WITH_CONTENT_SCAN
321 FALSE, /* mime_regex */
323 FALSE, /* ratelimit */
324 FALSE, /* recipients */
325 #ifdef WITH_CONTENT_SCAN
328 FALSE, /* sender_domains */
331 #ifdef WITH_CONTENT_SCAN
334 #ifdef EXPERIMENTAL_SPF
340 /* Bit map vector of which conditions are not allowed at certain times. For
341 each condition, there's a bitmap of dis-allowed times. For some, it is easier
342 to specify the negation of a small number of allowed times. */
344 static unsigned int cond_forbids[] = {
348 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* add_header */
349 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
350 (1<<ACL_WHERE_MIME)|(1<<ACL_WHERE_NOTSMTP)|
351 (1<<ACL_WHERE_NOTSMTP_START)),
353 (1<<ACL_WHERE_NOTSMTP)| /* authenticated */
354 (1<<ACL_WHERE_NOTSMTP_START)|
355 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO),
357 #ifdef EXPERIMENTAL_BRIGHTMAIL
358 (1<<ACL_WHERE_AUTH)| /* bmi_optin */
359 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
360 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_MIME)|
361 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
362 (1<<ACL_WHERE_MAILAUTH)|
363 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
364 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_PREDATA)|
365 (1<<ACL_WHERE_NOTSMTP_START),
370 /* Certain types of control are always allowed, so we let it through
371 always and check in the control processing itself. */
375 #ifdef WITH_CONTENT_SCAN
377 ~(1<<ACL_WHERE_MIME), /* decode */
382 #ifdef WITH_OLD_DEMIME
384 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* demime */
387 #ifdef EXPERIMENTAL_DOMAINKEYS
388 (1<<ACL_WHERE_AUTH)| /* dk_domain_source */
389 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
390 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
391 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
392 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
393 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
394 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
396 (1<<ACL_WHERE_AUTH)| /* dk_policy */
397 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
398 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
399 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
400 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
401 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
402 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
404 (1<<ACL_WHERE_AUTH)| /* dk_sender_domains */
405 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
406 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
407 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
408 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
409 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
410 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
412 (1<<ACL_WHERE_AUTH)| /* dk_sender_local_parts */
413 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
414 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
415 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
416 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
417 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
418 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
420 (1<<ACL_WHERE_AUTH)| /* dk_senders */
421 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
422 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
423 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
424 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
425 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
426 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
428 (1<<ACL_WHERE_AUTH)| /* dk_status */
429 (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
430 (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
431 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
432 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
433 (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
434 (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_NOTSMTP_START),
437 (1<<ACL_WHERE_NOTSMTP)| /* dnslists */
438 (1<<ACL_WHERE_NOTSMTP_START),
441 ~(1<<ACL_WHERE_RCPT), /* domains */
443 (1<<ACL_WHERE_NOTSMTP)| /* encrypted */
444 (1<<ACL_WHERE_CONNECT)|
445 (1<<ACL_WHERE_NOTSMTP_START)|
450 (1<<ACL_WHERE_NOTSMTP)| /* hosts */
451 (1<<ACL_WHERE_NOTSMTP_START),
454 ~(1<<ACL_WHERE_RCPT), /* local_parts */
458 0, /* log_reject_target */
462 #ifdef WITH_CONTENT_SCAN
464 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* malware */
469 #ifdef WITH_CONTENT_SCAN
471 ~(1<<ACL_WHERE_MIME), /* mime_regex */
477 ~(1<<ACL_WHERE_RCPT), /* recipients */
479 #ifdef WITH_CONTENT_SCAN
481 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* regex */
482 (1<<ACL_WHERE_MIME)),
485 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* sender_domains */
487 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
488 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
489 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
491 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* senders */
493 (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
494 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
495 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
499 #ifdef WITH_CONTENT_SCAN
501 ~((1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)), /* spam */
504 #ifdef EXPERIMENTAL_SPF
505 (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)| /* spf */
507 (1<<ACL_WHERE_MAILAUTH)|
508 (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
509 (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY)|
510 (1<<ACL_WHERE_NOTSMTP)|
511 (1<<ACL_WHERE_NOTSMTP_START),
514 /* Certain types of verify are always allowed, so we let it through
515 always and check in the verify function itself */
521 /* Bit map vector of which controls are not allowed at certain times. For
522 each control, there's a bitmap of dis-allowed times. For some, it is easier to
523 specify the negation of a small number of allowed times. */
525 static unsigned int control_forbids[] = {
527 ~((1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)), /* allow_auth_unadvertised */
529 #ifdef EXPERIMENTAL_BRIGHTMAIL
533 #ifdef EXPERIMENTAL_DOMAINKEYS
534 (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_NOTSMTP)| /* dk_verify */
535 (1<<ACL_WHERE_NOTSMTP_START),
541 ~(1<<ACL_WHERE_RCPT), /* caseful_local_part */
544 ~(1<<ACL_WHERE_RCPT), /* caselower_local_part */
546 (1<<ACL_WHERE_NOTSMTP)| /* enforce_sync */
547 (1<<ACL_WHERE_NOTSMTP_START),
549 (1<<ACL_WHERE_NOTSMTP)| /* no_enforce_sync */
550 (1<<ACL_WHERE_NOTSMTP_START),
553 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* freeze */
554 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
555 (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_MIME)),
558 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* queue_only */
559 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
560 (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_MIME)),
563 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* submission */
564 (1<<ACL_WHERE_PREDATA)),
567 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* suppress_local_fixups */
568 (1<<ACL_WHERE_PREDATA)|
569 (1<<ACL_WHERE_NOTSMTP_START)),
571 #ifdef WITH_CONTENT_SCAN
573 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* no_mbox_unspool */
574 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
575 (1<<ACL_WHERE_MIME)),
579 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* fakedefer */
580 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
581 (1<<ACL_WHERE_MIME)),
584 ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)| /* fakereject */
585 (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
586 (1<<ACL_WHERE_MIME)),
588 (1<<ACL_WHERE_NOTSMTP)| /* no_multiline */
589 (1<<ACL_WHERE_NOTSMTP_START)
592 /* Structure listing various control arguments, with their characteristics. */
594 typedef struct control_def {
596 int value; /* CONTROL_xxx value */
597 BOOL has_option; /* Has /option(s) following */
600 static control_def controls_list[] = {
601 { US"allow_auth_unadvertised", CONTROL_AUTH_UNADVERTISED, FALSE },
602 #ifdef EXPERIMENTAL_BRIGHTMAIL
603 { US"bmi_run", CONTROL_BMI_RUN, FALSE },
605 #ifdef EXPERIMENTAL_DOMAINKEYS
606 { US"dk_verify", CONTROL_DK_VERIFY, FALSE },
608 { US"caseful_local_part", CONTROL_CASEFUL_LOCAL_PART, FALSE },
609 { US"caselower_local_part", CONTROL_CASELOWER_LOCAL_PART, FALSE },
610 { US"enforce_sync", CONTROL_ENFORCE_SYNC, FALSE },
611 { US"freeze", CONTROL_FREEZE, TRUE },
612 { US"no_enforce_sync", CONTROL_NO_ENFORCE_SYNC, FALSE },
613 { US"no_multiline_responses", CONTROL_NO_MULTILINE, FALSE },
614 { US"queue_only", CONTROL_QUEUE_ONLY, FALSE },
615 #ifdef WITH_CONTENT_SCAN
616 { US"no_mbox_unspool", CONTROL_NO_MBOX_UNSPOOL, FALSE },
618 { US"fakedefer", CONTROL_FAKEDEFER, TRUE },
619 { US"fakereject", CONTROL_FAKEREJECT, TRUE },
620 { US"submission", CONTROL_SUBMISSION, TRUE },
621 { US"suppress_local_fixups", CONTROL_SUPPRESS_LOCAL_FIXUPS, FALSE }
624 /* Support data structures for Client SMTP Authorization. acl_verify_csa()
625 caches its result in a tree to avoid repeated DNS queries. The result is an
626 integer code which is used as an index into the following tables of
627 explanatory strings and verification return codes. */
629 static tree_node *csa_cache = NULL;
631 enum { CSA_UNKNOWN, CSA_OK, CSA_DEFER_SRV, CSA_DEFER_ADDR,
632 CSA_FAIL_EXPLICIT, CSA_FAIL_DOMAIN, CSA_FAIL_NOADDR, CSA_FAIL_MISMATCH };
634 /* The acl_verify_csa() return code is translated into an acl_verify() return
635 code using the following table. It is OK unless the client is definitely not
636 authorized. This is because CSA is supposed to be optional for sending sites,
637 so recipients should not be too strict about checking it - especially because
638 DNS problems are quite likely to occur. It's possible to use $csa_status in
639 further ACL conditions to distinguish ok, unknown, and defer if required, but
640 the aim is to make the usual configuration simple. */
642 static int csa_return_code[] = {
644 FAIL, FAIL, FAIL, FAIL
647 static uschar *csa_status_string[] = {
648 US"unknown", US"ok", US"defer", US"defer",
649 US"fail", US"fail", US"fail", US"fail"
652 static uschar *csa_reason_string[] = {
655 US"deferred (SRV lookup failed)",
656 US"deferred (target address lookup failed)",
657 US"failed (explicit authorization required)",
658 US"failed (host name not authorized)",
659 US"failed (no authorized addresses)",
660 US"failed (client address mismatch)"
663 /* Enable recursion between acl_check_internal() and acl_check_condition() */
665 static int acl_check_internal(int, address_item *, uschar *, int, uschar **,
669 /*************************************************
670 * Pick out name from list *
671 *************************************************/
673 /* Use a binary chop method
680 Returns: offset in list, or -1 if not found
684 acl_checkname(uschar *name, uschar **list, int end)
690 int mid = (start + end)/2;
691 int c = Ustrcmp(name, list[mid]);
692 if (c == 0) return mid;
693 if (c < 0) end = mid; else start = mid + 1;
700 /*************************************************
701 * Read and parse one ACL *
702 *************************************************/
704 /* This function is called both from readconf in order to parse the ACLs in the
705 configuration file, and also when an ACL is encountered dynamically (e.g. as
706 the result of an expansion). It is given a function to call in order to
707 retrieve the lines of the ACL. This function handles skipping comments and
708 blank lines (where relevant).
711 func function to get next line of ACL
712 error where to put an error message
714 Returns: pointer to ACL, or NULL
715 NULL can be legal (empty ACL); in this case error will be NULL
719 acl_read(uschar *(*func)(void), uschar **error)
721 acl_block *yield = NULL;
722 acl_block **lastp = &yield;
723 acl_block *this = NULL;
724 acl_condition_block *cond;
725 acl_condition_block **condp = NULL;
730 while ((s = (*func)()) != NULL)
733 BOOL negated = FALSE;
734 uschar *saveline = s;
737 /* Conditions (but not verbs) are allowed to be negated by an initial
740 while (isspace(*s)) s++;
747 /* Read the name of a verb or a condition, or the start of a new ACL, which
748 can be started by a name, or by a macro definition. */
750 s = readconf_readname(name, sizeof(name), s);
751 if (*s == ':' || (isupper(name[0]) && *s == '=')) return yield;
753 /* If a verb is unrecognized, it may be another condition or modifier that
754 continues the previous verb. */
756 v = acl_checkname(name, verbs, sizeof(verbs)/sizeof(char *));
761 *error = string_sprintf("unknown ACL verb \"%s\" in \"%s\"", name,
773 *error = string_sprintf("malformed ACL line \"%s\"", saveline);
776 this = store_get(sizeof(acl_block));
778 lastp = &(this->next);
781 this->condition = NULL;
782 condp = &(this->condition);
783 if (*s == 0) continue; /* No condition on this line */
789 s = readconf_readname(name, sizeof(name), s); /* Condition name */
792 /* Handle a condition or modifier. */
794 c = acl_checkname(name, conditions, sizeof(conditions)/sizeof(char *));
797 *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
802 /* The modifiers may not be negated */
804 if (negated && cond_modifiers[c])
806 *error = string_sprintf("ACL error: negation is not allowed with "
807 "\"%s\"", conditions[c]);
811 /* ENDPASS may occur only with ACCEPT or DISCARD. */
813 if (c == ACLC_ENDPASS &&
814 this->verb != ACL_ACCEPT &&
815 this->verb != ACL_DISCARD)
817 *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
818 conditions[c], verbs[this->verb]);
822 cond = store_get(sizeof(acl_condition_block));
825 cond->u.negated = negated;
828 condp = &(cond->next);
830 /* The "set" modifier is different in that its argument is "name=value"
831 rather than just a value, and we can check the validity of the name, which
832 gives us a variable name to insert into the data block. The original ACL
833 variable names were acl_c0 ... acl_c9 and acl_m0 ... acl_m9. This was
834 extended to 20 of each type, but after that people successfully argued for
835 arbitrary names. In the new scheme, the names must start with acl_c or acl_m.
836 After that, we allow alphanumerics and underscores, but the first character
837 after c or m must be a digit or an underscore. This retains backwards
844 if (Ustrncmp(s, "acl_c", 5) != 0 &&
845 Ustrncmp(s, "acl_m", 5) != 0)
847 *error = string_sprintf("invalid variable name after \"set\" in ACL "
848 "modifier \"set %s\" (must start \"acl_c\" or \"acl_m\")", s);
853 if (!isdigit(*endptr) && *endptr != '_')
855 *error = string_sprintf("invalid variable name after \"set\" in ACL "
856 "modifier \"set %s\" (digit or underscore must follow acl_c or acl_m)",
861 while (*endptr != 0 && *endptr != '=' && !isspace(*endptr))
863 if (!isalnum(*endptr) && *endptr != '_')
865 *error = string_sprintf("invalid character \"%c\" in variable name "
866 "in ACL modifier \"set %s\"", *endptr, s);
872 cond->u.varname = string_copyn(s + 4, endptr - s - 4);
874 while (isspace(*s)) s++;
877 /* For "set", we are now positioned for the data. For the others, only
878 "endpass" has no data */
880 if (c != ACLC_ENDPASS)
884 *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
885 cond_modifiers[c]? US"modifier" : US"condition");
888 while (isspace(*s)) s++;
889 cond->arg = string_copy(s);
898 /*************************************************
899 * Set up added header line(s) *
900 *************************************************/
902 /* This function is called by the add_header modifier, and also from acl_warn()
903 to implement the now-deprecated way of adding header lines using "message" on a
904 "warn" verb. The argument is treated as a sequence of header lines which are
905 added to a chain, provided there isn't an identical one already there.
907 Argument: string of header lines
912 setup_header(uschar *hstring)
915 int hlen = Ustrlen(hstring);
917 /* An empty string does nothing; otherwise add a final newline if necessary. */
919 if (hlen <= 0) return;
920 if (hstring[hlen-1] != '\n') hstring = string_sprintf("%s\n", hstring);
922 /* Loop for multiple header lines, taking care about continuations */
924 for (p = q = hstring; *p != 0; )
927 int newtype = htype_add_bot;
928 header_line **hptr = &acl_added_headers;
930 /* Find next header line within the string */
934 q = Ustrchr(q, '\n');
935 if (*(++q) != ' ' && *q != '\t') break;
938 /* If the line starts with a colon, interpret the instruction for where to
939 add it. This temporarily sets up a new type. */
943 if (strncmpic(p, US":after_received:", 16) == 0)
945 newtype = htype_add_rec;
948 else if (strncmpic(p, US":at_start_rfc:", 14) == 0)
950 newtype = htype_add_rfc;
953 else if (strncmpic(p, US":at_start:", 10) == 0)
955 newtype = htype_add_top;
958 else if (strncmpic(p, US":at_end:", 8) == 0)
960 newtype = htype_add_bot;
963 while (*p == ' ' || *p == '\t') p++;
966 /* See if this line starts with a header name, and if not, add X-ACL-Warn:
967 to the front of it. */
969 for (s = p; s < q - 1; s++)
971 if (*s == ':' || !isgraph(*s)) break;
974 s = string_sprintf("%s%.*s", (*s == ':')? "" : "X-ACL-Warn: ", q - p, p);
977 /* See if this line has already been added */
979 while (*hptr != NULL)
981 if (Ustrncmp((*hptr)->text, s, hlen) == 0) break;
982 hptr = &((*hptr)->next);
985 /* Add if not previously present */
989 header_line *h = store_get(sizeof(header_line));
998 /* Advance for next header line within the string */
1007 /*************************************************
1009 *************************************************/
1011 /* This function is called when a WARN verb's conditions are true. It adds to
1012 the message's headers, and/or writes information to the log. In each case, this
1013 only happens once (per message for headers, per connection for log).
1015 ** NOTE: The header adding action using the "message" setting is historic, and
1016 its use is now deprecated. The new add_header modifier should be used instead.
1019 where ACL_WHERE_xxxx indicating which ACL this is
1020 user_message message for adding to headers
1021 log_message message for logging, if different
1027 acl_warn(int where, uschar *user_message, uschar *log_message)
1029 if (log_message != NULL && log_message != user_message)
1032 string_item *logged;
1034 text = string_sprintf("%s Warning: %s", host_and_ident(TRUE),
1035 string_printing(log_message));
1037 /* If a sender verification has failed, and the log message is "sender verify
1038 failed", add the failure message. */
1040 if (sender_verified_failed != NULL &&
1041 sender_verified_failed->message != NULL &&
1042 strcmpic(log_message, US"sender verify failed") == 0)
1043 text = string_sprintf("%s: %s", text, sender_verified_failed->message);
1045 /* Search previously logged warnings. They are kept in malloc
1046 store so they can be freed at the start of a new message. */
1048 for (logged = acl_warn_logged; logged != NULL; logged = logged->next)
1049 if (Ustrcmp(logged->text, text) == 0) break;
1053 int length = Ustrlen(text) + 1;
1054 log_write(0, LOG_MAIN, "%s", text);
1055 logged = store_malloc(sizeof(string_item) + length);
1056 logged->text = (uschar *)logged + sizeof(string_item);
1057 memcpy(logged->text, text, length);
1058 logged->next = acl_warn_logged;
1059 acl_warn_logged = logged;
1063 /* If there's no user message, we are done. */
1065 if (user_message == NULL) return;
1067 /* If this isn't a message ACL, we can't do anything with a user message.
1070 if (where > ACL_WHERE_NOTSMTP)
1072 log_write(0, LOG_MAIN|LOG_PANIC, "ACL \"warn\" with \"message\" setting "
1073 "found in a non-message (%s) ACL: cannot specify header lines here: "
1074 "message ignored", acl_wherenames[where]);
1078 /* The code for setting up header lines is now abstracted into a separate
1079 function so that it can be used for the add_header modifier as well. */
1081 setup_header(user_message);
1086 /*************************************************
1087 * Verify and check reverse DNS *
1088 *************************************************/
1090 /* Called from acl_verify() below. We look up the host name(s) of the client IP
1091 address if this has not yet been done. The host_name_lookup() function checks
1092 that one of these names resolves to an address list that contains the client IP
1093 address, so we don't actually have to do the check here.
1096 user_msgptr pointer for user message
1097 log_msgptr pointer for log message
1099 Returns: OK verification condition succeeded
1100 FAIL verification failed
1101 DEFER there was a problem verifying
1105 acl_verify_reverse(uschar **user_msgptr, uschar **log_msgptr)
1109 user_msgptr = user_msgptr; /* stop compiler warning */
1111 /* Previous success */
1113 if (sender_host_name != NULL) return OK;
1115 /* Previous failure */
1117 if (host_lookup_failed)
1119 *log_msgptr = string_sprintf("host lookup failed%s", host_lookup_msg);
1123 /* Need to do a lookup */
1126 debug_printf("looking up host name to force name/address consistency check\n");
1128 if ((rc = host_name_lookup()) != OK)
1130 *log_msgptr = (rc == DEFER)?
1131 US"host lookup deferred for reverse lookup check"
1133 string_sprintf("host lookup failed for reverse lookup check%s",
1135 return rc; /* DEFER or FAIL */
1138 host_build_sender_fullhost();
1144 /*************************************************
1145 * Check client IP address matches CSA target *
1146 *************************************************/
1148 /* Called from acl_verify_csa() below. This routine scans a section of a DNS
1149 response for address records belonging to the CSA target hostname. The section
1150 is specified by the reset argument, either RESET_ADDITIONAL or RESET_ANSWERS.
1151 If one of the addresses matches the client's IP address, then the client is
1152 authorized by CSA. If there are target IP addresses but none of them match
1153 then the client is using an unauthorized IP address. If there are no target IP
1154 addresses then the client cannot be using an authorized IP address. (This is
1155 an odd configuration - why didn't the SRV record have a weight of 1 instead?)
1158 dnsa the DNS answer block
1159 dnss a DNS scan block for us to use
1160 reset option specifing what portion to scan, as described above
1161 target the target hostname to use for matching RR names
1163 Returns: CSA_OK successfully authorized
1164 CSA_FAIL_MISMATCH addresses found but none matched
1165 CSA_FAIL_NOADDR no target addresses found
1169 acl_verify_csa_address(dns_answer *dnsa, dns_scan *dnss, int reset,
1175 BOOL target_found = FALSE;
1177 for (rr = dns_next_rr(dnsa, dnss, reset);
1179 rr = dns_next_rr(dnsa, dnss, RESET_NEXT))
1181 /* Check this is an address RR for the target hostname. */
1185 && rr->type != T_AAAA
1192 if (strcmpic(target, rr->name) != 0) continue;
1194 target_found = TRUE;
1196 /* Turn the target address RR into a list of textual IP addresses and scan
1197 the list. There may be more than one if it is an A6 RR. */
1199 for (da = dns_address_from_rr(dnsa, rr); da != NULL; da = da->next)
1201 /* If the client IP address matches the target IP address, it's good! */
1203 DEBUG(D_acl) debug_printf("CSA target address is %s\n", da->address);
1205 if (strcmpic(sender_host_address, da->address) == 0) return CSA_OK;
1209 /* If we found some target addresses but none of them matched, the client is
1210 using an unauthorized IP address, otherwise the target has no authorized IP
1213 if (target_found) return CSA_FAIL_MISMATCH;
1214 else return CSA_FAIL_NOADDR;
1219 /*************************************************
1220 * Verify Client SMTP Authorization *
1221 *************************************************/
1223 /* Called from acl_verify() below. This routine calls dns_lookup_special()
1224 to find the CSA SRV record corresponding to the domain argument, or
1225 $sender_helo_name if no argument is provided. It then checks that the
1226 client is authorized, and that its IP address corresponds to the SRV
1227 target's address by calling acl_verify_csa_address() above. The address
1228 should have been returned in the DNS response's ADDITIONAL section, but if
1229 not we perform another DNS lookup to get it.
1232 domain pointer to optional parameter following verify = csa
1234 Returns: CSA_UNKNOWN no valid CSA record found
1235 CSA_OK successfully authorized
1236 CSA_FAIL_* client is definitely not authorized
1237 CSA_DEFER_* there was a DNS problem
1241 acl_verify_csa(uschar *domain)
1245 int priority, weight, port;
1252 /* Work out the domain we are using for the CSA lookup. The default is the
1253 client's HELO domain. If the client has not said HELO, use its IP address
1254 instead. If it's a local client (exim -bs), CSA isn't applicable. */
1256 while (isspace(*domain) && *domain != '\0') ++domain;
1257 if (*domain == '\0') domain = sender_helo_name;
1258 if (domain == NULL) domain = sender_host_address;
1259 if (sender_host_address == NULL) return CSA_UNKNOWN;
1261 /* If we have an address literal, strip off the framing ready for turning it
1262 into a domain. The framing consists of matched square brackets possibly
1263 containing a keyword and a colon before the actual IP address. */
1265 if (domain[0] == '[')
1267 uschar *start = Ustrchr(domain, ':');
1268 if (start == NULL) start = domain;
1269 domain = string_copyn(start + 1, Ustrlen(start) - 2);
1272 /* Turn domains that look like bare IP addresses into domains in the reverse
1273 DNS. This code also deals with address literals and $sender_host_address. It's
1274 not quite kosher to treat bare domains such as EHLO 192.0.2.57 the same as
1275 address literals, but it's probably the most friendly thing to do. This is an
1276 extension to CSA, so we allow it to be turned off for proper conformance. */
1278 if (string_is_ip_address(domain, NULL) != 0)
1280 if (!dns_csa_use_reverse) return CSA_UNKNOWN;
1281 dns_build_reverse(domain, target);
1285 /* Find out if we've already done the CSA check for this domain. If we have,
1286 return the same result again. Otherwise build a new cached result structure
1287 for this domain. The name is filled in now, and the value is filled in when
1288 we return from this function. */
1290 t = tree_search(csa_cache, domain);
1291 if (t != NULL) return t->data.val;
1293 t = store_get_perm(sizeof(tree_node) + Ustrlen(domain));
1294 Ustrcpy(t->name, domain);
1295 (void)tree_insertnode(&csa_cache, t);
1297 /* Now we are ready to do the actual DNS lookup(s). */
1300 switch (dns_special_lookup(&dnsa, domain, T_CSA, &found))
1302 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1305 return t->data.val = CSA_DEFER_SRV;
1307 /* If we found nothing, the client's authorization is unknown. */
1311 return t->data.val = CSA_UNKNOWN;
1313 /* We got something! Go on to look at the reply in more detail. */
1319 /* Scan the reply for well-formed CSA SRV records. */
1321 for (rr = dns_next_rr(&dnsa, &dnss, RESET_ANSWERS);
1323 rr = dns_next_rr(&dnsa, &dnss, RESET_NEXT))
1325 if (rr->type != T_SRV) continue;
1327 /* Extract the numerical SRV fields (p is incremented) */
1330 GETSHORT(priority, p);
1331 GETSHORT(weight, p);
1335 debug_printf("CSA priority=%d weight=%d port=%d\n", priority, weight, port);
1337 /* Check the CSA version number */
1339 if (priority != 1) continue;
1341 /* If the domain does not have a CSA SRV record of its own (i.e. the domain
1342 found by dns_special_lookup() is a parent of the one we asked for), we check
1343 the subdomain assertions in the port field. At the moment there's only one
1344 assertion: legitimate SMTP clients are all explicitly authorized with CSA
1345 SRV records of their own. */
1347 if (found != domain)
1350 return t->data.val = CSA_FAIL_EXPLICIT;
1352 return t->data.val = CSA_UNKNOWN;
1355 /* This CSA SRV record refers directly to our domain, so we check the value
1356 in the weight field to work out the domain's authorization. 0 and 1 are
1357 unauthorized; 3 means the client is authorized but we can't check the IP
1358 address in order to authenticate it, so we treat it as unknown; values
1359 greater than 3 are undefined. */
1361 if (weight < 2) return t->data.val = CSA_FAIL_DOMAIN;
1363 if (weight > 2) continue;
1365 /* Weight == 2, which means the domain is authorized. We must check that the
1366 client's IP address is listed as one of the SRV target addresses. Save the
1367 target hostname then break to scan the additional data for its addresses. */
1369 (void)dn_expand(dnsa.answer, dnsa.answer + dnsa.answerlen, p,
1370 (DN_EXPAND_ARG4_TYPE)target, sizeof(target));
1372 DEBUG(D_acl) debug_printf("CSA target is %s\n", target);
1377 /* If we didn't break the loop then no appropriate records were found. */
1379 if (rr == NULL) return t->data.val = CSA_UNKNOWN;
1381 /* Do not check addresses if the target is ".", in accordance with RFC 2782.
1382 A target of "." indicates there are no valid addresses, so the client cannot
1383 be authorized. (This is an odd configuration because weight=2 target=. is
1384 equivalent to weight=1, but we check for it in order to keep load off the
1385 root name servers.) Note that dn_expand() turns "." into "". */
1387 if (Ustrcmp(target, "") == 0) return t->data.val = CSA_FAIL_NOADDR;
1389 /* Scan the additional section of the CSA SRV reply for addresses belonging
1390 to the target. If the name server didn't return any additional data (e.g.
1391 because it does not fully support SRV records), we need to do another lookup
1392 to obtain the target addresses; otherwise we have a definitive result. */
1394 rc = acl_verify_csa_address(&dnsa, &dnss, RESET_ADDITIONAL, target);
1395 if (rc != CSA_FAIL_NOADDR) return t->data.val = rc;
1397 /* The DNS lookup type corresponds to the IP version used by the client. */
1400 if (Ustrchr(sender_host_address, ':') != NULL)
1403 #endif /* HAVE_IPV6 */
1407 #if HAVE_IPV6 && defined(SUPPORT_A6)
1411 switch (dns_lookup(&dnsa, target, type, NULL))
1413 /* If something bad happened (most commonly DNS_AGAIN), defer. */
1416 return t->data.val = CSA_DEFER_ADDR;
1418 /* If the query succeeded, scan the addresses and return the result. */
1421 rc = acl_verify_csa_address(&dnsa, &dnss, RESET_ANSWERS, target);
1422 if (rc != CSA_FAIL_NOADDR) return t->data.val = rc;
1423 /* else fall through */
1425 /* If the target has no IP addresses, the client cannot have an authorized
1426 IP address. However, if the target site uses A6 records (not AAAA records)
1427 we have to do yet another lookup in order to check them. */
1432 #if HAVE_IPV6 && defined(SUPPORT_A6)
1433 if (type == T_AAAA) { type = T_A6; goto DNS_LOOKUP_AGAIN; }
1436 return t->data.val = CSA_FAIL_NOADDR;
1442 /*************************************************
1443 * Handle verification (address & other) *
1444 *************************************************/
1446 /* This function implements the "verify" condition. It is called when
1447 encountered in any ACL, because some tests are almost always permitted. Some
1448 just don't make sense, and always fail (for example, an attempt to test a host
1449 lookup for a non-TCP/IP message). Others are restricted to certain ACLs.
1452 where where called from
1453 addr the recipient address that the ACL is handling, or NULL
1454 arg the argument of "verify"
1455 user_msgptr pointer for user message
1456 log_msgptr pointer for log message
1457 basic_errno where to put verify errno
1459 Returns: OK verification condition succeeded
1460 FAIL verification failed
1461 DEFER there was a problem verifying
1466 acl_verify(int where, address_item *addr, uschar *arg,
1467 uschar **user_msgptr, uschar **log_msgptr, int *basic_errno)
1471 int callout_overall = -1;
1472 int callout_connect = -1;
1473 int verify_options = 0;
1475 BOOL verify_header_sender = FALSE;
1476 BOOL defer_ok = FALSE;
1477 BOOL callout_defer_ok = FALSE;
1478 BOOL no_details = FALSE;
1479 BOOL success_on_redirect = FALSE;
1480 address_item *sender_vaddr = NULL;
1481 uschar *verify_sender_address = NULL;
1482 uschar *pm_mailfrom = NULL;
1483 uschar *se_mailfrom = NULL;
1485 /* Some of the verify items have slash-separated options; some do not. Diagnose
1486 an error if options are given for items that don't expect them. This code has
1487 now got very message. Refactoring to use a table would be a good idea one day.
1490 uschar *slash = Ustrchr(arg, '/');
1492 uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);
1494 if (ss == NULL) goto BAD_VERIFY;
1496 /* Handle name/address consistency verification in a separate function. */
1498 if (strcmpic(ss, US"reverse_host_lookup") == 0)
1500 if (slash != NULL) goto NO_OPTIONS;
1501 if (sender_host_address == NULL) return OK;
1502 return acl_verify_reverse(user_msgptr, log_msgptr);
1505 /* TLS certificate verification is done at STARTTLS time; here we just
1506 test whether it was successful or not. (This is for optional verification; for
1507 mandatory verification, the connection doesn't last this long.) */
1509 if (strcmpic(ss, US"certificate") == 0)
1511 if (slash != NULL) goto NO_OPTIONS;
1512 if (tls_certificate_verified) return OK;
1513 *user_msgptr = US"no verified certificate";
1517 /* We can test the result of optional HELO verification that might have
1518 occurred earlier. If not, we can attempt the verification now. */
1520 if (strcmpic(ss, US"helo") == 0)
1522 if (slash != NULL) goto NO_OPTIONS;
1523 if (!helo_verified && !helo_verify_failed) smtp_verify_helo();
1524 return helo_verified? OK : FAIL;
1527 /* Do Client SMTP Authorization checks in a separate function, and turn the
1528 result code into user-friendly strings. */
1530 if (strcmpic(ss, US"csa") == 0)
1532 rc = acl_verify_csa(list);
1533 *log_msgptr = *user_msgptr = string_sprintf("client SMTP authorization %s",
1534 csa_reason_string[rc]);
1535 csa_status = csa_status_string[rc];
1536 DEBUG(D_acl) debug_printf("CSA result %s\n", csa_status);
1537 return csa_return_code[rc];
1540 /* Check that all relevant header lines have the correct syntax. If there is
1541 a syntax error, we return details of the error to the sender if configured to
1542 send out full details. (But a "message" setting on the ACL can override, as
1545 if (strcmpic(ss, US"header_syntax") == 0)
1547 if (slash != NULL) goto NO_OPTIONS;
1548 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1549 rc = verify_check_headers(log_msgptr);
1550 if (rc != OK && smtp_return_error_details && *log_msgptr != NULL)
1551 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1555 /* Check that no recipient of this message is "blind", that is, every envelope
1556 recipient must be mentioned in either To: or Cc:. */
1558 if (strcmpic(ss, US"not_blind") == 0)
1560 if (slash != NULL) goto NO_OPTIONS;
1561 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1562 rc = verify_check_notblind();
1565 *log_msgptr = string_sprintf("bcc recipient detected");
1566 if (smtp_return_error_details)
1567 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1572 /* The remaining verification tests check recipient and sender addresses,
1573 either from the envelope or from the header. There are a number of
1574 slash-separated options that are common to all of them. */
1577 /* Check that there is at least one verifiable sender address in the relevant
1578 header lines. This can be followed by callout and defer options, just like
1579 sender and recipient. */
1581 if (strcmpic(ss, US"header_sender") == 0)
1583 if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP) goto WRONG_ACL;
1584 verify_header_sender = TRUE;
1587 /* Otherwise, first item in verify argument must be "sender" or "recipient".
1588 In the case of a sender, this can optionally be followed by an address to use
1589 in place of the actual sender (rare special-case requirement). */
1591 else if (strncmpic(ss, US"sender", 6) == 0)
1594 if (where > ACL_WHERE_NOTSMTP)
1596 *log_msgptr = string_sprintf("cannot verify sender in ACL for %s "
1597 "(only possible for MAIL, RCPT, PREDATA, or DATA)",
1598 acl_wherenames[where]);
1602 verify_sender_address = sender_address;
1605 while (isspace(*s)) s++;
1606 if (*s++ != '=') goto BAD_VERIFY;
1607 while (isspace(*s)) s++;
1608 verify_sender_address = string_copy(s);
1613 if (strcmpic(ss, US"recipient") != 0) goto BAD_VERIFY;
1616 *log_msgptr = string_sprintf("cannot verify recipient in ACL for %s "
1617 "(only possible for RCPT)", acl_wherenames[where]);
1622 /* Remaining items are optional; they apply to sender and recipient
1623 verification, including "header sender" verification. */
1625 while ((ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))
1628 if (strcmpic(ss, US"defer_ok") == 0) defer_ok = TRUE;
1629 else if (strcmpic(ss, US"no_details") == 0) no_details = TRUE;
1630 else if (strcmpic(ss, US"success_on_redirect") == 0) success_on_redirect = TRUE;
1632 /* These two old options are left for backwards compatibility */
1634 else if (strcmpic(ss, US"callout_defer_ok") == 0)
1636 callout_defer_ok = TRUE;
1637 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1640 else if (strcmpic(ss, US"check_postmaster") == 0)
1643 if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
1646 /* The callout option has a number of sub-options, comma separated */
1648 else if (strncmpic(ss, US"callout", 7) == 0)
1650 callout = CALLOUT_TIMEOUT_DEFAULT;
1654 while (isspace(*ss)) ss++;
1660 while (isspace(*ss)) ss++;
1662 /* This callout option handling code has become a mess as new options
1663 have been added in an ad hoc manner. It should be tidied up into some
1664 kind of table-driven thing. */
1666 while ((opt = string_nextinlist(&ss, &optsep, buffer, sizeof(buffer)))
1669 if (strcmpic(opt, US"defer_ok") == 0) callout_defer_ok = TRUE;
1670 else if (strcmpic(opt, US"no_cache") == 0)
1671 verify_options |= vopt_callout_no_cache;
1672 else if (strcmpic(opt, US"random") == 0)
1673 verify_options |= vopt_callout_random;
1674 else if (strcmpic(opt, US"use_sender") == 0)
1675 verify_options |= vopt_callout_recipsender;
1676 else if (strcmpic(opt, US"use_postmaster") == 0)
1677 verify_options |= vopt_callout_recippmaster;
1678 else if (strcmpic(opt, US"postmaster") == 0) pm_mailfrom = US"";
1679 else if (strcmpic(opt, US"fullpostmaster") == 0)
1682 verify_options |= vopt_callout_fullpm;
1685 else if (strncmpic(opt, US"mailfrom", 8) == 0)
1687 if (!verify_header_sender)
1689 *log_msgptr = string_sprintf("\"mailfrom\" is allowed as a "
1690 "callout option only for verify=header_sender (detected in ACL "
1691 "condition \"%s\")", arg);
1695 while (isspace(*opt)) opt++;
1698 *log_msgptr = string_sprintf("'=' expected after "
1699 "\"mailfrom\" in ACL condition \"%s\"", arg);
1702 while (isspace(*opt)) opt++;
1703 se_mailfrom = string_copy(opt);
1706 else if (strncmpic(opt, US"postmaster_mailfrom", 19) == 0)
1709 while (isspace(*opt)) opt++;
1712 *log_msgptr = string_sprintf("'=' expected after "
1713 "\"postmaster_mailfrom\" in ACL condition \"%s\"", arg);
1716 while (isspace(*opt)) opt++;
1717 pm_mailfrom = string_copy(opt);
1720 else if (strncmpic(opt, US"maxwait", 7) == 0)
1723 while (isspace(*opt)) opt++;
1726 *log_msgptr = string_sprintf("'=' expected after \"maxwait\" in "
1727 "ACL condition \"%s\"", arg);
1730 while (isspace(*opt)) opt++;
1731 callout_overall = readconf_readtime(opt, 0, FALSE);
1732 if (callout_overall < 0)
1734 *log_msgptr = string_sprintf("bad time value in ACL condition "
1735 "\"verify %s\"", arg);
1739 else if (strncmpic(opt, US"connect", 7) == 0)
1742 while (isspace(*opt)) opt++;
1745 *log_msgptr = string_sprintf("'=' expected after "
1746 "\"callout_overaall\" in ACL condition \"%s\"", arg);
1749 while (isspace(*opt)) opt++;
1750 callout_connect = readconf_readtime(opt, 0, FALSE);
1751 if (callout_connect < 0)
1753 *log_msgptr = string_sprintf("bad time value in ACL condition "
1754 "\"verify %s\"", arg);
1758 else /* Plain time is callout connect/command timeout */
1760 callout = readconf_readtime(opt, 0, FALSE);
1763 *log_msgptr = string_sprintf("bad time value in ACL condition "
1764 "\"verify %s\"", arg);
1772 *log_msgptr = string_sprintf("'=' expected after \"callout\" in "
1773 "ACL condition \"%s\"", arg);
1779 /* Option not recognized */
1783 *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1784 "condition \"verify %s\"", ss, arg);
1789 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)) ==
1790 (vopt_callout_recipsender|vopt_callout_recippmaster))
1792 *log_msgptr = US"only one of use_sender and use_postmaster can be set "
1793 "for a recipient callout";
1797 /* Handle sender-in-header verification. Default the user message to the log
1798 message if giving out verification details. */
1800 if (verify_header_sender)
1803 rc = verify_check_header_address(user_msgptr, log_msgptr, callout,
1804 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, verify_options,
1808 *basic_errno = verrno;
1809 if (smtp_return_error_details)
1811 if (*user_msgptr == NULL && *log_msgptr != NULL)
1812 *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1813 if (rc == DEFER) acl_temp_details = TRUE;
1818 /* Handle a sender address. The default is to verify *the* sender address, but
1819 optionally a different address can be given, for special requirements. If the
1820 address is empty, we are dealing with a bounce message that has no sender, so
1821 we cannot do any checking. If the real sender address gets rewritten during
1822 verification (e.g. DNS widening), set the flag to stop it being rewritten again
1823 during message reception.
1825 A list of verified "sender" addresses is kept to try to avoid doing to much
1826 work repetitively when there are multiple recipients in a message and they all
1827 require sender verification. However, when callouts are involved, it gets too
1828 complicated because different recipients may require different callout options.
1829 Therefore, we always do a full sender verify when any kind of callout is
1830 specified. Caching elsewhere, for instance in the DNS resolver and in the
1831 callout handling, should ensure that this is not terribly inefficient. */
1833 else if (verify_sender_address != NULL)
1835 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster))
1838 *log_msgptr = US"use_sender or use_postmaster cannot be used for a "
1839 "sender verify callout";
1843 sender_vaddr = verify_checked_sender(verify_sender_address);
1844 if (sender_vaddr != NULL && /* Previously checked */
1845 callout <= 0) /* No callout needed this time */
1847 /* If the "routed" flag is set, it means that routing worked before, so
1848 this check can give OK (the saved return code value, if set, belongs to a
1849 callout that was done previously). If the "routed" flag is not set, routing
1850 must have failed, so we use the saved return code. */
1852 if (testflag(sender_vaddr, af_verify_routed)) rc = OK; else
1854 rc = sender_vaddr->special_action;
1855 *basic_errno = sender_vaddr->basic_errno;
1857 HDEBUG(D_acl) debug_printf("using cached sender verify result\n");
1860 /* Do a new verification, and cache the result. The cache is used to avoid
1861 verifying the sender multiple times for multiple RCPTs when callouts are not
1862 specified (see comments above).
1864 The cache is also used on failure to give details in response to the first
1865 RCPT that gets bounced for this reason. However, this can be suppressed by
1866 the no_details option, which sets the flag that says "this detail has already
1867 been sent". The cache normally contains just one address, but there may be
1868 more in esoteric circumstances. */
1873 uschar *save_address_data = deliver_address_data;
1875 sender_vaddr = deliver_make_addr(verify_sender_address, TRUE);
1876 if (no_details) setflag(sender_vaddr, af_sverify_told);
1877 if (verify_sender_address[0] != 0)
1879 /* If this is the real sender address, save the unrewritten version
1880 for use later in receive. Otherwise, set a flag so that rewriting the
1881 sender in verify_address() does not update sender_address. */
1883 if (verify_sender_address == sender_address)
1884 sender_address_unrewritten = sender_address;
1886 verify_options |= vopt_fake_sender;
1888 if (success_on_redirect)
1889 verify_options |= vopt_success_on_redirect;
1891 /* The recipient, qualify, and expn options are never set in
1894 rc = verify_address(sender_vaddr, NULL, verify_options, callout,
1895 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, &routed);
1897 HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1901 if (Ustrcmp(sender_vaddr->address, verify_sender_address) != 0)
1903 DEBUG(D_acl) debug_printf("sender %s verified ok as %s\n",
1904 verify_sender_address, sender_vaddr->address);
1908 DEBUG(D_acl) debug_printf("sender %s verified ok\n",
1909 verify_sender_address);
1912 else *basic_errno = sender_vaddr->basic_errno;
1914 else rc = OK; /* Null sender */
1916 /* Cache the result code */
1918 if (routed) setflag(sender_vaddr, af_verify_routed);
1919 if (callout > 0) setflag(sender_vaddr, af_verify_callout);
1920 sender_vaddr->special_action = rc;
1921 sender_vaddr->next = sender_verified_list;
1922 sender_verified_list = sender_vaddr;
1924 /* Restore the recipient address data, which might have been clobbered by
1925 the sender verification. */
1927 deliver_address_data = save_address_data;
1930 /* Put the sender address_data value into $sender_address_data */
1932 sender_address_data = sender_vaddr->p.address_data;
1935 /* A recipient address just gets a straightforward verify; again we must handle
1936 the DEFER overrides. */
1942 if (success_on_redirect)
1943 verify_options |= vopt_success_on_redirect;
1945 /* We must use a copy of the address for verification, because it might
1949 rc = verify_address(&addr2, NULL, verify_options|vopt_is_recipient, callout,
1950 callout_overall, callout_connect, se_mailfrom, pm_mailfrom, NULL);
1951 HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1953 *log_msgptr = addr2.message;
1954 *user_msgptr = (addr2.user_message != NULL)?
1955 addr2.user_message : addr2.message;
1956 *basic_errno = addr2.basic_errno;
1958 /* Make $address_data visible */
1959 deliver_address_data = addr2.p.address_data;
1962 /* We have a result from the relevant test. Handle defer overrides first. */
1964 if (rc == DEFER && (defer_ok ||
1965 (callout_defer_ok && *basic_errno == ERRNO_CALLOUTDEFER)))
1967 HDEBUG(D_acl) debug_printf("verify defer overridden by %s\n",
1968 defer_ok? "defer_ok" : "callout_defer_ok");
1972 /* If we've failed a sender, set up a recipient message, and point
1973 sender_verified_failed to the address item that actually failed. */
1975 if (rc != OK && verify_sender_address != NULL)
1979 *log_msgptr = *user_msgptr = US"Sender verify failed";
1981 else if (*basic_errno != ERRNO_CALLOUTDEFER)
1983 *log_msgptr = *user_msgptr = US"Could not complete sender verify";
1987 *log_msgptr = US"Could not complete sender verify callout";
1988 *user_msgptr = smtp_return_error_details? sender_vaddr->user_message :
1992 sender_verified_failed = sender_vaddr;
1995 /* Verifying an address messes up the values of $domain and $local_part,
1996 so reset them before returning if this is a RCPT ACL. */
2000 deliver_domain = addr->domain;
2001 deliver_localpart = addr->local_part;
2005 /* Syntax errors in the verify argument come here. */
2008 *log_msgptr = string_sprintf("expected \"sender[=address]\", \"recipient\", "
2009 "\"helo\", \"header_syntax\", \"header_sender\" or "
2010 "\"reverse_host_lookup\" at start of ACL condition "
2011 "\"verify %s\"", arg);
2014 /* Options supplied when not allowed come here */
2017 *log_msgptr = string_sprintf("unexpected '/' found in \"%s\" "
2018 "(this verify item has no options)", arg);
2021 /* Calls in the wrong ACL come here */
2024 *log_msgptr = string_sprintf("cannot check header contents in ACL for %s "
2025 "(only possible in ACL for DATA)", acl_wherenames[where]);
2032 /*************************************************
2033 * Check argument for control= modifier *
2034 *************************************************/
2036 /* Called from acl_check_condition() below
2039 arg the argument string for control=
2040 pptr set to point to the terminating character
2041 where which ACL we are in
2042 log_msgptr for error messages
2044 Returns: CONTROL_xxx value
2048 decode_control(uschar *arg, uschar **pptr, int where, uschar **log_msgptr)
2053 for (d = controls_list;
2054 d < controls_list + sizeof(controls_list)/sizeof(control_def);
2057 len = Ustrlen(d->name);
2058 if (Ustrncmp(d->name, arg, len) == 0) break;
2061 if (d >= controls_list + sizeof(controls_list)/sizeof(control_def) ||
2062 (arg[len] != 0 && (!d->has_option || arg[len] != '/')))
2064 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2065 return CONTROL_ERROR;
2074 /*************************************************
2075 * Handle rate limiting *
2076 *************************************************/
2078 /* Called by acl_check_condition() below to calculate the result
2079 of the ACL ratelimit condition.
2081 Note that the return value might be slightly unexpected: if the
2082 sender's rate is above the limit then the result is OK. This is
2083 similar to the dnslists condition, and is so that you can write
2084 ACL clauses like: defer ratelimit = 15 / 1h
2087 arg the option string for ratelimit=
2088 where ACL_WHERE_xxxx indicating which ACL this is
2089 log_msgptr for error messages
2091 Returns: OK - Sender's rate is above limit
2092 FAIL - Sender's rate is below limit
2093 DEFER - Problem opening ratelimit database
2094 ERROR - Syntax error in options.
2098 acl_ratelimit(uschar *arg, int where, uschar **log_msgptr)
2100 double limit, period;
2103 BOOL have_key = FALSE, leaky = FALSE, strict = FALSE;
2104 BOOL per_byte = FALSE, per_cmd = FALSE, per_conn = FALSE, per_mail = FALSE;
2106 tree_node **anchor, *t;
2107 open_db dbblock, *dbm;
2108 dbdata_ratelimit *dbd;
2111 /* Parse the first two options and record their values in expansion
2112 variables. These variables allow the configuration to have informative
2113 error messages based on rate limits obtained from a table lookup. */
2115 /* First is the maximum number of messages per period and maximum burst
2116 size, which must be greater than or equal to zero. Zero is useful for
2117 rate measurement as opposed to rate limiting. */
2119 sender_rate_limit = string_nextinlist(&arg, &sep, NULL, 0);
2120 if (sender_rate_limit == NULL)
2124 limit = Ustrtod(sender_rate_limit, &ss);
2125 if (tolower(*ss) == 'k') { limit *= 1024.0; ss++; }
2126 else if (tolower(*ss) == 'm') { limit *= 1024.0*1024.0; ss++; }
2127 else if (tolower(*ss) == 'g') { limit *= 1024.0*1024.0*1024.0; ss++; }
2129 if (limit < 0.0 || *ss != 0)
2131 *log_msgptr = string_sprintf("syntax error in argument for "
2132 "\"ratelimit\" condition: \"%s\" is not a positive number",
2137 /* We use the rest of the argument list following the limit as the
2138 lookup key, because it doesn't make sense to use the same stored data
2139 if the period or options are different. */
2143 /* Second is the rate measurement period and exponential smoothing time
2144 constant. This must be strictly greater than zero, because zero leads to
2145 run-time division errors. */
2147 sender_rate_period = string_nextinlist(&arg, &sep, NULL, 0);
2148 if (sender_rate_period == NULL) period = -1.0;
2149 else period = readconf_readtime(sender_rate_period, 0, FALSE);
2152 *log_msgptr = string_sprintf("syntax error in argument for "
2153 "\"ratelimit\" condition: \"%s\" is not a time value",
2154 sender_rate_period);
2158 /* Parse the other options. Should we check if the per_* options are being
2159 used in ACLs where they don't make sense, e.g. per_mail in the connect ACL? */
2161 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
2164 if (strcmpic(ss, US"leaky") == 0) leaky = TRUE;
2165 else if (strcmpic(ss, US"strict") == 0) strict = TRUE;
2166 else if (strcmpic(ss, US"per_byte") == 0) per_byte = TRUE;
2167 else if (strcmpic(ss, US"per_cmd") == 0) per_cmd = TRUE;
2168 else if (strcmpic(ss, US"per_conn") == 0) per_conn = TRUE;
2169 else if (strcmpic(ss, US"per_mail") == 0) per_mail = TRUE;
2170 else if (strcmpic(ss, US"per_rcpt") == 0) per_cmd = TRUE; /* alias */
2171 else have_key = TRUE;
2173 if (leaky + strict > 1 || per_byte + per_cmd + per_conn + per_mail > 1)
2175 *log_msgptr = US"conflicting options for \"ratelimit\" condition";
2179 /* Default option values */
2180 if (!strict) leaky = TRUE;
2181 if (!per_byte && !per_cmd && !per_conn) per_mail = TRUE;
2183 /* If there is no explicit key, use the sender_host_address. If there is no
2184 sender_host_address (e.g. -bs or acl_not_smtp) then we simply omit it. */
2186 if (!have_key && sender_host_address != NULL)
2187 key = string_sprintf("%s / %s", key, sender_host_address);
2189 HDEBUG(D_acl) debug_printf("ratelimit condition limit=%.0f period=%.0f key=%s\n",
2190 limit, period, key);
2192 /* See if we have already computed the rate by looking in the relevant tree. For
2193 per-connection rate limiting, store tree nodes and dbdata in the permanent pool
2194 so that they survive across resets. */
2197 old_pool = store_pool;
2201 anchor = &ratelimiters_conn;
2202 store_pool = POOL_PERM;
2204 else if (per_mail || per_byte)
2205 anchor = &ratelimiters_mail;
2207 anchor = &ratelimiters_cmd;
2209 if (anchor != NULL && (t = tree_search(*anchor, key)) != NULL)
2212 /* The following few lines duplicate some of the code below. */
2213 if (dbd->rate < limit) rc = FAIL;
2215 store_pool = old_pool;
2216 sender_rate = string_sprintf("%.1f", dbd->rate);
2218 debug_printf("ratelimit found pre-computed rate %s\n", sender_rate);
2222 /* We aren't using a pre-computed rate, so get a previously recorded
2223 rate from the database, update it, and write it back. If there's no
2224 previous rate for this key, create one. */
2226 dbm = dbfn_open(US"ratelimit", O_RDWR, &dbblock, TRUE);
2229 store_pool = old_pool;
2231 HDEBUG(D_acl) debug_printf("ratelimit database not available\n");
2232 *log_msgptr = US"ratelimit database not available";
2235 dbd = dbfn_read(dbm, key);
2237 gettimeofday(&tv, NULL);
2241 HDEBUG(D_acl) debug_printf("ratelimit initializing new key's data\n");
2242 dbd = store_get(sizeof(dbdata_ratelimit));
2243 dbd->time_stamp = tv.tv_sec;
2244 dbd->time_usec = tv.tv_usec;
2249 /* The smoothed rate is computed using an exponentially weighted moving
2250 average adjusted for variable sampling intervals. The standard EWMA for
2251 a fixed sampling interval is: f'(t) = (1 - a) * f(t) + a * f'(t - 1)
2252 where f() is the measured value and f'() is the smoothed value.
2254 Old data decays out of the smoothed value exponentially, such that data n
2255 samples old is multiplied by a^n. The exponential decay time constant p
2256 is defined such that data p samples old is multiplied by 1/e, which means
2257 that a = exp(-1/p). We can maintain the same time constant for a variable
2258 sampling interval i by using a = exp(-i/p).
2260 The rate we are measuring is messages per period, suitable for directly
2261 comparing with the limit. The average rate between now and the previous
2262 message is period / interval, which we feed into the EWMA as the sample.
2264 It turns out that the number of messages required for the smoothed rate
2265 to reach the limit when they are sent in a burst is equal to the limit.
2266 This can be seen by analysing the value of the smoothed rate after N
2267 messages sent at even intervals. Let k = (1 - a) * p/i
2269 rate_1 = (1 - a) * p/i + a * rate_0
2271 rate_2 = k + a * rate_1
2272 = k + a * k + a^2 * rate_0
2273 rate_3 = k + a * k + a^2 * k + a^3 * rate_0
2274 rate_N = rate_0 * a^N + k * SUM(x=0..N-1)(a^x)
2275 = rate_0 * a^N + k * (1 - a^N) / (1 - a)
2276 = rate_0 * a^N + p/i * (1 - a^N)
2278 When N is large, a^N -> 0 so rate_N -> p/i as desired.
2280 rate_N = p/i + (rate_0 - p/i) * a^N
2281 a^N = (rate_N - p/i) / (rate_0 - p/i)
2282 N * -i/p = log((rate_N - p/i) / (rate_0 - p/i))
2283 N = p/i * log((rate_0 - p/i) / (rate_N - p/i))
2285 Numerical analysis of the above equation, setting the computed rate to
2286 increase from rate_0 = 0 to rate_N = limit, shows that for large sending
2287 rates, p/i, the number of messages N = limit. So limit serves as both the
2288 maximum rate measured in messages per period, and the maximum number of
2289 messages that can be sent in a fast burst. */
2291 double this_time = (double)tv.tv_sec
2292 + (double)tv.tv_usec / 1000000.0;
2293 double prev_time = (double)dbd->time_stamp
2294 + (double)dbd->time_usec / 1000000.0;
2296 /* We must avoid division by zero, and deal gracefully with the clock going
2297 backwards. If we blunder ahead when time is in reverse then the computed
2298 rate will be bogus. To be safe we clamp interval to a very small number. */
2300 double interval = this_time - prev_time <= 0.0 ? 1e-9
2301 : this_time - prev_time;
2303 double i_over_p = interval / period;
2304 double a = exp(-i_over_p);
2306 dbd->time_stamp = tv.tv_sec;
2307 dbd->time_usec = tv.tv_usec;
2309 /* If we are measuring the rate in bytes per period, multiply the
2310 measured rate by the message size. If we don't know the message size
2311 then it's safe to just use a value of zero and let the recorded rate
2312 decay as if nothing happened. */
2315 dbd->rate = (message_size < 0 ? 0.0 : (double)message_size)
2316 * (1 - a) / i_over_p + a * dbd->rate;
2317 else if (per_cmd && where == ACL_WHERE_NOTSMTP)
2318 dbd->rate = (double)recipients_count
2319 * (1 - a) / i_over_p + a * dbd->rate;
2321 dbd->rate = (1 - a) / i_over_p + a * dbd->rate;
2324 /* Clients sending at the limit are considered to be over the limit. This
2325 matters for edge cases such the first message sent by a client (which gets
2326 the initial rate of 0.0) when the rate limit is zero (i.e. the client should
2327 be completely blocked). */
2329 if (dbd->rate < limit) rc = FAIL;
2332 /* Update the state if the rate is low or if we are being strict. If we
2333 are in leaky mode and the sender's rate is too high, we do not update
2334 the recorded rate in order to avoid an over-aggressive sender's retry
2335 rate preventing them from getting any email through. */
2337 if (rc == FAIL || !leaky)
2338 dbfn_write(dbm, key, dbd, sizeof(dbdata_ratelimit));
2341 /* Store the result in the tree for future reference, if necessary. */
2345 t = store_get(sizeof(tree_node) + Ustrlen(key));
2347 Ustrcpy(t->name, key);
2348 (void)tree_insertnode(anchor, t);
2351 /* We create the formatted version of the sender's rate very late in
2352 order to ensure that it is done using the correct storage pool. */
2354 store_pool = old_pool;
2355 sender_rate = string_sprintf("%.1f", dbd->rate);
2358 debug_printf("ratelimit computed rate %s\n", sender_rate);
2365 /*************************************************
2366 * Handle conditions/modifiers on an ACL item *
2367 *************************************************/
2369 /* Called from acl_check() below.
2373 cb ACL condition block - if NULL, result is OK
2374 where where called from
2375 addr the address being checked for RCPT, or NULL
2376 level the nesting level
2377 epp pointer to pass back TRUE if "endpass" encountered
2378 (applies only to "accept" and "discard")
2379 user_msgptr user message pointer
2380 log_msgptr log message pointer
2381 basic_errno pointer to where to put verify error
2383 Returns: OK - all conditions are met
2384 DISCARD - an "acl" condition returned DISCARD - only allowed
2385 for "accept" or "discard" verbs
2386 FAIL - at least one condition fails
2387 FAIL_DROP - an "acl" condition returned FAIL_DROP
2388 DEFER - can't tell at the moment (typically, lookup defer,
2389 but can be temporary callout problem)
2390 ERROR - ERROR from nested ACL or expansion failure or other
2395 acl_check_condition(int verb, acl_condition_block *cb, int where,
2396 address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
2397 uschar **log_msgptr, int *basic_errno)
2399 uschar *user_message = NULL;
2400 uschar *log_message = NULL;
2403 #ifdef WITH_CONTENT_SCAN
2407 for (; cb != NULL; cb = cb->next)
2412 /* The message and log_message items set up messages to be used in
2413 case of rejection. They are expanded later. */
2415 if (cb->type == ACLC_MESSAGE)
2417 user_message = cb->arg;
2421 if (cb->type == ACLC_LOG_MESSAGE)
2423 log_message = cb->arg;
2427 /* The endpass "condition" just sets a flag to show it occurred. This is
2428 checked at compile time to be on an "accept" or "discard" item. */
2430 if (cb->type == ACLC_ENDPASS)
2436 /* For other conditions and modifiers, the argument is expanded now for some
2437 of them, but not for all, because expansion happens down in some lower level
2438 checking functions in some cases. */
2440 if (cond_expand_at_top[cb->type])
2442 arg = expand_string(cb->arg);
2445 if (expand_string_forcedfail) continue;
2446 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
2447 cb->arg, expand_string_message);
2448 return search_find_defer? DEFER : ERROR;
2453 /* Show condition, and expanded condition if it's different */
2458 debug_printf("check %s%s %n",
2459 (!cond_modifiers[cb->type] && cb->u.negated)? "!":"",
2460 conditions[cb->type], &lhswidth);
2462 if (cb->type == ACLC_SET)
2464 debug_printf("acl_%s ", cb->u.varname);
2465 lhswidth += 5 + Ustrlen(cb->u.varname);
2468 debug_printf("= %s\n", cb->arg);
2471 debug_printf("%.*s= %s\n", lhswidth,
2475 /* Check that this condition makes sense at this time */
2477 if ((cond_forbids[cb->type] & (1 << where)) != 0)
2479 *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
2480 cond_modifiers[cb->type]? "use" : "test",
2481 conditions[cb->type], acl_wherenames[where]);
2485 /* Run the appropriate test for each condition, or take the appropriate
2486 action for the remaining modifiers. */
2490 case ACLC_ADD_HEADER:
2494 /* A nested ACL that returns "discard" makes sense only for an "accept" or
2498 rc = acl_check_internal(where, addr, arg, level+1, user_msgptr, log_msgptr);
2499 if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
2501 *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
2502 "\"%s\" command (only allowed with \"accept\" or \"discard\")",
2508 case ACLC_AUTHENTICATED:
2509 rc = (sender_host_authenticated == NULL)? FAIL :
2510 match_isinlist(sender_host_authenticated, &arg, 0, NULL, NULL, MCL_STRING,
2514 #ifdef EXPERIMENTAL_BRIGHTMAIL
2515 case ACLC_BMI_OPTIN:
2517 int old_pool = store_pool;
2518 store_pool = POOL_PERM;
2519 bmi_current_optin = string_copy(arg);
2520 store_pool = old_pool;
2525 case ACLC_CONDITION:
2526 if (Ustrspn(arg, "0123456789") == Ustrlen(arg)) /* Digits, or empty */
2527 rc = (Uatoi(arg) == 0)? FAIL : OK;
2529 rc = (strcmpic(arg, US"no") == 0 ||
2530 strcmpic(arg, US"false") == 0)? FAIL :
2531 (strcmpic(arg, US"yes") == 0 ||
2532 strcmpic(arg, US"true") == 0)? OK : DEFER;
2534 *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
2538 control_type = decode_control(arg, &p, where, log_msgptr);
2540 /* Check if this control makes sense at this time */
2542 if ((control_forbids[control_type] & (1 << where)) != 0)
2544 *log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
2545 controls[control_type], acl_wherenames[where]);
2549 switch(control_type)
2551 case CONTROL_AUTH_UNADVERTISED:
2552 allow_auth_unadvertised = TRUE;
2555 #ifdef EXPERIMENTAL_BRIGHTMAIL
2556 case CONTROL_BMI_RUN:
2561 #ifdef EXPERIMENTAL_DOMAINKEYS
2562 case CONTROL_DK_VERIFY:
2570 case CONTROL_CASEFUL_LOCAL_PART:
2571 deliver_localpart = addr->cc_local_part;
2574 case CONTROL_CASELOWER_LOCAL_PART:
2575 deliver_localpart = addr->lc_local_part;
2578 case CONTROL_ENFORCE_SYNC:
2579 smtp_enforce_sync = TRUE;
2582 case CONTROL_NO_ENFORCE_SYNC:
2583 smtp_enforce_sync = FALSE;
2586 #ifdef WITH_CONTENT_SCAN
2587 case CONTROL_NO_MBOX_UNSPOOL:
2588 no_mbox_unspool = TRUE;
2592 case CONTROL_NO_MULTILINE:
2593 no_multiline_responses = TRUE;
2596 case CONTROL_FAKEDEFER:
2597 case CONTROL_FAKEREJECT:
2598 fake_response = (control_type == CONTROL_FAKEDEFER) ? DEFER : FAIL;
2602 while (*pp != 0) pp++;
2603 fake_response_text = expand_string(string_copyn(p+1, pp-p-1));
2608 /* Explicitly reset to default string */
2609 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).";
2613 case CONTROL_FREEZE:
2614 deliver_freeze = TRUE;
2615 deliver_frozen_at = time(NULL);
2616 freeze_tell = freeze_tell_config; /* Reset to configured value */
2617 if (Ustrncmp(p, "/no_tell", 8) == 0)
2624 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2629 case CONTROL_QUEUE_ONLY:
2630 queue_only_policy = TRUE;
2633 case CONTROL_SUBMISSION:
2634 originator_name = US"";
2635 submission_mode = TRUE;
2638 if (Ustrncmp(p, "/sender_retain", 14) == 0)
2641 active_local_sender_retain = TRUE;
2642 active_local_from_check = FALSE;
2644 else if (Ustrncmp(p, "/domain=", 8) == 0)
2647 while (*pp != 0 && *pp != '/') pp++;
2648 submission_domain = string_copyn(p+8, pp-p-8);
2651 /* The name= option must be last, because it swallows the rest of
2653 else if (Ustrncmp(p, "/name=", 6) == 0)
2656 while (*pp != 0) pp++;
2657 submission_name = string_copy(parse_fix_phrase(p+6, pp-p-6,
2658 big_buffer, big_buffer_size));
2665 *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
2670 case CONTROL_SUPPRESS_LOCAL_FIXUPS:
2671 suppress_local_fixups = TRUE;
2676 #ifdef WITH_CONTENT_SCAN
2678 rc = mime_decode(&arg);
2684 int delay = readconf_readtime(arg, 0, FALSE);
2687 *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
2688 "modifier: \"%s\" is not a time value", arg);
2693 HDEBUG(D_acl) debug_printf("delay modifier requests %d-second delay\n",
2698 debug_printf("delay skipped in -bh checking mode\n");
2701 /* It appears to be impossible to detect that a TCP/IP connection has
2702 gone away without reading from it. This means that we cannot shorten
2703 the delay below if the client goes away, because we cannot discover
2704 that the client has closed its end of the connection. (The connection
2705 is actually in a half-closed state, waiting for the server to close its
2706 end.) It would be nice to be able to detect this state, so that the
2707 Exim process is not held up unnecessarily. However, it seems that we
2708 can't. The poll() function does not do the right thing, and in any case
2709 it is not always available.
2711 NOTE: If ever this state of affairs changes, remember that we may be
2712 dealing with stdin/stdout here, in addition to TCP/IP connections.
2713 Whatever is done must work in both cases. To detected the stdin/stdout
2714 case, check for smtp_in or smtp_out being NULL. */
2718 while (delay > 0) delay = sleep(delay);
2724 #ifdef WITH_OLD_DEMIME
2730 #ifdef EXPERIMENTAL_DOMAINKEYS
2731 case ACLC_DK_DOMAIN_SOURCE:
2732 if (dk_verify_block == NULL) { rc = FAIL; break; };
2733 /* check header source of domain against given string */
2734 switch (dk_verify_block->address_source) {
2735 case DK_EXIM_ADDRESS_FROM_FROM:
2736 rc = match_isinlist(US"from", &arg, 0, NULL,
2737 NULL, MCL_STRING, TRUE, NULL);
2739 case DK_EXIM_ADDRESS_FROM_SENDER:
2740 rc = match_isinlist(US"sender", &arg, 0, NULL,
2741 NULL, MCL_STRING, TRUE, NULL);
2743 case DK_EXIM_ADDRESS_NONE:
2744 rc = match_isinlist(US"none", &arg, 0, NULL,
2745 NULL, MCL_STRING, TRUE, NULL);
2750 case ACLC_DK_POLICY:
2751 if (dk_verify_block == NULL) { rc = FAIL; break; };
2752 /* check policy against given string, default FAIL */
2754 if (dk_verify_block->signsall)
2755 rc = match_isinlist(US"signsall", &arg, 0, NULL,
2756 NULL, MCL_STRING, TRUE, NULL);
2757 if (dk_verify_block->testing)
2758 rc = match_isinlist(US"testing", &arg, 0, NULL,
2759 NULL, MCL_STRING, TRUE, NULL);
2762 case ACLC_DK_SENDER_DOMAINS:
2763 if (dk_verify_block == NULL) { rc = FAIL; break; };
2764 if (dk_verify_block->domain != NULL)
2765 rc = match_isinlist(dk_verify_block->domain, &arg, 0, &domainlist_anchor,
2766 NULL, MCL_DOMAIN, TRUE, NULL);
2770 case ACLC_DK_SENDER_LOCAL_PARTS:
2771 if (dk_verify_block == NULL) { rc = FAIL; break; };
2772 if (dk_verify_block->local_part != NULL)
2773 rc = match_isinlist(dk_verify_block->local_part, &arg, 0, &localpartlist_anchor,
2774 NULL, MCL_LOCALPART, TRUE, NULL);
2778 case ACLC_DK_SENDERS:
2779 if (dk_verify_block == NULL) { rc = FAIL; break; };
2780 if (dk_verify_block->address != NULL)
2781 rc = match_address_list(dk_verify_block->address, TRUE, TRUE, &arg, NULL, -1, 0, NULL);
2785 case ACLC_DK_STATUS:
2786 if (dk_verify_block == NULL) { rc = FAIL; break; };
2787 if (dk_verify_block->result > 0) {
2788 switch(dk_verify_block->result) {
2789 case DK_EXIM_RESULT_BAD_FORMAT:
2790 rc = match_isinlist(US"bad format", &arg, 0, NULL,
2791 NULL, MCL_STRING, TRUE, NULL);
2793 case DK_EXIM_RESULT_NO_KEY:
2794 rc = match_isinlist(US"no key", &arg, 0, NULL,
2795 NULL, MCL_STRING, TRUE, NULL);
2797 case DK_EXIM_RESULT_NO_SIGNATURE:
2798 rc = match_isinlist(US"no signature", &arg, 0, NULL,
2799 NULL, MCL_STRING, TRUE, NULL);
2801 case DK_EXIM_RESULT_REVOKED:
2802 rc = match_isinlist(US"revoked", &arg, 0, NULL,
2803 NULL, MCL_STRING, TRUE, NULL);
2805 case DK_EXIM_RESULT_NON_PARTICIPANT:
2806 rc = match_isinlist(US"non-participant", &arg, 0, NULL,
2807 NULL, MCL_STRING, TRUE, NULL);
2809 case DK_EXIM_RESULT_GOOD:
2810 rc = match_isinlist(US"good", &arg, 0, NULL,
2811 NULL, MCL_STRING, TRUE, NULL);
2813 case DK_EXIM_RESULT_BAD:
2814 rc = match_isinlist(US"bad", &arg, 0, NULL,
2815 NULL, MCL_STRING, TRUE, NULL);
2823 rc = verify_check_dnsbl(&arg);
2827 rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
2828 addr->domain_cache, MCL_DOMAIN, TRUE, &deliver_domain_data);
2831 /* The value in tls_cipher is the full cipher name, for example,
2832 TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
2833 cipher names such as DES-CBC3-SHA. But program defensively. We don't know
2834 what may in practice come out of the SSL library - which at the time of
2835 writing is poorly documented. */
2837 case ACLC_ENCRYPTED:
2838 if (tls_cipher == NULL) rc = FAIL; else
2840 uschar *endcipher = NULL;
2841 uschar *cipher = Ustrchr(tls_cipher, ':');
2842 if (cipher == NULL) cipher = tls_cipher; else
2844 endcipher = Ustrchr(++cipher, ':');
2845 if (endcipher != NULL) *endcipher = 0;
2847 rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
2848 if (endcipher != NULL) *endcipher = ':';
2852 /* Use verify_check_this_host() instead of verify_check_host() so that
2853 we can pass over &host_data to catch any looked up data. Once it has been
2854 set, it retains its value so that it's still there if another ACL verb
2855 comes through here and uses the cache. However, we must put it into
2856 permanent store in case it is also expected to be used in a subsequent
2857 message in the same SMTP connection. */
2860 rc = verify_check_this_host(&arg, sender_host_cache, NULL,
2861 (sender_host_address == NULL)? US"" : sender_host_address, &host_data);
2862 if (host_data != NULL) host_data = string_copy_malloc(host_data);
2865 case ACLC_LOCAL_PARTS:
2866 rc = match_isinlist(addr->cc_local_part, &arg, 0,
2867 &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
2868 &deliver_localpart_data);
2871 case ACLC_LOG_REJECT_TARGET:
2877 while ((ss = string_nextinlist(&s, &sep, big_buffer, big_buffer_size))
2880 if (Ustrcmp(ss, "main") == 0) logbits |= LOG_MAIN;
2881 else if (Ustrcmp(ss, "panic") == 0) logbits |= LOG_PANIC;
2882 else if (Ustrcmp(ss, "reject") == 0) logbits |= LOG_REJECT;
2885 logbits |= LOG_MAIN|LOG_REJECT;
2886 log_write(0, LOG_MAIN|LOG_PANIC, "unknown log name \"%s\" in "
2887 "\"log_reject_target\" in %s ACL", ss, acl_wherenames[where]);
2890 log_reject_target = logbits;
2903 if (Ustrncmp(s, "main", 4) == 0)
2904 { logbits |= LOG_MAIN; s += 4; }
2905 else if (Ustrncmp(s, "panic", 5) == 0)
2906 { logbits |= LOG_PANIC; s += 5; }
2907 else if (Ustrncmp(s, "reject", 6) == 0)
2908 { logbits |= LOG_REJECT; s += 6; }
2911 logbits = LOG_MAIN|LOG_PANIC;
2912 s = string_sprintf(":unknown log name in \"%s\" in "
2913 "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
2919 while (isspace(*s)) s++;
2922 if (logbits == 0) logbits = LOG_MAIN;
2923 log_write(0, logbits, "%s", string_printing(s));
2927 #ifdef WITH_CONTENT_SCAN
2930 /* Separate the regular expression and any optional parameters. */
2931 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
2932 /* Run the malware backend. */
2934 /* Modify return code based upon the existance of options. */
2935 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
2937 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
2939 /* FAIL so that the message is passed to the next ACL */
2946 case ACLC_MIME_REGEX:
2947 rc = mime_regex(&arg);
2951 case ACLC_RATELIMIT:
2952 rc = acl_ratelimit(arg, where, log_msgptr);
2955 case ACLC_RECIPIENTS:
2956 rc = match_address_list(addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
2960 #ifdef WITH_CONTENT_SCAN
2966 case ACLC_SENDER_DOMAINS:
2969 sdomain = Ustrrchr(sender_address, '@');
2970 sdomain = (sdomain == NULL)? US"" : sdomain + 1;
2971 rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
2972 sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
2977 rc = match_address_list(sender_address, TRUE, TRUE, &arg,
2978 sender_address_cache, -1, 0, &sender_data);
2981 /* Connection variables must persist forever */
2985 int old_pool = store_pool;
2986 if (cb->u.varname[0] == 'c') store_pool = POOL_PERM;
2987 acl_var_create(cb->u.varname)->data.ptr = string_copy(arg);
2988 store_pool = old_pool;
2992 #ifdef WITH_CONTENT_SCAN
2995 /* Seperate the regular expression and any optional parameters. */
2996 uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
2997 /* Run the spam backend. */
2999 /* Modify return code based upon the existance of options. */
3000 while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
3002 if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
3004 /* FAIL so that the message is passed to the next ACL */
3012 #ifdef EXPERIMENTAL_SPF
3014 rc = spf_process(&arg, sender_address);
3018 /* If the verb is WARN, discard any user message from verification, because
3019 such messages are SMTP responses, not header additions. The latter come
3020 only from explicit "message" modifiers. However, put the user message into
3021 $acl_verify_message so it can be used in subsequent conditions or modifiers
3022 (until something changes it). */
3025 rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
3026 acl_verify_message = *user_msgptr;
3027 if (verb == ACL_WARN) *user_msgptr = NULL;
3031 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
3032 "condition %d", cb->type);
3036 /* If a condition was negated, invert OK/FAIL. */
3038 if (!cond_modifiers[cb->type] && cb->u.negated)
3040 if (rc == OK) rc = FAIL;
3041 else if (rc == FAIL || rc == FAIL_DROP) rc = OK;
3044 if (rc != OK) break; /* Conditions loop */
3048 /* If the result is the one for which "message" and/or "log_message" are used,
3049 handle the values of these modifiers. If there isn't a log message set, we make
3050 it the same as the user message.
3052 "message" is a user message that will be included in an SMTP response. Unless
3053 it is empty, it overrides any previously set user message.
3055 "log_message" is a non-user message, and it adds to any existing non-user
3056 message that is already set.
3058 Most verbs have but a single return for which the messages are relevant, but
3059 for "discard", it's useful to have the log message both when it succeeds and
3060 when it fails. For "accept", the message is used in the OK case if there is no
3061 "endpass", but (for backwards compatibility) in the FAIL case if "endpass" is
3064 if (*epp && rc == OK) user_message = NULL;
3066 if (((1<<rc) & msgcond[verb]) != 0)
3069 uschar *old_user_msgptr = *user_msgptr;
3070 uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;
3072 /* If the verb is "warn", messages generated by conditions (verification or
3073 nested ACLs) are always discarded. This also happens for acceptance verbs
3074 when they actually do accept. Only messages specified at this level are used.
3075 However, the value of an existing message is available in $acl_verify_message
3076 during expansions. */
3078 if (verb == ACL_WARN ||
3079 (rc == OK && (verb == ACL_ACCEPT || verb == ACL_DISCARD)))
3080 *log_msgptr = *user_msgptr = NULL;
3082 if (user_message != NULL)
3084 acl_verify_message = old_user_msgptr;
3085 expmessage = expand_string(user_message);
3086 if (expmessage == NULL)
3088 if (!expand_string_forcedfail)
3089 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
3090 user_message, expand_string_message);
3092 else if (expmessage[0] != 0) *user_msgptr = expmessage;
3095 if (log_message != NULL)
3097 acl_verify_message = old_log_msgptr;
3098 expmessage = expand_string(log_message);
3099 if (expmessage == NULL)
3101 if (!expand_string_forcedfail)
3102 log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
3103 log_message, expand_string_message);
3105 else if (expmessage[0] != 0)
3107 *log_msgptr = (*log_msgptr == NULL)? expmessage :
3108 string_sprintf("%s: %s", expmessage, *log_msgptr);
3112 /* If no log message, default it to the user message */
3114 if (*log_msgptr == NULL) *log_msgptr = *user_msgptr;
3117 acl_verify_message = NULL;
3125 /*************************************************
3126 * Get line from a literal ACL *
3127 *************************************************/
3129 /* This function is passed to acl_read() in order to extract individual lines
3130 of a literal ACL, which we access via static pointers. We can destroy the
3131 contents because this is called only once (the compiled ACL is remembered).
3133 This code is intended to treat the data in the same way as lines in the main
3134 Exim configuration file. That is:
3136 . Leading spaces are ignored.
3138 . A \ at the end of a line is a continuation - trailing spaces after the \
3139 are permitted (this is because I don't believe in making invisible things
3140 significant). Leading spaces on the continued part of a line are ignored.
3142 . Physical lines starting (significantly) with # are totally ignored, and
3143 may appear within a sequence of backslash-continued lines.
3145 . Blank lines are ignored, but will end a sequence of continuations.
3148 Returns: a pointer to the next line
3152 static uschar *acl_text; /* Current pointer in the text */
3153 static uschar *acl_text_end; /* Points one past the terminating '0' */
3161 /* This loop handles leading blank lines and comments. */
3165 while (isspace(*acl_text)) acl_text++; /* Leading spaces/empty lines */
3166 if (*acl_text == 0) return NULL; /* No more data */
3167 yield = acl_text; /* Potential data line */
3169 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
3171 /* If we hit the end before a newline, we have the whole logical line. If
3172 it's a comment, there's no more data to be given. Otherwise, yield it. */
3174 if (*acl_text == 0) return (*yield == '#')? NULL : yield;
3176 /* After reaching a newline, end this loop if the physical line does not
3177 start with '#'. If it does, it's a comment, and the loop continues. */
3179 if (*yield != '#') break;
3182 /* This loop handles continuations. We know we have some real data, ending in
3183 newline. See if there is a continuation marker at the end (ignoring trailing
3184 white space). We know that *yield is not white space, so no need to test for
3185 cont > yield in the backwards scanning loop. */
3190 for (cont = acl_text - 1; isspace(*cont); cont--);
3192 /* If no continuation follows, we are done. Mark the end of the line and
3201 /* We have encountered a continuation. Skip over whitespace at the start of
3202 the next line, and indeed the whole of the next line or lines if they are
3207 while (*(++acl_text) == ' ' || *acl_text == '\t');
3208 if (*acl_text != '#') break;
3209 while (*(++acl_text) != 0 && *acl_text != '\n');
3212 /* We have the start of a continuation line. Move all the rest of the data
3213 to join onto the previous line, and then find its end. If the end is not a
3214 newline, we are done. Otherwise loop to look for another continuation. */
3216 memmove(cont, acl_text, acl_text_end - acl_text);
3217 acl_text_end -= acl_text - cont;
3219 while (*acl_text != 0 && *acl_text != '\n') acl_text++;
3220 if (*acl_text == 0) return yield;
3223 /* Control does not reach here */
3230 /*************************************************
3231 * Check access using an ACL *
3232 *************************************************/
3234 /* This function is called from address_check. It may recurse via
3235 acl_check_condition() - hence the use of a level to stop looping. The ACL is
3236 passed as a string which is expanded. A forced failure implies no access check
3237 is required. If the result is a single word, it is taken as the name of an ACL
3238 which is sought in the global ACL tree. Otherwise, it is taken as literal ACL
3239 text, complete with newlines, and parsed as such. In both cases, the ACL check
3240 is then run. This function uses an auxiliary function for acl_read() to call
3241 for reading individual lines of a literal ACL. This is acl_getline(), which
3242 appears immediately above.
3245 where where called from
3246 addr address item when called from RCPT; otherwise NULL
3247 s the input string; NULL is the same as an empty ACL => DENY
3248 level the nesting level
3249 user_msgptr where to put a user error (for SMTP response)
3250 log_msgptr where to put a logging message (not for SMTP response)
3252 Returns: OK access is granted
3253 DISCARD access is apparently granted...
3254 FAIL access is denied
3255 FAIL_DROP access is denied; drop the connection
3256 DEFER can't tell at the moment
3261 acl_check_internal(int where, address_item *addr, uschar *s, int level,
3262 uschar **user_msgptr, uschar **log_msgptr)
3265 acl_block *acl = NULL;
3266 uschar *acl_name = US"inline ACL";
3269 /* Catch configuration loops */
3273 *log_msgptr = US"ACL nested too deep: possible loop";
3279 HDEBUG(D_acl) debug_printf("ACL is NULL: implicit DENY\n");
3283 /* At top level, we expand the incoming string. At lower levels, it has already
3284 been expanded as part of condition processing. */
3288 ss = expand_string(s);
3291 if (expand_string_forcedfail) return OK;
3292 *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s", s,
3293 expand_string_message);
3299 while (isspace(*ss))ss++;
3301 /* If we can't find a named ACL, the default is to parse it as an inline one.
3302 (Unless it begins with a slash; non-existent files give rise to an error.) */
3306 /* Handle the case of a string that does not contain any spaces. Look for a
3307 named ACL among those read from the configuration, or a previously read file.
3308 It is possible that the pointer to the ACL is NULL if the configuration
3309 contains a name with no data. If not found, and the text begins with '/',
3310 read an ACL from a file, and save it so it can be re-used. */
3312 if (Ustrchr(ss, ' ') == NULL)
3314 tree_node *t = tree_search(acl_anchor, ss);
3317 acl = (acl_block *)(t->data.ptr);
3320 HDEBUG(D_acl) debug_printf("ACL \"%s\" is empty: implicit DENY\n", ss);
3323 acl_name = string_sprintf("ACL \"%s\"", ss);
3324 HDEBUG(D_acl) debug_printf("using ACL \"%s\"\n", ss);
3327 else if (*ss == '/')
3329 struct stat statbuf;
3330 fd = Uopen(ss, O_RDONLY, 0);
3333 *log_msgptr = string_sprintf("failed to open ACL file \"%s\": %s", ss,
3338 if (fstat(fd, &statbuf) != 0)
3340 *log_msgptr = string_sprintf("failed to fstat ACL file \"%s\": %s", ss,
3345 acl_text = store_get(statbuf.st_size + 1);
3346 acl_text_end = acl_text + statbuf.st_size + 1;
3348 if (read(fd, acl_text, statbuf.st_size) != statbuf.st_size)
3350 *log_msgptr = string_sprintf("failed to read ACL file \"%s\": %s",
3351 ss, strerror(errno));
3354 acl_text[statbuf.st_size] = 0;
3357 acl_name = string_sprintf("ACL \"%s\"", ss);
3358 HDEBUG(D_acl) debug_printf("read ACL from file %s\n", ss);
3362 /* Parse an ACL that is still in text form. If it came from a file, remember it
3363 in the ACL tree, having read it into the POOL_PERM store pool so that it
3364 persists between multiple messages. */
3368 int old_pool = store_pool;
3369 if (fd >= 0) store_pool = POOL_PERM;
3370 acl = acl_read(acl_getline, log_msgptr);
3371 store_pool = old_pool;
3372 if (acl == NULL && *log_msgptr != NULL) return ERROR;
3375 tree_node *t = store_get_perm(sizeof(tree_node) + Ustrlen(ss));
3376 Ustrcpy(t->name, ss);
3378 (void)tree_insertnode(&acl_anchor, t);
3382 /* Now we have an ACL to use. It's possible it may be NULL. */
3387 int basic_errno = 0;
3388 BOOL endpass_seen = FALSE;
3390 *log_msgptr = *user_msgptr = NULL;
3391 acl_temp_details = FALSE;
3393 if (where == ACL_WHERE_QUIT &&
3394 acl->verb != ACL_ACCEPT &&
3395 acl->verb != ACL_WARN)
3397 *log_msgptr = string_sprintf("\"%s\" is not allowed in a QUIT ACL",
3402 HDEBUG(D_acl) debug_printf("processing \"%s\"\n", verbs[acl->verb]);
3404 /* Clear out any search error message from a previous check before testing
3407 search_error_message = NULL;
3408 cond = acl_check_condition(acl->verb, acl->condition, where, addr, level,
3409 &endpass_seen, user_msgptr, log_msgptr, &basic_errno);
3411 /* Handle special returns: DEFER causes a return except on a WARN verb;
3412 ERROR always causes a return. */
3417 HDEBUG(D_acl) debug_printf("%s: condition test deferred\n", verbs[acl->verb]);
3418 if (basic_errno != ERRNO_CALLOUTDEFER)
3420 if (search_error_message != NULL && *search_error_message != 0)
3421 *log_msgptr = search_error_message;
3422 if (smtp_return_error_details) acl_temp_details = TRUE;
3426 acl_temp_details = TRUE;
3428 if (acl->verb != ACL_WARN) return DEFER;
3431 default: /* Paranoia */
3433 HDEBUG(D_acl) debug_printf("%s: condition test error\n", verbs[acl->verb]);
3437 HDEBUG(D_acl) debug_printf("%s: condition test succeeded\n",
3442 HDEBUG(D_acl) debug_printf("%s: condition test failed\n", verbs[acl->verb]);
3445 /* DISCARD and DROP can happen only from a nested ACL condition, and
3446 DISCARD can happen only for an "accept" or "discard" verb. */
3449 HDEBUG(D_acl) debug_printf("%s: condition test yielded \"discard\"\n",
3454 HDEBUG(D_acl) debug_printf("%s: condition test yielded \"drop\"\n",
3459 /* At this point, cond for most verbs is either OK or FAIL or (as a result of
3460 a nested ACL condition) FAIL_DROP. However, for WARN, cond may be DEFER, and
3461 for ACCEPT and DISCARD, it may be DISCARD after a nested ACL call. */
3466 if (cond == OK || cond == DISCARD) return cond;
3469 HDEBUG(D_acl) debug_printf("accept: endpass encountered - denying access\n");
3477 acl_temp_details = TRUE;
3483 if (cond == OK) return FAIL;
3487 if (cond == OK || cond == DISCARD) return DISCARD;
3490 HDEBUG(D_acl) debug_printf("discard: endpass encountered - denying access\n");
3496 if (cond == OK) return FAIL_DROP;
3500 if (cond != OK) return cond;
3505 acl_warn(where, *user_msgptr, *log_msgptr);
3506 else if (cond == DEFER && (log_extra_selector & LX_acl_warn_skipped) != 0)
3507 log_write(0, LOG_MAIN, "%s Warning: ACL \"warn\" statement skipped: "
3508 "condition test deferred%s%s", host_and_ident(TRUE),
3509 (*log_msgptr == NULL)? US"" : US": ",
3510 (*log_msgptr == NULL)? US"" : *log_msgptr);
3511 *log_msgptr = *user_msgptr = NULL; /* In case implicit DENY follows */
3515 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown verb %d",
3520 /* Pass to the next ACL item */
3525 /* We have reached the end of the ACL. This is an implicit DENY. */
3527 HDEBUG(D_acl) debug_printf("end of %s: implicit DENY\n", acl_name);
3532 /*************************************************
3533 * Check access using an ACL *
3534 *************************************************/
3536 /* This is the external interface for ACL checks. It sets up an address and the
3537 expansions for $domain and $local_part when called after RCPT, then calls
3538 acl_check_internal() to do the actual work.
3541 where ACL_WHERE_xxxx indicating where called from
3542 recipient RCPT address for RCPT check, else NULL
3543 s the input string; NULL is the same as an empty ACL => DENY
3544 user_msgptr where to put a user error (for SMTP response)
3545 log_msgptr where to put a logging message (not for SMTP response)
3547 Returns: OK access is granted by an ACCEPT verb
3548 DISCARD access is granted by a DISCARD verb
3549 FAIL access is denied
3550 FAIL_DROP access is denied; drop the connection
3551 DEFER can't tell at the moment
3556 acl_check(int where, uschar *recipient, uschar *s, uschar **user_msgptr,
3557 uschar **log_msgptr)
3561 address_item *addr = NULL;
3563 *user_msgptr = *log_msgptr = NULL;
3564 sender_verified_failed = NULL;
3565 ratelimiters_cmd = NULL;
3566 log_reject_target = LOG_MAIN|LOG_REJECT;
3568 if (where == ACL_WHERE_RCPT)
3570 adb = address_defaults;
3572 addr->address = recipient;
3573 if (deliver_split_address(addr) == DEFER)
3575 *log_msgptr = US"defer in percent_hack_domains check";
3578 deliver_domain = addr->domain;
3579 deliver_localpart = addr->local_part;
3582 rc = acl_check_internal(where, addr, s, 0, user_msgptr, log_msgptr);
3584 deliver_domain = deliver_localpart = deliver_address_data =
3585 sender_address_data = NULL;
3587 /* A DISCARD response is permitted only for message ACLs, excluding the PREDATA
3588 ACL, which is really in the middle of an SMTP command. */
3592 if (where > ACL_WHERE_NOTSMTP || where == ACL_WHERE_PREDATA)
3594 log_write(0, LOG_MAIN|LOG_PANIC, "\"discard\" verb not allowed in %s "
3595 "ACL", acl_wherenames[where]);
3601 /* A DROP response is not permitted from MAILAUTH */
3603 if (rc == FAIL_DROP && where == ACL_WHERE_MAILAUTH)
3605 log_write(0, LOG_MAIN|LOG_PANIC, "\"drop\" verb not allowed in %s "
3606 "ACL", acl_wherenames[where]);
3610 /* Before giving a response, take a look at the length of any user message, and
3611 split it up into multiple lines if possible. */
3613 if (*user_msgptr != NULL && Ustrlen(*user_msgptr) > 75)
3615 uschar *s = *user_msgptr = string_copy(*user_msgptr);
3621 while (i < 75 && *ss != 0 && *ss != '\n') ss++, i++;
3622 if (*ss == 0) break;
3629 while (--t > s + 35)
3633 if (t[-1] == ':') { tt = t; break; }
3634 if (tt == NULL) tt = t;
3638 if (tt == NULL) /* Can't split behind - try ahead */
3643 if (*t == ' ' || *t == '\n')
3649 if (tt == NULL) break; /* Can't find anywhere to split */
3661 /*************************************************
3662 * Create ACL variable *
3663 *************************************************/
3665 /* Create an ACL variable or reuse an existing one. ACL variables are in a
3666 binary tree (see tree.c) with acl_var_c and acl_var_m as root nodes.
3669 name pointer to the variable's name, starting with c or m
3671 Returns the pointer to variable's tree node
3675 acl_var_create(uschar *name)
3677 tree_node *node, **root;
3678 root = (name[0] == 'c')? &acl_var_c : &acl_var_m;
3679 node = tree_search(*root, name);
3682 node = store_get(sizeof(tree_node) + Ustrlen(name));
3683 Ustrcpy(node->name, name);
3684 (void)tree_insertnode(root, node);
3686 node->data.ptr = NULL;
3692 /*************************************************
3693 * Write an ACL variable in spool format *
3694 *************************************************/
3696 /* This function is used as a callback for tree_walk when writing variables to
3697 the spool file. To retain spool file compatibility, what is written is -aclc or
3698 -aclm followed by the rest of the name and the data length, space separated,
3699 then the value itself, starting on a new line, and terminated by an additional
3700 newline. When we had only numbered ACL variables, the first line might look
3701 like this: "-aclc 5 20". Now it might be "-aclc foo 20" for the variable called
3705 name of the variable
3706 value of the variable
3707 ctx FILE pointer (as a void pointer)
3713 acl_var_write(uschar *name, uschar *value, void *ctx)
3715 FILE *f = (FILE *)ctx;
3716 fprintf(f, "-acl%c %s %d\n%s\n", name[0], name+1, Ustrlen(value), value);