Do RE compilations at daemon startup. Bug 1568
[exim.git] / src / src / malware.c
CommitLineData
8523533c
TK
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
5a66c31b 5/* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2003-2014 */
8523533c
TK
6/* License: GPL */
7
8/* Code for calling virus (malware) scanners. Called from acl.c. */
9
10#include "exim.h"
11#ifdef WITH_CONTENT_SCAN
12
b1f8e4f8 13typedef enum {M_FPROTD, M_DRWEB, M_AVES, M_FSEC, M_KAVD, M_CMDL,
e4413c34 14 M_SOPHIE, M_CLAMD, M_SOCK, M_MKSD, M_AVAST} scanner_t;
b1f8e4f8
JH
15typedef enum {MC_NONE, MC_TCP, MC_UNIX, MC_STRM} contype_t;
16static struct scan
17{
18 scanner_t scancode;
19 const uschar * name;
20 const uschar * options_default;
21 contype_t conn;
22} m_scans[] =
23{
24 { M_FPROTD, US"f-protd", US"localhost 10200-10204", MC_TCP },
25 { M_DRWEB, US"drweb", US"/usr/local/drweb/run/drwebd.sock", MC_STRM },
26 { M_AVES, US"aveserver", US"/var/run/aveserver", MC_UNIX },
27 { M_FSEC, US"fsecure", US"/var/run/.fsav", MC_UNIX },
28 { M_KAVD, US"kavdaemon", US"/var/run/AvpCtl", MC_UNIX },
29 { M_CMDL, US"cmdline", NULL, MC_NONE },
30 { M_SOPHIE, US"sophie", US"/var/run/sophie", MC_UNIX },
31 { M_CLAMD, US"clamd", US"/tmp/clamd", MC_NONE },
32 { M_SOCK, US"sock", US"/tmp/malware.sock", MC_STRM },
33 { M_MKSD, US"mksd", NULL, MC_NONE },
e4413c34 34 { M_AVAST, US"avast", US"/var/run/avast/scan.sock", MC_STRM },
b1f8e4f8
JH
35 { -1, NULL, NULL, MC_NONE } /* end-marker */
36};
37
599dcb77
TL
38/* The maximum number of clamd servers that are supported in the configuration */
39#define MAX_CLAMD_SERVERS 32
40#define MAX_CLAMD_SERVERS_S "32"
41/* Maximum length of the hostname that can be specified in the clamd address list */
42#define MAX_CLAMD_ADDRESS_LENGTH 64
43#define MAX_CLAMD_ADDRESS_LENGTH_S "64"
44
45typedef struct clamd_address_container {
c3680ef0 46 uschar tcp_addr[MAX_CLAMD_ADDRESS_LENGTH+1];
599dcb77
TL
47 unsigned int tcp_port;
48} clamd_address_container;
49
b1f8e4f8
JH
50#ifndef nelements
51# define nelements(arr) (sizeof(arr) / sizeof(arr[0]))
8523533c
TK
52#endif
53
a9ccd69a 54
0e42da1b 55#define MALWARE_TIMEOUT 120 /* default timeout, seconds */
a9ccd69a
PH
56
57
8523533c
TK
58#define DRWEBD_SCAN_CMD (1) /* scan file, buffer or diskfile */
59#define DRWEBD_RETURN_VIRUSES (1<<0) /* ask daemon return to us viruses names from report */
60#define DRWEBD_IS_MAIL (1<<19) /* say to daemon that format is "archive MAIL" */
61
2376f2f5
TK
62#define DERR_READ_ERR (1<<0) /* read error */
63#define DERR_NOMEMORY (1<<2) /* no memory */
64#define DERR_TIMEOUT (1<<9) /* scan timeout has run out */
65#define DERR_BAD_CALL (1<<15) /* wrong command */
66
2339c66a
JH
67
68static const uschar * malware_regex_default = US ".+";
69static const pcre * malware_default_re = NULL;
70
71static const uschar * drweb_re_str = US "infected\\swith\\s*(.+?)$";
72static const pcre * drweb_re = NULL;
73
74static const uschar * fsec_re_str = US "\\S{0,5}INFECTED\\t[^\\t]*\\t([^\\t]+)\\t\\S*$";
75static const pcre * fsec_re = NULL;
76
77static const uschar * kav_re_sus_str = US "suspicion:\\s*(.+?)\\s*$";
78static const uschar * kav_re_inf_str = US "infected:\\s*(.+?)\\s*$";
79static const pcre * kav_re_sus = NULL;
80static const pcre * kav_re_inf = NULL;
81
82static const uschar * ava_re_clean_str = US "(?!\\\\)\\t\\[\\+\\]";
83static const uschar * ava_re_virus_str = US "(?!\\\\)\\t\\[L\\]\\d\\.\\d\\t\\d\\s(.*)";
84static const pcre * ava_re_clean = NULL;
85static const pcre * ava_re_virus = NULL;
86
87
88
89/******************************************************************************/
90
b1f8e4f8 91/* Routine to check whether a system is big- or little-endian.
8523533c
TK
92 Ripped from http://www.faqs.org/faqs/graphics/fileformats-faq/part4/section-7.html
93 Needed for proper kavdaemon implementation. Sigh. */
94#define BIG_MY_ENDIAN 0
95#define LITTLE_MY_ENDIAN 1
b1f8e4f8
JH
96static int test_byte_order(void);
97static inline int
98test_byte_order()
99{
100 short int word = 0x0001;
101 char *byte = (char *) &word;
102 return(byte[0] ? LITTLE_MY_ENDIAN : BIG_MY_ENDIAN);
8523533c
TK
103}
104
b1f8e4f8 105BOOL malware_ok = FALSE;
8523533c 106
8544e77a
PP
107/* Gross hacks for the -bmalware option; perhaps we should just create
108the scan directory normally for that case, but look into rigging up the
109needed header variables if not already set on the command-line? */
110extern int spool_mbox_ok;
111extern uschar spooled_message_id[17];
112
8544e77a
PP
113
114
b1f8e4f8
JH
115static inline int
116malware_errlog_defer(const uschar * str)
117{
118 log_write(0, LOG_MAIN|LOG_PANIC, "malware acl condition: %s", str);
119 return DEFER;
120}
121
122static int
123m_errlog_defer(struct scan * scanent, const uschar * str)
124{
125 return malware_errlog_defer(string_sprintf("%s: %s", scanent->name, str));
126}
127static int
128m_errlog_defer_3(struct scan * scanent, const uschar * str,
129 int fd_to_close)
130{
131 (void) close(fd_to_close);
132 return m_errlog_defer(scanent, str);
133}
134
135/*************************************************/
136
137/* Only used by the Clamav code, which is working from a list of servers and
138uses the returned in_addr to get a second connection to the same system.
139*/
140static inline int
141m_tcpsocket(const uschar * hostname, unsigned int port,
142 host_item * host, uschar ** errstr)
143{
144 return ip_connectedsocket(SOCK_STREAM, hostname, port, port, 5, host, errstr);
145}
146
147static int
148m_tcpsocket_fromdef(const uschar * hostport, uschar ** errstr)
149{
150 int scan;
151 uschar hostname[256];
152 unsigned int portlow, porthigh;
153
154 /* extract host and port part */
155 scan = sscanf(CS hostport, "%255s %u-%u", hostname, &portlow, &porthigh);
156 if ( scan != 3 ) {
157 if ( scan != 2 ) {
158 *errstr = string_sprintf("invalid socket '%s'", hostport);
159 return -1;
160 }
161 porthigh = portlow;
162 }
163
164 return ip_connectedsocket(SOCK_STREAM, hostname, portlow, porthigh,
165 5, NULL, errstr);
166}
167
168static int
169m_unixsocket(const uschar * path, uschar ** errstr)
170{
171 int sock;
172 struct sockaddr_un server;
173
174 if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
175 *errstr = US"can't open UNIX socket.";
176 return -1;
177 }
178
179 server.sun_family = AF_UNIX;
180 Ustrncpy(server.sun_path, path, sizeof(server.sun_path)-1);
181 server.sun_path[sizeof(server.sun_path)-1] = '\0';
182 if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) {
183 int err = errno;
184 (void)close(sock);
185 *errstr = string_sprintf("unable to connect to UNIX socket (%s): %s",
186 path, strerror(err));
187 return -1;
188 }
189 return sock;
190}
191
192static inline int
193m_streamsocket(const uschar * spec, uschar ** errstr)
194{
195 return *spec == '/'
196 ? m_unixsocket(spec, errstr) : m_tcpsocket_fromdef(spec, errstr);
197}
198
199static int
200m_sock_send(int sock, uschar * buf, int cnt, uschar ** errstr)
201{
202 if (send(sock, buf, cnt, 0) < 0) {
203 int err = errno;
204 (void)close(sock);
205 *errstr = string_sprintf("unable to send to socket (%s): %s",
206 buf, strerror(err));
207 return -1;
208 }
209 return sock;
210}
211
212static const pcre *
213m_pcre_compile(const uschar * re, uschar ** errstr)
214{
215 const uschar * rerror;
216 int roffset;
217 const pcre * cre;
218
219 cre = pcre_compile(CS re, PCRE_COPT, (const char **)&rerror, &roffset, NULL);
220 if (!cre)
221 *errstr= string_sprintf("regular expression error in '%s': %s at offset %d",
222 re, rerror, roffset);
223 return cre;
224}
225
226uschar *
227m_pcre_exec(const pcre * cre, uschar * text)
228{
229 int ovector[10*3];
230 int i = pcre_exec(cre, NULL, CS text, Ustrlen(text), 0, 0,
231 ovector, nelements(ovector));
232 uschar * substr = NULL;
233 if (i >= 2) /* Got it */
234 pcre_get_substring(CS text, ovector, i, 1, (const char **) &substr);
235 return substr;
236}
237
238static const pcre *
239m_pcre_nextinlist(uschar ** list, int * sep, char * listerr, uschar ** errstr)
240{
241 const uschar * list_ele;
242 const pcre * cre = NULL;
243
244 if (!(list_ele = string_nextinlist(list, sep, NULL, 0)))
245 *errstr = US listerr;
246 else
247 cre = m_pcre_compile(CUS list_ele, errstr);
248 return cre;
249}
250
9439f85e
JH
251/*
252 Simple though inefficient wrapper for reading a line. Drop CRs and the
253 trailing newline. Can return early on buffer full. Null-terminate.
254 Apply initial timeout if no data ready.
255
0e42da1b
JH
256 Return: number of chars - zero for an empty line
257 -1 on EOF
258 -2 on timeout or error
9439f85e
JH
259*/
260static int
261recv_line(int fd, uschar * buffer, int bsize, int tmo)
262{
263uschar * p = buffer;
264ssize_t rcv;
0e42da1b 265BOOL ok = FALSE;
9439f85e
JH
266
267if (!fd_ready(fd, tmo-time(NULL)))
0e42da1b 268 return -2;
9439f85e 269
0e42da1b 270/*XXX tmo handling assumes we always get a whole line */
9439f85e 271/* read until \n */
0e42da1b 272errno = 0;
9439f85e
JH
273while ((rcv = read(fd, p, 1)) > 0)
274 {
0e42da1b 275 ok = TRUE;
9439f85e
JH
276 if (p-buffer > bsize-2) break;
277 if (*p == '\n') break;
278 if (*p != '\r') p++;
279 }
0e42da1b
JH
280if (!ok)
281 {
282 DEBUG(D_acl) debug_printf("Malware scan: read %s (%s)\n",
283 rcv==0 ? "EOF" : "error", strerror(errno));
284 return rcv==0 ? -1 : -2;
285 }
9439f85e
JH
286*p = '\0';
287
288DEBUG(D_acl) debug_printf("Malware scan: read '%s'\n", buffer);
289return p - buffer;
290}
291
292/* return TRUE iff size as requested */
293static BOOL
294recv_len(int sock, void * buf, int size, int tmo)
295{
296return fd_ready(sock, tmo-time(NULL))
297 ? recv(sock, buf, size, 0) == size
298 : FALSE;
299}
300
301
0e42da1b
JH
302
303/* ============= private routines for the "mksd" scanner type ============== */
304
305#include <sys/uio.h>
306
307static inline int
308mksd_writev (int sock, struct iovec * iov, int iovcnt)
309{
310int i;
311
312for (;;)
313 {
314 do
315 i = writev (sock, iov, iovcnt);
316 while (i < 0 && errno == EINTR);
317 if (i <= 0)
318 {
319 (void) malware_errlog_defer(
320 US"unable to write to mksd UNIX socket (/var/run/mksd/socket)");
321 return -1;
322 }
323 for (;;) /* check for short write */
324 if (i >= iov->iov_len)
325 {
326 if (--iovcnt == 0)
327 return 0;
328 i -= iov->iov_len;
329 iov++;
330 }
331 else
332 {
333 iov->iov_len -= i;
334 iov->iov_base = CS iov->iov_base + i;
335 break;
336 }
337 }
338}
339
340static inline int
341mksd_read_lines (int sock, uschar *av_buffer, int av_buffer_size, int tmo)
342{
343int offset = 0;
344int i;
345
346do
347 {
348 i = ip_recv(sock, av_buffer+offset, av_buffer_size-offset, tmo-time(NULL));
349 if (i <= 0)
350 {
351 (void) malware_errlog_defer(US"unable to read from mksd UNIX socket (/var/run/mksd/socket)");
352 return -1;
353 }
354
355 offset += i;
356 /* offset == av_buffer_size -> buffer full */
357 if (offset == av_buffer_size)
358 {
359 (void) malware_errlog_defer(US"malformed reply received from mksd");
360 return -1;
361 }
362 } while (av_buffer[offset-1] != '\n');
363
364av_buffer[offset] = '\0';
365return offset;
366}
367
368static inline int
369mksd_parse_line(struct scan * scanent, char * line)
370{
371char *p;
372
373switch (*line)
374 {
375 case 'O': /* OK */
376 return OK;
377
378 case 'E':
379 case 'A': /* ERR */
380 if ((p = strchr (line, '\n')) != NULL)
381 *p = '\0';
382 return m_errlog_defer(scanent,
383 string_sprintf("scanner failed: %s", line));
384
385 default: /* VIR */
386 if ((p = strchr (line, '\n')) != NULL)
387 {
388 *p = '\0';
389 if ( p-line > 5
390 && line[3] == ' '
391 && (p = strchr(line+4, ' ')) != NULL
392 && p-line > 4
393 )
394 {
395 *p = '\0';
396 malware_name = string_copy(US line+4);
397 return OK;
398 }
399 }
400 return m_errlog_defer(scanent,
401 string_sprintf("malformed reply received: %s", line));
402 }
403}
404
405static int
406mksd_scan_packed(struct scan * scanent, int sock, const uschar * scan_filename,
407 int tmo)
408{
409struct iovec iov[3];
410const char *cmd = "MSQ\n";
411uschar av_buffer[1024];
412
413iov[0].iov_base = (void *) cmd;
414iov[0].iov_len = 3;
415iov[1].iov_base = (void *) scan_filename;
416iov[1].iov_len = Ustrlen(scan_filename);
417iov[2].iov_base = (void *) (cmd + 3);
418iov[2].iov_len = 1;
419
420if (mksd_writev (sock, iov, 3) < 0)
421 return DEFER;
422
423if (mksd_read_lines (sock, av_buffer, sizeof (av_buffer), tmo) < 0)
424 return DEFER;
425
426return mksd_parse_line (scanent, CS av_buffer);
427}
428
8544e77a
PP
429/*************************************************
430* Scan content for malware *
431*************************************************/
432
433/* This is an internal interface for scanning an email; the normal interface
434is via malware(), or there's malware_in_file() used for testing/debugging.
435
436Arguments:
0e42da1b 437 malware_re match condition for "malware="
8544e77a 438 eml_filename the file holding the email to be scanned
0e42da1b 439 timeout if nonzero, non-default timeoutl
8544e77a
PP
440 faking whether or not we're faking this up for the -bmalware test
441
442Returns: Exim message processing code (OK, FAIL, DEFER, ...)
443 where true means malware was found (condition applies)
444*/
b1f8e4f8 445static int
0e42da1b
JH
446malware_internal(const uschar * malware_re, const uschar * eml_filename,
447 int timeout, BOOL faking)
b1f8e4f8 448{
0e42da1b
JH
449int sep = 0;
450uschar *av_scanner_work = av_scanner;
451uschar *scanner_name;
0e42da1b
JH
452unsigned long mbox_size;
453FILE *mbox_file;
454const pcre *re;
455uschar * errstr;
456struct scan * scanent;
457const uschar * scanner_options;
458int sock = -1;
459time_t tmo;
460
461/* make sure the eml mbox file is spooled up */
462if (!(mbox_file = spool_mbox(&mbox_size, faking ? eml_filename : NULL)))
463 return malware_errlog_defer(US"error while creating mbox spool file");
464
465/* none of our current scanners need the mbox
466 file as a stream, so we can close it right away */
467(void)fclose(mbox_file);
468
469if (!malware_re)
470 return FAIL; /* empty means "don't match anything" */
471
472/* parse 1st option */
473 if ( (strcmpic(malware_re, US"false") == 0) ||
474 (Ustrcmp(malware_re,"0") == 0) )
475 return FAIL; /* explicitly no matching */
476
477/* special cases (match anything except empty) */
2339c66a
JH
478if ( strcmpic(malware_re,US"true") == 0
479 || Ustrcmp(malware_re,"*") == 0
480 || Ustrcmp(malware_re,"1") == 0
481 )
482 {
483 if ( !malware_default_re
484 && !(malware_default_re = m_pcre_compile(malware_regex_default, &errstr)))
485 return malware_errlog_defer(errstr);
0e42da1b 486 malware_re = malware_regex_default;
2339c66a
JH
487 re = malware_default_re;
488 }
0e42da1b
JH
489
490/* compile the regex, see if it works */
2339c66a 491else if (!(re = m_pcre_compile(malware_re, &errstr)))
0e42da1b
JH
492 return malware_errlog_defer(errstr);
493
2339c66a
JH
494/* Reset sep that is set by previous string_nextinlist() call */
495sep = 0;
496
0e42da1b
JH
497/* if av_scanner starts with a dollar, expand it first */
498if (*av_scanner == '$')
499 {
500 if (!(av_scanner_work = expand_string(av_scanner)))
501 return malware_errlog_defer(
502 string_sprintf("av_scanner starts with $, but expansion failed: %s",
503 expand_string_message));
b1f8e4f8 504
0e42da1b 505 DEBUG(D_acl)
b1f8e4f8 506 debug_printf("Expanded av_scanner global: %s\n", av_scanner_work);
0e42da1b
JH
507 /* disable result caching in this case */
508 malware_name = NULL;
509 malware_ok = FALSE;
8523533c
TK
510 }
511
0e42da1b
JH
512/* Do not scan twice (unless av_scanner is dynamic). */
513if (!malware_ok)
514 {
515 /* find the scanner type from the av_scanner option */
516 if (!(scanner_name = string_nextinlist(&av_scanner_work, &sep, NULL, 0)))
517 return malware_errlog_defer(US"av_scanner configuration variable is empty");
518 if (!timeout) timeout = MALWARE_TIMEOUT;
519 tmo = time(NULL) + timeout;
520
521 for (scanent = m_scans; ; scanent++) {
522 if (!scanent->name)
523 return malware_errlog_defer(string_sprintf("unknown scanner type '%s'",
524 scanner_name));
525 if (strcmpic(scanner_name, US scanent->name) != 0)
526 continue;
527 if (!(scanner_options = string_nextinlist(&av_scanner_work, &sep, NULL, 0)))
528 scanner_options = scanent->options_default;
529 if (scanent->conn == MC_NONE)
b1f8e4f8 530 break;
0e42da1b
JH
531 switch(scanent->conn)
532 {
533 case MC_TCP: sock = m_tcpsocket_fromdef(scanner_options, &errstr); break;
534 case MC_UNIX: sock = m_unixsocket(scanner_options, &errstr); break;
535 case MC_STRM: sock = m_streamsocket(scanner_options, &errstr); break;
536 default: /* compiler quietening */ break;
384152a6 537 }
0e42da1b
JH
538 if (sock < 0)
539 return m_errlog_defer(scanent, errstr);
540 break;
541 }
542 DEBUG(D_acl) debug_printf("Malware scan: %s tmo %s\n", scanner_name, readconf_printtime(timeout));
8e669ac1 543
0e42da1b
JH
544 switch (scanent->scancode)
545 {
546 case M_FPROTD: /* "f-protd" scanner type -------------------------------- */
b1f8e4f8 547 {
0e42da1b
JH
548 uschar *fp_scan_option;
549 unsigned int detected=0, par_count=0;
550 uschar * scanrequest;
551 uschar buf[32768], *strhelper, *strhelper2;
552 uschar * malware_name_internal = NULL;
553 int len;
b1f8e4f8 554
0e42da1b 555 scanrequest = string_sprintf("GET %s", eml_filename);
b1f8e4f8 556
0e42da1b
JH
557 while ((fp_scan_option = string_nextinlist(&av_scanner_work, &sep,
558 NULL, 0)))
559 {
560 scanrequest = string_sprintf("%s%s%s", scanrequest,
561 par_count ? "%20" : "?", fp_scan_option);
562 par_count++;
563 }
564 scanrequest = string_sprintf("%s HTTP/1.0\r\n\r\n", scanrequest);
565 DEBUG(D_acl) debug_printf("Malware scan: issuing %s: %s\n",
566 scanner_name, scanrequest);
b1f8e4f8 567
0e42da1b
JH
568 /* send scan request */
569 if (m_sock_send(sock, scanrequest, Ustrlen(scanrequest)+1, &errstr) < 0)
570 return m_errlog_defer(scanent, errstr);
b1f8e4f8 571
0e42da1b
JH
572 while ((len = recv_line(sock, buf, sizeof(buf), tmo)) >= 0)
573 if (len > 0)
574 {
575 if (Ustrstr(buf, US"<detected type=\"") != NULL)
576 detected = 1;
577 else if (detected && (strhelper = Ustrstr(buf, US"<name>")))
9439f85e 578 {
0e42da1b 579 if ((strhelper2 = Ustrstr(buf, US"</name>")) != NULL)
9439f85e 580 {
0e42da1b
JH
581 *strhelper2 = '\0';
582 malware_name_internal = string_copy(strhelper+6);
9439f85e
JH
583 }
584 }
0e42da1b 585 else if (Ustrstr(buf, US"<summary code=\""))
9439f85e 586 {
0e42da1b
JH
587 malware_name = Ustrstr(buf, US"<summary code=\"11\">")
588 ? malware_name_internal : NULL;
589 break;
9439f85e 590 }
0e42da1b
JH
591 }
592 if (len < -1)
593 {
594 (void)close(sock);
595 return DEFER;
596 }
597 break;
598 } /* f-protd */
b1f8e4f8 599
0e42da1b
JH
600 case M_DRWEB: /* "drweb" scanner type ----------------------------------- */
601 /* v0.1 - added support for tcp sockets */
602 /* v0.0 - initial release -- support for unix sockets */
603 {
604 int result;
605 off_t fsize;
606 unsigned int fsize_uint;
607 uschar * tmpbuf, *drweb_fbuf;
608 int drweb_rc, drweb_cmd, drweb_flags = 0x0000, drweb_fd,
609 drweb_vnum, drweb_slen, drweb_fin = 0x0000;
0e42da1b
JH
610
611 /* prepare variables */
612 drweb_cmd = htonl(DRWEBD_SCAN_CMD);
613 drweb_flags = htonl(DRWEBD_RETURN_VIRUSES | DRWEBD_IS_MAIL);
614
615 if (*scanner_options != '/')
616 {
617 /* calc file size */
618 if ((drweb_fd = open(CCS eml_filename, O_RDONLY)) == -1)
619 return m_errlog_defer_3(scanent,
620 string_sprintf("can't open spool file %s: %s",
621 eml_filename, strerror(errno)),
622 sock);
b1f8e4f8 623
0e42da1b
JH
624 if ((fsize = lseek(drweb_fd, 0, SEEK_END)) == -1)
625 {
626 int err = errno;
b1f8e4f8 627 (void)close(drweb_fd);
0e42da1b
JH
628 return m_errlog_defer_3(scanent,
629 string_sprintf("can't seek spool file %s: %s",
630 eml_filename, strerror(err)),
631 sock);
632 }
633 fsize_uint = (unsigned int) fsize;
634 if ((off_t)fsize_uint != fsize)
635 {
b1f8e4f8 636 (void)close(drweb_fd);
0e42da1b
JH
637 return m_errlog_defer_3(scanent,
638 string_sprintf("seeking spool file %s, size overflow",
639 eml_filename),
640 sock);
9439f85e 641 }
0e42da1b
JH
642 drweb_slen = htonl(fsize);
643 lseek(drweb_fd, 0, SEEK_SET);
644
645 DEBUG(D_acl) debug_printf("Malware scan: issuing %s remote scan [%s]\n",
646 scanner_name, scanner_options);
647
648 /* send scan request */
649 if ((send(sock, &drweb_cmd, sizeof(drweb_cmd), 0) < 0) ||
650 (send(sock, &drweb_flags, sizeof(drweb_flags), 0) < 0) ||
651 (send(sock, &drweb_fin, sizeof(drweb_fin), 0) < 0) ||
652 (send(sock, &drweb_slen, sizeof(drweb_slen), 0) < 0))
9439f85e 653 {
0e42da1b
JH
654 (void)close(drweb_fd);
655 return m_errlog_defer_3(scanent, string_sprintf(
656 "unable to send commands to socket (%s)", scanner_options),
657 sock);
9439f85e 658 }
8e669ac1 659
0e42da1b
JH
660 if (!(drweb_fbuf = (uschar *) malloc (fsize_uint)))
661 {
662 (void)close(drweb_fd);
b1f8e4f8 663 return m_errlog_defer_3(scanent,
0e42da1b
JH
664 string_sprintf("unable to allocate memory %u for file (%s)",
665 fsize_uint, eml_filename),
666 sock);
667 }
b1f8e4f8 668
0e42da1b
JH
669 if ((result = read (drweb_fd, drweb_fbuf, fsize)) == -1)
670 {
671 int err = errno;
672 (void)close(drweb_fd);
673 free(drweb_fbuf);
b1f8e4f8 674 return m_errlog_defer_3(scanent,
0e42da1b
JH
675 string_sprintf("can't read spool file %s: %s",
676 eml_filename, strerror(err)),
677 sock);
678 }
679 (void)close(drweb_fd);
b1f8e4f8 680
0e42da1b
JH
681 /* send file body to socket */
682 if (send(sock, drweb_fbuf, fsize, 0) < 0)
9439f85e 683 {
0e42da1b
JH
684 free(drweb_fbuf);
685 return m_errlog_defer_3(scanent, string_sprintf(
686 "unable to send file body to socket (%s)", scanner_options),
687 sock);
688 }
689 (void)close(drweb_fd);
690 }
691 else
692 {
693 drweb_slen = htonl(Ustrlen(eml_filename));
b1f8e4f8 694
0e42da1b
JH
695 DEBUG(D_acl) debug_printf("Malware scan: issuing %s local scan [%s]\n",
696 scanner_name, scanner_options);
b1f8e4f8 697
0e42da1b
JH
698 /* send scan request */
699 if ((send(sock, &drweb_cmd, sizeof(drweb_cmd), 0) < 0) ||
700 (send(sock, &drweb_flags, sizeof(drweb_flags), 0) < 0) ||
701 (send(sock, &drweb_slen, sizeof(drweb_slen), 0) < 0) ||
702 (send(sock, eml_filename, Ustrlen(eml_filename), 0) < 0) ||
703 (send(sock, &drweb_fin, sizeof(drweb_fin), 0) < 0))
704 return m_errlog_defer_3(scanent, string_sprintf(
705 "unable to send commands to socket (%s)", scanner_options),
706 sock);
707 }
b1f8e4f8 708
0e42da1b
JH
709 /* wait for result */
710 if (!recv_len(sock, &drweb_rc, sizeof(drweb_rc), tmo))
711 return m_errlog_defer_3(scanent,
712 US"unable to read return code", sock);
713 drweb_rc = ntohl(drweb_rc);
714
715 if (!recv_len(sock, &drweb_vnum, sizeof(drweb_vnum), tmo))
716 return m_errlog_defer_3(scanent,
717 US"unable to read the number of viruses", sock);
718 drweb_vnum = ntohl(drweb_vnum);
719
720 /* "virus(es) found" if virus number is > 0 */
721 if (drweb_vnum)
722 {
723 int i;
b1f8e4f8 724
0e42da1b
JH
725 /* setup default virus name */
726 malware_name = US"unknown";
b1f8e4f8 727
0e42da1b 728 /* set up match regex */
2339c66a
JH
729 if (!drweb_re)
730 drweb_re = m_pcre_compile(drweb_re_str, &errstr);
b1f8e4f8 731
0e42da1b
JH
732 /* read and concatenate virus names into one string */
733 for (i = 0; i < drweb_vnum; i++)
9439f85e 734 {
0e42da1b
JH
735 int size = 0, off = 0, ovector[10*3];
736 /* read the size of report */
737 if (!recv_len(sock, &drweb_slen, sizeof(drweb_slen), tmo))
b1f8e4f8 738 return m_errlog_defer_3(scanent,
0e42da1b
JH
739 US"cannot read report size", sock);
740 drweb_slen = ntohl(drweb_slen);
741 tmpbuf = store_get(drweb_slen);
b1f8e4f8 742
0e42da1b
JH
743 /* read report body */
744 if (!recv_len(sock, tmpbuf, drweb_slen, tmo))
745 return m_errlog_defer_3(scanent,
746 US"cannot read report string", sock);
747 tmpbuf[drweb_slen] = '\0';
8544e77a 748
0e42da1b
JH
749 /* try matcher on the line, grab substring */
750 result = pcre_exec(drweb_re, NULL, CS tmpbuf, Ustrlen(tmpbuf), 0, 0,
751 ovector, nelements(ovector));
752 if (result >= 2)
753 {
754 const char * pre_malware_nb;
8e669ac1 755
0e42da1b 756 pcre_get_substring(CS tmpbuf, ovector, result, 1, &pre_malware_nb);
8e669ac1 757
0e42da1b
JH
758 if (i==0) /* the first name we just copy to malware_name */
759 malware_name = string_append(NULL, &size, &off,
760 1, pre_malware_nb);
8e669ac1 761
0e42da1b
JH
762 else /* concatenate each new virus name to previous */
763 malware_name = string_append(malware_name, &size, &off,
764 2, "/", pre_malware_nb);
8e669ac1 765
0e42da1b
JH
766 pcre_free_substring(pre_malware_nb);
767 }
768 }
769 }
770 else
771 {
772 const char *drweb_s = NULL;
773
774 if (drweb_rc & DERR_READ_ERR) drweb_s = "read error";
775 if (drweb_rc & DERR_NOMEMORY) drweb_s = "no memory";
776 if (drweb_rc & DERR_TIMEOUT) drweb_s = "timeout";
777 if (drweb_rc & DERR_BAD_CALL) drweb_s = "wrong command";
778 /* retcodes DERR_SYMLINK, DERR_NO_REGFILE, DERR_SKIPPED.
779 * DERR_TOO_BIG, DERR_TOO_COMPRESSED, DERR_SPAM,
780 * DERR_CRC_ERROR, DERR_READSOCKET, DERR_WRITE_ERR
781 * and others are ignored */
782 if (drweb_s)
783 return m_errlog_defer_3(scanent,
784 string_sprintf("drweb daemon retcode 0x%x (%s)", drweb_rc, drweb_s),
785 sock);
8e669ac1 786
0e42da1b 787 /* no virus found */
b1f8e4f8 788 malware_name = NULL;
0e42da1b
JH
789 }
790 break;
791 } /* drweb */
8e669ac1 792
0e42da1b
JH
793 case M_AVES: /* "aveserver" scanner type -------------------------------- */
794 {
795 uschar buf[32768];
796 int result;
8544e77a 797
0e42da1b
JH
798 /* read aveserver's greeting and see if it is ready (2xx greeting) */
799 buf[0] = 0;
800 recv_line(sock, buf, sizeof(buf), tmo);
8544e77a 801
0e42da1b
JH
802 if (buf[0] != '2') /* aveserver is having problems */
803 return m_errlog_defer_3(scanent,
804 string_sprintf("unavailable (Responded: %s).",
b1f8e4f8 805 ((buf[0] != 0) ? buf : (uschar *)"nothing") ),
0e42da1b 806 sock);
8e669ac1 807
0e42da1b
JH
808 /* prepare our command */
809 (void)string_format(buf, sizeof(buf), "SCAN bPQRSTUW %s\r\n",
810 eml_filename);
811
812 /* and send it */
813 DEBUG(D_acl) debug_printf("Malware scan: issuing %s %s\n",
814 scanner_name, buf);
815 if (m_sock_send(sock, buf, Ustrlen(buf), &errstr) < 0)
816 return m_errlog_defer(scanent, errstr);
817
818 malware_name = NULL;
819 result = 0;
820 /* read response lines, find malware name and final response */
821 while (recv_line(sock, buf, sizeof(buf), tmo) > 0)
822 {
823 if (buf[0] == '2')
824 break;
825 if (buf[0] == '5') /* aveserver is having problems */
9439f85e 826 {
0e42da1b
JH
827 result = m_errlog_defer(scanent,
828 string_sprintf("unable to scan file %s (Responded: %s).",
829 eml_filename, buf));
830 break;
9439f85e 831 }
0e42da1b
JH
832 if (Ustrncmp(buf,"322",3) == 0)
833 {
834 uschar *p = Ustrchr(&buf[4], ' ');
835 *p = '\0';
836 malware_name = string_copy(&buf[4]);
837 }
838 }
839
840 if (m_sock_send(sock, US"quit\r\n", 6, &errstr) < 0)
841 return m_errlog_defer(scanent, errstr);
842
843 /* read aveserver's greeting and see if it is ready (2xx greeting) */
844 buf[0] = 0;
845 recv_line(sock, buf, sizeof(buf), tmo);
846
847 if (buf[0] != '2') /* aveserver is having problems */
848 return m_errlog_defer_3(scanent,
849 string_sprintf("unable to quit dialogue (Responded: %s).",
850 ((buf[0] != 0) ? buf : (uschar *)"nothing") ),
851 sock);
852
853 if (result == DEFER)
854 {
855 (void)close(sock);
856 return DEFER;
857 }
858 break;
b1f8e4f8 859 } /* aveserver */
8e669ac1 860
b1f8e4f8
JH
861 case M_FSEC: /* "fsecure" scanner type ---------------------------------- */
862 {
0e42da1b
JH
863 int i, j, bread = 0;
864 uschar * file_name;
865 uschar av_buffer[1024];
0e42da1b
JH
866 static uschar *cmdopt[] = { US"CONFIGURE\tARCHIVE\t1\n",
867 US"CONFIGURE\tTIMEOUT\t0\n",
868 US"CONFIGURE\tMAXARCH\t5\n",
869 US"CONFIGURE\tMIME\t1\n" };
870
871 malware_name = NULL;
872
873 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
874 scanner_name, scanner_options);
875 /* pass options */
876 memset(av_buffer, 0, sizeof(av_buffer));
877 for (i = 0; i != nelements(cmdopt); i++)
878 {
b1f8e4f8 879
0e42da1b
JH
880 if (m_sock_send(sock, cmdopt[i], Ustrlen(cmdopt[i]), &errstr) < 0)
881 return m_errlog_defer(scanent, errstr);
b1f8e4f8 882
0e42da1b
JH
883 bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL));
884 if (bread > 0) av_buffer[bread]='\0';
885 if (bread < 0)
886 return m_errlog_defer_3(scanent,
887 string_sprintf("unable to read answer %d (%s)", i, strerror(errno)),
888 sock);
889 for (j = 0; j < bread; j++)
890 if (av_buffer[j] == '\r' || av_buffer[j] == '\n')
891 av_buffer[j] ='@';
892 }
8e669ac1 893
0e42da1b
JH
894 /* pass the mailfile to fsecure */
895 file_name = string_sprintf("SCAN\t%s\n", eml_filename);
b1f8e4f8 896
0e42da1b
JH
897 if (m_sock_send(sock, file_name, Ustrlen(file_name), &errstr) < 0)
898 return m_errlog_defer(scanent, errstr);
b1f8e4f8 899
0e42da1b
JH
900 /* set up match */
901 /* todo also SUSPICION\t */
2339c66a
JH
902 if (!fsec_re)
903 fsec_re = m_pcre_compile(fsec_re_str, &errstr);
b1f8e4f8 904
0e42da1b
JH
905 /* read report, linewise. Apply a timeout as the Fsecure daemon
906 sometimes wants an answer to "PING" but they won't tell us what */
e9253693 907 {
0e42da1b
JH
908 uschar * p = av_buffer;
909 uschar * q;
e9253693 910
0e42da1b
JH
911 for (;;)
912 {
913 errno = ETIME;
914 i = av_buffer+sizeof(av_buffer)-p;
915 if ((bread= ip_recv(sock, p, i-1, tmo-time(NULL))) < 0)
916 return m_errlog_defer_3(scanent,
917 string_sprintf("unable to read result (%s)", strerror(errno)),
918 sock);
b1f8e4f8 919
0e42da1b
JH
920 for (p[bread] = '\0'; q = strchr(p, '\n'); p = q+1)
921 {
922 *q = '\0';
e9253693 923
0e42da1b
JH
924 /* Really search for virus again? */
925 if (!malware_name)
926 /* try matcher on the line, grab substring */
2339c66a 927 malware_name = m_pcre_exec(fsec_re, p);
e9253693 928
0e42da1b
JH
929 if (Ustrstr(p, "OK\tScan ok."))
930 goto fsec_found;
931 }
e9253693 932
0e42da1b
JH
933 /* copy down the trailing partial line then read another chunk */
934 i = av_buffer+sizeof(av_buffer)-p;
935 memmove(av_buffer, p, i);
936 p = av_buffer+i;
e9253693 937 }
b1f8e4f8 938 }
e9253693
JH
939
940 fsec_found:
b1f8e4f8
JH
941 break;
942 } /* fsecure */
599dcb77 943
b1f8e4f8
JH
944 case M_KAVD: /* "kavdaemon" scanner type -------------------------------- */
945 {
0e42da1b
JH
946 time_t t;
947 uschar tmpbuf[1024];
948 uschar * scanrequest;
949 int kav_rc;
950 unsigned long kav_reportlen, bread;
951 const pcre *kav_re;
952 uschar *p;
953
954 /* get current date and time, build scan request */
955 time(&t);
956 /* pdp note: before the eml_filename parameter, this scanned the
957 directory; not finding documentation, so we'll strip off the directory.
958 The side-effect is that the test framework scanning may end up in
959 scanning more than was requested, but for the normal interface, this is
960 fine. */
961
962 strftime(CS tmpbuf, sizeof(tmpbuf), "%d %b %H:%M:%S", localtime(&t));
963 scanrequest = string_sprintf("<0>%s:%s", CS tmpbuf, eml_filename);
964 p = Ustrrchr(scanrequest, '/');
965 if (p)
966 *p = '\0';
967
968 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
969 scanner_name, scanner_options);
970
971 /* send scan request */
972 if (m_sock_send(sock, scanrequest, Ustrlen(scanrequest)+1, &errstr) < 0)
973 return m_errlog_defer(scanent, errstr);
b1f8e4f8 974
0e42da1b
JH
975 /* wait for result */
976 if (!recv_len(sock, tmpbuf, 2, tmo))
977 return m_errlog_defer_3(scanent,
978 US"unable to read 2 bytes from socket.", sock);
b1f8e4f8 979
0e42da1b
JH
980 /* get errorcode from one nibble */
981 kav_rc = tmpbuf[ test_byte_order()==LITTLE_MY_ENDIAN ? 0 : 1 ] & 0x0F;
982 switch(kav_rc)
983 {
984 case 5: case 6: /* improper kavdaemon configuration */
985 return m_errlog_defer_3(scanent,
986 US"please reconfigure kavdaemon to NOT disinfect or remove infected files.",
987 sock);
988 case 1:
989 return m_errlog_defer_3(scanent,
990 US"reported 'scanning not completed' (code 1).", sock);
991 case 7:
992 return m_errlog_defer_3(scanent,
993 US"reported 'kavdaemon damaged' (code 7).", sock);
994 }
b1f8e4f8 995
0e42da1b
JH
996 /* code 8 is not handled, since it is ambigous. It appears mostly on
997 bounces where part of a file has been cut off */
b1f8e4f8 998
0e42da1b
JH
999 /* "virus found" return codes (2-4) */
1000 if (kav_rc > 1 && kav_rc < 5)
b1f8e4f8 1001 {
0e42da1b 1002 int report_flag = 0;
599dcb77 1003
0e42da1b
JH
1004 /* setup default virus name */
1005 malware_name = US"unknown";
b1f8e4f8 1006
0e42da1b 1007 report_flag = tmpbuf[ test_byte_order() == LITTLE_MY_ENDIAN ? 1 : 0 ];
b1f8e4f8 1008
0e42da1b
JH
1009 /* read the report, if available */
1010 if (report_flag == 1)
1011 {
1012 /* read report size */
1013 if (!recv_len(sock, &kav_reportlen, 4, tmo))
1014 return m_errlog_defer_3(scanent,
1015 US"cannot read report size", sock);
b1f8e4f8 1016
0e42da1b
JH
1017 /* it's possible that avp returns av_buffer[1] == 1 but the
1018 reportsize is 0 (!?) */
1019 if (kav_reportlen > 0)
9439f85e 1020 {
0e42da1b 1021 /* set up match regex, depends on retcode */
2339c66a
JH
1022 if (kav_rc == 3)
1023 {
1024 if (!kav_re_sus) kav_re_sus = m_pcre_compile(kav_re_sus_str, &errstr);
1025 kav_re = kav_re_sus;
1026 }
1027 else
1028 {
1029 if (!kav_re_inf) kav_re_inf = m_pcre_compile(kav_re_inf_str, &errstr);
1030 kav_re = kav_re_inf;
1031 }
0e42da1b
JH
1032
1033 /* read report, linewise */
1034 while (kav_reportlen > 0)
9439f85e 1035 {
0e42da1b
JH
1036 if ((bread = recv_line(sock, tmpbuf, sizeof(tmpbuf), tmo)) < 0)
1037 break;
1038 kav_reportlen -= bread+1;
1039
1040 /* try matcher on the line, grab substring */
1041 if ((malware_name = m_pcre_exec(kav_re, tmpbuf)))
1042 break;
b1f8e4f8
JH
1043 }
1044 }
1045 }
0e42da1b
JH
1046 }
1047 else /* no virus found */
1048 malware_name = NULL;
599dcb77 1049
0e42da1b 1050 break;
599dcb77 1051 }
8544e77a 1052
b1f8e4f8
JH
1053 case M_CMDL: /* "cmdline" scanner type ---------------------------------- */
1054 {
0e42da1b
JH
1055 const uschar *cmdline_scanner = scanner_options;
1056 const pcre *cmdline_trigger_re;
1057 const pcre *cmdline_regex_re;
1058 uschar * file_name;
1059 uschar * commandline;
1060 void (*eximsigchld)(int);
1061 void (*eximsigpipe)(int);
1062 FILE *scanner_out = NULL;
1063 int scanner_fd;
1064 FILE *scanner_record = NULL;
1065 uschar linebuffer[32767];
1066 int rcnt;
1067 int trigger = 0;
1068 uschar *p;
1069
1070 if (!cmdline_scanner)
1071 return m_errlog_defer(scanent, errstr);
b1f8e4f8 1072
0e42da1b
JH
1073 /* find scanner output trigger */
1074 cmdline_trigger_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1075 "missing trigger specification", &errstr);
1076 if (!cmdline_trigger_re)
1077 return m_errlog_defer(scanent, errstr);
b1f8e4f8 1078
0e42da1b
JH
1079 /* find scanner name regex */
1080 cmdline_regex_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1081 "missing virus name regex specification", &errstr);
1082 if (!cmdline_regex_re)
1083 return m_errlog_defer(scanent, errstr);
b1f8e4f8 1084
0e42da1b
JH
1085 /* prepare scanner call; despite the naming, file_name holds a directory
1086 name which is documented as the value given to %s. */
b1f8e4f8 1087
0e42da1b
JH
1088 file_name = string_copy(eml_filename);
1089 p = Ustrrchr(file_name, '/');
1090 if (p)
1091 *p = '\0';
1092 commandline = string_sprintf(CS cmdline_scanner, file_name);
b1f8e4f8 1093
0e42da1b
JH
1094 /* redirect STDERR too */
1095 commandline = string_sprintf("%s 2>&1", commandline);
b1f8e4f8 1096
0e42da1b
JH
1097 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
1098 scanner_name, commandline);
b1f8e4f8 1099
0e42da1b
JH
1100 /* store exims signal handlers */
1101 eximsigchld = signal(SIGCHLD,SIG_DFL);
1102 eximsigpipe = signal(SIGPIPE,SIG_DFL);
b1f8e4f8 1103
0e42da1b
JH
1104 if (!(scanner_out = popen(CS commandline,"r")))
1105 {
1106 int err = errno;
1107 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1108 return m_errlog_defer(scanent,
1109 string_sprintf("call (%s) failed: %s.", commandline, strerror(err)));
1110 }
1111 scanner_fd = fileno(scanner_out);
94a18f28 1112
0e42da1b
JH
1113 file_name = string_sprintf("%s/scan/%s/%s_scanner_output",
1114 spool_directory, message_id, message_id);
b1f8e4f8 1115
0e42da1b
JH
1116 if (!(scanner_record = modefopen(file_name, "wb", SPOOL_MODE)))
1117 {
1118 int err = errno;
1119 (void) pclose(scanner_out);
1120 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1121 return m_errlog_defer(scanent, string_sprintf(
1122 "opening scanner output file (%s) failed: %s.",
1123 file_name, strerror(err)));
1124 }
8e669ac1 1125
0e42da1b
JH
1126 /* look for trigger while recording output */
1127 while ((rcnt = recv_line(scanner_fd, linebuffer,
1128 sizeof(linebuffer), tmo)))
1129 {
1130 if (rcnt < 0)
1131 if (rcnt == -1)
1132 break;
1133 else
9439f85e 1134 {
0e42da1b 1135 int err = errno;
9439f85e
JH
1136 (void) pclose(scanner_out);
1137 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1138 return m_errlog_defer(scanent, string_sprintf(
0e42da1b
JH
1139 "unable to read from scanner (%s): %s",
1140 commandline, strerror(err)));
9439f85e
JH
1141 }
1142
0e42da1b
JH
1143 if (Ustrlen(linebuffer) > fwrite(linebuffer, 1, Ustrlen(linebuffer), scanner_record))
1144 {
1145 /* short write */
1146 (void) pclose(scanner_out);
1147 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1148 return m_errlog_defer(scanent, string_sprintf(
1149 "short write on scanner output file (%s).", file_name));
9439f85e 1150 }
0e42da1b
JH
1151 putc('\n', scanner_record);
1152 /* try trigger match */
1153 if ( !trigger
1154 && regex_match_and_setup(cmdline_trigger_re, linebuffer, 0, -1)
1155 )
1156 trigger = 1;
1157 }
8e669ac1 1158
0e42da1b
JH
1159 (void)fclose(scanner_record);
1160 sep = pclose(scanner_out);
1161 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1162 if (sep != 0)
1163 return m_errlog_defer(scanent,
1164 sep == -1
1165 ? string_sprintf("running scanner failed: %s", strerror(sep))
1166 : string_sprintf("scanner returned error code: %d", sep));
b1f8e4f8 1167
0e42da1b
JH
1168 if (trigger)
1169 {
1170 uschar * s;
1171 /* setup default virus name */
1172 malware_name = US"unknown";
b1f8e4f8 1173
0e42da1b
JH
1174 /* re-open the scanner output file, look for name match */
1175 scanner_record = fopen(CS file_name, "rb");
1176 while (fgets(CS linebuffer, sizeof(linebuffer), scanner_record))
1177 {
1178 /* try match */
1179 if ((s = m_pcre_exec(cmdline_regex_re, linebuffer)))
1180 malware_name = s;
9439f85e 1181 }
0e42da1b
JH
1182 (void)fclose(scanner_record);
1183 }
1184 else /* no virus found */
1185 malware_name = NULL;
1186 break;
b1f8e4f8 1187 } /* cmdline */
599dcb77 1188
b1f8e4f8
JH
1189 case M_SOPHIE: /* "sophie" scanner type --------------------------------- */
1190 {
0e42da1b
JH
1191 int bread = 0;
1192 uschar *p;
1193 uschar * file_name;
1194 uschar av_buffer[1024];
b1f8e4f8 1195
0e42da1b
JH
1196 /* pass the scan directory to sophie */
1197 file_name = string_copy(eml_filename);
1198 if ((p = Ustrrchr(file_name, '/')))
1199 *p = '\0';
b1f8e4f8 1200
0e42da1b
JH
1201 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
1202 scanner_name, scanner_options);
b1f8e4f8 1203
0e42da1b
JH
1204 if ( write(sock, file_name, Ustrlen(file_name)) < 0
1205 || write(sock, "\n", 1) != 1
1206 )
1207 return m_errlog_defer_3(scanent,
1208 string_sprintf("unable to write to UNIX socket (%s)", scanner_options),
1209 sock);
b1f8e4f8 1210
0e42da1b
JH
1211 /* wait for result */
1212 memset(av_buffer, 0, sizeof(av_buffer));
1213 if ((bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL))) <= 0)
1214 return m_errlog_defer_3(scanent,
1215 string_sprintf("unable to read from UNIX socket (%s)", scanner_options),
1216 sock);
1217
1218 /* infected ? */
1219 if (av_buffer[0] == '1') {
1220 uschar * s = Ustrchr(av_buffer, '\n');
1221 if (s)
1222 *s = '\0';
1223 malware_name = string_copy(&av_buffer[2]);
1224 }
1225 else if (!strncmp(CS av_buffer, "-1", 2))
1226 return m_errlog_defer_3(scanent, US"scanner reported error", sock);
1227 else /* all ok, no virus */
1228 malware_name = NULL;
599dcb77 1229
0e42da1b 1230 break;
8544e77a 1231 }
8e669ac1 1232
b1f8e4f8
JH
1233 case M_CLAMD: /* "clamd" scanner type ----------------------------------- */
1234 {
0e42da1b
JH
1235/* This code was originally contributed by David Saez */
1236/* There are three scanning methods available to us:
1237* (1) Use the SCAN command, pointing to a file in the filesystem
1238* (2) Use the STREAM command, send the data on a separate port
1239* (3) Use the zINSTREAM command, send the data inline
1240* The zINSTREAM command was introduced with ClamAV 0.95, which marked
1241* STREAM deprecated; see: http://wiki.clamav.net/bin/view/Main/UpgradeNotes095
1242* In Exim, we use SCAN if using a Unix-domain socket or explicitly told that
1243* the TCP-connected daemon is actually local; otherwise we use zINSTREAM unless
1244* WITH_OLD_CLAMAV_STREAM is defined.
1245* See Exim bug 926 for details. */
1246
1247 uschar *p, *vname, *result_tag, *response_end;
1248 int bread=0;
1249 uschar * file_name;
1250 uschar av_buffer[1024];
1251 uschar *hostname = US"";
1252 host_item connhost;
1253 uschar *clamav_fbuf;
1254 int clam_fd, result;
1255 off_t fsize;
1256 unsigned int fsize_uint;
1257 BOOL use_scan_command = FALSE;
1258 clamd_address_container * clamd_address_vector[MAX_CLAMD_SERVERS];
1259 int current_server;
1260 int num_servers = 0;
1261#ifdef WITH_OLD_CLAMAV_STREAM
1262 unsigned int port;
1263 uschar av_buffer2[1024];
1264 int sockData;
1265#else
1266 uint32_t send_size, send_final_zeroblock;
1267#endif
1268
1269 if (*scanner_options == '/')
1270 /* Local file; so we def want to use_scan_command and don't want to try
1271 * passing IP/port combinations */
1272 use_scan_command = TRUE;
1273 else
1274 {
1275 const uschar *address = scanner_options;
1276 uschar address_buffer[MAX_CLAMD_ADDRESS_LENGTH + 20];
1277
1278 /* Go through the rest of the list of host/port and construct an array
1279 * of servers to try. The first one is the bit we just passed from
1280 * scanner_options so process that first and then scan the remainder of
1281 * the address buffer */
1282 do
9439f85e 1283 {
0e42da1b 1284 clamd_address_container *this_clamd;
b1f8e4f8 1285
0e42da1b
JH
1286 /* The 'local' option means use the SCAN command over the network
1287 * socket (ie common file storage in use) */
1288 if (strcmpic(address,US"local") == 0)
1289 {
1290 use_scan_command = TRUE;
1291 continue;
1292 }
b1f8e4f8 1293
0e42da1b
JH
1294 /* XXX: If unsuccessful we should free this memory */
1295 this_clamd =
1296 (clamd_address_container *)store_get(sizeof(clamd_address_container));
b1f8e4f8 1297
0e42da1b
JH
1298 /* extract host and port part */
1299 if( sscanf(CS address, "%" MAX_CLAMD_ADDRESS_LENGTH_S "s %u",
1300 this_clamd->tcp_addr, &(this_clamd->tcp_port)) != 2 )
1301 {
1302 (void) m_errlog_defer(scanent,
1303 string_sprintf("invalid address '%s'", address));
1304 continue;
1305 }
b1f8e4f8 1306
0e42da1b
JH
1307 clamd_address_vector[num_servers] = this_clamd;
1308 num_servers++;
1309 if (num_servers >= MAX_CLAMD_SERVERS)
1310 {
1311 (void) m_errlog_defer(scanent,
1312 US"More than " MAX_CLAMD_SERVERS_S " clamd servers "
1313 "specified; only using the first " MAX_CLAMD_SERVERS_S );
1314 break;
1315 }
1316 } while ((address = string_nextinlist(&av_scanner_work, &sep,
1317 address_buffer,
1318 sizeof(address_buffer))) != NULL);
8e669ac1 1319
0e42da1b
JH
1320 /* check if we have at least one server */
1321 if (!num_servers)
b1f8e4f8 1322 return m_errlog_defer(scanent,
0e42da1b
JH
1323 US"no useable server addresses in malware configuration option.");
1324 }
b1f8e4f8 1325
0e42da1b
JH
1326 /* See the discussion of response formats below to see why we really
1327 don't like colons in filenames when passing filenames to ClamAV. */
1328 if (use_scan_command && Ustrchr(eml_filename, ':'))
1329 return m_errlog_defer(scanent,
1330 string_sprintf("local/SCAN mode incompatible with" \
1331 " : in path to email filename [%s]", eml_filename));
b1f8e4f8 1332
0e42da1b
JH
1333 /* We have some network servers specified */
1334 if (num_servers)
1335 {
1336 /* Confirmed in ClamAV source (0.95.3) that the TCPAddr option of clamd
1337 * only supports AF_INET, but we should probably be looking to the
1338 * future and rewriting this to be protocol-independent anyway. */
b1f8e4f8 1339
0e42da1b
JH
1340 while (num_servers > 0)
1341 {
1342 int i;
1343 /* Randomly pick a server to start with */
1344 current_server = random_number( num_servers );
b1f8e4f8 1345
0e42da1b
JH
1346 DEBUG(D_acl)
1347 debug_printf("trying server name %s, port %u\n",
1348 clamd_address_vector[current_server]->tcp_addr,
1349 clamd_address_vector[current_server]->tcp_port);
1350
1351 /* Lookup the host. This is to ensure that we connect to the same IP
1352 * on both connections (as one host could resolve to multiple ips) */
1353 sock= m_tcpsocket(clamd_address_vector[current_server]->tcp_addr,
1354 clamd_address_vector[current_server]->tcp_port,
1355 &connhost, &errstr);
1356 if (sock >= 0)
1357 {
1358 /* Connection successfully established with a server */
1359 hostname = clamd_address_vector[current_server]->tcp_addr;
1360 break;
9439f85e 1361 }
b1f8e4f8 1362
0e42da1b
JH
1363 (void) m_errlog_defer(scanent, errstr);
1364
1365 /* Remove the server from the list. XXX We should free the memory */
1366 num_servers--;
1367 for (i = current_server; i < num_servers; i++)
1368 clamd_address_vector[i] = clamd_address_vector[i+1];
9439f85e 1369 }
8e669ac1 1370
0e42da1b
JH
1371 if (num_servers == 0)
1372 return m_errlog_defer(scanent, US"all servers failed");
1373 }
1374 else
1375 {
1376 if ((sock = m_unixsocket(scanner_options, &errstr)) < 0)
1377 return m_errlog_defer(scanent, errstr);
1378 }
b1f8e4f8 1379
0e42da1b
JH
1380 /* have socket in variable "sock"; command to use is semi-independent of
1381 * the socket protocol. We use SCAN if is local (either Unix/local
1382 * domain socket, or explicitly told local) else we stream the data.
1383 * How we stream the data depends upon how we were built. */
1384
1385 if (!use_scan_command)
1386 {
9439f85e 1387#ifdef WITH_OLD_CLAMAV_STREAM
0e42da1b
JH
1388 /* "STREAM\n" command, get back a "PORT <N>\n" response, send data to
1389 * that port on a second connection; then in the scan-method-neutral
1390 * part, read the response back on the original connection. */
b1f8e4f8 1391
0e42da1b
JH
1392 DEBUG(D_acl) debug_printf(
1393 "Malware scan: issuing %s old-style remote scan (PORT)\n",
1394 scanner_name);
b1f8e4f8 1395
0e42da1b
JH
1396 /* Pass the string to ClamAV (7 = "STREAM\n") */
1397 if (m_sock_send(sock, US"STREAM\n", 7, &errstr) < 0)
1398 return m_errlog_defer(scanent, errstr);
b1f8e4f8 1399
0e42da1b
JH
1400 memset(av_buffer2, 0, sizeof(av_buffer2));
1401 bread = ip_recv(sock, av_buffer2, sizeof(av_buffer2), tmo-time(NULL));
b1f8e4f8 1402
0e42da1b
JH
1403 if (bread < 0)
1404 return m_errlog_defer_3(scanent,
1405 string_sprintf("unable to read PORT from socket (%s)",
1406 strerror(errno)),
1407 sock);
b1f8e4f8 1408
0e42da1b
JH
1409 if (bread == sizeof(av_buffer2))
1410 return m_errlog_defer_3(scanent, "buffer too small", sock);
b1f8e4f8 1411
0e42da1b
JH
1412 if (!(*av_buffer2))
1413 return m_errlog_defer_3(scanent, "ClamAV returned null", sock);
b1f8e4f8 1414
0e42da1b
JH
1415 av_buffer2[bread] = '\0';
1416 if( sscanf(CS av_buffer2, "PORT %u\n", &port) != 1 )
1417 return m_errlog_defer_3(scanent,
1418 string_sprintf("Expected port information from clamd, got '%s'",
1419 av_buffer2),
1420 sock);
b1f8e4f8 1421
0e42da1b
JH
1422 sockData = m_tcpsocket(connhost.address, port, NULL, &errstr);
1423 if (sockData < 0)
1424 return m_errlog_defer_3(scanent, errstr, sock);
b1f8e4f8 1425
9439f85e
JH
1426# define CLOSE_SOCKDATA (void)close(sockData)
1427#else /* WITH_OLD_CLAMAV_STREAM not defined */
0e42da1b
JH
1428 /* New protocol: "zINSTREAM\n" followed by a sequence of <length><data>
1429 chunks, <n> a 4-byte number (network order), terminated by a zero-length
1430 chunk. */
b1f8e4f8 1431
0e42da1b
JH
1432 DEBUG(D_acl) debug_printf(
1433 "Malware scan: issuing %s new-style remote scan (zINSTREAM)\n",
1434 scanner_name);
b1f8e4f8 1435
0e42da1b
JH
1436 /* Pass the string to ClamAV (10 = "zINSTREAM\0") */
1437 if (send(sock, "zINSTREAM", 10, 0) < 0)
1438 return m_errlog_defer_3(scanent,
1439 string_sprintf("unable to send zINSTREAM to socket (%s)",
1440 strerror(errno)),
1441 sock);
b1f8e4f8 1442
9439f85e
JH
1443# define CLOSE_SOCKDATA /**/
1444#endif
b1f8e4f8 1445
0e42da1b
JH
1446 /* calc file size */
1447 if ((clam_fd = open(CS eml_filename, O_RDONLY)) < 0)
1448 {
1449 int err = errno;
1450 CLOSE_SOCKDATA;
1451 return m_errlog_defer_3(scanent,
1452 string_sprintf("can't open spool file %s: %s",
1453 eml_filename, strerror(err)),
1454 sock);
1455 }
1456 if ((fsize = lseek(clam_fd, 0, SEEK_END)) < 0)
1457 {
1458 int err = errno;
1459 CLOSE_SOCKDATA; (void)close(clam_fd);
1460 return m_errlog_defer_3(scanent,
1461 string_sprintf("can't seek spool file %s: %s",
1462 eml_filename, strerror(err)),
1463 sock);
1464 }
1465 fsize_uint = (unsigned int) fsize;
1466 if ((off_t)fsize_uint != fsize)
1467 {
1468 CLOSE_SOCKDATA; (void)close(clam_fd);
1469 return m_errlog_defer_3(scanent,
1470 string_sprintf("seeking spool file %s, size overflow",
1471 eml_filename),
1472 sock);
1473 }
1474 lseek(clam_fd, 0, SEEK_SET);
b1f8e4f8 1475
0e42da1b
JH
1476 if (!(clamav_fbuf = (uschar *) malloc (fsize_uint)))
1477 {
1478 CLOSE_SOCKDATA; (void)close(clam_fd);
1479 return m_errlog_defer_3(scanent,
1480 string_sprintf("unable to allocate memory %u for file (%s)",
1481 fsize_uint, eml_filename),
1482 sock);
1483 }
b1f8e4f8 1484
0e42da1b
JH
1485 if ((result = read(clam_fd, clamav_fbuf, fsize_uint)) < 0)
1486 {
1487 int err = errno;
1488 free(clamav_fbuf); CLOSE_SOCKDATA; (void)close(clam_fd);
1489 return m_errlog_defer_3(scanent,
1490 string_sprintf("can't read spool file %s: %s",
1491 eml_filename, strerror(err)),
1492 sock);
1493 }
1494 (void)close(clam_fd);
b1f8e4f8 1495
0e42da1b 1496 /* send file body to socket */
9439f85e 1497#ifdef WITH_OLD_CLAMAV_STREAM
0e42da1b
JH
1498 if (send(sockData, clamav_fbuf, fsize_uint, 0) < 0)
1499 {
1500 free(clamav_fbuf); CLOSE_SOCKDATA;
1501 return m_errlog_defer_3(scanent,
1502 string_sprintf("unable to send file body to socket (%s:%u)",
1503 hostname, port),
1504 sock);
1505 }
9439f85e 1506#else
0e42da1b
JH
1507 send_size = htonl(fsize_uint);
1508 send_final_zeroblock = 0;
1509 if ((send(sock, &send_size, sizeof(send_size), 0) < 0) ||
1510 (send(sock, clamav_fbuf, fsize_uint, 0) < 0) ||
1511 (send(sock, &send_final_zeroblock, sizeof(send_final_zeroblock), 0) < 0))
1512 {
b1f8e4f8 1513 free(clamav_fbuf);
0e42da1b
JH
1514 return m_errlog_defer_3(scanent,
1515 string_sprintf("unable to send file body to socket (%s)", hostname),
1516 sock);
9439f85e 1517 }
0e42da1b 1518#endif
b1f8e4f8 1519
0e42da1b 1520 free(clamav_fbuf);
b1f8e4f8 1521
0e42da1b
JH
1522 CLOSE_SOCKDATA;
1523#undef CLOSE_SOCKDATA
1524 }
1525 else
1526 { /* use scan command */
1527 /* Send a SCAN command pointing to a filename; then in the then in the
1528 * scan-method-neutral part, read the response back */
1529
1530/* ================================================================= */
1531
1532 /* Prior to the reworking post-Exim-4.72, this scanned a directory,
1533 which dates to when ClamAV needed us to break apart the email into the
1534 MIME parts (eg, with the now deprecated demime condition coming first).
1535 Some time back, ClamAV gained the ability to deconstruct the emails, so
1536 doing this would actually have resulted in the mail attachments being
1537 scanned twice, in the broken out files and from the original .eml.
1538 Since ClamAV now handles emails (and has for quite some time) we can
1539 just use the email file itself. */
1540 /* Pass the string to ClamAV (7 = "SCAN \n" + \0) */
1541 file_name = string_sprintf("SCAN %s\n", eml_filename);
1542
1543 DEBUG(D_acl) debug_printf(
1544 "Malware scan: issuing %s local-path scan [%s]\n",
1545 scanner_name, scanner_options);
b1f8e4f8 1546
0e42da1b
JH
1547 if (send(sock, file_name, Ustrlen(file_name), 0) < 0)
1548 return m_errlog_defer_3(scanent,
1549 string_sprintf("unable to write to socket (%s)", strerror(errno)),
1550 sock);
b1f8e4f8 1551
0e42da1b
JH
1552 /* Do not shut down the socket for writing; a user report noted that
1553 * clamd 0.70 does not react well to this. */
1554 }
1555 /* Commands have been sent, no matter which scan method or connection
1556 * type we're using; now just read the result, independent of method. */
1557
1558 /* Read the result */
1559 memset(av_buffer, 0, sizeof(av_buffer));
1560 bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL));
1561 (void)close(sock);
1562 sock = -1;
1563
1564 if (bread <= 0)
1565 return m_errlog_defer(scanent,
1566 string_sprintf("unable to read from socket (%s)",
1567 errno == 0 ? "EOF" : strerror(errno)));
1568
1569 if (bread == sizeof(av_buffer))
1570 return m_errlog_defer(scanent, US"buffer too small");
1571 /* We're now assured of a NULL at the end of av_buffer */
1572
1573 /* Check the result. ClamAV returns one of two result formats.
1574 In the basic mode, the response is of the form:
1575 infected: -> "<filename>: <virusname> FOUND"
1576 not-infected: -> "<filename>: OK"
1577 error: -> "<filename>: <errcode> ERROR
1578 If the ExtendedDetectionInfo option has been turned on, then we get:
1579 "<filename>: <virusname>(<virushash>:<virussize>) FOUND"
1580 for the infected case. Compare:
1581/tmp/eicar.com: Eicar-Test-Signature FOUND
1582/tmp/eicar.com: Eicar-Test-Signature(44d88612fea8a8f36de82e1278abb02f:68) FOUND
1583
1584 In the streaming case, clamd uses the filename "stream" which you should
1585 be able to verify with { ktrace clamdscan --stream /tmp/eicar.com }. (The
1586 client app will replace "stream" with the original filename before returning
1587 results to stdout, but the trace shows the data).
1588
1589 We will assume that the pathname passed to clamd from Exim does not contain
1590 a colon. We will have whined loudly above if the eml_filename does (and we're
1591 passing a filename to clamd). */
1592
1593 if (!(*av_buffer))
1594 return m_errlog_defer(scanent, US"ClamAV returned null");
1595
1596 /* strip newline at the end (won't be present for zINSTREAM)
1597 (also any trailing whitespace, which shouldn't exist, but we depend upon
1598 this below, so double-check) */
1599 p = av_buffer + Ustrlen(av_buffer) - 1;
1600 if (*p == '\n') *p = '\0';
1601
1602 DEBUG(D_acl) debug_printf("Malware response: %s\n", av_buffer);
1603
1604 while (isspace(*--p) && (p > av_buffer))
1605 *p = '\0';
1606 if (*p) ++p;
1607 response_end = p;
1608
1609 /* colon in returned output? */
1610 if((p = Ustrchr(av_buffer,':')) == NULL)
1611 return m_errlog_defer(scanent, string_sprintf(
1612 "ClamAV returned malformed result (missing colon): %s",
1613 av_buffer));
1614
1615 /* strip filename */
1616 while (*p && isspace(*++p)) /**/;
1617 vname = p;
1618
1619 /* It would be bad to encounter a virus with "FOUND" in part of the name,
1620 but we should at least be resistant to it. */
1621 p = Ustrrchr(vname, ' ');
1622 result_tag = p ? p+1 : vname;
1623
1624 if (Ustrcmp(result_tag, "FOUND") == 0)
1625 {
1626 /* p should still be the whitespace before the result_tag */
1627 while (isspace(*p)) --p;
1628 *++p = '\0';
1629 /* Strip off the extended information too, which will be in parens
1630 after the virus name, with no intervening whitespace. */
1631 if (*--p == ')')
9439f85e 1632 {
0e42da1b
JH
1633 /* "(hash:size)", so previous '(' will do; if not found, we have
1634 a curious virus name, but not an error. */
1635 p = Ustrrchr(vname, '(');
1636 if (p)
1637 *p = '\0';
9439f85e 1638 }
0e42da1b
JH
1639 malware_name = string_copy(vname);
1640 DEBUG(D_acl) debug_printf("Malware found, name \"%s\"\n", malware_name);
b1f8e4f8 1641
0e42da1b
JH
1642 }
1643 else if (Ustrcmp(result_tag, "ERROR") == 0)
1644 return m_errlog_defer(scanent,
1645 string_sprintf("ClamAV returned: %s", av_buffer));
b1f8e4f8 1646
0e42da1b
JH
1647 else if (Ustrcmp(result_tag, "OK") == 0)
1648 {
1649 /* Everything should be OK */
1650 malware_name = NULL;
1651 DEBUG(D_acl) debug_printf("Malware not found\n");
b1f8e4f8 1652
0e42da1b
JH
1653 }
1654 else
1655 return m_errlog_defer(scanent,
1656 string_sprintf("unparseable response from ClamAV: {%s}", av_buffer));
1657
1658 break;
b1f8e4f8
JH
1659 } /* clamd */
1660
1661 case M_SOCK: /* "sock" scanner type ------------------------------------- */
0e42da1b
JH
1662 /* This code was derived by Martin Poole from the clamd code contributed
1663 by David Saez and the cmdline code
1664 */
b1f8e4f8 1665 {
0e42da1b
JH
1666 int bread;
1667 uschar * commandline;
1668 uschar av_buffer[1024];
1669 uschar * linebuffer;
1670 uschar * sockline_scanner;
1671 uschar sockline_scanner_default[] = "%s\n";
1672 const pcre *sockline_trig_re;
1673 const pcre *sockline_name_re;
1674
1675 /* find scanner command line */
1676 if ((sockline_scanner = string_nextinlist(&av_scanner_work, &sep,
1677 NULL, 0)))
1678 { /* check for no expansions apart from one %s */
1679 uschar * s = Ustrchr(sockline_scanner, '%');
1680 if (s++)
1681 if ((*s != 's' && *s != '%') || Ustrchr(s+1, '%'))
1682 return m_errlog_defer_3(scanent,
1683 US"unsafe sock scanner call spec", sock);
1684 }
1685 else
1686 sockline_scanner = sockline_scanner_default;
b1f8e4f8 1687
0e42da1b
JH
1688 /* find scanner output trigger */
1689 sockline_trig_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1690 "missing trigger specification", &errstr);
1691 if (!sockline_trig_re)
1692 return m_errlog_defer_3(scanent, errstr, sock);
b1f8e4f8 1693
0e42da1b
JH
1694 /* find virus name regex */
1695 sockline_name_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1696 "missing virus name regex specification", &errstr);
1697 if (!sockline_name_re)
1698 return m_errlog_defer_3(scanent, errstr, sock);
b1f8e4f8 1699
0e42da1b
JH
1700 /* prepare scanner call - security depends on expansions check above */
1701 commandline = string_sprintf("%s/scan/%s/%s.eml", spool_directory, message_id, message_id);
1702 commandline = string_sprintf( CS sockline_scanner, CS commandline);
b1f8e4f8
JH
1703
1704
0e42da1b
JH
1705 /* Pass the command string to the socket */
1706 if (m_sock_send(sock, commandline, Ustrlen(commandline), &errstr) < 0)
1707 return m_errlog_defer(scanent, errstr);
b1f8e4f8 1708
0e42da1b
JH
1709 /* Read the result */
1710 bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL));
b1f8e4f8 1711
0e42da1b
JH
1712 if (bread <= 0)
1713 return m_errlog_defer_3(scanent,
1714 string_sprintf("unable to read from socket (%s)", strerror(errno)),
1715 sock);
b1f8e4f8 1716
0e42da1b
JH
1717 if (bread == sizeof(av_buffer))
1718 return m_errlog_defer_3(scanent, US"buffer too small", sock);
1719 av_buffer[bread] = '\0';
1720 linebuffer = string_copy(av_buffer);
b1f8e4f8 1721
0e42da1b
JH
1722 /* try trigger match */
1723 if (regex_match_and_setup(sockline_trig_re, linebuffer, 0, -1))
1724 {
1725 if (!(malware_name = m_pcre_exec(sockline_name_re, av_buffer)))
1726 malware_name = US "unknown";
b1f8e4f8 1727 }
0e42da1b
JH
1728 else /* no virus found */
1729 malware_name = NULL;
1730 break;
8523533c 1731 }
8e669ac1 1732
b1f8e4f8
JH
1733 case M_MKSD: /* "mksd" scanner type ------------------------------------- */
1734 {
0e42da1b
JH
1735 char *mksd_options_end;
1736 int mksd_maxproc = 1; /* default, if no option supplied */
1737 int retval;
b1f8e4f8 1738
0e42da1b
JH
1739 if (scanner_options)
1740 {
1741 mksd_maxproc = (int)strtol(CS scanner_options, &mksd_options_end, 10);
1742 if ( *scanner_options == '\0'
1743 || *mksd_options_end != '\0'
1744 || mksd_maxproc < 1
1745 || mksd_maxproc > 32
1746 )
1747 return m_errlog_defer(scanent,
1748 string_sprintf("invalid option '%s'", scanner_options));
1749 }
8e669ac1 1750
0e42da1b
JH
1751 if((sock = m_unixsocket(US "/var/run/mksd/socket", &errstr)) < 0)
1752 return m_errlog_defer(scanent, errstr);
8e669ac1 1753
0e42da1b 1754 malware_name = NULL;
94a18f28 1755
0e42da1b 1756 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan\n", scanner_name);
94a18f28 1757
0e42da1b
JH
1758 if ((retval = mksd_scan_packed(scanent, sock, eml_filename, tmo)) != OK)
1759 {
1760 close (sock);
1761 return retval;
1762 }
1763 break;
8523533c 1764 }
0e42da1b 1765
e4413c34
JH
1766 case M_AVAST: /* "avast" scanner type ----------------------------------- */
1767 {
1768 int ovector[1*3];
1769 uschar buf[1024];
1770 uschar * scanrequest;
237e7c0a 1771 enum {AVA_HELO, AVA_OPT, AVA_RSP, AVA_DONE} avast_stage;
0e42da1b 1772 int nread;
237e7c0a
HSHR
1773
1774 /* According to Martin Tuma @avast the protocol uses "escaped
1775 whitespace", that is, every embedded whitespace is backslash
1776 escaped, as well as backslash is protected by backslash.
1777 The returned lines contain the name of the scanned file, a tab
1778 and the [ ] marker.
1779 [+] - not infected
1780 [L] - infected
1781 [E] - some error occured
1782 Such marker follows the first non-escaped TAB. */
2339c66a
JH
1783 if ( ( !ava_re_clean
1784 && !(ava_re_clean = m_pcre_compile(ava_re_clean_str, &errstr)))
1785 || ( !ava_re_virus
1786 && !(ava_re_virus = m_pcre_compile(ava_re_virus_str, &errstr)))
e4413c34
JH
1787 )
1788 return malware_errlog_defer(errstr);
1789
1790 /* wait for result */
0e42da1b
JH
1791 for (avast_stage = AVA_HELO;
1792 (nread = recv_line(sock, buf, sizeof(buf), tmo)) > 0;
1793 )
e4413c34
JH
1794 {
1795 int slen = Ustrlen(buf);
237e7c0a 1796 if (slen >= 1)
e4413c34 1797 {
237e7c0a
HSHR
1798 DEBUG(D_acl) debug_printf("got from avast: %s\n", buf);
1799 switch (avast_stage)
1800 {
1801 case AVA_HELO:
1802 if (Ustrncmp(buf, "220", 3) != 0)
1803 goto endloop; /* require a 220 */
1804 goto sendreq;
1805
1806 case AVA_OPT:
1807 if (Ustrncmp(buf, "210", 3) == 0)
1808 break; /* ignore 210 responses */
1809 if (Ustrncmp(buf, "200", 3) != 0)
1810 goto endloop; /* require a 200 */
1811
1812 sendreq:
6fc611ad
JH
1813 {
1814 int len;
237e7c0a
HSHR
1815 /* Check for another option to send. Newline-terminate it. */
1816 if ((scanrequest = string_nextinlist(&av_scanner_work, &sep,
1817 NULL, 0)))
1818 {
1819 scanrequest = string_sprintf("%s\n", scanrequest);
1820 avast_stage = AVA_OPT; /* just sent option */
1821 }
1822 else
1823 {
6fc611ad 1824 scanrequest = string_sprintf("SCAN %s/scan/%s\n",
237e7c0a
HSHR
1825 spool_directory, message_id);
1826 avast_stage = AVA_RSP; /* just sent command */
1827 }
e4413c34 1828
237e7c0a 1829 /* send config-cmd or scan-request to socket */
6fc611ad
JH
1830 len = Ustrlen(scanrequest);
1831 if (send(sock, scanrequest, len, 0) < 0)
1832 {
1833 scanrequest[len-1] = '\0';
237e7c0a 1834 return m_errlog_defer_3(scanent, string_sprintf(
6fc611ad
JH
1835 "unable to send request '%s' to socket (%s): %s",
1836 scanrequest, scanner_options, strerror(errno)), sock);
1837 }
237e7c0a 1838 break;
6fc611ad 1839 }
e4413c34 1840
237e7c0a
HSHR
1841 case AVA_RSP:
1842 if (Ustrncmp(buf, "210", 3) == 0)
1843 break; /* ignore the "210 SCAN DATA" message */
1844
2339c66a 1845 if (pcre_exec(ava_re_clean, NULL, CS buf, slen,
237e7c0a
HSHR
1846 0, 0, ovector, nelements(ovector)) > 0)
1847 break;
1848
2339c66a 1849 if ((malware_name = m_pcre_exec(ava_re_virus, buf)))
237e7c0a
HSHR
1850 { /* remove backslash in front of [whitespace|backslash] */
1851 uschar * p, * p0;
1852 for (p = malware_name; *p; ++p)
1853 if (*p == '\\' && (isspace(p[1]) || p[1] == '\\'))
1854 for (p0 = p; *p0; ++p0) *p0 = p0[1];
1855
1856 avast_stage = AVA_DONE;
1857 goto endloop;
1858 }
e4413c34 1859
237e7c0a
HSHR
1860 if (Ustrncmp(buf, "200 SCAN OK", 11) == 0)
1861 { /* we're done finally */
1862 if (send(sock, "QUIT\n", 5, 0) < 0) /* courtesy */
1863 return m_errlog_defer_3(scanent, string_sprintf(
1864 "unable to send quit request to socket (%s): %s",
1865 scanner_options, strerror(errno)),
1866 sock);
1867 malware_name = NULL;
1868 avast_stage = AVA_DONE;
1869 goto endloop;
1870 }
e4413c34 1871
237e7c0a 1872 /* here for any unexpected response from the scanner */
e4413c34 1873 goto endloop;
237e7c0a 1874 }
0e42da1b 1875 }
e4413c34
JH
1876 }
1877 endloop:
1878
1879 switch(avast_stage)
1880 {
0e42da1b 1881 case AVA_HELO:
237e7c0a 1882 case AVA_OPT:
0e42da1b
JH
1883 case AVA_RSP: return m_errlog_defer_3(scanent,
1884 nread >= 0
1885 ? string_sprintf(
1886 "invalid response from scanner: '%s'", buf)
1887 : nread == -1
1888 ? US"EOF from scanner"
1889 : US"timeout from scanner",
1890 sock);
e4413c34
JH
1891 default: break;
1892 }
1893 }
0e42da1b
JH
1894 break;
1895 } /* scanner type switch */
8523533c 1896
0e42da1b
JH
1897 if (sock >= 0)
1898 (void) close (sock);
1899 malware_ok = TRUE; /* set "been here, done that" marker */
b1f8e4f8 1900 }
8523533c 1901
0e42da1b
JH
1902/* match virus name against pattern (caseless ------->----------v) */
1903if (malware_name && regex_match_and_setup(re, malware_name, 0, -1))
1904 {
1905 DEBUG(D_acl) debug_printf(
1906 "Matched regex to malware [%s] [%s]\n", malware_re, malware_name);
1907 return OK;
1908 }
1909else
1910 return FAIL;
8523533c
TK
1911}
1912
1913
0e42da1b
JH
1914/*************************************************
1915* Scan an email for malware *
1916*************************************************/
8523533c 1917
0e42da1b
JH
1918/* This is the normal interface for scanning an email, which doesn't need a
1919filename; it's a wrapper around the malware_file function.
8523533c 1920
0e42da1b
JH
1921Arguments:
1922 malware_re match condition for "malware="
1923 timeout if nonzero, timeout in seconds
1924
1925Returns: Exim message processing code (OK, FAIL, DEFER, ...)
1926 where true means malware was found (condition applies)
1927*/
1928int
1929malware(const uschar * malware_re, int timeout)
8523533c 1930{
0e42da1b
JH
1931 uschar * scan_filename;
1932 int ret;
8e669ac1 1933
0e42da1b
JH
1934 scan_filename = string_sprintf("%s/scan/%s/%s.eml",
1935 spool_directory, message_id, message_id);
1936 ret = malware_internal(malware_re, scan_filename, timeout, FALSE);
1937 if (ret == DEFER) av_failed = TRUE;
1938
1939 return ret;
8523533c
TK
1940}
1941
8e669ac1 1942
0e42da1b
JH
1943/*************************************************
1944* Scan a file for malware *
1945*************************************************/
8e669ac1 1946
0e42da1b
JH
1947/* This is a test wrapper for scanning an email, which is not used in
1948normal processing. Scan any file, using the Exim scanning interface.
1949This function tampers with various global variables so is unsafe to use
1950in any other context.
8e669ac1 1951
0e42da1b
JH
1952Arguments:
1953 eml_filename a file holding the message to be scanned
8523533c 1954
0e42da1b
JH
1955Returns: Exim message processing code (OK, FAIL, DEFER, ...)
1956 where true means malware was found (condition applies)
1957*/
1958int
1959malware_in_file(uschar *eml_filename)
8523533c 1960{
0e42da1b
JH
1961 uschar message_id_buf[64];
1962 int ret;
8523533c 1963
0e42da1b
JH
1964 /* spool_mbox() assumes various parameters exist, when creating
1965 the relevant directory and the email within */
1966 (void) string_format(message_id_buf, sizeof(message_id_buf),
1967 "dummy-%d", vaguely_random_number(INT_MAX));
1968 message_id = message_id_buf;
1969 sender_address = US"malware-sender@example.net";
1970 return_path = US"";
1971 recipients_list = NULL;
1972 receive_add_recipient(US"malware-victim@example.net", -1);
1973 enable_dollar_recipients = TRUE;
8e669ac1 1974
0e42da1b 1975 ret = malware_internal(US"*", eml_filename, 0, TRUE);
8544e77a 1976
0e42da1b
JH
1977 Ustrncpy(spooled_message_id, message_id, sizeof(spooled_message_id));
1978 spool_mbox_ok = 1;
1979 /* don't set no_mbox_unspool; at present, there's no way for it to become
1980 set, but if that changes, then it should apply to these tests too */
1981 unspool_mbox();
8e669ac1 1982
0e42da1b
JH
1983 /* silence static analysis tools */
1984 message_id = NULL;
8e669ac1 1985
0e42da1b 1986 return ret;
8523533c
TK
1987}
1988
2339c66a
JH
1989
1990void
1991malware_init(void)
1992{
1993if (!malware_default_re)
1994 malware_default_re = regex_must_compile(malware_regex_default, FALSE, TRUE);
1995if (!drweb_re)
1996 drweb_re = regex_must_compile(drweb_re_str, FALSE, TRUE);
1997if (!fsec_re)
1998 fsec_re = regex_must_compile(fsec_re_str, FALSE, TRUE);
1999if (!kav_re_sus)
2000 kav_re_sus = regex_must_compile(kav_re_sus_str, FALSE, TRUE);
2001if (!kav_re_inf)
2002 kav_re_inf = regex_must_compile(kav_re_inf_str, FALSE, TRUE);
2003if (!ava_re_clean)
2004 ava_re_clean = regex_must_compile(ava_re_clean_str, FALSE, TRUE);
2005if (!ava_re_virus)
2006 ava_re_virus = regex_must_compile(ava_re_virus_str, FALSE, TRUE);
2007}
2008
b1f8e4f8
JH
2009#endif /*WITH_CONTENT_SCAN*/
2010/*
2011 * vi: aw ai sw=2
2012 */