WITH_CONTENT_SCAN checkin - compiles OK now
[users/jgh/exim.git] / src / src / acl.c
1 /* $Cambridge: exim/src/src/acl.c,v 1.5.2.2 2004/11/30 15:18:58 tom Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) University of Cambridge 1995 - 2004 */
8 /* See the file NOTICE for conditions of use and distribution. */
9
10 /* Code for handling Access Control Lists (ACLs) */
11
12 #include "exim.h"
13
14
15 /* Default callout timeout */
16
17 #define CALLOUT_TIMEOUT_DEFAULT 30
18
19 /* ACL verb codes - keep in step with the table of verbs that follows */
20
21 enum { ACL_ACCEPT, ACL_DEFER, ACL_DENY, ACL_DISCARD, ACL_DROP, ACL_REQUIRE,
22        ACL_WARN };
23
24 /* ACL verbs */
25
26 static uschar *verbs[] =
27   { US"accept", US"defer", US"deny", US"discard", US"drop", US"require",
28     US"warn" };
29
30 /* For each verb, the condition for which "message" is used */
31
32 static int msgcond[] = { FAIL, OK, OK, FAIL, OK, FAIL, OK };
33
34 /* ACL condition and modifier codes - keep in step with the table that
35 follows. */
36
37 enum { ACLC_ACL, ACLC_AUTHENTICATED, ACLC_CONDITION, ACLC_CONTROL,
38 #ifdef WITH_CONTENT_SCAN
39        ACLC_DECODE,
40 #endif
41        ACLC_DELAY, ACLC_DNSLISTS, ACLC_DOMAINS, ACLC_ENCRYPTED, ACLC_ENDPASS,
42        ACLC_HOSTS, ACLC_LOCAL_PARTS, ACLC_LOG_MESSAGE, ACLC_LOGWRITE,
43 #ifdef WITH_CONTENT_SCAN
44        ACLC_MALWARE,
45 #endif
46        ACLC_MESSAGE,
47 #ifdef WITH_CONTENT_SCAN
48        ACLC_MIME_REGEX,
49 #endif
50        ACLC_RECIPIENTS,
51 #ifdef WITH_CONTENT_SCAN
52        ACLC_REGEX,
53 #endif
54        ACLC_SENDER_DOMAINS, ACLC_SENDERS, ACLC_SET,
55 #ifdef WITH_CONTENT_SCAN
56        ACLC_SPAM,       
57 #endif
58        ACLC_VERIFY };
59
60 /* ACL conditions/modifiers: "delay", "control", "endpass", "message",
61 "log_message", "logwrite", and "set" are modifiers that look like conditions
62 but always return TRUE. They are used for their side effects. */
63
64 static uschar *conditions[] = { US"acl", US"authenticated", US"condition",
65   US"control", 
66 #ifdef WITH_CONTENT_SCAN
67   US"decode",
68 #endif
69   US"delay", US"dnslists", US"domains", US"encrypted",
70   US"endpass", US"hosts", US"local_parts", US"log_message", US"logwrite",
71 #ifdef WITH_CONTENT_SCAN
72   US"malware",
73 #endif
74   US"message",
75 #ifdef WITH_CONTENT_SCAN
76   US"mime_regex",
77 #endif
78   US"recipients",
79 #ifdef WITH_CONTENT_SCAN
80   US"regex",
81 #endif
82   US"sender_domains", US"senders", US"set",
83 #ifdef WITH_CONTENT_SCAN
84   US"spam",
85 #endif
86   US"verify" };
87   
88 /* ACL control names */
89
90 static uschar *controls[] = { US"error", US"caseful_local_part",
91   US"caselower_local_part", US"enforce_sync", US"no_enforce_sync", US"freeze",
92   US"queue_only", US"submission", US"no_multiline"}; 
93
94 /* Flags to indicate for which conditions /modifiers a string expansion is done
95 at the outer level. In the other cases, expansion already occurs in the
96 checking functions. */
97
98 static uschar cond_expand_at_top[] = {
99   TRUE,    /* acl */
100   FALSE,   /* authenticated */
101   TRUE,    /* condition */
102   TRUE,    /* control */
103 #ifdef WITH_CONTENT_SCAN
104   TRUE,    /* decode */
105 #endif
106   TRUE,    /* delay */
107   TRUE,    /* dnslists */
108   FALSE,   /* domains */
109   FALSE,   /* encrypted */
110   TRUE,    /* endpass */
111   FALSE,   /* hosts */
112   FALSE,   /* local_parts */
113   TRUE,    /* log_message */
114   TRUE,    /* logwrite */
115 #ifdef WITH_CONTENT_SCAN
116   TRUE,    /* malware */
117 #endif
118   TRUE,    /* message */
119 #ifdef WITH_CONTENT_SCAN
120   TRUE,    /* mime_regex */
121 #endif
122   FALSE,   /* recipients */
123 #ifdef WITH_CONTENT_SCAN
124   TRUE,    /* regex */
125 #endif
126   FALSE,   /* sender_domains */
127   FALSE,   /* senders */
128   TRUE,    /* set */
129 #ifdef WITH_CONTENT_SCAN
130   TRUE,    /* spam */
131 #endif
132   TRUE     /* verify */
133 };
134
135 /* Flags to identify the modifiers */
136
137 static uschar cond_modifiers[] = {
138   FALSE,   /* acl */
139   FALSE,   /* authenticated */
140   FALSE,   /* condition */
141   TRUE,    /* control */
142 #ifdef WITH_CONTENT_SCAN
143   FALSE,   /* decode */
144 #endif
145   TRUE,    /* delay */
146   FALSE,   /* dnslists */
147   FALSE,   /* domains */
148   FALSE,   /* encrypted */
149   TRUE,    /* endpass */
150   FALSE,   /* hosts */
151   FALSE,   /* local_parts */
152   TRUE,    /* log_message */
153   TRUE,    /* logwrite */
154 #ifdef WITH_CONTENT_SCAN
155   FALSE,   /* malware */
156 #endif
157   TRUE,    /* message */
158 #ifdef WITH_CONTENT_SCAN
159   FALSE,   /* mime_regex */
160 #endif
161   FALSE,   /* recipients */
162 #ifdef WITH_CONTENT_SCAN
163   FALSE,   /* regex */
164 #endif
165   FALSE,   /* sender_domains */
166   FALSE,   /* senders */
167   TRUE,    /* set */
168 #ifdef WITH_CONTENT_SCAN
169   FALSE,   /* spam */
170 #endif
171   FALSE    /* verify */
172 };
173
174 /* Bit map vector of which conditions are not allowed at certain times. For
175 each condition, there's a bitmap of dis-allowed times. */
176
177 static unsigned int cond_forbids[] = {
178   0,                                               /* acl */
179   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_CONNECT)|   /* authenticated */
180     (1<<ACL_WHERE_HELO),
181   0,                                               /* condition */
182
183   /* Certain types of control are always allowed, so we let it through
184   always and check in the control processing itself */
185
186   0,                                               /* control */
187
188 #ifdef WITH_CONTENT_SCAN
189   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* decode */
190     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
191     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
192     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
193     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
194     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
195     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_RCPT),
196 #endif
197
198   0,                                               /* delay */
199   (1<<ACL_WHERE_NOTSMTP),                          /* dnslists */
200
201   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* domains */
202     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
203     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
204     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
205     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
206     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
207     (1<<ACL_WHERE_VRFY),
208
209   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_CONNECT)|   /* encrypted */
210     (1<<ACL_WHERE_HELO),
211   0,                                               /* endpass */
212   (1<<ACL_WHERE_NOTSMTP),                          /* hosts */
213
214   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* local_parts */
215     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
216     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
217     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
218     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
219     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
220     (1<<ACL_WHERE_VRFY),
221
222   0,                                               /* log_message */
223   0,                                               /* logwrite */
224   
225 #ifdef WITH_CONTENT_SCAN
226   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* malware */
227     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
228     (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
229     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
230     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
231     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
232     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_MIME),
233 #endif
234
235   0,                                               /* message */
236
237 #ifdef WITH_CONTENT_SCAN
238   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* mime_regex */
239     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
240     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
241     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
242     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
243     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
244     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_RCPT),
245 #endif
246
247   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* recipients */
248     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
249     (1<<ACL_WHERE_DATA)|(1<<ACL_WHERE_PREDATA)|
250     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
251     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
252     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
253     (1<<ACL_WHERE_VRFY),
254
255 #ifdef WITH_CONTENT_SCAN
256   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* regex */
257     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
258     (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
259     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
260     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
261     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
262     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_MIME),
263 #endif
264
265   (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)|      /* sender_domains */
266     (1<<ACL_WHERE_HELO)|
267     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
268     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
269     (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
270
271   (1<<ACL_WHERE_AUTH)|(1<<ACL_WHERE_CONNECT)|      /* senders */
272     (1<<ACL_WHERE_HELO)|
273     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
274     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
275     (1<<ACL_WHERE_STARTTLS)|(1<<ACL_WHERE_VRFY),
276
277   0,                                               /* set */
278
279 #ifdef WITH_CONTENT_SCAN
280   (1<<ACL_WHERE_NOTSMTP)|(1<<ACL_WHERE_AUTH)|      /* spam */
281     (1<<ACL_WHERE_CONNECT)|(1<<ACL_WHERE_HELO)|
282     (1<<ACL_WHERE_RCPT)|(1<<ACL_WHERE_PREDATA)|
283     (1<<ACL_WHERE_ETRN)|(1<<ACL_WHERE_EXPN)|
284     (1<<ACL_WHERE_MAILAUTH)|(1<<ACL_WHERE_QUIT)|
285     (1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_STARTTLS)|
286     (1<<ACL_WHERE_VRFY)|(1<<ACL_WHERE_MIME),
287 #endif
288
289   /* Certain types of verify are always allowed, so we let it through
290   always and check in the verify function itself */
291
292   0                                                /* verify */
293 };
294
295
296 /* Return values from decode_control() */
297
298 enum { CONTROL_ERROR, CONTROL_CASEFUL_LOCAL_PART, CONTROL_CASELOWER_LOCAL_PART,
299   CONTROL_ENFORCE_SYNC, CONTROL_NO_ENFORCE_SYNC, CONTROL_FREEZE,
300   CONTROL_QUEUE_ONLY, CONTROL_SUBMISSION,
301 #ifdef WITH_CONTENT_SCAN
302   CONTROL_NO_MBOX_UNSPOOL, CONTROL_FAKEREJECT,
303 #endif
304   CONTROL_NO_MULTILINE };
305
306 /* Bit map vector of which controls are not allowed at certain times. For
307 each control, there's a bitmap of dis-allowed times. For some, it is easier to
308 specify the negation of a small number of allowed times. */
309
310 static unsigned int control_forbids[] = {
311   0,                                               /* error */
312   ~(1<<ACL_WHERE_RCPT),                            /* caseful_local_part */
313   ~(1<<ACL_WHERE_RCPT),                            /* caselower_local_part */
314   (1<<ACL_WHERE_NOTSMTP),                          /* enforce_sync */
315   (1<<ACL_WHERE_NOTSMTP),                          /* no_enforce_sync */
316    
317   ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)|       /* freeze */
318     (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
319     (1<<ACL_WHERE_NOTSMTP)),
320      
321   ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)|       /* queue_only */
322     (1<<ACL_WHERE_PREDATA)|(1<<ACL_WHERE_DATA)|
323     (1<<ACL_WHERE_NOTSMTP)),
324      
325   ~((1<<ACL_WHERE_MAIL)|(1<<ACL_WHERE_RCPT)|       /* submission */
326     (1<<ACL_WHERE_PREDATA)),                       
327
328 #ifdef WITH_CONTENT_SCAN
329   (1<<ACL_WHERE_NOTSMTP),                          /* no_mbox_unspool */
330   (1<<ACL_WHERE_NOTSMTP),                          /* fakereject */
331 #endif
332
333   (1<<ACL_WHERE_NOTSMTP)                           /* no_multiline */
334 };
335
336 /* Structure listing various control arguments, with their characteristics. */
337
338 typedef struct control_def {
339   uschar *name;
340   int    value;                  /* CONTROL_xxx value */
341   BOOL   has_option;             /* Has /option(s) following */
342 } control_def;
343
344 static control_def controls_list[] = {
345   { US"caseful_local_part",     CONTROL_CASEFUL_LOCAL_PART, FALSE},
346   { US"caselower_local_part",   CONTROL_CASELOWER_LOCAL_PART, FALSE},
347   { US"enforce_sync",           CONTROL_ENFORCE_SYNC, FALSE},
348   { US"freeze",                 CONTROL_FREEZE, FALSE},
349   { US"no_enforce_sync",        CONTROL_NO_ENFORCE_SYNC, FALSE},
350   { US"no_multiline_responses", CONTROL_NO_MULTILINE, FALSE},
351   { US"queue_only",             CONTROL_QUEUE_ONLY, FALSE},
352 #ifdef WITH_CONTENT_SCAN
353   { US"no_mbox_unspool",        CONTROL_NO_MBOX_UNSPOOL, FALSE},
354   { US"fakereject",             CONTROL_FAKEREJECT, TRUE},
355 #endif
356   { US"submission",             CONTROL_SUBMISSION, TRUE}
357   };
358
359 /* Enable recursion between acl_check_internal() and acl_check_condition() */
360
361 static int acl_check_internal(int, address_item *, uschar *, int, uschar **,
362          uschar **);
363
364
365 /*************************************************
366 *         Pick out name from list                *
367 *************************************************/
368
369 /* Use a binary chop method
370
371 Arguments:
372   name        name to find
373   list        list of names
374   end         size of list
375
376 Returns:      offset in list, or -1 if not found
377 */
378
379 static int
380 acl_checkname(uschar *name, uschar **list, int end)
381 {
382 int start = 0;
383
384 while (start < end)
385   {
386   int mid = (start + end)/2;
387   int c = Ustrcmp(name, list[mid]);
388   if (c == 0) return mid;
389   if (c < 0) end = mid; else start = mid + 1;
390   }
391
392 return -1;
393 }
394
395
396 /*************************************************
397 *            Read and parse one ACL              *
398 *************************************************/
399
400 /* This function is called both from readconf in order to parse the ACLs in the
401 configuration file, and also when an ACL is encountered dynamically (e.g. as
402 the result of an expansion). It is given a function to call in order to
403 retrieve the lines of the ACL. This function handles skipping comments and
404 blank lines (where relevant).
405
406 Arguments:
407   func        function to get next line of ACL
408   error       where to put an error message
409
410 Returns:      pointer to ACL, or NULL
411               NULL can be legal (empty ACL); in this case error will be NULL
412 */
413
414 acl_block *
415 acl_read(uschar *(*func)(void), uschar **error)
416 {
417 acl_block *yield = NULL;
418 acl_block **lastp = &yield;
419 acl_block *this = NULL;
420 acl_condition_block *cond;
421 acl_condition_block **condp = NULL;
422 uschar *s;
423
424 *error = NULL;
425
426 while ((s = (*func)()) != NULL)
427   {
428   int v, c;
429   BOOL negated = FALSE;
430   uschar *saveline = s;
431   uschar name[64];
432
433   /* Conditions (but not verbs) are allowed to be negated by an initial
434   exclamation mark. */
435
436   while (isspace(*s)) s++;
437   if (*s == '!')
438     {
439     negated = TRUE;
440     s++;
441     }
442
443   /* Read the name of a verb or a condition, or the start of a new ACL */
444
445   s = readconf_readname(name, sizeof(name), s);
446   if (*s == ':')
447     {
448     if (negated || name[0] == 0)
449       {
450       *error = string_sprintf("malformed ACL name in \"%s\"", saveline);
451       return NULL;
452       }
453     break;
454     }
455
456   /* If a verb is unrecognized, it may be another condition or modifier that
457   continues the previous verb. */
458
459   v = acl_checkname(name, verbs, sizeof(verbs)/sizeof(char *));
460   if (v < 0)
461     {
462     if (this == NULL)
463       {
464       *error = string_sprintf("unknown ACL verb in \"%s\"", saveline);
465       return NULL;
466       }
467     }
468
469   /* New verb */
470
471   else
472     {
473     if (negated)
474       {
475       *error = string_sprintf("malformed ACL line \"%s\"", saveline);
476       return NULL;
477       }
478     this = store_get(sizeof(acl_block));
479     *lastp = this;
480     lastp = &(this->next);
481     this->next = NULL;
482     this->verb = v;
483     this->condition = NULL;
484     condp = &(this->condition);
485     if (*s == 0) continue;               /* No condition on this line */
486     if (*s == '!')
487       {
488       negated = TRUE;
489       s++;
490       }
491     s = readconf_readname(name, sizeof(name), s);  /* Condition name */
492     }
493
494   /* Handle a condition or modifier. */
495
496   c = acl_checkname(name, conditions, sizeof(conditions)/sizeof(char *));
497   if (c < 0)
498     {
499     *error = string_sprintf("unknown ACL condition/modifier in \"%s\"",
500       saveline);
501     return NULL;
502     }
503
504   /* The modifiers may not be negated */
505
506   if (negated && cond_modifiers[c])
507     {
508     *error = string_sprintf("ACL error: negation is not allowed with "
509       "\"%s\"", conditions[c]);
510     return NULL;
511     }
512
513   /* ENDPASS may occur only with ACCEPT or DISCARD. */
514
515   if (c == ACLC_ENDPASS &&
516       this->verb != ACL_ACCEPT &&
517       this->verb != ACL_DISCARD)
518     {
519     *error = string_sprintf("ACL error: \"%s\" is not allowed with \"%s\"",
520       conditions[c], verbs[this->verb]);
521     return NULL;
522     }
523
524   cond = store_get(sizeof(acl_condition_block));
525   cond->next = NULL;
526   cond->type = c;
527   cond->u.negated = negated;
528
529   *condp = cond;
530   condp = &(cond->next);
531
532   /* The "set" modifier is different in that its argument is "name=value"
533   rather than just a value, and we can check the validity of the name, which
534   gives us a variable number to insert into the data block. */
535
536   if (c == ACLC_SET)
537     {
538     if (Ustrncmp(s, "acl_", 4) != 0 || (s[4] != 'c' && s[4] != 'm') ||
539         !isdigit(s[5]) || (!isspace(s[6]) && s[6] != '='))
540       {
541       *error = string_sprintf("unrecognized name after \"set\" in ACL "
542         "modifier \"set %s\"", s);
543       return NULL;
544       }
545
546     cond->u.varnumber = s[5] - '0';
547     if (s[4] == 'm') cond->u.varnumber += ACL_C_MAX;
548     s += 6;
549     while (isspace(*s)) s++;
550     }
551
552   /* For "set", we are now positioned for the data. For the others, only
553   "endpass" has no data */
554
555   if (c != ACLC_ENDPASS)
556     {
557     if (*s++ != '=')
558       {
559       *error = string_sprintf("\"=\" missing after ACL \"%s\" %s", name,
560         cond_modifiers[c]? US"modifier" : US"condition");
561       return NULL;
562       }
563     while (isspace(*s)) s++;
564     cond->arg = string_copy(s);
565     }
566   }
567
568 return yield;
569 }
570
571
572
573 /*************************************************
574 *               Handle warnings                  *
575 *************************************************/
576
577 /* This function is called when a WARN verb's conditions are true. It adds to
578 the message's headers, and/or writes information to the log. In each case, this
579 only happens once (per message for headers, per connection for log).
580
581 Arguments:
582   where          ACL_WHERE_xxxx indicating which ACL this is
583   user_message   message for adding to headers
584   log_message    message for logging, if different
585
586 Returns:         nothing
587 */
588
589 static void
590 acl_warn(int where, uschar *user_message, uschar *log_message)
591 {
592 int hlen;
593
594 if (log_message != NULL && log_message != user_message)
595   {
596   uschar *text;
597   string_item *logged;
598
599   text = string_sprintf("%s Warning: %s",  host_and_ident(TRUE),
600     string_printing(log_message));
601
602   /* If a sender verification has failed, and the log message is "sender verify
603   failed", add the failure message. */
604
605   if (sender_verified_failed != NULL &&
606       sender_verified_failed->message != NULL &&
607       strcmpic(log_message, US"sender verify failed") == 0)
608     text = string_sprintf("%s: %s", text, sender_verified_failed->message);
609
610   /* Search previously logged warnings. They are kept in malloc store so they
611   can be freed at the start of a new message. */
612
613   for (logged = acl_warn_logged; logged != NULL; logged = logged->next)
614     if (Ustrcmp(logged->text, text) == 0) break;
615
616   if (logged == NULL)
617     {
618     int length = Ustrlen(text) + 1;
619     log_write(0, LOG_MAIN, "%s", text);
620     logged = store_malloc(sizeof(string_item) + length);
621     logged->text = (uschar *)logged + sizeof(string_item);
622     memcpy(logged->text, text, length);
623     logged->next = acl_warn_logged;
624     acl_warn_logged = logged;
625     }
626   }
627
628 /* If there's no user message, we are done. */
629
630 if (user_message == NULL) return;
631
632 /* If this isn't a message ACL, we can't do anything with a user message.
633 Log an error. */
634
635 if (where > ACL_WHERE_NOTSMTP)
636   {
637   log_write(0, LOG_MAIN|LOG_PANIC, "ACL \"warn\" with \"message\" setting "
638     "found in a non-message (%s) ACL: cannot specify header lines here: "
639     "message ignored", acl_wherenames[where]);
640   return;
641   }
642
643 /* Treat the user message as a sequence of one or more header lines. */
644
645 hlen = Ustrlen(user_message);
646 if (hlen > 0)
647   {
648   uschar *text, *p, *q;
649
650   /* Add a final newline if not present */
651
652   text = ((user_message)[hlen-1] == '\n')? user_message :
653     string_sprintf("%s\n", user_message);
654
655   /* Loop for multiple header lines, taking care about continuations */
656
657   for (p = q = text; *p != 0; )
658     {
659     uschar *s;
660     int newtype = htype_add_bot;
661     header_line **hptr = &acl_warn_headers;
662
663     /* Find next header line within the string */
664
665     for (;;)
666       {
667       q = Ustrchr(q, '\n');
668       if (*(++q) != ' ' && *q != '\t') break;
669       }
670
671     /* If the line starts with a colon, interpret the instruction for where to
672     add it. This temporarily sets up a new type. */
673
674     if (*p == ':')
675       {
676       if (strncmpic(p, US":after_received:", 16) == 0)
677         {
678         newtype = htype_add_rec;
679         p += 16;
680         }
681       else if (strncmpic(p, US":at_start:", 10) == 0)
682         {
683         newtype = htype_add_top;
684         p += 10;
685         }
686       else if (strncmpic(p, US":at_end:", 8) == 0)
687         {
688         newtype = htype_add_bot;
689         p += 8;
690         }
691       while (*p == ' ' || *p == '\t') p++;
692       }
693
694     /* See if this line starts with a header name, and if not, add X-ACL-Warn:
695     to the front of it. */
696
697     for (s = p; s < q - 1; s++)
698       {
699       if (*s == ':' || !isgraph(*s)) break;
700       }
701
702     s = string_sprintf("%s%.*s", (*s == ':')? "" : "X-ACL-Warn: ", q - p, p);
703     hlen = Ustrlen(s);
704
705     /* See if this line has already been added */
706
707     while (*hptr != NULL)
708       {
709       if (Ustrncmp((*hptr)->text, s, hlen) == 0) break;
710       hptr = &((*hptr)->next);
711       }
712
713     /* Add if not previously present */
714
715     if (*hptr == NULL)
716       {
717       header_line *h = store_get(sizeof(header_line));
718       h->text = s;
719       h->next = NULL;
720       h->type = newtype;
721       h->slen = hlen;
722       *hptr = h;
723       hptr = &(h->next);
724       }
725
726     /* Advance for next header line within the string */
727
728     p = q;
729     }
730   }
731 }
732
733
734
735 /*************************************************
736 *         Verify and check reverse DNS           *
737 *************************************************/
738
739 /* Called from acl_verify() below. We look up the host name(s) of the client IP
740 address if this has not yet been done. The host_name_lookup() function checks
741 that one of these names resolves to an address list that contains the client IP
742 address, so we don't actually have to do the check here.
743
744 Arguments:
745   user_msgptr  pointer for user message
746   log_msgptr   pointer for log message
747
748 Returns:       OK        verification condition succeeded
749                FAIL      verification failed
750                DEFER     there was a problem verifying
751 */
752
753 static int
754 acl_verify_reverse(uschar **user_msgptr, uschar **log_msgptr)
755 {
756 int rc;
757
758 user_msgptr = user_msgptr;  /* stop compiler warning */
759
760 /* Previous success */
761
762 if (sender_host_name != NULL) return OK;
763
764 /* Previous failure */
765
766 if (host_lookup_failed)
767   {
768   *log_msgptr = string_sprintf("host lookup failed%s", host_lookup_msg);
769   return FAIL;
770   }
771
772 /* Need to do a lookup */
773
774 HDEBUG(D_acl)
775   debug_printf("looking up host name to force name/address consistency check\n");
776
777 if ((rc = host_name_lookup()) != OK)
778   {
779   *log_msgptr = (rc == DEFER)?
780     US"host lookup deferred for reverse lookup check"
781     :
782     string_sprintf("host lookup failed for reverse lookup check%s",
783       host_lookup_msg);
784   return rc;    /* DEFER or FAIL */
785   }
786
787 host_build_sender_fullhost();
788 return OK;
789 }
790
791
792
793 /*************************************************
794 *     Handle verification (address & other)      *
795 *************************************************/
796
797 /* This function implements the "verify" condition. It is called when
798 encountered in any ACL, because some tests are almost always permitted. Some
799 just don't make sense, and always fail (for example, an attempt to test a host
800 lookup for a non-TCP/IP message). Others are restricted to certain ACLs.
801
802 Arguments:
803   where        where called from
804   addr         the recipient address that the ACL is handling, or NULL
805   arg          the argument of "verify"
806   user_msgptr  pointer for user message
807   log_msgptr   pointer for log message
808   basic_errno  where to put verify errno
809
810 Returns:       OK        verification condition succeeded
811                FAIL      verification failed
812                DEFER     there was a problem verifying
813                ERROR     syntax error
814 */
815
816 static int
817 acl_verify(int where, address_item *addr, uschar *arg,
818   uschar **user_msgptr, uschar **log_msgptr, int *basic_errno)
819 {
820 int sep = '/';
821 int callout = -1;
822 int callout_overall = -1;
823 int callout_connect = -1;
824 int verify_options = 0;
825 int rc;
826 BOOL verify_header_sender = FALSE;
827 BOOL defer_ok = FALSE;
828 BOOL callout_defer_ok = FALSE;
829 BOOL no_details = FALSE;
830 address_item *sender_vaddr = NULL;
831 uschar *verify_sender_address = NULL;
832 uschar *pm_mailfrom = NULL;
833 uschar *se_mailfrom = NULL;
834 uschar *list = arg;
835 uschar *ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size);
836
837 if (ss == NULL) goto BAD_VERIFY;
838
839 /* Handle name/address consistency verification in a separate function. */
840
841 if (strcmpic(ss, US"reverse_host_lookup") == 0)
842   {
843   if (sender_host_address == NULL) return OK;
844   return acl_verify_reverse(user_msgptr, log_msgptr);
845   }
846
847 /* TLS certificate verification is done at STARTTLS time; here we just
848 test whether it was successful or not. (This is for optional verification; for
849 mandatory verification, the connection doesn't last this long.) */
850
851 if (strcmpic(ss, US"certificate") == 0)
852   {
853   if (tls_certificate_verified) return OK;
854   *user_msgptr = US"no verified certificate";
855   return FAIL;
856   }
857
858 /* We can test the result of optional HELO verification */
859
860 if (strcmpic(ss, US"helo") == 0) return helo_verified? OK : FAIL;
861
862 /* Handle header verification options - permitted only after DATA or a non-SMTP
863 message. */
864
865 if (strncmpic(ss, US"header_", 7) == 0)
866   {
867   if (where != ACL_WHERE_DATA && where != ACL_WHERE_NOTSMTP)
868     {
869     *log_msgptr = string_sprintf("cannot check header contents in ACL for %s "
870       "(only possible in ACL for DATA)", acl_wherenames[where]);
871     return ERROR;
872     }
873
874   /* Check that all relevant header lines have the correct syntax. If there is
875   a syntax error, we return details of the error to the sender if configured to
876   send out full details. (But a "message" setting on the ACL can override, as
877   always). */
878
879   if (strcmpic(ss+7, US"syntax") == 0)
880     {
881     int rc = verify_check_headers(log_msgptr);
882     if (rc != OK && smtp_return_error_details && *log_msgptr != NULL)
883       *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
884     return rc;
885     }
886
887   /* Check that there is at least one verifiable sender address in the relevant
888   header lines. This can be followed by callout and defer options, just like
889   sender and recipient. */
890
891   else if (strcmpic(ss+7, US"sender") == 0) verify_header_sender = TRUE;
892
893   /* Unknown verify argument starting with "header_" */
894
895   else goto BAD_VERIFY;
896   }
897
898 /* Otherwise, first item in verify argument must be "sender" or "recipient".
899 In the case of a sender, this can optionally be followed by an address to use
900 in place of the actual sender (rare special-case requirement). */
901
902 else if (strncmpic(ss, US"sender", 6) == 0)
903   {
904   uschar *s = ss + 6;
905   if (where > ACL_WHERE_NOTSMTP)
906     {
907     *log_msgptr = string_sprintf("cannot verify sender in ACL for %s "
908       "(only possible for MAIL, RCPT, PREDATA, or DATA)",
909       acl_wherenames[where]);
910     return ERROR;
911     }
912   if (*s == 0)
913     verify_sender_address = sender_address;
914   else
915     {
916     while (isspace(*s)) s++;
917     if (*s++ != '=') goto BAD_VERIFY;
918     while (isspace(*s)) s++;
919     verify_sender_address = string_copy(s);
920     }
921   }
922 else
923   {
924   if (strcmpic(ss, US"recipient") != 0) goto BAD_VERIFY;
925   if (addr == NULL)
926     {
927     *log_msgptr = string_sprintf("cannot verify recipient in ACL for %s "
928       "(only possible for RCPT)", acl_wherenames[where]);
929     return ERROR;
930     }
931   }
932
933 /* Remaining items are optional */
934
935 while ((ss = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))
936       != NULL)
937   {
938   if (strcmpic(ss, US"defer_ok") == 0) defer_ok = TRUE;
939   else if (strcmpic(ss, US"no_details") == 0) no_details = TRUE;
940
941   /* These two old options are left for backwards compatibility */
942
943   else if (strcmpic(ss, US"callout_defer_ok") == 0)
944     {
945     callout_defer_ok = TRUE;
946     if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
947     }
948
949   else if (strcmpic(ss, US"check_postmaster") == 0)
950      {
951      pm_mailfrom = US"";
952      if (callout == -1) callout = CALLOUT_TIMEOUT_DEFAULT;
953      }
954
955   /* The callout option has a number of sub-options, comma separated */
956
957   else if (strncmpic(ss, US"callout", 7) == 0)
958     {
959     callout = CALLOUT_TIMEOUT_DEFAULT;
960     ss += 7;
961     if (*ss != 0)
962       {
963       while (isspace(*ss)) ss++;
964       if (*ss++ == '=')
965         {
966         int optsep = ',';
967         uschar *opt;
968         uschar buffer[256];
969         while (isspace(*ss)) ss++;
970         
971         /* This callout option handling code has become a mess as new options 
972         have been added in an ad hoc manner. It should be tidied up into some 
973         kind of table-driven thing. */
974  
975         while ((opt = string_nextinlist(&ss, &optsep, buffer, sizeof(buffer)))
976               != NULL)
977           {
978           if (strcmpic(opt, US"defer_ok") == 0) callout_defer_ok = TRUE;
979           else if (strcmpic(opt, US"no_cache") == 0)
980              verify_options |= vopt_callout_no_cache;
981           else if (strcmpic(opt, US"random") == 0)
982              verify_options |= vopt_callout_random;
983           else if (strcmpic(opt, US"use_sender") == 0)
984              verify_options |= vopt_callout_recipsender;
985           else if (strcmpic(opt, US"use_postmaster") == 0)
986              verify_options |= vopt_callout_recippmaster;
987           else if (strcmpic(opt, US"postmaster") == 0) pm_mailfrom = US"";
988
989           else if (strncmpic(opt, US"mailfrom", 8) == 0)
990             {
991             if (!verify_header_sender)
992               {
993               *log_msgptr = string_sprintf("\"mailfrom\" is allowed as a "
994                 "callout option only for verify=header_sender (detected in ACL "
995                 "condition \"%s\")", arg);
996               return ERROR;
997               }
998             opt += 8;
999             while (isspace(*opt)) opt++;
1000             if (*opt++ != '=')
1001               {
1002               *log_msgptr = string_sprintf("'=' expected after "
1003                 "\"mailfrom\" in ACL condition \"%s\"", arg);
1004               return ERROR;
1005               }
1006             while (isspace(*opt)) opt++;
1007             se_mailfrom = string_copy(opt);
1008             }
1009
1010           else if (strncmpic(opt, US"postmaster_mailfrom", 19) == 0)
1011             {
1012             opt += 19;
1013             while (isspace(*opt)) opt++;
1014             if (*opt++ != '=')
1015               {
1016               *log_msgptr = string_sprintf("'=' expected after "
1017                 "\"postmaster_mailfrom\" in ACL condition \"%s\"", arg);
1018               return ERROR;
1019               }
1020             while (isspace(*opt)) opt++;
1021             pm_mailfrom = string_copy(opt);
1022             }
1023
1024           else if (strncmpic(opt, US"maxwait", 7) == 0)
1025             {
1026             opt += 7;
1027             while (isspace(*opt)) opt++;
1028             if (*opt++ != '=')
1029               {
1030               *log_msgptr = string_sprintf("'=' expected after \"maxwait\" in "
1031                 "ACL condition \"%s\"", arg);
1032               return ERROR;
1033               }
1034             while (isspace(*opt)) opt++;
1035             callout_overall = readconf_readtime(opt, 0, FALSE);
1036             if (callout_overall < 0)
1037               {
1038               *log_msgptr = string_sprintf("bad time value in ACL condition "
1039                 "\"verify %s\"", arg);
1040               return ERROR;
1041               }
1042             }
1043           else if (strncmpic(opt, US"connect", 7) == 0)
1044             {
1045             opt += 7;
1046             while (isspace(*opt)) opt++;
1047             if (*opt++ != '=')
1048               {
1049               *log_msgptr = string_sprintf("'=' expected after "
1050                 "\"callout_overaall\" in ACL condition \"%s\"", arg);
1051               return ERROR;
1052               }
1053             while (isspace(*opt)) opt++;
1054             callout_connect = readconf_readtime(opt, 0, FALSE);
1055             if (callout_connect < 0)
1056               {
1057               *log_msgptr = string_sprintf("bad time value in ACL condition "
1058                 "\"verify %s\"", arg);
1059               return ERROR;
1060               }
1061             }
1062           else    /* Plain time is callout connect/command timeout */
1063             {
1064             callout = readconf_readtime(opt, 0, FALSE);
1065             if (callout < 0)
1066               {
1067               *log_msgptr = string_sprintf("bad time value in ACL condition "
1068                 "\"verify %s\"", arg);
1069               return ERROR;
1070               }
1071             }
1072           }
1073         }
1074       else
1075         {
1076         *log_msgptr = string_sprintf("'=' expected after \"callout\" in "
1077           "ACL condition \"%s\"", arg);
1078         return ERROR;
1079         }
1080       }
1081     }
1082
1083   /* Option not recognized */
1084
1085   else
1086     {
1087     *log_msgptr = string_sprintf("unknown option \"%s\" in ACL "
1088       "condition \"verify %s\"", ss, arg);
1089     return ERROR;
1090     }
1091   }
1092
1093 if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster)) ==
1094       (vopt_callout_recipsender|vopt_callout_recippmaster))
1095   {
1096   *log_msgptr = US"only one of use_sender and use_postmaster can be set "
1097     "for a recipient callout";
1098   return ERROR;
1099   }
1100
1101 /* Handle sender-in-header verification. Default the user message to the log
1102 message if giving out verification details. */
1103
1104 if (verify_header_sender)
1105   {
1106   rc = verify_check_header_address(user_msgptr, log_msgptr, callout,
1107     callout_overall, callout_connect, se_mailfrom, pm_mailfrom, verify_options);
1108   if (smtp_return_error_details)
1109     {
1110     if (*user_msgptr == NULL && *log_msgptr != NULL)
1111       *user_msgptr = string_sprintf("Rejected after DATA: %s", *log_msgptr);
1112     if (rc == DEFER) acl_temp_details = TRUE;
1113     }
1114   }
1115
1116 /* Handle a sender address. The default is to verify *the* sender address, but
1117 optionally a different address can be given, for special requirements. If the
1118 address is empty, we are dealing with a bounce message that has no sender, so
1119 we cannot do any checking. If the real sender address gets rewritten during
1120 verification (e.g. DNS widening), set the flag to stop it being rewritten again
1121 during message reception.
1122
1123 A list of verified "sender" addresses is kept to try to avoid doing to much
1124 work repetitively when there are multiple recipients in a message and they all
1125 require sender verification. However, when callouts are involved, it gets too
1126 complicated because different recipients may require different callout options.
1127 Therefore, we always do a full sender verify when any kind of callout is
1128 specified. Caching elsewhere, for instance in the DNS resolver and in the
1129 callout handling, should ensure that this is not terribly inefficient. */
1130
1131 else if (verify_sender_address != NULL)
1132   {
1133   if ((verify_options & (vopt_callout_recipsender|vopt_callout_recippmaster))
1134        != 0)
1135     {
1136     *log_msgptr = US"use_sender or use_postmaster cannot be used for a "
1137       "sender verify callout";
1138     return ERROR;
1139     }
1140
1141   sender_vaddr = verify_checked_sender(verify_sender_address);
1142   if (sender_vaddr != NULL &&               /* Previously checked */
1143       callout <= 0)                         /* No callout needed this time */
1144     {
1145     /* If the "routed" flag is set, it means that routing worked before, so
1146     this check can give OK (the saved return code value, if set, belongs to a
1147     callout that was done previously). If the "routed" flag is not set, routing
1148     must have failed, so we use the saved return code. */
1149
1150     if (testflag(sender_vaddr, af_verify_routed)) rc = OK; else
1151       {
1152       rc = sender_vaddr->special_action;
1153       *basic_errno = sender_vaddr->basic_errno;
1154       }
1155     HDEBUG(D_acl) debug_printf("using cached sender verify result\n");
1156     }
1157
1158   /* Do a new verification, and cache the result. The cache is used to avoid
1159   verifying the sender multiple times for multiple RCPTs when callouts are not
1160   specified (see comments above).
1161
1162   The cache is also used on failure to give details in response to the first
1163   RCPT that gets bounced for this reason. However, this can be suppressed by
1164   the no_details option, which sets the flag that says "this detail has already
1165   been sent". The cache normally contains just one address, but there may be
1166   more in esoteric circumstances. */
1167
1168   else
1169     {
1170     BOOL routed = TRUE;
1171     uschar *save_address_data = deliver_address_data;
1172       
1173     sender_vaddr = deliver_make_addr(verify_sender_address, TRUE);
1174     if (no_details) setflag(sender_vaddr, af_sverify_told);
1175     if (verify_sender_address[0] != 0)
1176       {
1177       /* If this is the real sender address, save the unrewritten version
1178       for use later in receive. Otherwise, set a flag so that rewriting the
1179       sender in verify_address() does not update sender_address. */
1180
1181       if (verify_sender_address == sender_address)
1182         sender_address_unrewritten = sender_address;
1183       else
1184         verify_options |= vopt_fake_sender;
1185
1186       /* The recipient, qualify, and expn options are never set in
1187       verify_options. */
1188
1189       rc = verify_address(sender_vaddr, NULL, verify_options, callout,
1190         callout_overall, callout_connect, se_mailfrom, pm_mailfrom, &routed);
1191
1192       HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1193
1194       if (rc == OK)
1195         {
1196         if (Ustrcmp(sender_vaddr->address, verify_sender_address) != 0)
1197           {
1198           DEBUG(D_acl) debug_printf("sender %s verified ok as %s\n",
1199             verify_sender_address, sender_vaddr->address);
1200           }
1201         else
1202           {
1203           DEBUG(D_acl) debug_printf("sender %s verified ok\n",
1204             verify_sender_address);
1205           }
1206         }
1207       else *basic_errno = sender_vaddr->basic_errno;
1208       }
1209     else rc = OK;  /* Null sender */
1210
1211     /* Cache the result code */
1212
1213     if (routed) setflag(sender_vaddr, af_verify_routed);
1214     if (callout > 0) setflag(sender_vaddr, af_verify_callout);
1215     sender_vaddr->special_action = rc;
1216     sender_vaddr->next = sender_verified_list;
1217     sender_verified_list = sender_vaddr;
1218     
1219     /* Restore the recipient address data, which might have been clobbered by 
1220     the sender verification. */
1221   
1222     deliver_address_data = save_address_data;
1223     }
1224     
1225   /* Put the sender address_data value into $sender_address_data */
1226
1227   sender_address_data = sender_vaddr->p.address_data; 
1228   }
1229
1230 /* A recipient address just gets a straightforward verify; again we must handle
1231 the DEFER overrides. */
1232
1233 else
1234   {
1235   address_item addr2;
1236
1237   /* We must use a copy of the address for verification, because it might
1238   get rewritten. */
1239
1240   addr2 = *addr;
1241   rc = verify_address(&addr2, NULL, verify_options|vopt_is_recipient, callout,
1242     callout_overall, callout_connect, se_mailfrom, pm_mailfrom, NULL);
1243   HDEBUG(D_acl) debug_printf("----------- end verify ------------\n");
1244   *log_msgptr = addr2.message;
1245   *user_msgptr = addr2.user_message;
1246   *basic_errno = addr2.basic_errno;
1247
1248   /* Make $address_data visible */
1249   deliver_address_data = addr2.p.address_data;
1250   }
1251
1252 /* We have a result from the relevant test. Handle defer overrides first. */
1253
1254 if (rc == DEFER && (defer_ok ||
1255    (callout_defer_ok && *basic_errno == ERRNO_CALLOUTDEFER)))
1256   {
1257   HDEBUG(D_acl) debug_printf("verify defer overridden by %s\n",
1258     defer_ok? "defer_ok" : "callout_defer_ok");
1259   rc = OK;
1260   }
1261
1262 /* If we've failed a sender, set up a recipient message, and point
1263 sender_verified_failed to the address item that actually failed. */
1264
1265 if (rc != OK && verify_sender_address != NULL)
1266   {
1267   if (rc != DEFER)
1268     {
1269     *log_msgptr = *user_msgptr = US"Sender verify failed";
1270     }
1271   else if (*basic_errno != ERRNO_CALLOUTDEFER)
1272     {
1273     *log_msgptr = *user_msgptr = US"Could not complete sender verify";
1274     }
1275   else
1276     {
1277     *log_msgptr = US"Could not complete sender verify callout";
1278     *user_msgptr = smtp_return_error_details? sender_vaddr->user_message :
1279       *log_msgptr;
1280     }
1281
1282   sender_verified_failed = sender_vaddr;
1283   }
1284
1285 /* Verifying an address messes up the values of $domain and $local_part,
1286 so reset them before returning if this is a RCPT ACL. */
1287
1288 if (addr != NULL)
1289   {
1290   deliver_domain = addr->domain;
1291   deliver_localpart = addr->local_part;
1292   }
1293 return rc;
1294
1295 /* Syntax errors in the verify argument come here. */
1296
1297 BAD_VERIFY:
1298 *log_msgptr = string_sprintf("expected \"sender[=address]\", \"recipient\", "
1299   "\"header_syntax\" or \"header_sender\" at start of ACL condition "
1300   "\"verify %s\"", arg);
1301 return ERROR;
1302 }
1303
1304
1305
1306
1307 /*************************************************
1308 *        Check argument for control= modifier    *
1309 *************************************************/
1310
1311 /* Called from acl_check_condition() below
1312
1313 Arguments:
1314   arg         the argument string for control=
1315   pptr        set to point to the terminating character
1316   where       which ACL we are in
1317   log_msgptr  for error messages
1318
1319 Returns:      CONTROL_xxx value
1320 */
1321
1322 static int
1323 decode_control(uschar *arg, uschar **pptr, int where, uschar **log_msgptr)
1324 {
1325 int len;
1326 control_def *d;
1327
1328 for (d = controls_list;
1329      d < controls_list + sizeof(controls_list)/sizeof(control_def);
1330      d++)
1331   {
1332   len = Ustrlen(d->name);
1333   if (Ustrncmp(d->name, arg, len) == 0) break;
1334   }
1335
1336 if (d >= controls_list + sizeof(controls_list)/sizeof(control_def) ||
1337    (arg[len] != 0 && (!d->has_option || arg[len] != '/')))
1338   {
1339   *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
1340   return CONTROL_ERROR;
1341   }
1342
1343 *pptr = arg + len;
1344 return d->value;
1345 }
1346
1347
1348
1349 /*************************************************
1350 *   Handle conditions/modifiers on an ACL item   *
1351 *************************************************/
1352
1353 /* Called from acl_check() below.
1354
1355 Arguments:
1356   verb         ACL verb
1357   cb           ACL condition block - if NULL, result is OK
1358   where        where called from
1359   addr         the address being checked for RCPT, or NULL
1360   level        the nesting level
1361   epp          pointer to pass back TRUE if "endpass" encountered
1362                  (applies only to "accept" and "discard")
1363   user_msgptr  user message pointer
1364   log_msgptr   log message pointer
1365   basic_errno  pointer to where to put verify error
1366
1367 Returns:       OK        - all conditions are met
1368                DISCARD   - an "acl" condition returned DISCARD - only allowed
1369                              for "accept" or "discard" verbs
1370                FAIL      - at least one condition fails
1371                FAIL_DROP - an "acl" condition returned FAIL_DROP
1372                DEFER     - can't tell at the moment (typically, lookup defer,
1373                              but can be temporary callout problem)
1374                ERROR     - ERROR from nested ACL or expansion failure or other
1375                              error
1376 */
1377
1378 static int
1379 acl_check_condition(int verb, acl_condition_block *cb, int where,
1380   address_item *addr, int level, BOOL *epp, uschar **user_msgptr,
1381   uschar **log_msgptr, int *basic_errno)
1382 {
1383 uschar *user_message = NULL;
1384 uschar *log_message = NULL;
1385 uschar *p;
1386 int rc = OK;
1387 #ifdef WITH_CONTENT_SCAN
1388 int sep = '/';
1389 #endif
1390
1391 for (; cb != NULL; cb = cb->next)
1392   {
1393   uschar *arg;
1394   int control_type; 
1395
1396   /* The message and log_message items set up messages to be used in
1397   case of rejection. They are expanded later. */
1398
1399   if (cb->type == ACLC_MESSAGE)
1400     {
1401     user_message = cb->arg;
1402     continue;
1403     }
1404
1405   if (cb->type == ACLC_LOG_MESSAGE)
1406     {
1407     log_message = cb->arg;
1408     continue;
1409     }
1410
1411   /* The endpass "condition" just sets a flag to show it occurred. This is
1412   checked at compile time to be on an "accept" or "discard" item. */
1413
1414   if (cb->type == ACLC_ENDPASS)
1415     {
1416     *epp = TRUE;
1417     continue;
1418     }
1419
1420   /* For other conditions and modifiers, the argument is expanded now for some
1421   of them, but not for all, because expansion happens down in some lower level
1422   checking functions in some cases. */
1423
1424   if (cond_expand_at_top[cb->type])
1425     {
1426     arg = expand_string(cb->arg);
1427     if (arg == NULL)
1428       {
1429       if (expand_string_forcedfail) continue;
1430       *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s",
1431         cb->arg, expand_string_message);
1432       return search_find_defer? DEFER : ERROR;
1433       }
1434     }
1435   else arg = cb->arg;
1436
1437   /* Show condition, and expanded condition if it's different */
1438
1439   HDEBUG(D_acl)
1440     {
1441     int lhswidth = 0;
1442     debug_printf("check %s%s %n",
1443       (!cond_modifiers[cb->type] && cb->u.negated)? "!":"",
1444       conditions[cb->type], &lhswidth);
1445
1446     if (cb->type == ACLC_SET)
1447       {
1448       int n = cb->u.varnumber;
1449       int t = (n < ACL_C_MAX)? 'c' : 'm';
1450       if (n >= ACL_C_MAX) n -= ACL_C_MAX;
1451       debug_printf("acl_%c%d ", t, n);
1452       lhswidth += 7;
1453       }
1454
1455     debug_printf("= %s\n", cb->arg);
1456
1457     if (arg != cb->arg)
1458       debug_printf("%.*s= %s\n", lhswidth,
1459       US"                             ", CS arg);
1460     }
1461
1462   /* Check that this condition makes sense at this time */
1463
1464   if ((cond_forbids[cb->type] & (1 << where)) != 0)
1465     {
1466     *log_msgptr = string_sprintf("cannot %s %s condition in %s ACL",
1467       cond_modifiers[cb->type]? "use" : "test",
1468       conditions[cb->type], acl_wherenames[where]);
1469     return ERROR;
1470     }
1471
1472   /* Run the appropriate test for each condition, or take the appropriate
1473   action for the remaining modifiers. */
1474
1475   switch(cb->type)
1476     {
1477     /* A nested ACL that returns "discard" makes sense only for an "accept" or
1478     "discard" verb. */
1479
1480     case ACLC_ACL:
1481     rc = acl_check_internal(where, addr, arg, level+1, user_msgptr, log_msgptr);
1482     if (rc == DISCARD && verb != ACL_ACCEPT && verb != ACL_DISCARD)
1483       {
1484       *log_msgptr = string_sprintf("nested ACL returned \"discard\" for "
1485         "\"%s\" command (only allowed with \"accept\" or \"discard\")",
1486         verbs[verb]);
1487       return ERROR;
1488       }
1489     break;
1490
1491     case ACLC_AUTHENTICATED:
1492     rc = (sender_host_authenticated == NULL)? FAIL :
1493       match_isinlist(sender_host_authenticated, &arg, 0, NULL, NULL, MCL_STRING,
1494         TRUE, NULL);
1495     break;
1496
1497     case ACLC_CONDITION:
1498     if (Ustrspn(arg, "0123456789") == Ustrlen(arg))     /* Digits, or empty */
1499       rc = (Uatoi(arg) == 0)? FAIL : OK;
1500     else
1501       rc = (strcmpic(arg, US"no") == 0 ||
1502             strcmpic(arg, US"false") == 0)? FAIL :
1503            (strcmpic(arg, US"yes") == 0 ||
1504             strcmpic(arg, US"true") == 0)? OK : DEFER;
1505     if (rc == DEFER)
1506       *log_msgptr = string_sprintf("invalid \"condition\" value \"%s\"", arg);
1507     break;
1508
1509     case ACLC_CONTROL:
1510     control_type = decode_control(arg, &p, where, log_msgptr);
1511
1512     /* Check this control makes sense at this time */
1513
1514     if ((control_forbids[control_type] & (1 << where)) != 0)
1515       {
1516       *log_msgptr = string_sprintf("cannot use \"control=%s\" in %s ACL",
1517         controls[control_type], acl_wherenames[where]);
1518       return ERROR;
1519       }                                                     
1520
1521     switch(control_type)
1522       {
1523       case CONTROL_ERROR:
1524       return ERROR;
1525
1526       case CONTROL_CASEFUL_LOCAL_PART:
1527       deliver_localpart = addr->cc_local_part;
1528       break;
1529
1530       case CONTROL_CASELOWER_LOCAL_PART:
1531       deliver_localpart = addr->lc_local_part;
1532       break;
1533
1534       case CONTROL_ENFORCE_SYNC:
1535       smtp_enforce_sync = TRUE;
1536       break;
1537
1538       case CONTROL_NO_ENFORCE_SYNC:
1539       smtp_enforce_sync = FALSE;
1540       break;
1541
1542 #ifdef WITH_CONTENT_SCAN
1543       case CONTROL_NO_MBOX_UNSPOOL:
1544       no_mbox_unspool = TRUE;
1545       break;
1546 #endif
1547
1548       case CONTROL_NO_MULTILINE:
1549       no_multiline_responses = TRUE;
1550       break;
1551
1552 #ifdef WITH_CONTENT_SCAN
1553       case CONTROL_FAKEREJECT:
1554       fake_reject = TRUE;
1555       break;
1556 #endif
1557
1558       case CONTROL_FREEZE:
1559       deliver_freeze = TRUE;
1560       deliver_frozen_at = time(NULL);
1561       break;
1562
1563       case CONTROL_QUEUE_ONLY:
1564       queue_only_policy = TRUE;
1565       break;
1566
1567       case CONTROL_SUBMISSION:
1568       submission_mode = TRUE;
1569       while (*p == '/')
1570         { 
1571         if (Ustrncmp(p, "/sender_retain", 14) == 0)
1572           {
1573           p += 14;
1574           active_local_sender_retain = TRUE;
1575           active_local_from_check = FALSE;   
1576           }  
1577         else if (Ustrncmp(p, "/domain=", 8) == 0)
1578           {
1579           uschar *pp = p + 8;
1580           while (*pp != 0 && *pp != '/') pp++; 
1581           submission_domain = string_copyn(p+8, pp-p);
1582           p = pp; 
1583           }
1584         else break;   
1585         }   
1586       if (*p != 0)
1587         {
1588         *log_msgptr = string_sprintf("syntax error in \"control=%s\"", arg);
1589         return ERROR;
1590         }
1591       break;
1592       }
1593     break;
1594
1595 #ifdef WITH_CONTENT_SCAN
1596     case ACLC_DECODE:
1597     rc = mime_decode(&arg);
1598     break;
1599 #endif
1600
1601     case ACLC_DELAY:
1602       {
1603       int delay = readconf_readtime(arg, 0, FALSE);
1604       if (delay < 0)
1605         {
1606         *log_msgptr = string_sprintf("syntax error in argument for \"delay\" "
1607           "modifier: \"%s\" is not a time value", arg);
1608         return ERROR;
1609         }
1610       else
1611         {
1612         HDEBUG(D_acl) debug_printf("delay modifier requests %d-second delay\n",
1613           delay);
1614         if (host_checking)
1615           {
1616           HDEBUG(D_acl)
1617             debug_printf("delay skipped in -bh checking mode\n");
1618           }
1619         else sleep(delay);
1620         }
1621       }
1622     break;
1623
1624     case ACLC_DNSLISTS:
1625     rc = verify_check_dnsbl(&arg);
1626     break;
1627
1628     case ACLC_DOMAINS:
1629     rc = match_isinlist(addr->domain, &arg, 0, &domainlist_anchor,
1630       addr->domain_cache, MCL_DOMAIN, TRUE, &deliver_domain_data);
1631     break;
1632
1633     /* The value in tls_cipher is the full cipher name, for example,
1634     TLSv1:DES-CBC3-SHA:168, whereas the values to test for are just the
1635     cipher names such as DES-CBC3-SHA. But program defensively. We don't know
1636     what may in practice come out of the SSL library - which at the time of
1637     writing is poorly documented. */
1638
1639     case ACLC_ENCRYPTED:
1640     if (tls_cipher == NULL) rc = FAIL; else
1641       {
1642       uschar *endcipher = NULL;
1643       uschar *cipher = Ustrchr(tls_cipher, ':');
1644       if (cipher == NULL) cipher = tls_cipher; else
1645         {
1646         endcipher = Ustrchr(++cipher, ':');
1647         if (endcipher != NULL) *endcipher = 0;
1648         }
1649       rc = match_isinlist(cipher, &arg, 0, NULL, NULL, MCL_STRING, TRUE, NULL);
1650       if (endcipher != NULL) *endcipher = ':';
1651       }
1652     break;
1653
1654     /* Use verify_check_this_host() instead of verify_check_host() so that
1655     we can pass over &host_data to catch any looked up data. Once it has been
1656     set, it retains its value so that it's still there if another ACL verb
1657     comes through here and uses the cache. However, we must put it into
1658     permanent store in case it is also expected to be used in a subsequent
1659     message in the same SMTP connection. */
1660
1661     case ACLC_HOSTS:
1662     rc = verify_check_this_host(&arg, sender_host_cache, NULL,
1663       (sender_host_address == NULL)? US"" : sender_host_address, &host_data);
1664     if (host_data != NULL) host_data = string_copy_malloc(host_data);
1665     break;
1666
1667     case ACLC_LOCAL_PARTS:
1668     rc = match_isinlist(addr->cc_local_part, &arg, 0,
1669       &localpartlist_anchor, addr->localpart_cache, MCL_LOCALPART, TRUE,
1670       &deliver_localpart_data);
1671     break;
1672
1673     case ACLC_LOGWRITE:
1674       {
1675       int logbits = 0;
1676       uschar *s = arg;
1677       if (*s == ':')
1678         {
1679         s++;
1680         while (*s != ':')
1681           {
1682           if (Ustrncmp(s, "main", 4) == 0)
1683             { logbits |= LOG_MAIN; s += 4; }
1684           else if (Ustrncmp(s, "panic", 5) == 0)
1685             { logbits |= LOG_PANIC; s += 5; }
1686           else if (Ustrncmp(s, "reject", 6) == 0)
1687             { logbits |= LOG_REJECT; s += 6; }
1688           else
1689             {
1690             logbits = LOG_MAIN|LOG_PANIC;
1691             s = string_sprintf(":unknown log name in \"%s\" in "
1692               "\"logwrite\" in %s ACL", arg, acl_wherenames[where]);
1693             }
1694           if (*s == ',') s++;
1695           }
1696         s++;
1697         }
1698       while (isspace(*s)) s++;
1699       if (logbits == 0) logbits = LOG_MAIN;
1700       log_write(0, logbits, "%s", string_printing(s));
1701       }
1702     break;
1703     
1704 #ifdef WITH_CONTENT_SCAN
1705     case ACLC_MALWARE:
1706       {
1707       /* Seperate the regular expression and any optional parameters. */
1708       uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
1709       /* Run the malware backend. */
1710       rc = malware(&ss);
1711       /* Modify return code based upon the existance of options. */
1712       while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
1713             != NULL) {
1714         if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
1715           {
1716           /* FAIL so that the message is passed to the next ACL */
1717           rc = FAIL;
1718           }
1719         }
1720       }
1721     break;
1722
1723     case ACLC_MIME_REGEX:
1724       rc = mime_regex(&arg);
1725     break;
1726 #endif
1727
1728     case ACLC_RECIPIENTS:
1729     rc = match_address_list(addr->address, TRUE, TRUE, &arg, NULL, -1, 0,
1730       &recipient_data);
1731     break;
1732
1733 #ifdef WITH_CONTENT_SCAN
1734    case ACLC_REGEX:
1735       rc = regex(&arg);
1736     break;
1737 #endif
1738
1739     case ACLC_SENDER_DOMAINS:
1740       {
1741       uschar *sdomain;
1742       sdomain = Ustrrchr(sender_address, '@');
1743       sdomain = (sdomain == NULL)? US"" : sdomain + 1;
1744       rc = match_isinlist(sdomain, &arg, 0, &domainlist_anchor,
1745         sender_domain_cache, MCL_DOMAIN, TRUE, NULL);
1746       }
1747     break;
1748
1749     case ACLC_SENDERS:
1750     rc = match_address_list(sender_address, TRUE, TRUE, &arg,
1751       sender_address_cache, -1, 0, &sender_data);
1752     break;
1753
1754     /* Connection variables must persist forever */
1755
1756     case ACLC_SET:
1757       {
1758       int old_pool = store_pool;
1759       if (cb->u.varnumber < ACL_C_MAX) store_pool = POOL_PERM;
1760       acl_var[cb->u.varnumber] = string_copy(arg);
1761       store_pool = old_pool;
1762       }
1763     break;
1764
1765 #ifdef WITH_CONTENT_SCAN
1766     case ACLC_SPAM:
1767       {
1768       /* Seperate the regular expression and any optional parameters. */
1769       uschar *ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size);
1770       /* Run the spam backend. */
1771       rc = spam(&ss);
1772       /* Modify return code based upon the existance of options. */
1773       while ((ss = string_nextinlist(&arg, &sep, big_buffer, big_buffer_size))
1774             != NULL) {
1775         if (strcmpic(ss, US"defer_ok") == 0 && rc == DEFER)
1776           {
1777           /* FAIL so that the message is passed to the next ACL */
1778           rc = FAIL;
1779           }
1780         }
1781       }
1782     break;
1783 #endif
1784
1785     /* If the verb is WARN, discard any user message from verification, because
1786     such messages are SMTP responses, not header additions. The latter come
1787     only from explicit "message" modifiers. */
1788
1789     case ACLC_VERIFY:
1790     rc = acl_verify(where, addr, arg, user_msgptr, log_msgptr, basic_errno);
1791     if (verb == ACL_WARN) *user_msgptr = NULL;
1792     break;
1793
1794     default:
1795     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown "
1796       "condition %d", cb->type);
1797     break;
1798     }
1799
1800   /* If a condition was negated, invert OK/FAIL. */
1801
1802   if (!cond_modifiers[cb->type] && cb->u.negated)
1803     {
1804     if (rc == OK) rc = FAIL;
1805       else if (rc == FAIL || rc == FAIL_DROP) rc = OK;
1806     }
1807
1808   if (rc != OK) break;   /* Conditions loop */
1809   }
1810
1811
1812 /* If the result is the one for which "message" and/or "log_message" are used,
1813 handle the values of these options. Most verbs have but a single return for
1814 which the messages are relevant, but for "discard", it's useful to have the log
1815 message both when it succeeds and when it fails. Also, for an "accept" that
1816 appears in a QUIT ACL, we want to handle the user message. Since only "accept"
1817 and "warn" are permitted in that ACL, we don't need to test the verb.
1818
1819 These modifiers act in different ways:
1820
1821 "message" is a user message that will be included in an SMTP response. Unless
1822 it is empty, it overrides any previously set user message.
1823
1824 "log_message" is a non-user message, and it adds to any existing non-user
1825 message that is already set.
1826
1827 If there isn't a log message set, we make it the same as the user message. */
1828
1829 if (((rc == FAIL_DROP)? FAIL : rc) == msgcond[verb] ||
1830     (verb == ACL_DISCARD && rc == OK) ||
1831     (where == ACL_WHERE_QUIT))
1832   {
1833   uschar *expmessage;
1834
1835   /* If the verb is "warn", messages generated by conditions (verification or
1836   nested ACLs) are discarded. Only messages specified at this level are used.
1837   However, the value of an existing message is available in $acl_verify_message
1838   during expansions. */
1839
1840   uschar *old_user_msgptr = *user_msgptr;
1841   uschar *old_log_msgptr = (*log_msgptr != NULL)? *log_msgptr : old_user_msgptr;
1842
1843   if (verb == ACL_WARN) *log_msgptr = *user_msgptr = NULL;
1844
1845   if (user_message != NULL)
1846     {
1847     acl_verify_message = old_user_msgptr;
1848     expmessage = expand_string(user_message);
1849     if (expmessage == NULL)
1850       {
1851       if (!expand_string_forcedfail)
1852         log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
1853           user_message, expand_string_message);
1854       }
1855     else if (expmessage[0] != 0) *user_msgptr = expmessage;
1856     }
1857
1858   if (log_message != NULL)
1859     {
1860     acl_verify_message = old_log_msgptr;
1861     expmessage = expand_string(log_message);
1862     if (expmessage == NULL)
1863       {
1864       if (!expand_string_forcedfail)
1865         log_write(0, LOG_MAIN|LOG_PANIC, "failed to expand ACL message \"%s\": %s",
1866           log_message, expand_string_message);
1867       }
1868     else if (expmessage[0] != 0)
1869       {
1870       *log_msgptr = (*log_msgptr == NULL)? expmessage :
1871         string_sprintf("%s: %s", expmessage, *log_msgptr);
1872       }
1873     }
1874
1875   /* If no log message, default it to the user message */
1876
1877   if (*log_msgptr == NULL) *log_msgptr = *user_msgptr;
1878   }
1879
1880 acl_verify_message = NULL;
1881 return rc;
1882 }
1883
1884
1885
1886
1887
1888 /*************************************************
1889 *        Get line from a literal ACL             *
1890 *************************************************/
1891
1892 /* This function is passed to acl_read() in order to extract individual lines
1893 of a literal ACL, which we access via static pointers. We can destroy the
1894 contents because this is called only once (the compiled ACL is remembered).
1895
1896 This code is intended to treat the data in the same way as lines in the main
1897 Exim configuration file. That is:
1898
1899   . Leading spaces are ignored.
1900
1901   . A \ at the end of a line is a continuation - trailing spaces after the \
1902     are permitted (this is because I don't believe in making invisible things
1903     significant). Leading spaces on the continued part of a line are ignored.
1904
1905   . Physical lines starting (significantly) with # are totally ignored, and
1906     may appear within a sequence of backslash-continued lines.
1907
1908   . Blank lines are ignored, but will end a sequence of continuations.
1909
1910 Arguments: none
1911 Returns:   a pointer to the next line
1912 */
1913
1914
1915 static uschar *acl_text;          /* Current pointer in the text */
1916 static uschar *acl_text_end;      /* Points one past the terminating '0' */
1917
1918
1919 static uschar *
1920 acl_getline(void)
1921 {
1922 uschar *yield;
1923
1924 /* This loop handles leading blank lines and comments. */
1925
1926 for(;;)
1927   {
1928   while (isspace(*acl_text)) acl_text++;   /* Leading spaces/empty lines */
1929   if (*acl_text == 0) return NULL;         /* No more data */
1930   yield = acl_text;                        /* Potential data line */
1931
1932   while (*acl_text != 0 && *acl_text != '\n') acl_text++;
1933
1934   /* If we hit the end before a newline, we have the whole logical line. If
1935   it's a comment, there's no more data to be given. Otherwise, yield it. */
1936
1937   if (*acl_text == 0) return (*yield == '#')? NULL : yield;
1938
1939   /* After reaching a newline, end this loop if the physical line does not
1940   start with '#'. If it does, it's a comment, and the loop continues. */
1941
1942   if (*yield != '#') break;
1943   }
1944
1945 /* This loop handles continuations. We know we have some real data, ending in
1946 newline. See if there is a continuation marker at the end (ignoring trailing
1947 white space). We know that *yield is not white space, so no need to test for
1948 cont > yield in the backwards scanning loop. */
1949
1950 for(;;)
1951   {
1952   uschar *cont;
1953   for (cont = acl_text - 1; isspace(*cont); cont--);
1954
1955   /* If no continuation follows, we are done. Mark the end of the line and
1956   return it. */
1957
1958   if (*cont != '\\')
1959     {
1960     *acl_text++ = 0;
1961     return yield;
1962     }
1963
1964   /* We have encountered a continuation. Skip over whitespace at the start of
1965   the next line, and indeed the whole of the next line or lines if they are
1966   comment lines. */
1967
1968   for (;;)
1969     {
1970     while (*(++acl_text) == ' ' || *acl_text == '\t');
1971     if (*acl_text != '#') break;
1972     while (*(++acl_text) != 0 && *acl_text != '\n');
1973     }
1974
1975   /* We have the start of a continuation line. Move all the rest of the data
1976   to join onto the previous line, and then find its end. If the end is not a
1977   newline, we are done. Otherwise loop to look for another continuation. */
1978
1979   memmove(cont, acl_text, acl_text_end - acl_text);
1980   acl_text_end -= acl_text - cont;
1981   acl_text = cont;
1982   while (*acl_text != 0 && *acl_text != '\n') acl_text++;
1983   if (*acl_text == 0) return yield;
1984   }
1985
1986 /* Control does not reach here */
1987 }
1988
1989
1990
1991
1992
1993 /*************************************************
1994 *        Check access using an ACL               *
1995 *************************************************/
1996
1997 /* This function is called from address_check. It may recurse via
1998 acl_check_condition() - hence the use of a level to stop looping. The ACL is
1999 passed as a string which is expanded. A forced failure implies no access check
2000 is required. If the result is a single word, it is taken as the name of an ACL
2001 which is sought in the global ACL tree. Otherwise, it is taken as literal ACL
2002 text, complete with newlines, and parsed as such. In both cases, the ACL check
2003 is then run. This function uses an auxiliary function for acl_read() to call
2004 for reading individual lines of a literal ACL. This is acl_getline(), which
2005 appears immediately above.
2006
2007 Arguments:
2008   where        where called from
2009   addr         address item when called from RCPT; otherwise NULL
2010   s            the input string; NULL is the same as an empty ACL => DENY
2011   level        the nesting level
2012   user_msgptr  where to put a user error (for SMTP response)
2013   log_msgptr   where to put a logging message (not for SMTP response)
2014
2015 Returns:       OK         access is granted
2016                DISCARD    access is apparently granted...
2017                FAIL       access is denied
2018                FAIL_DROP  access is denied; drop the connection
2019                DEFER      can't tell at the moment
2020                ERROR      disaster
2021 */
2022
2023 static int
2024 acl_check_internal(int where, address_item *addr, uschar *s, int level,
2025   uschar **user_msgptr, uschar **log_msgptr)
2026 {
2027 int fd = -1;
2028 acl_block *acl = NULL;
2029 uschar *acl_name = US"inline ACL";
2030 uschar *ss;
2031
2032 /* Catch configuration loops */
2033
2034 if (level > 20)
2035   {
2036   *log_msgptr = US"ACL nested too deep: possible loop";
2037   return ERROR;
2038   }
2039
2040 if (s == NULL)
2041   {
2042   HDEBUG(D_acl) debug_printf("ACL is NULL: implicit DENY\n");
2043   return FAIL;
2044   }
2045
2046 /* At top level, we expand the incoming string. At lower levels, it has already
2047 been expanded as part of condition processing. */
2048
2049 if (level == 0)
2050   {
2051   ss = expand_string(s);
2052   if (ss == NULL)
2053     {
2054     if (expand_string_forcedfail) return OK;
2055     *log_msgptr = string_sprintf("failed to expand ACL string \"%s\": %s", s,
2056       expand_string_message);
2057     return ERROR;
2058     }
2059   }
2060 else ss = s;
2061
2062 while (isspace(*ss))ss++;
2063
2064 /* If we can't find a named ACL, the default is to parse it as an inline one.
2065 (Unless it begins with a slash; non-existent files give rise to an error.) */
2066
2067 acl_text = ss;
2068
2069 /* Handle the case of a string that does not contain any spaces. Look for a
2070 named ACL among those read from the configuration, or a previously read file.
2071 It is possible that the pointer to the ACL is NULL if the configuration
2072 contains a name with no data. If not found, and the text begins with '/',
2073 read an ACL from a file, and save it so it can be re-used. */
2074
2075 if (Ustrchr(ss, ' ') == NULL)
2076   {
2077   tree_node *t = tree_search(acl_anchor, ss);
2078   if (t != NULL)
2079     {
2080     acl = (acl_block *)(t->data.ptr);
2081     if (acl == NULL)
2082       {
2083       HDEBUG(D_acl) debug_printf("ACL \"%s\" is empty: implicit DENY\n", ss);
2084       return FAIL;
2085       }
2086     acl_name = string_sprintf("ACL \"%s\"", ss);
2087     HDEBUG(D_acl) debug_printf("using ACL \"%s\"\n", ss);
2088     }
2089
2090   else if (*ss == '/')
2091     {
2092     struct stat statbuf;
2093     fd = Uopen(ss, O_RDONLY, 0);
2094     if (fd < 0)
2095       {
2096       *log_msgptr = string_sprintf("failed to open ACL file \"%s\": %s", ss,
2097         strerror(errno));
2098       return ERROR;
2099       }
2100
2101     if (fstat(fd, &statbuf) != 0)
2102       {
2103       *log_msgptr = string_sprintf("failed to fstat ACL file \"%s\": %s", ss,
2104         strerror(errno));
2105       return ERROR;
2106       }
2107
2108     acl_text = store_get(statbuf.st_size + 1);
2109     acl_text_end = acl_text + statbuf.st_size + 1;
2110
2111     if (read(fd, acl_text, statbuf.st_size) != statbuf.st_size)
2112       {
2113       *log_msgptr = string_sprintf("failed to read ACL file \"%s\": %s",
2114         ss, strerror(errno));
2115       return ERROR;
2116       }
2117     acl_text[statbuf.st_size] = 0;
2118     close(fd);
2119
2120     acl_name = string_sprintf("ACL \"%s\"", ss);
2121     HDEBUG(D_acl) debug_printf("read ACL from file %s\n", ss);
2122     }
2123   }
2124
2125 /* Parse an ACL that is still in text form. If it came from a file, remember it
2126 in the ACL tree, having read it into the POOL_PERM store pool so that it
2127 persists between multiple messages. */
2128
2129 if (acl == NULL)
2130   {
2131   int old_pool = store_pool;
2132   if (fd >= 0) store_pool = POOL_PERM;
2133   acl = acl_read(acl_getline, log_msgptr);
2134   store_pool = old_pool;
2135   if (acl == NULL && *log_msgptr != NULL) return ERROR;
2136   if (fd >= 0)
2137     {
2138     tree_node *t = store_get_perm(sizeof(tree_node) + Ustrlen(ss));
2139     Ustrcpy(t->name, ss);
2140     t->data.ptr = acl;
2141     (void)tree_insertnode(&acl_anchor, t);
2142     }
2143   }
2144
2145 /* Now we have an ACL to use. It's possible it may be NULL. */
2146
2147 while (acl != NULL)
2148   {
2149   int cond;
2150   int basic_errno = 0;
2151   BOOL endpass_seen = FALSE;
2152
2153   *log_msgptr = *user_msgptr = NULL;
2154   acl_temp_details = FALSE;
2155
2156   if (where == ACL_WHERE_QUIT &&
2157       acl->verb != ACL_ACCEPT &&
2158       acl->verb != ACL_WARN)
2159     {
2160     *log_msgptr = string_sprintf("\"%s\" is not allowed in a QUIT ACL",
2161       verbs[acl->verb]);
2162     return ERROR;
2163     }
2164
2165   HDEBUG(D_acl) debug_printf("processing \"%s\"\n", verbs[acl->verb]);
2166
2167   /* Clear out any search error message from a previous check before testing
2168   this condition. */
2169
2170   search_error_message = NULL;
2171   cond = acl_check_condition(acl->verb, acl->condition, where, addr, level,
2172     &endpass_seen, user_msgptr, log_msgptr, &basic_errno);
2173
2174   /* Handle special returns: DEFER causes a return except on a WARN verb;
2175   ERROR always causes a return. */
2176
2177   switch (cond)
2178     {
2179     case DEFER:
2180     HDEBUG(D_acl) debug_printf("%s: condition test deferred\n", verbs[acl->verb]);
2181     if (basic_errno != ERRNO_CALLOUTDEFER)
2182       {
2183       if (search_error_message != NULL && *search_error_message != 0)
2184         *log_msgptr = search_error_message;
2185       if (smtp_return_error_details) acl_temp_details = TRUE;
2186       }
2187     else
2188       {
2189       acl_temp_details = TRUE;
2190       }
2191     if (acl->verb != ACL_WARN) return DEFER;
2192     break;
2193
2194     default:      /* Paranoia */
2195     case ERROR:
2196     HDEBUG(D_acl) debug_printf("%s: condition test error\n", verbs[acl->verb]);
2197     return ERROR;
2198
2199     case OK:
2200     HDEBUG(D_acl) debug_printf("%s: condition test succeeded\n",
2201       verbs[acl->verb]);
2202     break;
2203
2204     case FAIL:
2205     HDEBUG(D_acl) debug_printf("%s: condition test failed\n", verbs[acl->verb]);
2206     break;
2207
2208     /* DISCARD and DROP can happen only from a nested ACL condition, and
2209     DISCARD can happen only for an "accept" or "discard" verb. */
2210
2211     case DISCARD:
2212     HDEBUG(D_acl) debug_printf("%s: condition test yielded \"discard\"\n",
2213       verbs[acl->verb]);
2214     break;
2215
2216     case FAIL_DROP:
2217     HDEBUG(D_acl) debug_printf("%s: condition test yielded \"drop\"\n",
2218       verbs[acl->verb]);
2219     break;
2220     }
2221
2222   /* At this point, cond for most verbs is either OK or FAIL or (as a result of
2223   a nested ACL condition) FAIL_DROP. However, for WARN, cond may be DEFER, and
2224   for ACCEPT and DISCARD, it may be DISCARD after a nested ACL call. */
2225
2226   switch(acl->verb)
2227     {
2228     case ACL_ACCEPT:
2229     if (cond == OK || cond == DISCARD) return cond;
2230     if (endpass_seen)
2231       {
2232       HDEBUG(D_acl) debug_printf("accept: endpass encountered - denying access\n");
2233       return cond;
2234       }
2235     break;
2236
2237     case ACL_DEFER:
2238     if (cond == OK)
2239       {
2240       acl_temp_details = TRUE;
2241       return DEFER;
2242       }
2243     break;
2244
2245     case ACL_DENY:
2246     if (cond == OK) return FAIL;
2247     break;
2248
2249     case ACL_DISCARD:
2250     if (cond == OK || cond == DISCARD) return DISCARD;
2251     if (endpass_seen)
2252       {
2253       HDEBUG(D_acl) debug_printf("discard: endpass encountered - denying access\n");
2254       return cond;
2255       }
2256     break;
2257
2258     case ACL_DROP:
2259     if (cond == OK) return FAIL_DROP;
2260     break;
2261
2262     case ACL_REQUIRE:
2263     if (cond != OK) return cond;
2264     break;
2265
2266     case ACL_WARN:
2267     if (cond == OK)
2268       acl_warn(where, *user_msgptr, *log_msgptr);
2269     else if (cond == DEFER)
2270       acl_warn(where, NULL, string_sprintf("ACL \"warn\" statement skipped: "
2271         "condition test deferred: %s",
2272         (*log_msgptr == NULL)? US"" : *log_msgptr));
2273     *log_msgptr = *user_msgptr = NULL;  /* In case implicit DENY follows */
2274     break;
2275
2276     default:
2277     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal ACL error: unknown verb %d",
2278       acl->verb);
2279     break;
2280     }
2281
2282   /* Pass to the next ACL item */
2283
2284   acl = acl->next;
2285   }
2286
2287 /* We have reached the end of the ACL. This is an implicit DENY. */
2288
2289 HDEBUG(D_acl) debug_printf("end of %s: implicit DENY\n", acl_name);
2290 return FAIL;
2291 }
2292
2293
2294 /*************************************************
2295 *        Check access using an ACL               *
2296 *************************************************/
2297
2298 /* This is the external interface for ACL checks. It sets up an address and the
2299 expansions for $domain and $local_part when called after RCPT, then calls
2300 acl_check_internal() to do the actual work.
2301
2302 Arguments:
2303   where        ACL_WHERE_xxxx indicating where called from
2304   data_string  RCPT address, or SMTP command argument, or NULL
2305   s            the input string; NULL is the same as an empty ACL => DENY
2306   user_msgptr  where to put a user error (for SMTP response)
2307   log_msgptr   where to put a logging message (not for SMTP response)
2308
2309 Returns:       OK         access is granted by an ACCEPT verb
2310                DISCARD    access is granted by a DISCARD verb
2311                FAIL       access is denied
2312                FAIL_DROP  access is denied; drop the connection
2313                DEFER      can't tell at the moment
2314                ERROR      disaster
2315 */
2316
2317 int
2318 acl_check(int where, uschar *data_string, uschar *s, uschar **user_msgptr,
2319   uschar **log_msgptr)
2320 {
2321 int rc;
2322 address_item adb;
2323 address_item *addr;
2324
2325 *user_msgptr = *log_msgptr = NULL;
2326 sender_verified_failed = NULL;
2327
2328 if (where == ACL_WHERE_RCPT)
2329   {
2330   adb = address_defaults;
2331   addr = &adb;
2332   addr->address = data_string;
2333   if (deliver_split_address(addr) == DEFER)
2334     {
2335     *log_msgptr = US"defer in percent_hack_domains check";
2336     return DEFER;
2337     }
2338   deliver_domain = addr->domain;
2339   deliver_localpart = addr->local_part;
2340   }
2341 else
2342   {
2343   addr = NULL;
2344   smtp_command_argument = data_string;
2345   }
2346
2347 rc = acl_check_internal(where, addr, s, 0, user_msgptr, log_msgptr);
2348
2349 smtp_command_argument = deliver_domain =
2350   deliver_localpart = deliver_address_data = sender_address_data = NULL;
2351
2352 /* A DISCARD response is permitted only for message ACLs, excluding the PREDATA
2353 ACL, which is really in the middle of an SMTP command. */
2354
2355 if (rc == DISCARD)
2356   {
2357   if (where > ACL_WHERE_NOTSMTP || where == ACL_WHERE_PREDATA)
2358     {
2359     log_write(0, LOG_MAIN|LOG_PANIC, "\"discard\" verb not allowed in %s "
2360       "ACL", acl_wherenames[where]);
2361     return ERROR;
2362     }
2363   return DISCARD;
2364   }
2365
2366 /* A DROP response is not permitted from MAILAUTH */
2367
2368 if (rc == FAIL_DROP && where == ACL_WHERE_MAILAUTH)
2369   {
2370   log_write(0, LOG_MAIN|LOG_PANIC, "\"drop\" verb not allowed in %s "
2371     "ACL", acl_wherenames[where]);
2372   return ERROR;
2373   }
2374
2375 /* Before giving an error response, take a look at the length of any user
2376 message, and split it up into multiple lines if possible. */
2377
2378 if (rc != OK && *user_msgptr != NULL && Ustrlen(*user_msgptr) > 75)
2379   {
2380   uschar *s = *user_msgptr = string_copy(*user_msgptr);
2381   uschar *ss = s;
2382
2383   for (;;)
2384     {
2385     int i = 0;
2386     while (i < 75 && *ss != 0 && *ss != '\n') ss++, i++;
2387     if (*ss == 0) break;
2388     if (*ss == '\n')
2389       s = ++ss;
2390     else
2391       {
2392       uschar *t = ss + 1;
2393       uschar *tt = NULL;
2394       while (--t > s + 35)
2395         {
2396         if (*t == ' ')
2397           {
2398           if (t[-1] == ':') { tt = t; break; }
2399           if (tt == NULL) tt = t;
2400           }
2401         }
2402
2403       if (tt == NULL)          /* Can't split behind - try ahead */
2404         {
2405         t = ss + 1;
2406         while (*t != 0)
2407           {
2408           if (*t == ' ' || *t == '\n')
2409             { tt = t; break; }
2410           t++;
2411           }
2412         }
2413
2414       if (tt == NULL) break;   /* Can't find anywhere to split */
2415       *tt = '\n';
2416       s = ss = tt+1;
2417       }
2418     }
2419   }
2420
2421 return rc;
2422 }
2423
2424 /* End of acl.c */