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;
51 # define nelements(arr) (sizeof(arr) / sizeof(arr[0]))
55 #define MALWARE_TIMEOUT 120 /* default timeout, seconds */
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" */
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 */
68 static const uschar * malware_regex_default = US ".+";
69 static const pcre * malware_default_re = NULL;
71 static const uschar * drweb_re_str = US "infected\\swith\\s*(.+?)$";
72 static const pcre * drweb_re = NULL;
74 static const uschar * fsec_re_str = US "\\S{0,5}INFECTED\\t[^\\t]*\\t([^\\t]+)\\t\\S*$";
75 static const pcre * fsec_re = NULL;
77 static const uschar * kav_re_sus_str = US "suspicion:\\s*(.+?)\\s*$";
78 static const uschar * kav_re_inf_str = US "infected:\\s*(.+?)\\s*$";
79 static const pcre * kav_re_sus = NULL;
80 static const pcre * kav_re_inf = NULL;
82 static const uschar * ava_re_clean_str = US "(?!\\\\)\\t\\[\\+\\]";
83 static const uschar * ava_re_virus_str = US "(?!\\\\)\\t\\[L\\]\\d\\.\\d\\t\\d\\s(.*)";
84 static const pcre * ava_re_clean = NULL;
85 static const pcre * ava_re_virus = NULL;
89 /******************************************************************************/
91 /* Routine to check whether a system is big- or little-endian.
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
96 static int test_byte_order(void);
100 short int word = 0x0001;
101 char *byte = (char *) &word;
102 return(byte[0] ? LITTLE_MY_ENDIAN : BIG_MY_ENDIAN);
105 BOOL malware_ok = FALSE;
107 /* Gross hacks for the -bmalware option; perhaps we should just create
108 the scan directory normally for that case, but look into rigging up the
109 needed header variables if not already set on the command-line? */
110 extern int spool_mbox_ok;
111 extern uschar spooled_message_id[17];
116 malware_errlog_defer(const uschar * str)
118 log_write(0, LOG_MAIN|LOG_PANIC, "malware acl condition: %s", str);
123 m_errlog_defer(struct scan * scanent, const uschar * str)
125 return malware_errlog_defer(string_sprintf("%s: %s", scanent->name, str));
128 m_errlog_defer_3(struct scan * scanent, const uschar * str,
131 (void) close(fd_to_close);
132 return m_errlog_defer(scanent, str);
135 /*************************************************/
137 /* Only used by the Clamav code, which is working from a list of servers and
138 uses the returned in_addr to get a second connection to the same system.
141 m_tcpsocket(const uschar * hostname, unsigned int port,
142 host_item * host, uschar ** errstr)
144 return ip_connectedsocket(SOCK_STREAM, hostname, port, port, 5, host, errstr);
148 m_tcpsocket_fromdef(const uschar * hostport, uschar ** errstr)
151 uschar hostname[256];
152 unsigned int portlow, porthigh;
154 /* extract host and port part */
155 scan = sscanf(CS hostport, "%255s %u-%u", hostname, &portlow, &porthigh);
158 *errstr = string_sprintf("invalid socket '%s'", hostport);
164 return ip_connectedsocket(SOCK_STREAM, hostname, portlow, porthigh,
169 m_unixsocket(const uschar * path, uschar ** errstr)
172 struct sockaddr_un server;
174 if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
175 *errstr = US"can't open UNIX socket.";
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) {
185 *errstr = string_sprintf("unable to connect to UNIX socket (%s): %s",
186 path, strerror(err));
193 m_streamsocket(const uschar * spec, uschar ** errstr)
196 ? m_unixsocket(spec, errstr) : m_tcpsocket_fromdef(spec, errstr);
200 m_sock_send(int sock, uschar * buf, int cnt, uschar ** errstr)
202 if (send(sock, buf, cnt, 0) < 0) {
205 *errstr = string_sprintf("unable to send to socket (%s): %s",
213 m_pcre_compile(const uschar * re, uschar ** errstr)
215 const uschar * rerror;
219 cre = pcre_compile(CS re, PCRE_COPT, (const char **)&rerror, &roffset, NULL);
221 *errstr= string_sprintf("regular expression error in '%s': %s at offset %d",
222 re, rerror, roffset);
227 m_pcre_exec(const pcre * cre, uschar * text)
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);
239 m_pcre_nextinlist(uschar ** list, int * sep, char * listerr, uschar ** errstr)
241 const uschar * list_ele;
242 const pcre * cre = NULL;
244 if (!(list_ele = string_nextinlist(list, sep, NULL, 0)))
245 *errstr = US listerr;
247 cre = m_pcre_compile(CUS list_ele, errstr);
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.
256 Return: number of chars - zero for an empty line
258 -2 on timeout or error
261 recv_line(int fd, uschar * buffer, int bsize, int tmo)
267 if (!fd_ready(fd, tmo-time(NULL)))
270 /*XXX tmo handling assumes we always get a whole line */
273 while ((rcv = read(fd, p, 1)) > 0)
276 if (p-buffer > bsize-2) break;
277 if (*p == '\n') break;
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;
288 DEBUG(D_acl) debug_printf("Malware scan: read '%s'\n", buffer);
292 /* return TRUE iff size as requested */
294 recv_len(int sock, void * buf, int size, int tmo)
296 return fd_ready(sock, tmo-time(NULL))
297 ? recv(sock, buf, size, 0) == size
303 /* ============= private routines for the "mksd" scanner type ============== */
308 mksd_writev (int sock, struct iovec * iov, int iovcnt)
315 i = writev (sock, iov, iovcnt);
316 while (i < 0 && errno == EINTR);
319 (void) malware_errlog_defer(
320 US"unable to write to mksd UNIX socket (/var/run/mksd/socket)");
323 for (;;) /* check for short write */
324 if (i >= iov->iov_len)
334 iov->iov_base = CS iov->iov_base + i;
341 mksd_read_lines (int sock, uschar *av_buffer, int av_buffer_size, int tmo)
348 i = ip_recv(sock, av_buffer+offset, av_buffer_size-offset, tmo-time(NULL));
351 (void) malware_errlog_defer(US"unable to read from mksd UNIX socket (/var/run/mksd/socket)");
356 /* offset == av_buffer_size -> buffer full */
357 if (offset == av_buffer_size)
359 (void) malware_errlog_defer(US"malformed reply received from mksd");
362 } while (av_buffer[offset-1] != '\n');
364 av_buffer[offset] = '\0';
369 mksd_parse_line(struct scan * scanent, char * line)
380 if ((p = strchr (line, '\n')) != NULL)
382 return m_errlog_defer(scanent,
383 string_sprintf("scanner failed: %s", line));
386 if ((p = strchr (line, '\n')) != NULL)
391 && (p = strchr(line+4, ' ')) != NULL
396 malware_name = string_copy(US line+4);
400 return m_errlog_defer(scanent,
401 string_sprintf("malformed reply received: %s", line));
406 mksd_scan_packed(struct scan * scanent, int sock, const uschar * scan_filename,
410 const char *cmd = "MSQ\n";
411 uschar av_buffer[1024];
413 iov[0].iov_base = (void *) cmd;
415 iov[1].iov_base = (void *) scan_filename;
416 iov[1].iov_len = Ustrlen(scan_filename);
417 iov[2].iov_base = (void *) (cmd + 3);
420 if (mksd_writev (sock, iov, 3) < 0)
423 if (mksd_read_lines (sock, av_buffer, sizeof (av_buffer), tmo) < 0)
426 return mksd_parse_line (scanent, CS av_buffer);
429 /*************************************************
430 * Scan content for malware *
431 *************************************************/
433 /* This is an internal interface for scanning an email; the normal interface
434 is via malware(), or there's malware_in_file() used for testing/debugging.
437 malware_re match condition for "malware="
438 eml_filename the file holding the email to be scanned
439 timeout if nonzero, non-default timeoutl
440 faking whether or not we're faking this up for the -bmalware test
442 Returns: Exim message processing code (OK, FAIL, DEFER, ...)
443 where true means malware was found (condition applies)
446 malware_internal(const uschar * malware_re, const uschar * eml_filename,
447 int timeout, BOOL faking)
450 uschar *av_scanner_work = av_scanner;
451 uschar *scanner_name;
452 unsigned long mbox_size;
456 struct scan * scanent;
457 const uschar * scanner_options;
461 /* make sure the eml mbox file is spooled up */
462 if (!(mbox_file = spool_mbox(&mbox_size, faking ? eml_filename : NULL)))
463 return malware_errlog_defer(US"error while creating mbox spool file");
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);
470 return FAIL; /* empty means "don't match anything" */
472 /* parse 1st option */
473 if ( (strcmpic(malware_re, US"false") == 0) ||
474 (Ustrcmp(malware_re,"0") == 0) )
475 return FAIL; /* explicitly no matching */
477 /* special cases (match anything except empty) */
478 if ( strcmpic(malware_re,US"true") == 0
479 || Ustrcmp(malware_re,"*") == 0
480 || Ustrcmp(malware_re,"1") == 0
483 if ( !malware_default_re
484 && !(malware_default_re = m_pcre_compile(malware_regex_default, &errstr)))
485 return malware_errlog_defer(errstr);
486 malware_re = malware_regex_default;
487 re = malware_default_re;
490 /* compile the regex, see if it works */
491 else if (!(re = m_pcre_compile(malware_re, &errstr)))
492 return malware_errlog_defer(errstr);
494 /* Reset sep that is set by previous string_nextinlist() call */
497 /* if av_scanner starts with a dollar, expand it first */
498 if (*av_scanner == '$')
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));
506 debug_printf("Expanded av_scanner global: %s\n", av_scanner_work);
507 /* disable result caching in this case */
512 /* Do not scan twice (unless av_scanner is dynamic). */
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;
521 for (scanent = m_scans; ; scanent++) {
523 return malware_errlog_defer(string_sprintf("unknown scanner type '%s'",
525 if (strcmpic(scanner_name, US scanent->name) != 0)
527 if (!(scanner_options = string_nextinlist(&av_scanner_work, &sep, NULL, 0)))
528 scanner_options = scanent->options_default;
529 if (scanent->conn == MC_NONE)
531 switch(scanent->conn)
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;
539 return m_errlog_defer(scanent, errstr);
542 DEBUG(D_acl) debug_printf("Malware scan: %s tmo %s\n", scanner_name, readconf_printtime(timeout));
544 switch (scanent->scancode)
546 case M_FPROTD: /* "f-protd" scanner type -------------------------------- */
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;
555 scanrequest = string_sprintf("GET %s", eml_filename);
557 while ((fp_scan_option = string_nextinlist(&av_scanner_work, &sep,
560 scanrequest = string_sprintf("%s%s%s", scanrequest,
561 par_count ? "%20" : "?", fp_scan_option);
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);
568 /* send scan request */
569 if (m_sock_send(sock, scanrequest, Ustrlen(scanrequest)+1, &errstr) < 0)
570 return m_errlog_defer(scanent, errstr);
572 while ((len = recv_line(sock, buf, sizeof(buf), tmo)) >= 0)
575 if (Ustrstr(buf, US"<detected type=\"") != NULL)
577 else if (detected && (strhelper = Ustrstr(buf, US"<name>")))
579 if ((strhelper2 = Ustrstr(buf, US"</name>")) != NULL)
582 malware_name_internal = string_copy(strhelper+6);
585 else if (Ustrstr(buf, US"<summary code=\""))
587 malware_name = Ustrstr(buf, US"<summary code=\"11\">")
588 ? malware_name_internal : NULL;
600 case M_DRWEB: /* "drweb" scanner type ----------------------------------- */
601 /* v0.1 - added support for tcp sockets */
602 /* v0.0 - initial release -- support for unix sockets */
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;
611 /* prepare variables */
612 drweb_cmd = htonl(DRWEBD_SCAN_CMD);
613 drweb_flags = htonl(DRWEBD_RETURN_VIRUSES | DRWEBD_IS_MAIL);
615 if (*scanner_options != '/')
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)),
624 if ((fsize = lseek(drweb_fd, 0, SEEK_END)) == -1)
627 (void)close(drweb_fd);
628 return m_errlog_defer_3(scanent,
629 string_sprintf("can't seek spool file %s: %s",
630 eml_filename, strerror(err)),
633 fsize_uint = (unsigned int) fsize;
634 if ((off_t)fsize_uint != fsize)
636 (void)close(drweb_fd);
637 return m_errlog_defer_3(scanent,
638 string_sprintf("seeking spool file %s, size overflow",
642 drweb_slen = htonl(fsize);
643 lseek(drweb_fd, 0, SEEK_SET);
645 DEBUG(D_acl) debug_printf("Malware scan: issuing %s remote scan [%s]\n",
646 scanner_name, scanner_options);
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))
654 (void)close(drweb_fd);
655 return m_errlog_defer_3(scanent, string_sprintf(
656 "unable to send commands to socket (%s)", scanner_options),
660 if (!(drweb_fbuf = (uschar *) malloc (fsize_uint)))
662 (void)close(drweb_fd);
663 return m_errlog_defer_3(scanent,
664 string_sprintf("unable to allocate memory %u for file (%s)",
665 fsize_uint, eml_filename),
669 if ((result = read (drweb_fd, drweb_fbuf, fsize)) == -1)
672 (void)close(drweb_fd);
674 return m_errlog_defer_3(scanent,
675 string_sprintf("can't read spool file %s: %s",
676 eml_filename, strerror(err)),
679 (void)close(drweb_fd);
681 /* send file body to socket */
682 if (send(sock, drweb_fbuf, fsize, 0) < 0)
685 return m_errlog_defer_3(scanent, string_sprintf(
686 "unable to send file body to socket (%s)", scanner_options),
689 (void)close(drweb_fd);
693 drweb_slen = htonl(Ustrlen(eml_filename));
695 DEBUG(D_acl) debug_printf("Malware scan: issuing %s local scan [%s]\n",
696 scanner_name, scanner_options);
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),
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);
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);
720 /* "virus(es) found" if virus number is > 0 */
725 /* setup default virus name */
726 malware_name = US"unknown";
728 /* set up match regex */
730 drweb_re = m_pcre_compile(drweb_re_str, &errstr);
732 /* read and concatenate virus names into one string */
733 for (i = 0; i < drweb_vnum; i++)
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))
738 return m_errlog_defer_3(scanent,
739 US"cannot read report size", sock);
740 drweb_slen = ntohl(drweb_slen);
741 tmpbuf = store_get(drweb_slen);
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';
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));
754 const char * pre_malware_nb;
756 pcre_get_substring(CS tmpbuf, ovector, result, 1, &pre_malware_nb);
758 if (i==0) /* the first name we just copy to malware_name */
759 malware_name = string_append(NULL, &size, &off,
762 else /* concatenate each new virus name to previous */
763 malware_name = string_append(malware_name, &size, &off,
764 2, "/", pre_malware_nb);
766 pcre_free_substring(pre_malware_nb);
772 const char *drweb_s = NULL;
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 */
783 return m_errlog_defer_3(scanent,
784 string_sprintf("drweb daemon retcode 0x%x (%s)", drweb_rc, drweb_s),
793 case M_AVES: /* "aveserver" scanner type -------------------------------- */
798 /* read aveserver's greeting and see if it is ready (2xx greeting) */
800 recv_line(sock, buf, sizeof(buf), tmo);
802 if (buf[0] != '2') /* aveserver is having problems */
803 return m_errlog_defer_3(scanent,
804 string_sprintf("unavailable (Responded: %s).",
805 ((buf[0] != 0) ? buf : (uschar *)"nothing") ),
808 /* prepare our command */
809 (void)string_format(buf, sizeof(buf), "SCAN bPQRSTUW %s\r\n",
813 DEBUG(D_acl) debug_printf("Malware scan: issuing %s %s\n",
815 if (m_sock_send(sock, buf, Ustrlen(buf), &errstr) < 0)
816 return m_errlog_defer(scanent, errstr);
820 /* read response lines, find malware name and final response */
821 while (recv_line(sock, buf, sizeof(buf), tmo) > 0)
825 if (buf[0] == '5') /* aveserver is having problems */
827 result = m_errlog_defer(scanent,
828 string_sprintf("unable to scan file %s (Responded: %s).",
832 if (Ustrncmp(buf,"322",3) == 0)
834 uschar *p = Ustrchr(&buf[4], ' ');
836 malware_name = string_copy(&buf[4]);
840 if (m_sock_send(sock, US"quit\r\n", 6, &errstr) < 0)
841 return m_errlog_defer(scanent, errstr);
843 /* read aveserver's greeting and see if it is ready (2xx greeting) */
845 recv_line(sock, buf, sizeof(buf), tmo);
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") ),
861 case M_FSEC: /* "fsecure" scanner type ---------------------------------- */
865 uschar av_buffer[1024];
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" };
873 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
874 scanner_name, scanner_options);
876 memset(av_buffer, 0, sizeof(av_buffer));
877 for (i = 0; i != nelements(cmdopt); i++)
880 if (m_sock_send(sock, cmdopt[i], Ustrlen(cmdopt[i]), &errstr) < 0)
881 return m_errlog_defer(scanent, errstr);
883 bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL));
884 if (bread > 0) av_buffer[bread]='\0';
886 return m_errlog_defer_3(scanent,
887 string_sprintf("unable to read answer %d (%s)", i, strerror(errno)),
889 for (j = 0; j < bread; j++)
890 if (av_buffer[j] == '\r' || av_buffer[j] == '\n')
894 /* pass the mailfile to fsecure */
895 file_name = string_sprintf("SCAN\t%s\n", eml_filename);
897 if (m_sock_send(sock, file_name, Ustrlen(file_name), &errstr) < 0)
898 return m_errlog_defer(scanent, errstr);
901 /* todo also SUSPICION\t */
903 fsec_re = m_pcre_compile(fsec_re_str, &errstr);
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 */
908 uschar * p = av_buffer;
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)),
920 for (p[bread] = '\0'; q = strchr(p, '\n'); p = q+1)
924 /* Really search for virus again? */
926 /* try matcher on the line, grab substring */
927 malware_name = m_pcre_exec(fsec_re, p);
929 if (Ustrstr(p, "OK\tScan ok."))
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);
944 case M_KAVD: /* "kavdaemon" scanner type -------------------------------- */
948 uschar * scanrequest;
950 unsigned long kav_reportlen, bread;
954 /* get current date and time, build scan request */
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
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, '/');
968 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
969 scanner_name, scanner_options);
971 /* send scan request */
972 if (m_sock_send(sock, scanrequest, Ustrlen(scanrequest)+1, &errstr) < 0)
973 return m_errlog_defer(scanent, errstr);
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);
980 /* get errorcode from one nibble */
981 kav_rc = tmpbuf[ test_byte_order()==LITTLE_MY_ENDIAN ? 0 : 1 ] & 0x0F;
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.",
989 return m_errlog_defer_3(scanent,
990 US"reported 'scanning not completed' (code 1).", sock);
992 return m_errlog_defer_3(scanent,
993 US"reported 'kavdaemon damaged' (code 7).", sock);
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 */
999 /* "virus found" return codes (2-4) */
1000 if (kav_rc > 1 && kav_rc < 5)
1002 int report_flag = 0;
1004 /* setup default virus name */
1005 malware_name = US"unknown";
1007 report_flag = tmpbuf[ test_byte_order() == LITTLE_MY_ENDIAN ? 1 : 0 ];
1009 /* read the report, if available */
1010 if (report_flag == 1)
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);
1017 /* it's possible that avp returns av_buffer[1] == 1 but the
1018 reportsize is 0 (!?) */
1019 if (kav_reportlen > 0)
1021 /* set up match regex, depends on retcode */
1024 if (!kav_re_sus) kav_re_sus = m_pcre_compile(kav_re_sus_str, &errstr);
1025 kav_re = kav_re_sus;
1029 if (!kav_re_inf) kav_re_inf = m_pcre_compile(kav_re_inf_str, &errstr);
1030 kav_re = kav_re_inf;
1033 /* read report, linewise */
1034 while (kav_reportlen > 0)
1036 if ((bread = recv_line(sock, tmpbuf, sizeof(tmpbuf), tmo)) < 0)
1038 kav_reportlen -= bread+1;
1040 /* try matcher on the line, grab substring */
1041 if ((malware_name = m_pcre_exec(kav_re, tmpbuf)))
1047 else /* no virus found */
1048 malware_name = NULL;
1053 case M_CMDL: /* "cmdline" scanner type ---------------------------------- */
1055 const uschar *cmdline_scanner = scanner_options;
1056 const pcre *cmdline_trigger_re;
1057 const pcre *cmdline_regex_re;
1059 uschar * commandline;
1060 void (*eximsigchld)(int);
1061 void (*eximsigpipe)(int);
1062 FILE *scanner_out = NULL;
1064 FILE *scanner_record = NULL;
1065 uschar linebuffer[32767];
1070 if (!cmdline_scanner)
1071 return m_errlog_defer(scanent, errstr);
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);
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);
1085 /* prepare scanner call; despite the naming, file_name holds a directory
1086 name which is documented as the value given to %s. */
1088 file_name = string_copy(eml_filename);
1089 p = Ustrrchr(file_name, '/');
1092 commandline = string_sprintf(CS cmdline_scanner, file_name);
1094 /* redirect STDERR too */
1095 commandline = string_sprintf("%s 2>&1", commandline);
1097 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
1098 scanner_name, commandline);
1100 /* store exims signal handlers */
1101 eximsigchld = signal(SIGCHLD,SIG_DFL);
1102 eximsigpipe = signal(SIGPIPE,SIG_DFL);
1104 if (!(scanner_out = popen(CS commandline,"r")))
1107 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1108 return m_errlog_defer(scanent,
1109 string_sprintf("call (%s) failed: %s.", commandline, strerror(err)));
1111 scanner_fd = fileno(scanner_out);
1113 file_name = string_sprintf("%s/scan/%s/%s_scanner_output",
1114 spool_directory, message_id, message_id);
1116 if (!(scanner_record = modefopen(file_name, "wb", SPOOL_MODE)))
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)));
1126 /* look for trigger while recording output */
1127 while ((rcnt = recv_line(scanner_fd, linebuffer,
1128 sizeof(linebuffer), tmo)))
1136 (void) pclose(scanner_out);
1137 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1138 return m_errlog_defer(scanent, string_sprintf(
1139 "unable to read from scanner (%s): %s",
1140 commandline, strerror(err)));
1143 if (Ustrlen(linebuffer) > fwrite(linebuffer, 1, Ustrlen(linebuffer), scanner_record))
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));
1151 putc('\n', scanner_record);
1152 /* try trigger match */
1154 && regex_match_and_setup(cmdline_trigger_re, linebuffer, 0, -1)
1159 (void)fclose(scanner_record);
1160 sep = pclose(scanner_out);
1161 signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1163 return m_errlog_defer(scanent,
1165 ? string_sprintf("running scanner failed: %s", strerror(sep))
1166 : string_sprintf("scanner returned error code: %d", sep));
1171 /* setup default virus name */
1172 malware_name = US"unknown";
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))
1179 if ((s = m_pcre_exec(cmdline_regex_re, linebuffer)))
1182 (void)fclose(scanner_record);
1184 else /* no virus found */
1185 malware_name = NULL;
1189 case M_SOPHIE: /* "sophie" scanner type --------------------------------- */
1194 uschar av_buffer[1024];
1196 /* pass the scan directory to sophie */
1197 file_name = string_copy(eml_filename);
1198 if ((p = Ustrrchr(file_name, '/')))
1201 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
1202 scanner_name, scanner_options);
1204 if ( write(sock, file_name, Ustrlen(file_name)) < 0
1205 || write(sock, "\n", 1) != 1
1207 return m_errlog_defer_3(scanent,
1208 string_sprintf("unable to write to UNIX socket (%s)", scanner_options),
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),
1219 if (av_buffer[0] == '1') {
1220 uschar * s = Ustrchr(av_buffer, '\n');
1223 malware_name = string_copy(&av_buffer[2]);
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;
1233 case M_CLAMD: /* "clamd" scanner type ----------------------------------- */
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. */
1247 uschar *p, *vname, *result_tag, *response_end;
1250 uschar av_buffer[1024];
1251 uschar *hostname = US"";
1253 uschar *clamav_fbuf;
1254 int clam_fd, result;
1256 unsigned int fsize_uint;
1257 BOOL use_scan_command = FALSE;
1258 clamd_address_container * clamd_address_vector[MAX_CLAMD_SERVERS];
1260 int num_servers = 0;
1261 #ifdef WITH_OLD_CLAMAV_STREAM
1263 uschar av_buffer2[1024];
1266 uint32_t send_size, send_final_zeroblock;
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;
1275 const uschar *address = scanner_options;
1276 uschar address_buffer[MAX_CLAMD_ADDRESS_LENGTH + 20];
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 */
1284 clamd_address_container *this_clamd;
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)
1290 use_scan_command = TRUE;
1294 /* XXX: If unsuccessful we should free this memory */
1296 (clamd_address_container *)store_get(sizeof(clamd_address_container));
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 )
1302 (void) m_errlog_defer(scanent,
1303 string_sprintf("invalid address '%s'", address));
1307 clamd_address_vector[num_servers] = this_clamd;
1309 if (num_servers >= MAX_CLAMD_SERVERS)
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 );
1316 } while ((address = string_nextinlist(&av_scanner_work, &sep,
1318 sizeof(address_buffer))) != NULL);
1320 /* check if we have at least one server */
1322 return m_errlog_defer(scanent,
1323 US"no useable server addresses in malware configuration option.");
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));
1333 /* We have some network servers specified */
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. */
1340 while (num_servers > 0)
1343 /* Randomly pick a server to start with */
1344 current_server = random_number( num_servers );
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);
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);
1358 /* Connection successfully established with a server */
1359 hostname = clamd_address_vector[current_server]->tcp_addr;
1363 (void) m_errlog_defer(scanent, errstr);
1365 /* Remove the server from the list. XXX We should free the memory */
1367 for (i = current_server; i < num_servers; i++)
1368 clamd_address_vector[i] = clamd_address_vector[i+1];
1371 if (num_servers == 0)
1372 return m_errlog_defer(scanent, US"all servers failed");
1376 if ((sock = m_unixsocket(scanner_options, &errstr)) < 0)
1377 return m_errlog_defer(scanent, errstr);
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. */
1385 if (!use_scan_command)
1387 #ifdef WITH_OLD_CLAMAV_STREAM
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. */
1392 DEBUG(D_acl) debug_printf(
1393 "Malware scan: issuing %s old-style remote scan (PORT)\n",
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);
1400 memset(av_buffer2, 0, sizeof(av_buffer2));
1401 bread = ip_recv(sock, av_buffer2, sizeof(av_buffer2), tmo-time(NULL));
1404 return m_errlog_defer_3(scanent,
1405 string_sprintf("unable to read PORT from socket (%s)",
1409 if (bread == sizeof(av_buffer2))
1410 return m_errlog_defer_3(scanent, "buffer too small", sock);
1413 return m_errlog_defer_3(scanent, "ClamAV returned null", sock);
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'",
1422 sockData = m_tcpsocket(connhost.address, port, NULL, &errstr);
1424 return m_errlog_defer_3(scanent, errstr, sock);
1426 # define CLOSE_SOCKDATA (void)close(sockData)
1427 #else /* WITH_OLD_CLAMAV_STREAM not defined */
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
1432 DEBUG(D_acl) debug_printf(
1433 "Malware scan: issuing %s new-style remote scan (zINSTREAM)\n",
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)",
1443 # define CLOSE_SOCKDATA /**/
1446 /* calc file size */
1447 if ((clam_fd = open(CS eml_filename, O_RDONLY)) < 0)
1451 return m_errlog_defer_3(scanent,
1452 string_sprintf("can't open spool file %s: %s",
1453 eml_filename, strerror(err)),
1456 if ((fsize = lseek(clam_fd, 0, SEEK_END)) < 0)
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)),
1465 fsize_uint = (unsigned int) fsize;
1466 if ((off_t)fsize_uint != fsize)
1468 CLOSE_SOCKDATA; (void)close(clam_fd);
1469 return m_errlog_defer_3(scanent,
1470 string_sprintf("seeking spool file %s, size overflow",
1474 lseek(clam_fd, 0, SEEK_SET);
1476 if (!(clamav_fbuf = (uschar *) malloc (fsize_uint)))
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),
1485 if ((result = read(clam_fd, clamav_fbuf, fsize_uint)) < 0)
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)),
1494 (void)close(clam_fd);
1496 /* send file body to socket */
1497 #ifdef WITH_OLD_CLAMAV_STREAM
1498 if (send(sockData, clamav_fbuf, fsize_uint, 0) < 0)
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)",
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))
1514 return m_errlog_defer_3(scanent,
1515 string_sprintf("unable to send file body to socket (%s)", hostname),
1523 #undef CLOSE_SOCKDATA
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 */
1530 /* ================================================================= */
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);
1543 DEBUG(D_acl) debug_printf(
1544 "Malware scan: issuing %s local-path scan [%s]\n",
1545 scanner_name, scanner_options);
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)),
1552 /* Do not shut down the socket for writing; a user report noted that
1553 * clamd 0.70 does not react well to this. */
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. */
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));
1565 return m_errlog_defer(scanent,
1566 string_sprintf("unable to read from socket (%s)",
1567 errno == 0 ? "EOF" : strerror(errno)));
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 */
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
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).
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). */
1594 return m_errlog_defer(scanent, US"ClamAV returned null");
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';
1602 DEBUG(D_acl) debug_printf("Malware response: %s\n", av_buffer);
1604 while (isspace(*--p) && (p > av_buffer))
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",
1615 /* strip filename */
1616 while (*p && isspace(*++p)) /**/;
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;
1624 if (Ustrcmp(result_tag, "FOUND") == 0)
1626 /* p should still be the whitespace before the result_tag */
1627 while (isspace(*p)) --p;
1629 /* Strip off the extended information too, which will be in parens
1630 after the virus name, with no intervening whitespace. */
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, '(');
1639 malware_name = string_copy(vname);
1640 DEBUG(D_acl) debug_printf("Malware found, name \"%s\"\n", malware_name);
1643 else if (Ustrcmp(result_tag, "ERROR") == 0)
1644 return m_errlog_defer(scanent,
1645 string_sprintf("ClamAV returned: %s", av_buffer));
1647 else if (Ustrcmp(result_tag, "OK") == 0)
1649 /* Everything should be OK */
1650 malware_name = NULL;
1651 DEBUG(D_acl) debug_printf("Malware not found\n");
1655 return m_errlog_defer(scanent,
1656 string_sprintf("unparseable response from ClamAV: {%s}", av_buffer));
1661 case M_SOCK: /* "sock" scanner type ------------------------------------- */
1662 /* This code was derived by Martin Poole from the clamd code contributed
1663 by David Saez and the cmdline code
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;
1675 /* find scanner command line */
1676 if ((sockline_scanner = string_nextinlist(&av_scanner_work, &sep,
1678 { /* check for no expansions apart from one %s */
1679 uschar * s = Ustrchr(sockline_scanner, '%');
1681 if ((*s != 's' && *s != '%') || Ustrchr(s+1, '%'))
1682 return m_errlog_defer_3(scanent,
1683 US"unsafe sock scanner call spec", sock);
1686 sockline_scanner = sockline_scanner_default;
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);
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);
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);
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);
1709 /* Read the result */
1710 bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL));
1713 return m_errlog_defer_3(scanent,
1714 string_sprintf("unable to read from socket (%s)", strerror(errno)),
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);
1722 /* try trigger match */
1723 if (regex_match_and_setup(sockline_trig_re, linebuffer, 0, -1))
1725 if (!(malware_name = m_pcre_exec(sockline_name_re, av_buffer)))
1726 malware_name = US "unknown";
1728 else /* no virus found */
1729 malware_name = NULL;
1733 case M_MKSD: /* "mksd" scanner type ------------------------------------- */
1735 char *mksd_options_end;
1736 int mksd_maxproc = 1; /* default, if no option supplied */
1739 if (scanner_options)
1741 mksd_maxproc = (int)strtol(CS scanner_options, &mksd_options_end, 10);
1742 if ( *scanner_options == '\0'
1743 || *mksd_options_end != '\0'
1745 || mksd_maxproc > 32
1747 return m_errlog_defer(scanent,
1748 string_sprintf("invalid option '%s'", scanner_options));
1751 if((sock = m_unixsocket(US "/var/run/mksd/socket", &errstr)) < 0)
1752 return m_errlog_defer(scanent, errstr);
1754 malware_name = NULL;
1756 DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan\n", scanner_name);
1758 if ((retval = mksd_scan_packed(scanent, sock, eml_filename, tmo)) != OK)
1766 case M_AVAST: /* "avast" scanner type ----------------------------------- */
1770 uschar * scanrequest;
1771 enum {AVA_HELO, AVA_OPT, AVA_RSP, AVA_DONE} avast_stage;
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
1781 [E] - some error occured
1782 Such marker follows the first non-escaped TAB. */
1783 if ( ( !ava_re_clean
1784 && !(ava_re_clean = m_pcre_compile(ava_re_clean_str, &errstr)))
1786 && !(ava_re_virus = m_pcre_compile(ava_re_virus_str, &errstr)))
1788 return malware_errlog_defer(errstr);
1790 /* wait for result */
1791 for (avast_stage = AVA_HELO;
1792 (nread = recv_line(sock, buf, sizeof(buf), tmo)) > 0;
1795 int slen = Ustrlen(buf);
1798 DEBUG(D_acl) debug_printf("got from avast: %s\n", buf);
1799 switch (avast_stage)
1802 if (Ustrncmp(buf, "220", 3) != 0)
1803 goto endloop; /* require a 220 */
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 */
1815 /* Check for another option to send. Newline-terminate it. */
1816 if ((scanrequest = string_nextinlist(&av_scanner_work, &sep,
1819 scanrequest = string_sprintf("%s\n", scanrequest);
1820 avast_stage = AVA_OPT; /* just sent option */
1824 scanrequest = string_sprintf("SCAN %s/scan/%s\n",
1825 spool_directory, message_id);
1826 avast_stage = AVA_RSP; /* just sent command */
1829 /* send config-cmd or scan-request to socket */
1830 len = Ustrlen(scanrequest);
1831 if (send(sock, scanrequest, len, 0) < 0)
1833 scanrequest[len-1] = '\0';
1834 return m_errlog_defer_3(scanent, string_sprintf(
1835 "unable to send request '%s' to socket (%s): %s",
1836 scanrequest, scanner_options, strerror(errno)), sock);
1842 if (Ustrncmp(buf, "210", 3) == 0)
1843 break; /* ignore the "210 SCAN DATA" message */
1845 if (pcre_exec(ava_re_clean, NULL, CS buf, slen,
1846 0, 0, ovector, nelements(ovector)) > 0)
1849 if ((malware_name = m_pcre_exec(ava_re_virus, buf)))
1850 { /* remove backslash in front of [whitespace|backslash] */
1852 for (p = malware_name; *p; ++p)
1853 if (*p == '\\' && (isspace(p[1]) || p[1] == '\\'))
1854 for (p0 = p; *p0; ++p0) *p0 = p0[1];
1856 avast_stage = AVA_DONE;
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)),
1867 malware_name = NULL;
1868 avast_stage = AVA_DONE;
1872 /* here for any unexpected response from the scanner */
1883 case AVA_RSP: return m_errlog_defer_3(scanent,
1886 "invalid response from scanner: '%s'", buf)
1888 ? US"EOF from scanner"
1889 : US"timeout from scanner",
1895 } /* scanner type switch */
1898 (void) close (sock);
1899 malware_ok = TRUE; /* set "been here, done that" marker */
1902 /* match virus name against pattern (caseless ------->----------v) */
1903 if (malware_name && regex_match_and_setup(re, malware_name, 0, -1))
1905 DEBUG(D_acl) debug_printf(
1906 "Matched regex to malware [%s] [%s]\n", malware_re, malware_name);
1914 /*************************************************
1915 * Scan an email for malware *
1916 *************************************************/
1918 /* This is the normal interface for scanning an email, which doesn't need a
1919 filename; it's a wrapper around the malware_file function.
1922 malware_re match condition for "malware="
1923 timeout if nonzero, timeout in seconds
1925 Returns: Exim message processing code (OK, FAIL, DEFER, ...)
1926 where true means malware was found (condition applies)
1929 malware(const uschar * malware_re, int timeout)
1931 uschar * scan_filename;
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;
1943 /*************************************************
1944 * Scan a file for malware *
1945 *************************************************/
1947 /* This is a test wrapper for scanning an email, which is not used in
1948 normal processing. Scan any file, using the Exim scanning interface.
1949 This function tampers with various global variables so is unsafe to use
1950 in any other context.
1953 eml_filename a file holding the message to be scanned
1955 Returns: Exim message processing code (OK, FAIL, DEFER, ...)
1956 where true means malware was found (condition applies)
1959 malware_in_file(uschar *eml_filename)
1961 uschar message_id_buf[64];
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";
1971 recipients_list = NULL;
1972 receive_add_recipient(US"malware-victim@example.net", -1);
1973 enable_dollar_recipients = TRUE;
1975 ret = malware_internal(US"*", eml_filename, 0, TRUE);
1977 Ustrncpy(spooled_message_id, message_id, sizeof(spooled_message_id));
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 */
1983 /* silence static analysis tools */
1993 if (!malware_default_re)
1994 malware_default_re = regex_must_compile(malware_regex_default, FALSE, TRUE);
1996 drweb_re = regex_must_compile(drweb_re_str, FALSE, TRUE);
1998 fsec_re = regex_must_compile(fsec_re_str, FALSE, TRUE);
2000 kav_re_sus = regex_must_compile(kav_re_sus_str, FALSE, TRUE);
2002 kav_re_inf = regex_must_compile(kav_re_inf_str, FALSE, TRUE);
2004 ava_re_clean = regex_must_compile(ava_re_clean_str, FALSE, TRUE);
2006 ava_re_virus = regex_must_compile(ava_re_virus_str, FALSE, TRUE);
2009 #endif /*WITH_CONTENT_SCAN*/