1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2003-2014 */
8 /* Code for calling virus (malware) scanners. Called from acl.c. */
11 #ifdef WITH_CONTENT_SCAN
13 typedef enum {M_FPROTD, M_DRWEB, M_AVES, M_FSEC, M_KAVD, M_CMDL,
14 M_SOPHIE, M_CLAMD, M_SOCK, M_MKSD, M_AVAST} scanner_t;
15 typedef enum {MC_NONE, MC_TCP, MC_UNIX, MC_STRM} contype_t;
20 const uschar * options_default;
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 },
34 { M_AVAST, US"avast", US"/var/run/avast/scan.sock", MC_STRM },
35 { -1, NULL, NULL, MC_NONE } /* end-marker */
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"
45 typedef struct clamd_address_container {
46 uschar tcp_addr[MAX_CLAMD_ADDRESS_LENGTH+1];
47 unsigned int tcp_port;
48 } clamd_address_container;
50 /* declaration of private routines */
51 static int mksd_scan_packed(struct scan * scanent, int sock, uschar *scan_filename);
52 static int malware_internal(uschar **listptr, uschar *eml_filename, BOOL faking);
55 # define nelements(arr) (sizeof(arr) / sizeof(arr[0]))
59 #define MALWARE_TIMEOUT 120
62 #define DRWEBD_SCAN_CMD (1) /* scan file, buffer or diskfile */
63 #define DRWEBD_RETURN_VIRUSES (1<<0) /* ask daemon return to us viruses names from report */
64 #define DRWEBD_IS_MAIL (1<<19) /* say to daemon that format is "archive MAIL" */
66 #define DERR_READ_ERR (1<<0) /* read error */
67 #define DERR_NOMEMORY (1<<2) /* no memory */
68 #define DERR_TIMEOUT (1<<9) /* scan timeout has run out */
69 #define DERR_BAD_CALL (1<<15) /* wrong command */
71 /* Routine to check whether a system is big- or little-endian.
72 Ripped from http://www.faqs.org/faqs/graphics/fileformats-faq/part4/section-7.html
73 Needed for proper kavdaemon implementation. Sigh. */
74 #define BIG_MY_ENDIAN 0
75 #define LITTLE_MY_ENDIAN 1
76 static int test_byte_order(void);
80 short int word = 0x0001;
81 char *byte = (char *) &word;
82 return(byte[0] ? LITTLE_MY_ENDIAN : BIG_MY_ENDIAN);
85 BOOL malware_ok = FALSE;
87 /* Gross hacks for the -bmalware option; perhaps we should just create
88 the scan directory normally for that case, but look into rigging up the
89 needed header variables if not already set on the command-line? */
90 extern int spool_mbox_ok;
91 extern uschar spooled_message_id[17];
93 /*************************************************
94 * Scan an email for malware *
95 *************************************************/
97 /* This is the normal interface for scanning an email, which doesn't need a
98 filename; it's a wrapper around the malware_file function.
101 listptr the list of options to the "malware = ..." ACL condition
103 Returns: Exim message processing code (OK, FAIL, DEFER, ...)
104 where true means malware was found (condition applies)
107 malware(uschar **listptr)
109 uschar * scan_filename;
112 scan_filename = string_sprintf("%s/scan/%s/%s.eml",
113 spool_directory, message_id, message_id);
114 ret = malware_internal(listptr, scan_filename, FALSE);
115 if (ret == DEFER) av_failed = TRUE;
121 /*************************************************
122 * Scan a file for malware *
123 *************************************************/
125 /* This is a test wrapper for scanning an email, which is not used in
126 normal processing. Scan any file, using the Exim scanning interface.
127 This function tampers with various global variables so is unsafe to use
128 in any other context.
131 eml_filename a file holding the message to be scanned
133 Returns: Exim message processing code (OK, FAIL, DEFER, ...)
134 where true means malware was found (condition applies)
137 malware_in_file(uschar *eml_filename)
139 uschar *scan_options[2];
140 uschar message_id_buf[64];
143 scan_options[0] = US"*";
144 scan_options[1] = NULL;
146 /* spool_mbox() assumes various parameters exist, when creating
147 the relevant directory and the email within */
148 (void) string_format(message_id_buf, sizeof(message_id_buf),
149 "dummy-%d", vaguely_random_number(INT_MAX));
150 message_id = message_id_buf;
151 sender_address = US"malware-sender@example.net";
153 recipients_list = NULL;
154 receive_add_recipient(US"malware-victim@example.net", -1);
155 enable_dollar_recipients = TRUE;
157 ret = malware_internal(scan_options, eml_filename, TRUE);
159 Ustrncpy(spooled_message_id, message_id, sizeof(spooled_message_id));
161 /* don't set no_mbox_unspool; at present, there's no way for it to become
162 set, but if that changes, then it should apply to these tests too */
165 /* silence static analysis tools */
173 malware_errlog_defer(const uschar * str)
175 log_write(0, LOG_MAIN|LOG_PANIC, "malware acl condition: %s", str);
180 m_errlog_defer(struct scan * scanent, const uschar * str)
182 return malware_errlog_defer(string_sprintf("%s: %s", scanent->name, str));
185 m_errlog_defer_3(struct scan * scanent, const uschar * str,
188 (void) close(fd_to_close);
189 return m_errlog_defer(scanent, str);
192 /*************************************************/
194 /* Only used by the Clamav code, which is working from a list of servers and
195 uses the returned in_addr to get a second connection to the same system.
198 m_tcpsocket(const uschar * hostname, unsigned int port,
199 host_item * host, uschar ** errstr)
201 return ip_connectedsocket(SOCK_STREAM, hostname, port, port, 5, host, errstr);
205 m_tcpsocket_fromdef(const uschar * hostport, uschar ** errstr)
208 uschar hostname[256];
209 unsigned int portlow, porthigh;
211 /* extract host and port part */
212 scan = sscanf(CS hostport, "%255s %u-%u", hostname, &portlow, &porthigh);
215 *errstr = string_sprintf("invalid socket '%s'", hostport);
221 return ip_connectedsocket(SOCK_STREAM, hostname, portlow, porthigh,
226 m_unixsocket(const uschar * path, uschar ** errstr)
229 struct sockaddr_un server;
231 if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
232 *errstr = US"can't open UNIX socket.";
236 server.sun_family = AF_UNIX;
237 Ustrncpy(server.sun_path, path, sizeof(server.sun_path)-1);
238 server.sun_path[sizeof(server.sun_path)-1] = '\0';
239 if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) {
242 *errstr = string_sprintf("unable to connect to UNIX socket (%s): %s",
243 path, strerror(err));
250 m_streamsocket(const uschar * spec, uschar ** errstr)
253 ? m_unixsocket(spec, errstr) : m_tcpsocket_fromdef(spec, errstr);
257 m_sock_send(int sock, uschar * buf, int cnt, uschar ** errstr)
259 if (send(sock, buf, cnt, 0) < 0) {
262 *errstr = string_sprintf("unable to send to socket (%s): %s",
270 m_pcre_compile(const uschar * re, uschar ** errstr)
272 const uschar * rerror;
276 cre = pcre_compile(CS re, PCRE_COPT, (const char **)&rerror, &roffset, NULL);
278 *errstr= string_sprintf("regular expression error in '%s': %s at offset %d",
279 re, rerror, roffset);
284 m_pcre_exec(const pcre * cre, uschar * text)
287 int i = pcre_exec(cre, NULL, CS text, Ustrlen(text), 0, 0,
288 ovector, nelements(ovector));
289 uschar * substr = NULL;
290 if (i >= 2) /* Got it */
291 pcre_get_substring(CS text, ovector, i, 1, (const char **) &substr);
296 m_pcre_nextinlist(uschar ** list, int * sep, char * listerr, uschar ** errstr)
298 const uschar * list_ele;
299 const pcre * cre = NULL;
301 if (!(list_ele = string_nextinlist(list, sep, NULL, 0)))
302 *errstr = US listerr;
304 cre = m_pcre_compile(CUS list_ele, errstr);
308 /*************************************************
309 * Scan content for malware *
310 *************************************************/
312 /* This is an internal interface for scanning an email; the normal interface
313 is via malware(), or there's malware_in_file() used for testing/debugging.
316 listptr the list of options to the "malware = ..." ACL condition
317 eml_filename the file holding the email to be scanned
318 faking whether or not we're faking this up for the -bmalware test
320 Returns: Exim message processing code (OK, FAIL, DEFER, ...)
321 where true means malware was found (condition applies)
324 malware_internal(uschar **listptr, uschar *eml_filename, BOOL faking)
327 uschar *list = *listptr;
328 uschar *av_scanner_work = av_scanner;
329 uschar *scanner_name;
330 uschar *malware_regex;
331 uschar malware_regex_default[] = ".+";
332 unsigned long mbox_size;
336 struct scan * scanent;
337 const uschar * scanner_options;
340 /* make sure the eml mbox file is spooled up */
341 if (!(mbox_file = spool_mbox(&mbox_size, faking ? eml_filename : NULL)))
342 return malware_errlog_defer(US"error while creating mbox spool file");
344 /* none of our current scanners need the mbox
345 file as a stream, so we can close it right away */
346 (void)fclose(mbox_file);
348 /* extract the malware regex to match against from the option list */
349 if (!(malware_regex = string_nextinlist(&list, &sep, NULL, 0)))
350 return FAIL; /* empty means "don't match anything" */
352 /* parse 1st option */
353 if ( (strcmpic(malware_regex,US"false") == 0) ||
354 (Ustrcmp(malware_regex,"0") == 0) )
355 return FAIL; /* explicitly no matching */
357 /* special cases (match anything except empty) */
358 if ( (strcmpic(malware_regex,US"true") == 0) ||
359 (Ustrcmp(malware_regex,"*") == 0) ||
360 (Ustrcmp(malware_regex,"1") == 0) )
361 malware_regex = malware_regex_default;
363 /* Reset sep that is set by previous string_nextinlist() call */
366 /* compile the regex, see if it works */
367 if (!(re = m_pcre_compile(malware_regex, &errstr)))
368 return malware_errlog_defer(errstr);
370 /* if av_scanner starts with a dollar, expand it first */
371 if (*av_scanner == '$') {
372 if (!(av_scanner_work = expand_string(av_scanner)))
373 return malware_errlog_defer(
374 string_sprintf("av_scanner starts with $, but expansion failed: %s",
375 expand_string_message));
377 debug_printf("Expanded av_scanner global: %s\n", av_scanner_work);
378 /* disable result caching in this case */
383 /* Do not scan twice (unless av_scanner is dynamic). */
386 /* find the scanner type from the av_scanner option */
387 if (!(scanner_name = string_nextinlist(&av_scanner_work, &sep, NULL, 0)))
388 return malware_errlog_defer(US"av_scanner configuration variable is empty");
390 for (scanent = m_scans; ; scanent++) {
392 return malware_errlog_defer(string_sprintf("unknown scanner type '%s'",
394 if (strcmpic(scanner_name, US scanent->name) != 0)
396 if (!(scanner_options = string_nextinlist(&av_scanner_work, &sep, NULL, 0)))
397 scanner_options = scanent->options_default;
398 if (scanent->conn == MC_NONE)
400 switch(scanent->conn)
402 case MC_TCP: sock = m_tcpsocket_fromdef(scanner_options, &errstr); break;
403 case MC_UNIX: sock = m_unixsocket(scanner_options, &errstr); break;
404 case MC_STRM: sock = m_streamsocket(scanner_options, &errstr); break;
405 default: /* compiler quietening */ break;
408 return m_errlog_defer(scanent, errstr);
411 DEBUG(D_lookup) debug_printf("Malware scan: %s\n", scanner_name);
413 switch (scanent->scancode) {
414 case M_FPROTD: /* "f-protd" scanner type -------------------------------- */
416 uschar *fp_scan_option;
417 unsigned int detected=0, par_count=0;
418 uschar * scanrequest;
419 uschar buf[32768], *strhelper, *strhelper2;
420 uschar * malware_name_internal = NULL;
422 DEBUG(D_acl) debug_printf("Malware scan: issuing %s GET\n", scanner_name);
423 scanrequest = string_sprintf("GET %s", eml_filename);
425 while ((fp_scan_option = string_nextinlist(&av_scanner_work, &sep,
427 scanrequest = string_sprintf("%s%s%s", scanrequest,
428 par_count ? "%20" : "?", fp_scan_option);
431 scanrequest = string_sprintf("%s HTTP/1.0\r\n\r\n", scanrequest);
433 /* send scan request */
434 if (m_sock_send(sock, scanrequest, Ustrlen(scanrequest)+1, &errstr) < 0)
435 return m_errlog_defer(scanent, errstr);
437 /* We get a lot of empty lines, so we need this hack to check for any data at all */
438 while( recv(sock, buf, 1, MSG_PEEK) > 0 ) {
439 if ( recv_line(sock, buf, sizeof(buf)) > 0) {
440 if ( Ustrstr(buf, US"<detected type=\"") != NULL )
442 else if ( detected && (strhelper = Ustrstr(buf, US"<name>")) ) {
443 if ((strhelper2 = Ustrstr(buf, US"</name>")) != NULL) {
445 malware_name_internal = string_copy(strhelper+6);
447 } else if ( Ustrstr(buf, US"<summary code=\"") )
448 malware_name = Ustrstr(buf, US"<summary code=\"11\">")
449 ? malware_name_internal : NULL;
455 case M_DRWEB: /* "drweb" scanner type ----------------------------------- */
456 /* v0.1 - added support for tcp sockets */
457 /* v0.0 - initial release -- support for unix sockets */
461 unsigned int fsize_uint;
462 uschar * tmpbuf, *drweb_fbuf;
463 int drweb_rc, drweb_cmd, drweb_flags = 0x0000, drweb_fd,
464 drweb_vnum, drweb_slen, drweb_fin = 0x0000;
466 const pcre *drweb_re;
468 /* prepare variables */
469 drweb_cmd = htonl(DRWEBD_SCAN_CMD);
470 drweb_flags = htonl(DRWEBD_RETURN_VIRUSES | DRWEBD_IS_MAIL);
472 if (*scanner_options != '/') {
475 if ((drweb_fd = open(CS eml_filename, O_RDONLY)) == -1)
476 return m_errlog_defer_3(scanent,
477 string_sprintf("can't open spool file %s: %s",
478 eml_filename, strerror(errno)),
481 if ((fsize = lseek(drweb_fd, 0, SEEK_END)) == -1) {
483 (void)close(drweb_fd);
484 return m_errlog_defer_3(scanent,
485 string_sprintf("can't seek spool file %s: %s",
486 eml_filename, strerror(err)),
489 fsize_uint = (unsigned int) fsize;
490 if ((off_t)fsize_uint != fsize) {
491 (void)close(drweb_fd);
492 return m_errlog_defer_3(scanent,
493 string_sprintf("seeking spool file %s, size overflow",
497 drweb_slen = htonl(fsize);
498 lseek(drweb_fd, 0, SEEK_SET);
500 DEBUG(D_acl) debug_printf("Malware scan: issuing %s remote scan [%s]\n",
501 scanner_name, scanner_options);
503 /* send scan request */
504 if ((send(sock, &drweb_cmd, sizeof(drweb_cmd), 0) < 0) ||
505 (send(sock, &drweb_flags, sizeof(drweb_flags), 0) < 0) ||
506 (send(sock, &drweb_fin, sizeof(drweb_fin), 0) < 0) ||
507 (send(sock, &drweb_slen, sizeof(drweb_slen), 0) < 0)) {
508 (void)close(drweb_fd);
509 return m_errlog_defer_3(scanent,
510 string_sprintf("unable to send commands to socket (%s)", scanner_options),
514 if (!(drweb_fbuf = (uschar *) malloc (fsize_uint))) {
515 (void)close(drweb_fd);
516 return m_errlog_defer_3(scanent,
517 string_sprintf("unable to allocate memory %u for file (%s)",
518 fsize_uint, eml_filename),
522 if ((result = read (drweb_fd, drweb_fbuf, fsize)) == -1) {
524 (void)close(drweb_fd);
526 return m_errlog_defer_3(scanent,
527 string_sprintf("can't read spool file %s: %s",
528 eml_filename, strerror(err)),
531 (void)close(drweb_fd);
533 /* send file body to socket */
534 if (send(sock, drweb_fbuf, fsize, 0) < 0) {
536 return m_errlog_defer_3(scanent,
537 string_sprintf("unable to send file body to socket (%s)", scanner_options),
540 (void)close(drweb_fd);
544 drweb_slen = htonl(Ustrlen(eml_filename));
546 DEBUG(D_acl) debug_printf("Malware scan: issuing %s local scan [%s]\n",
547 scanner_name, scanner_options);
549 /* send scan request */
550 if ((send(sock, &drweb_cmd, sizeof(drweb_cmd), 0) < 0) ||
551 (send(sock, &drweb_flags, sizeof(drweb_flags), 0) < 0) ||
552 (send(sock, &drweb_slen, sizeof(drweb_slen), 0) < 0) ||
553 (send(sock, eml_filename, Ustrlen(eml_filename), 0) < 0) ||
554 (send(sock, &drweb_fin, sizeof(drweb_fin), 0) < 0))
555 return m_errlog_defer_3(scanent,
556 string_sprintf("unable to send commands to socket (%s)", scanner_options),
560 /* wait for result */
561 if ((bread = recv(sock, &drweb_rc, sizeof(drweb_rc), 0) != sizeof(drweb_rc)))
562 return m_errlog_defer_3(scanent,
563 US"unable to read return code", sock);
564 drweb_rc = ntohl(drweb_rc);
566 if ((bread = recv(sock, &drweb_vnum, sizeof(drweb_vnum), 0) != sizeof(drweb_vnum)))
567 return m_errlog_defer_3(scanent,
568 US"unable to read the number of viruses", sock);
569 drweb_vnum = ntohl(drweb_vnum);
571 /* "virus(es) found" if virus number is > 0 */
575 /* setup default virus name */
576 malware_name = US"unknown";
578 /* set up match regex */
579 drweb_re = m_pcre_compile(US"infected\\swith\\s*(.+?)$", &errstr);
581 /* read and concatenate virus names into one string */
582 for (i=0;i<drweb_vnum;i++)
584 int size = 0, off = 0, ovector[10*3];
585 /* read the size of report */
586 if ((bread = recv(sock, &drweb_slen, sizeof(drweb_slen), 0) != sizeof(drweb_slen)))
587 return m_errlog_defer_3(scanent,
588 US"cannot read report size", sock);
589 drweb_slen = ntohl(drweb_slen);
590 tmpbuf = store_get(drweb_slen);
592 /* read report body */
593 if ((bread = recv(sock, tmpbuf, drweb_slen, 0)) != drweb_slen)
594 return m_errlog_defer_3(scanent,
595 US"cannot read report string", sock);
596 tmpbuf[drweb_slen] = '\0';
598 /* try matcher on the line, grab substring */
599 result = pcre_exec(drweb_re, NULL, CS tmpbuf, Ustrlen(tmpbuf), 0, 0,
600 ovector, nelements(ovector));
602 const char * pre_malware_nb;
604 pcre_get_substring(CS tmpbuf, ovector, result, 1, &pre_malware_nb);
606 if (i==0) /* the first name we just copy to malware_name */
607 malware_name = string_append(NULL, &size, &off,
610 else /* concatenate each new virus name to previous */
611 malware_name = string_append(malware_name, &size, &off,
612 2, "/", pre_malware_nb);
614 pcre_free_substring(pre_malware_nb);
619 const char *drweb_s = NULL;
621 if (drweb_rc & DERR_READ_ERR) drweb_s = "read error";
622 if (drweb_rc & DERR_NOMEMORY) drweb_s = "no memory";
623 if (drweb_rc & DERR_TIMEOUT) drweb_s = "timeout";
624 if (drweb_rc & DERR_BAD_CALL) drweb_s = "wrong command";
625 /* retcodes DERR_SYMLINK, DERR_NO_REGFILE, DERR_SKIPPED.
626 * DERR_TOO_BIG, DERR_TOO_COMPRESSED, DERR_SPAM,
627 * DERR_CRC_ERROR, DERR_READSOCKET, DERR_WRITE_ERR
628 * and others are ignored */
630 return m_errlog_defer_3(scanent,
631 string_sprintf("drweb daemon retcode 0x%x (%s)", drweb_rc, drweb_s),
640 case M_AVES: /* "aveserver" scanner type -------------------------------- */
645 /* read aveserver's greeting and see if it is ready (2xx greeting) */
646 recv_line(sock, buf, sizeof(buf));
648 if (buf[0] != '2') /* aveserver is having problems */
649 return m_errlog_defer_3(scanent,
650 string_sprintf("unavailable (Responded: %s).",
651 ((buf[0] != 0) ? buf : (uschar *)"nothing") ),
654 /* prepare our command */
655 (void)string_format(buf, sizeof(buf), "SCAN bPQRSTUW %s\r\n",
658 DEBUG(D_acl) debug_printf("Malware scan: issuing %s SCAN\n", scanner_name);
661 if (m_sock_send(sock, buf, Ustrlen(buf), &errstr) < 0)
662 return m_errlog_defer(scanent, errstr);
666 /* read response lines, find malware name and final response */
667 while (recv_line(sock, buf, sizeof(buf)) > 0) {
668 debug_printf("aveserver: %s\n", buf);
671 if (buf[0] == '5') { /* aveserver is having problems */
672 result = m_errlog_defer(scanent,
673 string_sprintf("unable to scan file %s (Responded: %s).",
676 } else if (Ustrncmp(buf,"322",3) == 0) {
677 uschar *p = Ustrchr(&buf[4],' ');
679 malware_name = string_copy(&buf[4]);
684 if (m_sock_send(sock, US"quit\r\n", 6, &errstr) < 0)
685 return m_errlog_defer(scanent, errstr);
687 /* read aveserver's greeting and see if it is ready (2xx greeting) */
688 recv_line(sock, buf, sizeof(buf));
690 if (buf[0] != '2') /* aveserver is having problems */
691 return m_errlog_defer_3(scanent,
692 string_sprintf("unable to quit dialogue (Responded: %s).",
693 ((buf[0] != 0) ? buf : (uschar *)"nothing") ),
696 if (result == DEFER) {
703 case M_FSEC: /* "fsecure" scanner type ---------------------------------- */
707 uschar av_buffer[1024];
709 static uschar *cmdopt[] = { US"CONFIGURE\tARCHIVE\t1\n",
710 US"CONFIGURE\tTIMEOUT\t0\n",
711 US"CONFIGURE\tMAXARCH\t5\n",
712 US"CONFIGURE\tMIME\t1\n" };
716 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
717 scanner_name, scanner_options);
720 memset(av_buffer, 0, sizeof(av_buffer));
721 for (i=0; i != nelements(cmdopt); i++) {
723 if (m_sock_send(sock, cmdopt[i], Ustrlen(cmdopt[i]), &errstr) < 0)
724 return m_errlog_defer(scanent, errstr);
726 bread = ip_recv(sock, av_buffer, sizeof(av_buffer), MALWARE_TIMEOUT);
727 if (bread >0) av_buffer[bread]='\0';
729 return m_errlog_defer_3(scanent,
730 string_sprintf("unable to read answer %d (%s)", i, strerror(errno)),
732 for (j=0;j<bread;j++)
733 if((av_buffer[j]=='\r')||(av_buffer[j]=='\n'))
737 /* pass the mailfile to fsecure */
738 file_name = string_sprintf("SCAN\t%s\n", eml_filename);
740 if (m_sock_send(sock, file_name, Ustrlen(file_name), &errstr) < 0)
741 return m_errlog_defer(scanent, errstr);
744 /* todo also SUSPICION\t */
745 fs_inf = m_pcre_compile(US"\\S{0,5}INFECTED\\t[^\\t]*\\t([^\\t]+)\\t\\S*$", &errstr);
747 /* read report, linewise */
750 memset(av_buffer, 0, sizeof(av_buffer));
752 if ((bread= ip_recv(sock, &av_buffer[i], 1, MALWARE_TIMEOUT)) < 0)
753 return m_errlog_defer_3(scanent,
754 string_sprintf("unable to read result (%s)", strerror(errno)),
756 } while (++i < sizeof(av_buffer)-1 && av_buffer[i-1] != '\n');
757 av_buffer[i-1] = '\0';
759 /* Really search for virus again? */
760 if (malware_name == NULL)
761 /* try matcher on the line, grab substring */
762 malware_name = m_pcre_exec(fs_inf, av_buffer);
764 while (Ustrstr(av_buffer, "OK\tScan ok.") == NULL);
768 case M_KAVD: /* "kavdaemon" scanner type -------------------------------- */
772 uschar * scanrequest;
774 unsigned long kav_reportlen, bread;
778 /* get current date and time, build scan request */
780 /* pdp note: before the eml_filename parameter, this scanned the
781 directory; not finding documentation, so we'll strip off the directory.
782 The side-effect is that the test framework scanning may end up in
783 scanning more than was requested, but for the normal interface, this is
786 strftime(CS tmpbuf, sizeof(tmpbuf), "%d %b %H:%M:%S", localtime(&t));
787 scanrequest = string_sprintf("<0>%s:%s", CS tmpbuf, eml_filename);
788 p = Ustrrchr(scanrequest, '/');
792 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
793 scanner_name, scanner_options);
795 /* send scan request */
796 if (m_sock_send(sock, scanrequest, Ustrlen(scanrequest)+1, &errstr) < 0)
797 return m_errlog_defer(scanent, errstr);
799 /* wait for result */
800 if ((bread = recv(sock, tmpbuf, 2, 0) != 2))
801 return m_errlog_defer_3(scanent,
802 US"unable to read 2 bytes from socket.", sock);
804 /* get errorcode from one nibble */
805 kav_rc = tmpbuf[ test_byte_order()==LITTLE_MY_ENDIAN ? 0 : 1 ] & 0x0F;
808 case 5: case 6: /* improper kavdaemon configuration */
809 return m_errlog_defer_3(scanent,
810 US"please reconfigure kavdaemon to NOT disinfect or remove infected files.",
813 return m_errlog_defer_3(scanent,
814 US"reported 'scanning not completed' (code 1).", sock);
816 return m_errlog_defer_3(scanent,
817 US"reported 'kavdaemon damaged' (code 7).", sock);
820 /* code 8 is not handled, since it is ambigous. It appears mostly on
821 bounces where part of a file has been cut off */
823 /* "virus found" return codes (2-4) */
824 if ((kav_rc > 1) && (kav_rc < 5)) {
827 /* setup default virus name */
828 malware_name = US"unknown";
830 report_flag = tmpbuf[ test_byte_order() == LITTLE_MY_ENDIAN ? 1 : 0 ];
832 /* read the report, if available */
833 if( report_flag == 1 ) {
834 /* read report size */
835 if ((bread = recv(sock, &kav_reportlen, 4, 0)) != 4)
836 return m_errlog_defer_3(scanent,
837 US"cannot read report size", sock);
839 /* it's possible that avp returns av_buffer[1] == 1 but the
840 reportsize is 0 (!?) */
841 if (kav_reportlen > 0) {
842 /* set up match regex, depends on retcode */
843 kav_re = m_pcre_compile( kav_rc == 3
844 ? US"suspicion:\\s*(.+?)\\s*$"
845 : US"infected:\\s*(.+?)\\s*$",
848 /* read report, linewise */
849 while (kav_reportlen > 0) {
851 while ( recv(sock, &tmpbuf[bread], 1, 0) == 1 ) {
853 if ( (tmpbuf[bread] == '\n') || (bread > 1021) ) break;
857 tmpbuf[bread] = '\0';
859 /* try matcher on the line, grab substring */
860 if ((malware_name = m_pcre_exec(kav_re, tmpbuf)))
866 else /* no virus found */
872 case M_CMDL: /* "cmdline" scanner type ---------------------------------- */
874 const uschar *cmdline_scanner = scanner_options;
875 const pcre *cmdline_trigger_re;
876 const pcre *cmdline_regex_re;
878 uschar * commandline;
879 void (*eximsigchld)(int);
880 void (*eximsigpipe)(int);
881 FILE *scanner_out = NULL;
882 FILE *scanner_record = NULL;
883 uschar linebuffer[32767];
887 if (!cmdline_scanner)
888 return m_errlog_defer(scanent, errstr);
890 /* find scanner output trigger */
891 cmdline_trigger_re = m_pcre_nextinlist(&av_scanner_work, &sep,
892 "missing trigger specification", &errstr);
893 if (!cmdline_trigger_re)
894 return m_errlog_defer(scanent, errstr);
896 /* find scanner name regex */
897 cmdline_regex_re = m_pcre_nextinlist(&av_scanner_work, &sep,
898 "missing virus name regex specification", &errstr);
899 if (!cmdline_regex_re)
900 return m_errlog_defer(scanent, errstr);
902 /* prepare scanner call; despite the naming, file_name holds a directory
903 name which is documented as the value given to %s. */
905 file_name = string_copy(eml_filename);
906 p = Ustrrchr(file_name, '/');
909 commandline = string_sprintf(CS cmdline_scanner, file_name);
911 /* redirect STDERR too */
912 commandline = string_sprintf("%s 2>&1", commandline);
914 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n", scanner_name, commandline);
916 /* store exims signal handlers */
917 eximsigchld = signal(SIGCHLD,SIG_DFL);
918 eximsigpipe = signal(SIGPIPE,SIG_DFL);
920 if (!(scanner_out = popen(CS commandline,"r"))) {
922 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
923 return m_errlog_defer(scanent,
924 string_sprintf("call (%s) failed: %s.", commandline, strerror(err)));
927 file_name = string_sprintf("%s/scan/%s/%s_scanner_output",
928 spool_directory, message_id, message_id);
929 scanner_record = modefopen(file_name, "wb", SPOOL_MODE);
931 if (scanner_record == NULL) {
933 (void) pclose(scanner_out);
934 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
935 return m_errlog_defer(scanent,
936 string_sprintf("opening scanner output file (%s) failed: %s.",
937 file_name, strerror(err)));
940 /* look for trigger while recording output */
941 while(fgets(CS linebuffer, sizeof(linebuffer), scanner_out)) {
942 if ( Ustrlen(linebuffer) > fwrite(linebuffer, 1, Ustrlen(linebuffer), scanner_record) ) {
944 (void) pclose(scanner_out);
945 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
946 return m_errlog_defer(scanent,
947 string_sprintf("short write on scanner output file (%s).", file_name));
949 /* try trigger match */
950 if (!trigger && regex_match_and_setup(cmdline_trigger_re, linebuffer, 0, -1))
954 (void)fclose(scanner_record);
955 sep = pclose(scanner_out);
956 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
958 return m_errlog_defer(scanent,
960 ? string_sprintf("running scanner failed: %s", strerror(sep))
961 : string_sprintf("scanner returned error code: %d", sep));
965 /* setup default virus name */
966 malware_name = US"unknown";
968 /* re-open the scanner output file, look for name match */
969 scanner_record = fopen(CS file_name, "rb");
970 while(fgets(CS linebuffer, sizeof(linebuffer), scanner_record)) {
972 if ((s = m_pcre_exec(cmdline_regex_re, linebuffer)))
975 (void)fclose(scanner_record);
977 else /* no virus found */
982 case M_SOPHIE: /* "sophie" scanner type --------------------------------- */
987 uschar av_buffer[1024];
989 /* pass the scan directory to sophie */
990 file_name = string_copy(eml_filename);
991 if ((p = Ustrrchr(file_name, '/')))
994 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
995 scanner_name, scanner_options);
997 if ( write(sock, file_name, Ustrlen(file_name)) < 0
998 || write(sock, "\n", 1) != 1
1000 return m_errlog_defer_3(scanent,
1001 string_sprintf("unable to write to UNIX socket (%s)", scanner_options),
1004 /* wait for result */
1005 memset(av_buffer, 0, sizeof(av_buffer));
1006 if ((!(bread = ip_recv(sock, av_buffer, sizeof(av_buffer), MALWARE_TIMEOUT)) > 0))
1007 return m_errlog_defer_3(scanent,
1008 string_sprintf("unable to read from UNIX socket (%s)", scanner_options),
1012 if (av_buffer[0] == '1') {
1013 uschar * s = Ustrchr(av_buffer, '\n');
1016 malware_name = string_copy(&av_buffer[2]);
1018 else if (!strncmp(CS av_buffer, "-1", 2))
1019 return m_errlog_defer_3(scanent, US"scanner reported error", sock);
1020 else /* all ok, no virus */
1021 malware_name = NULL;
1026 case M_CLAMD: /* "clamd" scanner type ----------------------------------- */
1028 /* This code was originally contributed by David Saez */
1029 /* There are three scanning methods available to us:
1030 * (1) Use the SCAN command, pointing to a file in the filesystem
1031 * (2) Use the STREAM command, send the data on a separate port
1032 * (3) Use the zINSTREAM command, send the data inline
1033 * The zINSTREAM command was introduced with ClamAV 0.95, which marked
1034 * STREAM deprecated; see: http://wiki.clamav.net/bin/view/Main/UpgradeNotes095
1035 * In Exim, we use SCAN if using a Unix-domain socket or explicitly told that
1036 * the TCP-connected daemon is actually local; otherwise we use zINSTREAM unless
1037 * WITH_OLD_CLAMAV_STREAM is defined.
1038 * See Exim bug 926 for details. */
1040 uschar *p, *vname, *result_tag, *response_end;
1043 uschar av_buffer[1024];
1044 uschar *hostname = US"";
1046 uschar *clamav_fbuf;
1047 int clam_fd, result;
1049 unsigned int fsize_uint;
1050 BOOL use_scan_command = FALSE;
1051 clamd_address_container * clamd_address_vector[MAX_CLAMD_SERVERS];
1053 int num_servers = 0;
1054 #ifdef WITH_OLD_CLAMAV_STREAM
1056 uschar av_buffer2[1024];
1059 uint32_t send_size, send_final_zeroblock;
1062 if (*scanner_options == '/')
1063 /* Local file; so we def want to use_scan_command and don't want to try
1064 * passing IP/port combinations */
1065 use_scan_command = TRUE;
1067 const uschar *address = scanner_options;
1068 uschar address_buffer[MAX_CLAMD_ADDRESS_LENGTH + 20];
1070 /* Go through the rest of the list of host/port and construct an array
1071 * of servers to try. The first one is the bit we just passed from
1072 * scanner_options so process that first and then scan the remainder of
1073 * the address buffer */
1075 clamd_address_container *this_clamd;
1077 /* The 'local' option means use the SCAN command over the network
1078 * socket (ie common file storage in use) */
1079 if (strcmpic(address,US"local") == 0) {
1080 use_scan_command = TRUE;
1084 /* XXX: If unsuccessful we should free this memory */
1086 (clamd_address_container *)store_get(sizeof(clamd_address_container));
1088 /* extract host and port part */
1089 if( sscanf(CS address, "%" MAX_CLAMD_ADDRESS_LENGTH_S "s %u",
1090 this_clamd->tcp_addr, &(this_clamd->tcp_port)) != 2 ) {
1091 (void) m_errlog_defer(scanent,
1092 string_sprintf("invalid address '%s'", address));
1096 clamd_address_vector[num_servers] = this_clamd;
1098 if (num_servers >= MAX_CLAMD_SERVERS) {
1099 (void) m_errlog_defer(scanent,
1100 US"More than " MAX_CLAMD_SERVERS_S " clamd servers "
1101 "specified; only using the first " MAX_CLAMD_SERVERS_S );
1104 } while ((address = string_nextinlist(&av_scanner_work, &sep,
1106 sizeof(address_buffer))) != NULL);
1108 /* check if we have at least one server */
1110 return m_errlog_defer(scanent,
1111 US"no useable server addresses in malware configuration option.");
1114 /* See the discussion of response formats below to see why we really don't
1115 like colons in filenames when passing filenames to ClamAV. */
1116 if (use_scan_command && Ustrchr(eml_filename, ':'))
1117 return m_errlog_defer(scanent,
1118 string_sprintf("local/SCAN mode incompatible with" \
1119 " : in path to email filename [%s]", eml_filename));
1121 /* We have some network servers specified */
1124 /* Confirmed in ClamAV source (0.95.3) that the TCPAddr option of clamd
1125 * only supports AF_INET, but we should probably be looking to the
1126 * future and rewriting this to be protocol-independent anyway. */
1128 while ( num_servers > 0 ) {
1129 /* Randomly pick a server to start with */
1130 current_server = random_number( num_servers );
1132 debug_printf("trying server name %s, port %u\n",
1133 clamd_address_vector[current_server]->tcp_addr,
1134 clamd_address_vector[current_server]->tcp_port);
1136 /* Lookup the host. This is to ensure that we connect to the same IP
1137 * on both connections (as one host could resolve to multiple ips) */
1138 sock= m_tcpsocket(clamd_address_vector[current_server]->tcp_addr,
1139 clamd_address_vector[current_server]->tcp_port,
1140 &connhost, &errstr);
1142 /* Connection successfully established with a server */
1143 hostname = clamd_address_vector[current_server]->tcp_addr;
1147 (void) m_errlog_defer(scanent, errstr);
1149 /* Remove the server from the list. XXX We should free the memory */
1152 for( i = current_server; i < num_servers; i++ )
1153 clamd_address_vector[i] = clamd_address_vector[i+1];
1156 if ( num_servers == 0 )
1157 return m_errlog_defer(scanent, US"all servers failed");
1160 if ((sock = m_unixsocket(scanner_options, &errstr)) < 0)
1161 return m_errlog_defer(scanent, errstr);
1164 /* have socket in variable "sock"; command to use is semi-independent of
1165 * the socket protocol. We use SCAN if is local (either Unix/local
1166 * domain socket, or explicitly told local) else we stream the data.
1167 * How we stream the data depends upon how we were built. */
1169 if (!use_scan_command) {
1171 #ifdef WITH_OLD_CLAMAV_STREAM
1172 /* "STREAM\n" command, get back a "PORT <N>\n" response, send data to
1173 * that port on a second connection; then in the scan-method-neutral
1174 * part, read the response back on the original connection. */
1176 DEBUG(D_acl) debug_printf("Malware scan: issuing %s old-style remote scan (PORT)\n",
1179 /* Pass the string to ClamAV (7 = "STREAM\n") */
1180 if (m_sock_send(sock, US"STREAM\n", 7, &errstr) < 0)
1181 return m_errlog_defer(scanent, errstr);
1183 memset(av_buffer2, 0, sizeof(av_buffer2));
1184 bread = ip_recv(sock, av_buffer2, sizeof(av_buffer2), MALWARE_TIMEOUT);
1187 return m_errlog_defer_3(scanent,
1188 string_sprintf("unable to read PORT from socket (%s)",
1192 if (bread == sizeof(av_buffer2))
1193 return m_errlog_defer_3(scanent, "buffer too small", sock);
1196 return m_errlog_defer_3(scanent, "ClamAV returned null", sock);
1198 av_buffer2[bread] = '\0';
1199 if( sscanf(CS av_buffer2, "PORT %u\n", &port) != 1 )
1200 return m_errlog_defer_3(scanent,
1201 string_sprintf("Expected port information from clamd, got '%s'",
1205 sockData = m_tcpsocket(connhost.address, port, NULL, &errstr);
1207 return m_errlog_defer_3(scanent, errstr, sock);
1209 #define CLOSE_SOCKDATA (void)close(sockData)
1210 #else /* WITH_OLD_CLAMAV_STREAM not defined */
1211 /* New protocol: "zINSTREAM\n" followed by a sequence of <length><data>
1212 chunks, <n> a 4-byte number (network order), terminated by a zero-length
1215 DEBUG(D_acl) debug_printf("Malware scan: issuing %s new-style remote scan (zINSTREAM)\n",
1218 /* Pass the string to ClamAV (10 = "zINSTREAM\0") */
1219 if (send(sock, "zINSTREAM", 10, 0) < 0)
1220 return m_errlog_defer_3(scanent,
1221 string_sprintf("unable to send zINSTREAM to socket (%s)",
1225 #define CLOSE_SOCKDATA /**/
1228 /* calc file size */
1229 if ((clam_fd = open(CS eml_filename, O_RDONLY)) < 0) {
1232 return m_errlog_defer_3(scanent,
1233 string_sprintf("can't open spool file %s: %s",
1234 eml_filename, strerror(err)),
1237 if ((fsize = lseek(clam_fd, 0, SEEK_END)) < 0) {
1239 CLOSE_SOCKDATA; (void)close(clam_fd);
1240 return m_errlog_defer_3(scanent,
1241 string_sprintf("can't seek spool file %s: %s",
1242 eml_filename, strerror(err)),
1245 fsize_uint = (unsigned int) fsize;
1246 if ((off_t)fsize_uint != fsize) {
1247 CLOSE_SOCKDATA; (void)close(clam_fd);
1248 return m_errlog_defer_3(scanent,
1249 string_sprintf("seeking spool file %s, size overflow",
1253 lseek(clam_fd, 0, SEEK_SET);
1255 if (!(clamav_fbuf = (uschar *) malloc (fsize_uint))) {
1256 CLOSE_SOCKDATA; (void)close(clam_fd);
1257 return m_errlog_defer_3(scanent,
1258 string_sprintf("unable to allocate memory %u for file (%s)",
1259 fsize_uint, eml_filename),
1263 if ((result = read(clam_fd, clamav_fbuf, fsize_uint)) < 0) {
1265 free(clamav_fbuf); CLOSE_SOCKDATA; (void)close(clam_fd);
1266 return m_errlog_defer_3(scanent,
1267 string_sprintf("can't read spool file %s: %s",
1268 eml_filename, strerror(err)),
1271 (void)close(clam_fd);
1273 /* send file body to socket */
1274 #ifdef WITH_OLD_CLAMAV_STREAM
1275 if (send(sockData, clamav_fbuf, fsize_uint, 0) < 0) {
1276 free(clamav_fbuf); CLOSE_SOCKDATA;
1277 return m_errlog_defer_3(scanent,
1278 string_sprintf("unable to send file body to socket (%s:%u)",
1283 send_size = htonl(fsize_uint);
1284 send_final_zeroblock = 0;
1285 if ((send(sock, &send_size, sizeof(send_size), 0) < 0) ||
1286 (send(sock, clamav_fbuf, fsize_uint, 0) < 0) ||
1287 (send(sock, &send_final_zeroblock, sizeof(send_final_zeroblock), 0) < 0))
1290 return m_errlog_defer_3(scanent,
1291 string_sprintf("unable to send file body to socket (%s)", hostname),
1299 #undef CLOSE_SOCKDATA
1301 } else { /* use scan command */
1302 /* Send a SCAN command pointing to a filename; then in the then in the
1303 * scan-method-neutral part, read the response back */
1305 /* ================================================================= */
1307 /* Prior to the reworking post-Exim-4.72, this scanned a directory,
1308 which dates to when ClamAV needed us to break apart the email into the
1309 MIME parts (eg, with the now deprecated demime condition coming first).
1310 Some time back, ClamAV gained the ability to deconstruct the emails, so
1311 doing this would actually have resulted in the mail attachments being
1312 scanned twice, in the broken out files and from the original .eml.
1313 Since ClamAV now handles emails (and has for quite some time) we can
1314 just use the email file itself. */
1315 /* Pass the string to ClamAV (7 = "SCAN \n" + \0) */
1316 file_name = string_sprintf("SCAN %s\n", eml_filename);
1318 DEBUG(D_acl) debug_printf("Malware scan: issuing %s local-path scan [%s]\n",
1319 scanner_name, scanner_options);
1321 if (send(sock, file_name, Ustrlen(file_name), 0) < 0)
1322 return m_errlog_defer_3(scanent,
1323 string_sprintf("unable to write to socket (%s)", strerror(errno)),
1326 /* Do not shut down the socket for writing; a user report noted that
1327 * clamd 0.70 does not react well to this. */
1329 /* Commands have been sent, no matter which scan method or connection
1330 * type we're using; now just read the result, independent of method. */
1332 /* Read the result */
1333 memset(av_buffer, 0, sizeof(av_buffer));
1334 bread = ip_recv(sock, av_buffer, sizeof(av_buffer), MALWARE_TIMEOUT);
1339 return m_errlog_defer(scanent,
1340 string_sprintf("unable to read from socket (%s)", strerror(errno)));
1342 if (bread == sizeof(av_buffer))
1343 return m_errlog_defer(scanent, US"buffer too small");
1344 /* We're now assured of a NULL at the end of av_buffer */
1346 /* Check the result. ClamAV returns one of two result formats.
1347 In the basic mode, the response is of the form:
1348 infected: -> "<filename>: <virusname> FOUND"
1349 not-infected: -> "<filename>: OK"
1350 error: -> "<filename>: <errcode> ERROR
1351 If the ExtendedDetectionInfo option has been turned on, then we get:
1352 "<filename>: <virusname>(<virushash>:<virussize>) FOUND"
1353 for the infected case. Compare:
1354 /tmp/eicar.com: Eicar-Test-Signature FOUND
1355 /tmp/eicar.com: Eicar-Test-Signature(44d88612fea8a8f36de82e1278abb02f:68) FOUND
1357 In the streaming case, clamd uses the filename "stream" which you should
1358 be able to verify with { ktrace clamdscan --stream /tmp/eicar.com }. (The
1359 client app will replace "stream" with the original filename before returning
1360 results to stdout, but the trace shows the data).
1362 We will assume that the pathname passed to clamd from Exim does not contain
1363 a colon. We will have whined loudly above if the eml_filename does (and we're
1364 passing a filename to clamd). */
1367 return m_errlog_defer(scanent, US"ClamAV returned null");
1369 /* strip newline at the end (won't be present for zINSTREAM)
1370 (also any trailing whitespace, which shouldn't exist, but we depend upon
1371 this below, so double-check) */
1372 p = av_buffer + Ustrlen(av_buffer) - 1;
1373 if (*p == '\n') *p = '\0';
1375 DEBUG(D_acl) debug_printf("Malware response: %s\n", av_buffer);
1377 while (isspace(*--p) && (p > av_buffer))
1382 /* colon in returned output? */
1383 if((p = Ustrchr(av_buffer,':')) == NULL)
1384 return m_errlog_defer(scanent,
1385 string_sprintf("ClamAV returned malformed result (missing colon): %s",
1388 /* strip filename */
1389 while (*p && isspace(*++p)) /**/;
1392 /* It would be bad to encounter a virus with "FOUND" in part of the name,
1393 but we should at least be resistant to it. */
1394 p = Ustrrchr(vname, ' ');
1395 result_tag = p ? p+1 : vname;
1397 if (Ustrcmp(result_tag, "FOUND") == 0) {
1398 /* p should still be the whitespace before the result_tag */
1399 while (isspace(*p)) --p;
1401 /* Strip off the extended information too, which will be in parens
1402 after the virus name, with no intervening whitespace. */
1404 /* "(hash:size)", so previous '(' will do; if not found, we have
1405 a curious virus name, but not an error. */
1406 p = Ustrrchr(vname, '(');
1410 malware_name = string_copy(vname);
1411 DEBUG(D_acl) debug_printf("Malware found, name \"%s\"\n", malware_name);
1413 } else if (Ustrcmp(result_tag, "ERROR") == 0)
1414 return m_errlog_defer(scanent,
1415 string_sprintf("ClamAV returned: %s", av_buffer));
1417 else if (Ustrcmp(result_tag, "OK") == 0) {
1418 /* Everything should be OK */
1419 malware_name = NULL;
1420 DEBUG(D_acl) debug_printf("Malware not found\n");
1423 return m_errlog_defer(scanent,
1424 string_sprintf("unparseable response from ClamAV: {%s}", av_buffer));
1429 case M_SOCK: /* "sock" scanner type ------------------------------------- */
1430 /* This code was derived by Martin Poole from the clamd code contributed
1431 by David Saez and the cmdline code
1435 uschar * commandline;
1436 uschar av_buffer[1024];
1437 uschar * linebuffer;
1438 uschar * sockline_scanner;
1439 uschar sockline_scanner_default[] = "%s\n";
1440 const pcre *sockline_trig_re;
1441 const pcre *sockline_name_re;
1443 /* find scanner command line */
1444 if ((sockline_scanner = string_nextinlist(&av_scanner_work, &sep,
1446 { /* check for no expansions apart from one %s */
1447 uschar * s = Ustrchr(sockline_scanner, '%');
1449 if ((*s != 's' && *s != '%') || Ustrchr(s+1, '%'))
1450 return m_errlog_defer_3(scanent,
1451 US"unsafe sock scanner call spec", sock);
1454 sockline_scanner = sockline_scanner_default;
1456 /* find scanner output trigger */
1457 sockline_trig_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1458 "missing trigger specification", &errstr);
1459 if (!sockline_trig_re)
1460 return m_errlog_defer_3(scanent, errstr, sock);
1462 /* find virus name regex */
1463 sockline_name_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1464 "missing virus name regex specification", &errstr);
1465 if (!sockline_name_re)
1466 return m_errlog_defer_3(scanent, errstr, sock);
1468 /* prepare scanner call - security depends on expansions check above */
1469 commandline = string_sprintf("%s/scan/%s/%s.eml", spool_directory, message_id, message_id);
1470 commandline = string_sprintf( CS sockline_scanner, CS commandline);
1473 /* Pass the command string to the socket */
1474 if (m_sock_send(sock, commandline, Ustrlen(commandline), &errstr) < 0)
1475 return m_errlog_defer(scanent, errstr);
1477 /* Read the result */
1478 memset(av_buffer, 0, sizeof(av_buffer));
1479 bread = read(sock, av_buffer, sizeof(av_buffer));
1482 return m_errlog_defer_3(scanent,
1483 string_sprintf("unable to read from socket (%s)", strerror(errno)),
1486 if (bread == sizeof(av_buffer))
1487 return m_errlog_defer_3(scanent, US"buffer too small", sock);
1488 linebuffer = string_copy(av_buffer);
1490 /* try trigger match */
1491 if (regex_match_and_setup(sockline_trig_re, linebuffer, 0, -1)) {
1492 if (!(malware_name = m_pcre_exec(sockline_name_re, av_buffer)))
1493 malware_name = US "unknown";
1495 else /* no virus found */
1496 malware_name = NULL;
1500 case M_MKSD: /* "mksd" scanner type ------------------------------------- */
1502 char *mksd_options_end;
1503 int mksd_maxproc = 1; /* default, if no option supplied */
1507 if (scanner_options) {
1508 mksd_maxproc = (int)strtol(CS scanner_options, &mksd_options_end, 10);
1509 if ( *scanner_options == '\0'
1510 || *mksd_options_end != '\0'
1512 || mksd_maxproc > 32
1514 return m_errlog_defer(scanent,
1515 string_sprintf("invalid option '%s'", scanner_options));
1518 if((sock = m_unixsocket(US "/var/run/mksd/socket", &errstr)) < 0)
1519 return m_errlog_defer(scanent, errstr);
1521 malware_name = NULL;
1523 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan\n", scanner_name);
1525 if ((retval = mksd_scan_packed(scanent, sock, eml_filename)) != OK) {
1531 case M_AVAST: /* "avast" scanner type ----------------------------------- */
1535 uschar * scanrequest;
1536 const pcre * avast_clean_re, * avast_virus_re;
1537 enum {AVA_HELO, AVA_OPT, AVA_RSP, AVA_DONE} avast_stage;
1539 /* According to Martin Tuma @avast the protocol uses "escaped
1540 whitespace", that is, every embedded whitespace is backslash
1541 escaped, as well as backslash is protected by backslash.
1542 The returned lines contain the name of the scanned file, a tab
1546 [E] - some error occured
1547 Such marker follows the first non-escaped TAB. */
1548 if ( !(avast_clean_re =
1549 m_pcre_compile(US"(?!\\\\)\\t\\[\\+\\]", &errstr))
1550 || !(avast_virus_re =
1551 m_pcre_compile(US"(?!\\\\)\\t\\[L\\]\\d\\.\\d\\t\\d\\s(.*)",
1554 return malware_errlog_defer(errstr);
1556 /* wait for result */
1557 for (avast_stage = AVA_HELO; recv_line(sock, buf, sizeof(buf)) > 0; )
1559 int slen = Ustrlen(buf);
1562 DEBUG(D_acl) debug_printf("got from avast: %s\n", buf);
1563 switch (avast_stage)
1566 if (Ustrncmp(buf, "220", 3) != 0)
1567 goto endloop; /* require a 220 */
1571 if (Ustrncmp(buf, "210", 3) == 0)
1572 break; /* ignore 210 responses */
1573 if (Ustrncmp(buf, "200", 3) != 0)
1574 goto endloop; /* require a 200 */
1577 /* Check for another option to send. Newline-terminate it. */
1578 if ((scanrequest = string_nextinlist(&av_scanner_work, &sep,
1581 scanrequest = string_sprintf("%s\n", scanrequest);
1582 avast_stage = AVA_OPT; /* just sent option */
1586 scanrequest = string_sprintf("SCAN %s/scan/%s\r\n",
1587 spool_directory, message_id);
1588 avast_stage = AVA_RSP; /* just sent command */
1591 /* send config-cmd or scan-request to socket */
1592 if (send(sock, scanrequest, Ustrlen(scanrequest), 0) < 0)
1593 return m_errlog_defer_3(scanent, string_sprintf(
1594 "unable to send scan request to socket (%s): %s",
1595 scanner_options, strerror(errno)),
1600 if (Ustrncmp(buf, "210", 3) == 0)
1601 break; /* ignore the "210 SCAN DATA" message */
1603 if (pcre_exec(avast_clean_re, NULL, CS buf, slen,
1604 0, 0, ovector, nelements(ovector)) > 0)
1607 if ((malware_name = m_pcre_exec(avast_virus_re, buf)))
1608 { /* remove backslash in front of [whitespace|backslash] */
1610 for (p = malware_name; *p; ++p)
1611 if (*p == '\\' && (isspace(p[1]) || p[1] == '\\'))
1612 for (p0 = p; *p0; ++p0) *p0 = p0[1];
1614 avast_stage = AVA_DONE;
1618 if (Ustrncmp(buf, "200 SCAN OK", 11) == 0)
1619 { /* we're done finally */
1620 if (send(sock, "QUIT\n", 5, 0) < 0) /* courtesy */
1621 return m_errlog_defer_3(scanent, string_sprintf(
1622 "unable to send quit request to socket (%s): %s",
1623 scanner_options, strerror(errno)),
1625 malware_name = NULL;
1626 avast_stage = AVA_DONE;
1630 /* here for any unexpected response from the scanner */
1641 case AVA_RSP: return m_errlog_defer_3(scanent, string_sprintf(
1642 "invalid response from scanner: %s\n", buf), sock);
1646 } /* scanner type switch */
1649 (void) close (sock);
1650 malware_ok = TRUE; /* set "been here, done that" marker */
1653 /* match virus name against pattern (caseless ------->----------v) */
1654 if (malware_name && regex_match_and_setup(re, malware_name, 0, -1))
1656 DEBUG(D_acl) debug_printf("Matched regex to malware [%s] [%s]\n", malware_regex, malware_name);
1664 /* simple wrapper for reading lines from sockets */
1666 recv_line(int sock, uschar *buffer, int size)
1670 memset(buffer,0,size);
1672 while(recv(sock,p,1,0) > -1) {
1673 if ((p-buffer) > (size-2)) break;
1674 if (*p == '\n') break;
1675 if (*p != '\r') p++;
1683 /* ============= private routines for the "mksd" scanner type ============== */
1685 #include <sys/uio.h>
1688 mksd_writev (int sock, struct iovec *iov, int iovcnt)
1694 i = writev (sock, iov, iovcnt);
1695 while ((i < 0) && (errno == EINTR));
1697 (void) malware_errlog_defer(US"unable to write to mksd UNIX socket (/var/run/mksd/socket)");
1702 if (i >= iov->iov_len) {
1709 iov->iov_base = CS iov->iov_base + i;
1716 mksd_read_lines (int sock, uschar *av_buffer, int av_buffer_size)
1722 if ((i = recv (sock, av_buffer+offset, av_buffer_size-offset, 0)) <= 0) {
1723 (void) malware_errlog_defer(US"unable to read from mksd UNIX socket (/var/run/mksd/socket)");
1728 /* offset == av_buffer_size -> buffer full */
1729 if (offset == av_buffer_size) {
1730 (void) malware_errlog_defer(US"malformed reply received from mksd");
1733 } while (av_buffer[offset-1] != '\n');
1735 av_buffer[offset] = '\0';
1740 mksd_parse_line(struct scan * scanent, char *line)
1750 if ((p = strchr (line, '\n')) != NULL)
1752 return m_errlog_defer(scanent,
1753 string_sprintf("scanner failed: %s", line));
1756 if ((p = strchr (line, '\n')) != NULL) {
1758 if (((p-line) > 5) && (line[3] == ' '))
1759 if (((p = strchr (line+4, ' ')) != NULL) && ((p-line) > 4)) {
1761 malware_name = string_copy(US line+4);
1765 return m_errlog_defer(scanent,
1766 string_sprintf("malformed reply received: %s", line));
1771 mksd_scan_packed(struct scan * scanent, int sock, uschar *scan_filename)
1773 struct iovec iov[3];
1774 const char *cmd = "MSQ\n";
1775 uschar av_buffer[1024];
1777 iov[0].iov_base = (void *) cmd;
1779 iov[1].iov_base = CS scan_filename;
1780 iov[1].iov_len = Ustrlen(scan_filename);
1781 iov[2].iov_base = (void *) (cmd + 3);
1784 if (mksd_writev (sock, iov, 3) < 0)
1787 if (mksd_read_lines (sock, av_buffer, sizeof (av_buffer)) < 0)
1790 return mksd_parse_line (scanent, CS av_buffer);
1793 #endif /*WITH_CONTENT_SCAN*/