CVE-2020-28013: Heap buffer overflow in parse_fix_phrase()
[exim.git] / src / src / spam.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2003 - 2015
6  * License: GPL
7  * Copyright (c) The Exim Maintainers 2016 - 2020
8  */
9
10 /* Code for calling spamassassin's spamd. Called from acl.c. */
11
12 #include "exim.h"
13 #ifdef WITH_CONTENT_SCAN
14 #include "spam.h"
15
16 uschar spam_score_buffer[16];
17 uschar spam_score_int_buffer[16];
18 uschar spam_bar_buffer[128];
19 uschar spam_action_buffer[32];
20 uschar spam_report_buffer[32600];
21 uschar * prev_user_name = NULL;
22 int spam_ok = 0;
23 int spam_rc = 0;
24 uschar *prev_spamd_address_work = NULL;
25
26 static const uschar * loglabel = US"spam acl condition:";
27
28
29 static int
30 spamd_param_init(spamd_address_container *spamd)
31 {
32 /* default spamd server weight, time and priority value */
33 spamd->is_rspamd = FALSE;
34 spamd->is_failed = FALSE;
35 spamd->weight = SPAMD_WEIGHT;
36 spamd->timeout = SPAMD_TIMEOUT;
37 spamd->retry = 0;
38 spamd->priority = 1;
39 return 0;
40 }
41
42
43 static int
44 spamd_param(const uschar * param, spamd_address_container * spamd)
45 {
46 static int timesinceday = -1;
47 const uschar * s;
48 const uschar * name;
49
50 /*XXX more clever parsing could discard embedded spaces? */
51
52 if (sscanf(CCS param, "pri=%u", &spamd->priority))
53   return 0; /* OK */
54
55 if (sscanf(CCS param, "weight=%u", &spamd->weight))
56   {
57   if (spamd->weight == 0) /* this server disabled: skip it */
58     return 1;
59   return 0; /* OK */
60   }
61
62 if (Ustrncmp(param, "time=", 5) == 0)
63   {
64   unsigned int start_h = 0, start_m = 0, start_s = 0;
65   unsigned int end_h = 24, end_m = 0, end_s = 0;
66   unsigned int time_start, time_end;
67   const uschar * end_string;
68
69   name = US"time";
70   s = param+5;
71   if ((end_string = Ustrchr(s, '-')))
72     {
73     end_string++;
74     if (  sscanf(CS end_string, "%u.%u.%u", &end_h,   &end_m,   &end_s)   == 0
75        || sscanf(CS s,          "%u.%u.%u", &start_h, &start_m, &start_s) == 0
76        )
77       goto badval;
78     }
79   else
80     goto badval;
81
82   if (timesinceday < 0)
83     {
84     time_t now = time(NULL);
85     struct tm *tmp = localtime(&now);
86     timesinceday = tmp->tm_hour*3600 + tmp->tm_min*60 + tmp->tm_sec;
87     }
88
89   time_start = start_h*3600 + start_m*60 + start_s;
90   time_end = end_h*3600 + end_m*60 + end_s;
91
92   if (timesinceday < time_start || timesinceday >= time_end)
93     return 1; /* skip spamd server */
94
95   return 0; /* OK */
96   }
97
98 if (Ustrcmp(param, "variant=rspamd") == 0)
99   {
100   spamd->is_rspamd = TRUE;
101   return 0;
102   }
103
104 if (Ustrncmp(param, "tmo=", 4) == 0)
105   {
106   int sec = readconf_readtime((s = param+4), '\0', FALSE);
107   name = US"timeout";
108   if (sec < 0)
109     goto badval;
110   spamd->timeout = sec;
111   return 0;
112   }
113
114 if (Ustrncmp(param, "retry=", 6) == 0)
115   {
116   int sec = readconf_readtime((s = param+6), '\0', FALSE);
117   name = US"retry";
118   if (sec < 0)
119     goto badval;
120   spamd->retry = sec;
121   return 0;
122   }
123
124 log_write(0, LOG_MAIN, "%s warning - invalid spamd parameter: '%s'",
125   loglabel, param);
126 return -1; /* syntax error */
127
128 badval:
129   log_write(0, LOG_MAIN,
130     "%s warning - invalid spamd %s value: '%s'", loglabel, name, s);
131   return -1; /* syntax error */
132 }
133
134
135 static int
136 spamd_get_server(spamd_address_container ** spamds, int num_servers)
137 {
138 unsigned int i;
139 spamd_address_container * sd;
140 long weights;
141 unsigned pri;
142 static BOOL srandomed = FALSE;
143
144 /* speedup, if we have only 1 server */
145 if (num_servers == 1)
146   return (spamds[0]->is_failed ? -1 : 0);
147
148 /* init ranmod */
149 if (!srandomed)
150   {
151   struct timeval tv;
152   gettimeofday(&tv, NULL);
153   srandom((unsigned int)(tv.tv_usec/1000));
154   srandomed = TRUE;
155   }
156
157 /* scan for highest pri */
158 for (pri = 0, i = 0; i < num_servers; i++)
159   {
160   sd = spamds[i];
161   if (!sd->is_failed && sd->priority > pri) pri = sd->priority;
162   }
163
164 /* get sum of weights */
165 for (weights = 0, i = 0; i < num_servers; i++)
166   {
167   sd = spamds[i];
168   if (!sd->is_failed && sd->priority == pri) weights += sd->weight;
169   }
170 if (weights == 0)       /* all servers failed */
171   return -1;
172
173 for (long rnd = random() % weights, i = 0; i < num_servers; i++)
174   {
175   sd = spamds[i];
176   if (!sd->is_failed && sd->priority == pri)
177     if ((rnd -= sd->weight) < 0)
178       return i;
179   }
180
181 log_write(0, LOG_MAIN|LOG_PANIC,
182   "%s unknown error (memory/cpu corruption?)", loglabel);
183 return -1;
184 }
185
186
187 int
188 spam(const uschar **listptr)
189 {
190 int sep = 0;
191 const uschar *list = *listptr;
192 uschar *user_name;
193 unsigned long mbox_size;
194 FILE *mbox_file;
195 client_conn_ctx spamd_cctx = {.sock = -1};
196 uschar spamd_buffer[32600];
197 int i, j, offset, result;
198 uschar spamd_version[8];
199 uschar spamd_short_result[8];
200 uschar spamd_score_char;
201 double spamd_threshold, spamd_score, spamd_reject_score;
202 int spamd_report_offset;
203 uschar *p,*q;
204 int override = 0;
205 time_t start;
206 size_t read, wrote;
207 #ifndef NO_POLL_H
208 struct pollfd pollfd;
209 #else                               /* Patch posted by Erik ? for OS X */
210 struct timeval select_tv;         /* and applied by PH */
211 fd_set select_fd;
212 #endif
213 uschar *spamd_address_work;
214 spamd_address_container * sd;
215
216 /* stop compiler warning */
217 result = 0;
218
219 /* find the username from the option list */
220 if (!(user_name = string_nextinlist(&list, &sep, NULL, 0)))
221   {
222   /* no username given, this means no scanning should be done */
223   return FAIL;
224   }
225
226 /* if username is "0" or "false", do not scan */
227 if ( (Ustrcmp(user_name,"0") == 0) ||
228      (strcmpic(user_name,US"false") == 0) )
229   return FAIL;
230
231 /* if there is an additional option, check if it is "true" */
232 if (strcmpic(list,US"true") == 0)
233   /* in that case, always return true later */
234   override = 1;
235
236 /* expand spamd_address if needed */
237 if (*spamd_address == '$')
238   {
239   spamd_address_work = expand_string(spamd_address);
240   if (spamd_address_work == NULL)
241     {
242     log_write(0, LOG_MAIN|LOG_PANIC,
243       "%s spamd_address starts with $, but expansion failed: %s",
244       loglabel, expand_string_message);
245     return DEFER;
246     }
247   }
248 else
249   spamd_address_work = spamd_address;
250
251 DEBUG(D_acl) debug_printf_indent("spamd: addrlist '%s'\n", spamd_address_work);
252
253 /* check if previous spamd_address was expanded and has changed. dump cached results if so */
254 if (  spam_ok
255    && prev_spamd_address_work != NULL
256    && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0
257    )
258   spam_ok = 0;
259
260 /* if we scanned for this username last time, just return */
261 if (spam_ok && Ustrcmp(prev_user_name, user_name) == 0)
262   return override ? OK : spam_rc;
263
264 /* make sure the eml mbox file is spooled up */
265
266 if (!(mbox_file = spool_mbox(&mbox_size, NULL, NULL)))
267   {                                                             /* error while spooling */
268   log_write(0, LOG_MAIN|LOG_PANIC,
269          "%s error while creating mbox spool file", loglabel);
270   return DEFER;
271   }
272
273 start = time(NULL);
274
275   {
276   int num_servers = 0;
277   int current_server;
278   uschar * address;
279   const uschar * spamd_address_list_ptr = spamd_address_work;
280   spamd_address_container * spamd_address_vector[32];
281
282   /* Check how many spamd servers we have
283      and register their addresses */
284   sep = 0;                              /* default colon-sep */
285   while ((address = string_nextinlist(&spamd_address_list_ptr, &sep, NULL, 0)))
286     {
287     const uschar * sublist;
288     int sublist_sep = -(int)' ';        /* default space-sep */
289     unsigned args;
290     uschar * s;
291
292     DEBUG(D_acl) debug_printf_indent("spamd: addr entry '%s'\n", address);
293     sd = store_get(sizeof(spamd_address_container), FALSE);
294
295     for (sublist = address, args = 0, spamd_param_init(sd);
296          (s = string_nextinlist(&sublist, &sublist_sep, NULL, 0));
297          args++
298          )
299       {
300         DEBUG(D_acl) debug_printf_indent("spamd:  addr parm '%s'\n", s);
301         switch (args)
302         {
303         case 0:   sd->hostspec = s;
304                   if (*s == '/') args++;        /* local; no port */
305                   break;
306         case 1:   sd->hostspec = string_sprintf("%s %s", sd->hostspec, s);
307                   break;
308         default:  spamd_param(s, sd);
309                   break;
310         }
311       }
312     if (args < 2)
313       {
314       log_write(0, LOG_MAIN,
315         "%s warning - invalid spamd address: '%s'", loglabel, address);
316       continue;
317       }
318
319     spamd_address_vector[num_servers] = sd;
320     if (++num_servers > 31)
321       break;
322     }
323
324   /* check if we have at least one server */
325   if (!num_servers)
326     {
327     log_write(0, LOG_MAIN|LOG_PANIC,
328        "%s no useable spamd server addresses in spamd_address configuration option.",
329        loglabel);
330     goto defer;
331     }
332
333   current_server = spamd_get_server(spamd_address_vector, num_servers);
334   sd = spamd_address_vector[current_server];
335   for(;;)
336     {
337     uschar * errstr;
338
339     DEBUG(D_acl) debug_printf_indent("spamd: trying server %s\n", sd->hostspec);
340
341     for (;;)
342       {
343       /*XXX could potentially use TFO early-data here */
344       if (  (spamd_cctx.sock = ip_streamsocket(sd->hostspec, &errstr, 5, NULL)) >= 0
345          || sd->retry <= 0
346          )
347         break;
348       DEBUG(D_acl) debug_printf_indent("spamd: server %s: retry conn\n", sd->hostspec);
349       while (sd->retry > 0) sd->retry = sleep(sd->retry);
350       }
351     if (spamd_cctx.sock >= 0)
352       break;
353
354     log_write(0, LOG_MAIN, "%s spamd: %s", loglabel, errstr);
355     sd->is_failed = TRUE;
356
357     current_server = spamd_get_server(spamd_address_vector, num_servers);
358     if (current_server < 0)
359       {
360       log_write(0, LOG_MAIN|LOG_PANIC, "%s all spamd servers failed", loglabel);
361       goto defer;
362       }
363     sd = spamd_address_vector[current_server];
364     }
365   }
366
367 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
368 /* now we are connected to spamd on spamd_cctx.sock */
369 if (sd->is_rspamd)
370   {
371   gstring * req_str;
372   const uschar * s;
373
374   req_str = string_append(NULL, 8,
375     "CHECK RSPAMC/1.3\r\nContent-length: ", string_sprintf("%lu\r\n", mbox_size),
376     "Queue-Id: ", message_id,
377     "\r\nFrom: <", sender_address,
378     ">\r\nRecipient-Number: ", string_sprintf("%d\r\n", recipients_count));
379
380   for (int i = 0; i < recipients_count; i++)
381     req_str = string_append(req_str, 3,
382       "Rcpt: <", recipients_list[i].address, ">\r\n");
383   if ((s = expand_string(US"$sender_helo_name")) && *s)
384     req_str = string_append(req_str, 3, "Helo: ", s, "\r\n");
385   if ((s = expand_string(US"$sender_host_name")) && *s)
386     req_str = string_append(req_str, 3, "Hostname: ", s, "\r\n");
387   if (sender_host_address)
388     req_str = string_append(req_str, 3, "IP: ", sender_host_address, "\r\n");
389   if ((s = expand_string(US"$authenticated_id")) && *s)
390     req_str = string_append(req_str, 3, "User: ", s, "\r\n");
391   req_str = string_catn(req_str, US"\r\n", 2);
392   wrote = send(spamd_cctx.sock, req_str->s, req_str->ptr, 0);
393   }
394 else
395   {                             /* spamassassin variant */
396   int n;
397   uschar * s = string_sprintf(
398           "REPORT SPAMC/1.2\r\nUser: %s\r\nContent-length: %ld\r\n\r\n%n",
399           user_name, mbox_size, &n);
400   /* send our request */
401   wrote = send(spamd_cctx.sock, s, n, 0);
402   }
403
404 if (wrote == -1)
405   {
406   (void)close(spamd_cctx.sock);
407   log_write(0, LOG_MAIN|LOG_PANIC,
408        "%s spamd %s send failed: %s", loglabel, callout_address, strerror(errno));
409   goto defer;
410   }
411
412 /* now send the file */
413 /* spamd sometimes accepts connections but doesn't read data off
414  * the connection.  We make the file descriptor non-blocking so
415  * that the write will only write sufficient data without blocking
416  * and we poll the descriptor to make sure that we can write without
417  * blocking.  Short writes are gracefully handled and if the whole
418  * transaction takes too long it is aborted.
419  * Note: poll() is not supported in OSX 10.2 and is reported to be
420  *       broken in more recent versions (up to 10.4).
421  */
422 #ifndef NO_POLL_H
423 pollfd.fd = spamd_cctx.sock;
424 pollfd.events = POLLOUT;
425 #endif
426 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
427 do
428   {
429   read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file);
430   if (read > 0)
431     {
432     offset = 0;
433 again:
434 #ifndef NO_POLL_H
435     result = poll(&pollfd, 1, 1000);
436
437 /* Patch posted by Erik ? for OS X and applied by PH */
438 #else
439     select_tv.tv_sec = 1;
440     select_tv.tv_usec = 0;
441     FD_ZERO(&select_fd);
442     FD_SET(spamd_cctx.sock, &select_fd);
443     result = select(spamd_cctx.sock+1, NULL, &select_fd, NULL, &select_tv);
444 #endif
445 /* End Erik's patch */
446
447     if (result == -1 && errno == EINTR)
448       goto again;
449     else if (result < 1)
450       {
451       if (result == -1)
452         log_write(0, LOG_MAIN|LOG_PANIC,
453           "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
454       else
455         {
456         if (time(NULL) - start < sd->timeout)
457           goto again;
458         log_write(0, LOG_MAIN|LOG_PANIC,
459           "%s timed out writing spamd %s, socket", loglabel, callout_address);
460         }
461       (void)close(spamd_cctx.sock);
462       goto defer;
463       }
464
465     wrote = send(spamd_cctx.sock,spamd_buffer + offset,read - offset,0);
466     if (wrote == -1)
467       {
468       log_write(0, LOG_MAIN|LOG_PANIC,
469           "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
470       (void)close(spamd_cctx.sock);
471       goto defer;
472       }
473     if (offset + wrote != read)
474       {
475       offset += wrote;
476       goto again;
477       }
478     }
479   }
480 while (!feof(mbox_file) && !ferror(mbox_file));
481
482 if (ferror(mbox_file))
483   {
484   log_write(0, LOG_MAIN|LOG_PANIC,
485     "%s error reading spool file: %s", loglabel, strerror(errno));
486   (void)close(spamd_cctx.sock);
487   goto defer;
488   }
489
490 (void)fclose(mbox_file);
491
492 /* we're done sending, close socket for writing */
493 if (!sd->is_rspamd)
494   shutdown(spamd_cctx.sock,SHUT_WR);
495
496 /* read spamd response using what's left of the timeout.  */
497 memset(spamd_buffer, 0, sizeof(spamd_buffer));
498 offset = 0;
499 while ((i = ip_recv(&spamd_cctx,
500                    spamd_buffer + offset,
501                    sizeof(spamd_buffer) - offset - 1,
502                    sd->timeout + start)) > 0)
503   offset += i;
504 spamd_buffer[offset] = '\0';    /* guard byte */
505
506 /* error handling */
507 if (i <= 0 && errno != 0)
508   {
509   log_write(0, LOG_MAIN|LOG_PANIC,
510        "%s error reading from spamd %s, socket: %s", loglabel, callout_address, strerror(errno));
511   (void)close(spamd_cctx.sock);
512   return DEFER;
513   }
514
515 /* reading done */
516 (void)close(spamd_cctx.sock);
517
518 if (sd->is_rspamd)
519   {                             /* rspamd variant of reply */
520   int r;
521   if (  (r = sscanf(CS spamd_buffer,
522           "RSPAMD/%7s 0 EX_OK\r\nMetric: default; %7s %lf / %lf / %lf\r\n%n",
523           spamd_version, spamd_short_result, &spamd_score, &spamd_threshold,
524           &spamd_reject_score, &spamd_report_offset)) != 5
525      || spamd_report_offset >= offset           /* verify within buffer */
526      )
527     {
528     log_write(0, LOG_MAIN|LOG_PANIC,
529               "%s cannot parse spamd %s, output: %d", loglabel, callout_address, r);
530     return DEFER;
531     }
532   /* now parse action */
533   p = &spamd_buffer[spamd_report_offset];
534
535   if (Ustrncmp(p, "Action: ", sizeof("Action: ") - 1) == 0)
536     {
537     p += sizeof("Action: ") - 1;
538     q = &spam_action_buffer[0];
539     while (*p && *p != '\r' && (q - spam_action_buffer) < sizeof(spam_action_buffer) - 1)
540       *q++ = *p++;
541     *q = '\0';
542     }
543   }
544 else
545   {                             /* spamassassin */
546   /* dig in the spamd output and put the report in a multiline header,
547   if requested */
548   if (sscanf(CS spamd_buffer,
549        "SPAMD/%7s 0 EX_OK\r\nContent-length: %*u\r\n\r\n%lf/%lf\r\n%n",
550        spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
551     {
552       /* try to fall back to pre-2.50 spamd output */
553       if (sscanf(CS spamd_buffer,
554            "SPAMD/%7s 0 EX_OK\r\nSpam: %*s ; %lf / %lf\r\n\r\n%n",
555            spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
556         {
557         log_write(0, LOG_MAIN|LOG_PANIC,
558                   "%s cannot parse spamd %s output", loglabel, callout_address);
559         return DEFER;
560         }
561     }
562
563   Ustrcpy(spam_action_buffer,
564     spamd_score >= spamd_threshold ? US"reject" : US"no action");
565   }
566
567 /* Create report. Since this is a multiline string,
568 we must hack it into shape first */
569 p = &spamd_buffer[spamd_report_offset];
570 q = spam_report_buffer;
571 while (*p != '\0')
572   {
573   /* skip \r */
574   if (*p == '\r')
575     {
576     p++;
577     continue;
578     }
579   *q++ = *p;
580   if (*p++ == '\n')
581     {
582     /* add an extra space after the newline to ensure
583     that it is treated as a header continuation line */
584     *q++ = ' ';
585     }
586   }
587 /* NULL-terminate */
588 *q-- = '\0';
589 /* cut off trailing leftovers */
590 while (*q <= ' ')
591   *q-- = '\0';
592
593 spam_report = spam_report_buffer;
594 spam_action = spam_action_buffer;
595
596 /* create spam bar */
597 spamd_score_char = spamd_score > 0 ? '+' : '-';
598 j = abs((int)(spamd_score));
599 i = 0;
600 if (j != 0)
601   while ((i < j) && (i <= MAX_SPAM_BAR_CHARS))
602      spam_bar_buffer[i++] = spamd_score_char;
603 else
604   {
605   spam_bar_buffer[0] = '/';
606   i = 1;
607   }
608 spam_bar_buffer[i] = '\0';
609 spam_bar = spam_bar_buffer;
610
611 /* create "float" spam score */
612 (void)string_format(spam_score_buffer, sizeof(spam_score_buffer),
613         "%.1f", spamd_score);
614 spam_score = spam_score_buffer;
615
616 /* create "int" spam score */
617 j = (int)((spamd_score + 0.001)*10);
618 (void)string_format(spam_score_int_buffer, sizeof(spam_score_int_buffer),
619         "%d", j);
620 spam_score_int = spam_score_int_buffer;
621
622 /* compare threshold against score */
623 spam_rc = spamd_score >= spamd_threshold
624   ? OK  /* spam as determined by user's threshold */
625   : FAIL;       /* not spam */
626
627 /* remember expanded spamd_address if needed */
628 if (spamd_address_work != spamd_address)
629   prev_spamd_address_work = string_copy(spamd_address_work);
630
631 /* remember user name and "been here" for it */
632 prev_user_name = user_name;
633 spam_ok = 1;
634
635 return override
636   ? OK          /* always return OK, no matter what the score */
637   : spam_rc;
638
639 defer:
640   (void)fclose(mbox_file);
641   return DEFER;
642 }
643
644 #endif
645 /* vi: aw ai sw=2
646 */