clamav/clamd/scanner.c

640 lines
21 KiB
C
Raw Normal View History

2003-07-29 15:48:06 +00:00
/*
* Copyright (C) 2013-2021 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2013 Sourcefire, Inc.
*
* Authors: Tomasz Kojm, Török Edvin
2003-07-29 15:48:06 +00:00
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
2003-07-29 15:48:06 +00:00
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
2003-07-29 15:48:06 +00:00
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
2003-07-29 15:48:06 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_UNISTD_H
2003-07-29 15:48:06 +00:00
#include <unistd.h>
#endif
#include <errno.h>
2003-07-29 15:48:06 +00:00
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#ifndef _WIN32
#include <sys/time.h>
2003-07-29 15:48:06 +00:00
#include <sys/wait.h>
#include <sys/param.h>
#include <signal.h>
2003-07-29 15:48:06 +00:00
#include <sys/socket.h>
#include <netinet/in.h>
2004-04-05 13:30:09 +00:00
#include <arpa/inet.h>
#include <netdb.h>
#endif
#include <pthread.h>
Add CMake build tooling This patch adds experimental-quality CMake build tooling. The libmspack build required a modification to use "" instead of <> for header #includes. This will hopefully be included in the libmspack upstream project when adding CMake build tooling to libmspack. Removed use of libltdl when using CMake. Flex & Bison are now required to build. If -DMAINTAINER_MODE, then GPERF is also required, though it currently doesn't actually do anything. TODO! I found that the autotools build system was generating the lexer output but not actually compiling it, instead using previously generated (and manually renamed) lexer c source. As a consequence, changes to the .l and .y files weren't making it into the build. To resolve this, I removed generated flex/bison files and fixed the tooling to use the freshly generated files. Flex and bison are now required build tools. On Windows, this adds a dependency on the winflexbison package, which can be obtained using Chocolatey or may be manually installed. CMake tooling only has partial support for building with external LLVM library, and no support for the internal LLVM (to be removed in the future). I.e. The CMake build currently only supports the bytecode interpreter. Many files used include paths relative to the top source directory or relative to the current project, rather than relative to each build target. Modern CMake support requires including internal dependency headers the same way you would external dependency headers (albeit with "" instead of <>). This meant correcting all header includes to be relative to the build targets and not relative to the workspace. For example, ... ```c include "../libclamav/clamav.h" include "clamd/clamd_others.h" ``` ... becomes: ```c // libclamav include "clamav.h" // clamd include "clamd_others.h" ``` Fixes header name conflicts by renaming a few of the files. Converted the "shared" code into a static library, which depends on libclamav. The ironically named "shared" static library provides features common to the ClamAV apps which are not required in libclamav itself and are not intended for use by downstream projects. This change was required for correct modern CMake practices but was also required to use the automake "subdir-objects" option. This eliminates warnings when running autoreconf which, in the next version of autoconf & automake are likely to break the build. libclamav used to build in multiple stages where an earlier stage is a static library containing utils required by the "shared" code. Linking clamdscan and clamdtop with this libclamav utils static lib allowed these two apps to function without libclamav. While this is nice in theory, the practical gains are minimal and it complicates the build system. As such, the autotools and CMake tooling was simplified for improved maintainability and this feature was thrown out. clamdtop and clamdscan now require libclamav to function. Removed the nopthreads version of the autotools libclamav_internal_utils static library and added pthread linking to a couple apps that may have issues building on some platforms without it, with the intention of removing needless complexity from the source. Kept the regular version of libclamav_internal_utils.la though it is no longer used anywhere but in libclamav. Added an experimental doxygen build option which attempts to build clamav.h and libfreshclam doxygen html docs. The CMake build tooling also may build the example program(s), which isn't a feature in the Autotools build system. Changed C standard to C90+ due to inline linking issues with socket.h when linking libfreshclam.so on Linux. Generate common.rc for win32. Fix tabs/spaces in shared Makefile.am, and remove vestigial ifndef from misc.c. Add CMake files to the automake dist, so users can try the new CMake tooling w/out having to build from a git clone. clamonacc changes: - Renamed FANOTIFY macro to HAVE_SYS_FANOTIFY_H to better match other similar macros. - Added a new clamav-clamonacc.service systemd unit file, based on the work of ChadDevOps & Aaron Brighton. - Added missing clamonacc man page. Updates to clamdscan man page, add missing options. Remove vestigial CL_NOLIBCLAMAV definitions (all apps now use libclamav). Rename Windows mspack.dll to libmspack.dll so all ClamAV-built libraries have the lib-prefix with Visual Studio as with CMake.
2020-08-13 00:25:34 -07:00
// libclamav
#include "clamav.h"
#include "others.h"
#include "scanners.h"
2006-09-05 20:45:39 +00:00
Add CMake build tooling This patch adds experimental-quality CMake build tooling. The libmspack build required a modification to use "" instead of <> for header #includes. This will hopefully be included in the libmspack upstream project when adding CMake build tooling to libmspack. Removed use of libltdl when using CMake. Flex & Bison are now required to build. If -DMAINTAINER_MODE, then GPERF is also required, though it currently doesn't actually do anything. TODO! I found that the autotools build system was generating the lexer output but not actually compiling it, instead using previously generated (and manually renamed) lexer c source. As a consequence, changes to the .l and .y files weren't making it into the build. To resolve this, I removed generated flex/bison files and fixed the tooling to use the freshly generated files. Flex and bison are now required build tools. On Windows, this adds a dependency on the winflexbison package, which can be obtained using Chocolatey or may be manually installed. CMake tooling only has partial support for building with external LLVM library, and no support for the internal LLVM (to be removed in the future). I.e. The CMake build currently only supports the bytecode interpreter. Many files used include paths relative to the top source directory or relative to the current project, rather than relative to each build target. Modern CMake support requires including internal dependency headers the same way you would external dependency headers (albeit with "" instead of <>). This meant correcting all header includes to be relative to the build targets and not relative to the workspace. For example, ... ```c include "../libclamav/clamav.h" include "clamd/clamd_others.h" ``` ... becomes: ```c // libclamav include "clamav.h" // clamd include "clamd_others.h" ``` Fixes header name conflicts by renaming a few of the files. Converted the "shared" code into a static library, which depends on libclamav. The ironically named "shared" static library provides features common to the ClamAV apps which are not required in libclamav itself and are not intended for use by downstream projects. This change was required for correct modern CMake practices but was also required to use the automake "subdir-objects" option. This eliminates warnings when running autoreconf which, in the next version of autoconf & automake are likely to break the build. libclamav used to build in multiple stages where an earlier stage is a static library containing utils required by the "shared" code. Linking clamdscan and clamdtop with this libclamav utils static lib allowed these two apps to function without libclamav. While this is nice in theory, the practical gains are minimal and it complicates the build system. As such, the autotools and CMake tooling was simplified for improved maintainability and this feature was thrown out. clamdtop and clamdscan now require libclamav to function. Removed the nopthreads version of the autotools libclamav_internal_utils static library and added pthread linking to a couple apps that may have issues building on some platforms without it, with the intention of removing needless complexity from the source. Kept the regular version of libclamav_internal_utils.la though it is no longer used anywhere but in libclamav. Added an experimental doxygen build option which attempts to build clamav.h and libfreshclam doxygen html docs. The CMake build tooling also may build the example program(s), which isn't a feature in the Autotools build system. Changed C standard to C90+ due to inline linking issues with socket.h when linking libfreshclam.so on Linux. Generate common.rc for win32. Fix tabs/spaces in shared Makefile.am, and remove vestigial ifndef from misc.c. Add CMake files to the automake dist, so users can try the new CMake tooling w/out having to build from a git clone. clamonacc changes: - Renamed FANOTIFY macro to HAVE_SYS_FANOTIFY_H to better match other similar macros. - Added a new clamav-clamonacc.service systemd unit file, based on the work of ChadDevOps & Aaron Brighton. - Added missing clamonacc man page. Updates to clamdscan man page, add missing options. Remove vestigial CL_NOLIBCLAMAV definitions (all apps now use libclamav). Rename Windows mspack.dll to libmspack.dll so all ClamAV-built libraries have the lib-prefix with Visual Studio as with CMake.
2020-08-13 00:25:34 -07:00
// shared
#include "idmef_logging.h"
#include "optparser.h"
#include "output.h"
#include "misc.h"
2006-09-05 20:45:39 +00:00
Add CMake build tooling This patch adds experimental-quality CMake build tooling. The libmspack build required a modification to use "" instead of <> for header #includes. This will hopefully be included in the libmspack upstream project when adding CMake build tooling to libmspack. Removed use of libltdl when using CMake. Flex & Bison are now required to build. If -DMAINTAINER_MODE, then GPERF is also required, though it currently doesn't actually do anything. TODO! I found that the autotools build system was generating the lexer output but not actually compiling it, instead using previously generated (and manually renamed) lexer c source. As a consequence, changes to the .l and .y files weren't making it into the build. To resolve this, I removed generated flex/bison files and fixed the tooling to use the freshly generated files. Flex and bison are now required build tools. On Windows, this adds a dependency on the winflexbison package, which can be obtained using Chocolatey or may be manually installed. CMake tooling only has partial support for building with external LLVM library, and no support for the internal LLVM (to be removed in the future). I.e. The CMake build currently only supports the bytecode interpreter. Many files used include paths relative to the top source directory or relative to the current project, rather than relative to each build target. Modern CMake support requires including internal dependency headers the same way you would external dependency headers (albeit with "" instead of <>). This meant correcting all header includes to be relative to the build targets and not relative to the workspace. For example, ... ```c include "../libclamav/clamav.h" include "clamd/clamd_others.h" ``` ... becomes: ```c // libclamav include "clamav.h" // clamd include "clamd_others.h" ``` Fixes header name conflicts by renaming a few of the files. Converted the "shared" code into a static library, which depends on libclamav. The ironically named "shared" static library provides features common to the ClamAV apps which are not required in libclamav itself and are not intended for use by downstream projects. This change was required for correct modern CMake practices but was also required to use the automake "subdir-objects" option. This eliminates warnings when running autoreconf which, in the next version of autoconf & automake are likely to break the build. libclamav used to build in multiple stages where an earlier stage is a static library containing utils required by the "shared" code. Linking clamdscan and clamdtop with this libclamav utils static lib allowed these two apps to function without libclamav. While this is nice in theory, the practical gains are minimal and it complicates the build system. As such, the autotools and CMake tooling was simplified for improved maintainability and this feature was thrown out. clamdtop and clamdscan now require libclamav to function. Removed the nopthreads version of the autotools libclamav_internal_utils static library and added pthread linking to a couple apps that may have issues building on some platforms without it, with the intention of removing needless complexity from the source. Kept the regular version of libclamav_internal_utils.la though it is no longer used anywhere but in libclamav. Added an experimental doxygen build option which attempts to build clamav.h and libfreshclam doxygen html docs. The CMake build tooling also may build the example program(s), which isn't a feature in the Autotools build system. Changed C standard to C90+ due to inline linking issues with socket.h when linking libfreshclam.so on Linux. Generate common.rc for win32. Fix tabs/spaces in shared Makefile.am, and remove vestigial ifndef from misc.c. Add CMake files to the automake dist, so users can try the new CMake tooling w/out having to build from a git clone. clamonacc changes: - Renamed FANOTIFY macro to HAVE_SYS_FANOTIFY_H to better match other similar macros. - Added a new clamav-clamonacc.service systemd unit file, based on the work of ChadDevOps & Aaron Brighton. - Added missing clamonacc man page. Updates to clamdscan man page, add missing options. Remove vestigial CL_NOLIBCLAMAV definitions (all apps now use libclamav). Rename Windows mspack.dll to libmspack.dll so all ClamAV-built libraries have the lib-prefix with Visual Studio as with CMake.
2020-08-13 00:25:34 -07:00
#include "clamd_others.h"
2003-07-29 15:48:06 +00:00
#include "scanner.h"
2004-03-29 00:00:58 +00:00
#include "shared.h"
#include "thrmgr.h"
#include "server.h"
2003-07-29 15:48:06 +00:00
2004-05-11 00:14:14 +00:00
#ifdef C_LINUX
dev_t procdev; /* /proc device */
#endif
extern int progexit;
extern time_t reloaded_time;
extern pthread_mutex_t reload_mutex;
void msg_callback(enum cl_msg severity, const char *fullmsg, const char *msg, void *ctx)
{
struct cb_context *c = ctx;
const char *filename = (c && c->filename) ? c->filename : "";
UNUSEDPARAM(fullmsg);
switch (severity) {
case CL_MSG_ERROR:
logg("^[LibClamAV] %s: %s", filename, msg);
break;
case CL_MSG_WARN:
logg("~[LibClamAV] %s: %s", filename, msg);
break;
case CL_MSG_INFO_VERBOSE:
logg("*[LibClamAV] %s: %s", filename, msg);
break;
default:
logg("$[LibClamAV] %s: %s", filename, msg);
break;
}
}
void hash_callback(int fd, unsigned long long size, const unsigned char *md5, const char *virname, void *ctx)
{
struct cb_context *c = ctx;
UNUSEDPARAM(fd);
UNUSEDPARAM(virname);
if (!c)
return;
c->virsize = size;
strncpy(c->virhash, (const char *)md5, 32);
c->virhash[32] = '\0';
}
void clamd_virus_found_cb(int fd, const char *virname, void *ctx)
{
struct cb_context *c = ctx;
struct scan_cb_data *d = c->scandata;
const char *fname;
UNUSEDPARAM(fd);
if (d == NULL)
return;
if (!(d->options->general & CL_SCAN_GENERAL_ALLMATCHES) && !(d->options->general & CL_SCAN_GENERAL_HEURISTIC_PRECEDENCE))
return;
if (virname == NULL)
return;
fname = (c && c->filename) ? c->filename : "(filename not set)";
if (virname) {
d->infected++;
conn_reply_virus(d->conn, fname, virname);
if (c->virsize > 0 && optget(d->opts, "ExtendedDetectionInfo")->enabled)
logg("~%s: %s(%s:%llu) FOUND\n", fname, virname, c->virhash, c->virsize);
logg("~%s: %s FOUND\n", fname, virname);
}
return;
}
#define BUFFSIZE 1024
cl_error_t scan_callback(STATBUF *sb, char *filename, const char *msg, enum cli_ftw_reason reason, struct cli_ftw_cbdata *data)
2003-07-29 15:48:06 +00:00
{
struct scan_cb_data *scandata = data->data;
const char *virname = NULL;
int ret;
int type = scandata->type;
struct cb_context context;
char *real_filename = NULL;
if (NULL != filename) {
if (CL_SUCCESS != cli_realpath((const char *)filename, &real_filename)) {
clamonacc: Reduce warning log verbosity Users have complained about two specific log events that are extremely verbose in non-critical error conditions: - clamonacc reports "ERROR: Can't send to clamd: Bad address" This may occur when small files are created/destroyed before they can be sent to be scanned. The log message probably should only be reported in verbose mode. - clamonacc reports "ClamMisc: $/proc/XXX vanished before UIDs could be excluded; scanning anyway" This may occur when a process that accessed a file exits before clamonacc find out who accessed the file. This is a fairly frequent occurence. It can still be problematic if `clamd` was the process which accessed the file (like a clamd temp file if watching /tmp), generally it's not an issue and we want to silently scan it anyways. Also addressed copypaste issue in onas_send_stream() wherein fd is set to 0 (aka STDIN) if the provided fd == 0 (should've been -1 for invalid FD) and if filename == NULL. In fact clamonacc never scans STDIN so the scan should fail if filename == NULL and the provided FD is invalid (-1). I also found that "Access denied. ERROR" is easily provoked when using --fdpass or --stream using this simple script: for i in {1..5000}; do echo "blah $i" > tmp-$i && rm tmp-$i; done Clamdscan does not allow for scans to fail quietly because the file does not exist, but for clamonacc it's a common thing and we don't want to output an error. To solve this, I changed it so a return length of -1 will still result in an "internal error" message but return len 0 failures will be silently ignored. I've added a static variable to onas_client_scan() that keeps state in case clamd is stopped and started - that way it won't print an error message for every event when offline. Instead it will log an error for the first connection failure, and log again when the connection is re-established for a future scan. Calls to onas_client_scan() are already wrapped with the onas_scan_lock mutex so the static variable should be safe. Finally, there were a couple of error responses from clamd that can occur if the file isn't found which we want to silently ignore, so I've tweaked the code which checks for specific error messages to account for these.
2021-01-03 18:40:48 -08:00
conn_reply_errno(scandata->conn, msg, "Failed to determine real path:");
logg("^Failed to determine real path for: %s\n", filename);
logg("*Quarantine of the file may fail if file path contains symlinks.\n");
} else {
free(filename);
filename = real_filename;
}
}
/* detect disconnected socket,
* this should NOT detect half-shutdown sockets (SHUT_WR) */
if (send(scandata->conn->sd, &ret, 0, 0) == -1 && errno != EINTR) {
logg("$Client disconnected while command was active!\n");
thrmgr_group_terminate(scandata->conn->group);
if (reason == visit_file)
free(filename);
return CL_BREAK;
}
if (thrmgr_group_need_terminate(scandata->conn->group)) {
logg("^Client disconnected while scanjob was active\n");
if (reason == visit_file)
free(filename);
return CL_BREAK;
}
scandata->total++;
switch (reason) {
case error_mem:
if (msg)
logg("!Memory allocation failed during cli_ftw() on %s\n",
msg);
else
logg("!Memory allocation failed during cli_ftw()\n");
scandata->errors++;
return CL_EMEM;
case error_stat:
conn_reply_errno(scandata->conn, msg, "lstat() failed:");
logg("^lstat() failed on: %s\n", msg);
scandata->errors++;
return CL_SUCCESS;
case warning_skipped_dir:
logg("^Directory recursion limit reached, skipping %s\n",
msg);
return CL_SUCCESS;
case warning_skipped_link:
logg("$Skipping symlink: %s\n", msg);
return CL_SUCCESS;
case warning_skipped_special:
if (msg == scandata->toplevel_path)
conn_reply(scandata->conn, msg, "Not supported file type", "ERROR");
logg("*Not supported file type: %s\n", msg);
return CL_SUCCESS;
case visit_directory_toplev:
return CL_SUCCESS;
case visit_file:
break;
}
2003-07-29 15:48:06 +00:00
#ifdef C_LINUX
/* check whether the file is excluded */
if (procdev && sb && (sb->st_dev == procdev)) {
free(filename);
return CL_SUCCESS;
}
#endif
if (sb && sb->st_size == 0) { /* empty file */
if (msg == scandata->toplevel_path)
conn_reply_single(scandata->conn, filename, "Empty file");
free(filename);
return CL_SUCCESS;
2003-07-29 15:48:06 +00:00
}
if (type == TYPE_MULTISCAN) {
client_conn_t *client_conn = (client_conn_t *)calloc(1, sizeof(struct client_conn_tag));
if (client_conn) {
client_conn->scanfd = -1;
client_conn->sd = scandata->odesc;
client_conn->filename = filename;
client_conn->cmdtype = COMMAND_MULTISCANFILE;
client_conn->term = scandata->conn->term;
client_conn->options = scandata->options;
client_conn->opts = scandata->opts;
client_conn->group = scandata->group;
if (cl_engine_addref(scandata->engine)) {
logg("!cl_engine_addref() failed\n");
free(filename);
free(client_conn);
return CL_EMEM;
} else {
client_conn->engine = scandata->engine;
pthread_mutex_lock(&reload_mutex);
client_conn->engine_timestamp = reloaded_time;
pthread_mutex_unlock(&reload_mutex);
if (!thrmgr_group_dispatch(scandata->thr_pool, scandata->group, client_conn, 1)) {
logg("!thread dispatch failed\n");
cl_engine_free(scandata->engine);
free(filename);
free(client_conn);
return CL_EMEM;
}
}
} else {
logg("!Can't allocate memory for client_conn\n");
scandata->errors++;
free(filename);
return CL_EMEM;
}
return CL_SUCCESS;
2003-07-29 15:48:06 +00:00
}
2012-09-18 12:09:20 -07:00
thrmgr_setactivetask(filename, NULL);
context.filename = filename;
context.virsize = 0;
context.scandata = scandata;
ret = cl_scanfile_callback(filename, &virname, &scandata->scanned, scandata->engine, scandata->options, &context);
thrmgr_setactivetask(NULL, NULL);
2003-07-29 15:48:06 +00:00
if (thrmgr_group_need_terminate(scandata->conn->group)) {
free(filename);
logg("*Client disconnected while scanjob was active\n");
return ret == CL_ETIMEOUT ? ret : CL_BREAK;
}
if ((ret == CL_VIRUS) && (virname == NULL)) {
logg("*%s: reported CL_VIRUS but no virname returned!\n", filename);
ret = CL_EMEM;
}
if (ret == CL_EACCES) {
if (conn_reply(scandata->conn, filename, "Access denied.", "ERROR") == -1) {
free(filename);
return CL_ETIMEOUT;
}
logg("*Access denied: %s\n", filename);
scandata->errors++;
free(filename);
return CL_SUCCESS;
}
if (ret == CL_VIRUS) {
if (scandata->options->general & CL_SCAN_GENERAL_ALLMATCHES || (scandata->infected && scandata->options->general & CL_SCAN_GENERAL_HEURISTIC_PRECEDENCE)) {
if (optget(scandata->opts, "PreludeEnable")->enabled) {
prelude_logging(filename, virname, context.virhash, context.virsize);
}
virusaction(filename, virname, scandata->opts);
} else {
scandata->infected++;
if (conn_reply_virus(scandata->conn, filename, virname) == -1) {
free(filename);
return CL_ETIMEOUT;
}
if (optget(scandata->opts, "PreludeEnable")->enabled) {
prelude_logging(filename, virname, context.virhash, context.virsize);
}
if (context.virsize && optget(scandata->opts, "ExtendedDetectionInfo")->enabled)
logg("~%s: %s(%s:%llu) FOUND\n", filename, virname, context.virhash, context.virsize);
else
logg("~%s: %s FOUND\n", filename, virname);
virusaction(filename, virname, scandata->opts);
}
} else if (ret != CL_CLEAN) {
scandata->errors++;
if (conn_reply(scandata->conn, filename, cl_strerror(ret), "ERROR") == -1) {
free(filename);
return CL_ETIMEOUT;
}
logg("~%s: %s ERROR\n", filename, cl_strerror(ret));
} else if (logok) {
logg("~%s: OK\n", filename);
2003-07-29 15:48:06 +00:00
}
free(filename);
if (ret == CL_EMEM) /* stop scanning */
return ret;
2006-03-26 19:39:05 +00:00
if (type == TYPE_SCAN) {
/* virus -> break */
return ret;
2003-07-29 15:48:06 +00:00
}
/* keep scanning always */
return CL_SUCCESS;
2003-07-29 15:48:06 +00:00
}
int scan_pathchk(const char *path, struct cli_ftw_cbdata *data)
{
struct scan_cb_data *scandata = data->data;
const struct optstruct *opt;
STATBUF statbuf;
if ((opt = optget(scandata->opts, "ExcludePath"))->enabled) {
while (opt) {
if (match_regex(path, opt->strarg) == 1) {
if (scandata->type != TYPE_MULTISCAN)
conn_reply_single(scandata->conn, path, "Excluded");
return 1;
}
opt = (const struct optstruct *)opt->nextarg;
}
}
if (!optget(scandata->opts, "CrossFilesystems")->enabled) {
if (CLAMSTAT(path, &statbuf) == 0) {
if (statbuf.st_dev != scandata->dev) {
if (scandata->type != TYPE_MULTISCAN)
conn_reply_single(scandata->conn, path, "Excluded (another filesystem)");
return 1;
}
}
}
return 0;
}
cl_error_t scanfd(
const client_conn_t *conn,
unsigned long int *scanned,
const struct cl_engine *engine,
struct cl_scan_options *options,
const struct optstruct *opts,
int odesc,
int stream)
{
cl_error_t ret = -1;
int fd = conn->scanfd;
const char *virname = NULL;
STATBUF statbuf;
struct cb_context context;
char fdstr[32];
const char *reply_fdstr;
char *filepath = NULL;
char *log_filename = fdstr;
UNUSEDPARAM(odesc);
if (stream) {
struct sockaddr_in sa;
socklen_t salen = sizeof(sa);
if (getpeername(conn->sd, (struct sockaddr *)&sa, &salen) || salen > sizeof(sa) || sa.sin_family != AF_INET)
strncpy(fdstr, "instream(local)", sizeof(fdstr));
else
snprintf(fdstr, sizeof(fdstr), "instream(%s@%u)", inet_ntoa(sa.sin_addr), ntohs(sa.sin_port));
reply_fdstr = "stream";
} else {
snprintf(fdstr, sizeof(fdstr), "fd[%d]", fd);
reply_fdstr = fdstr;
}
if (FSTAT(fd, &statbuf) == -1 || !S_ISREG(statbuf.st_mode)) {
logg("%s: Not a regular file. ERROR\n", fdstr);
if (conn_reply(conn, reply_fdstr, "Not a regular file", "ERROR") == -1) {
ret = CL_ETIMEOUT;
goto done;
}
ret = CL_BREAK;
goto done;
}
/* Try and get the real filename, for logging purposes */
if (!stream) {
if (CL_SUCCESS != cli_get_filepath_from_filedesc(fd, &filepath)) {
logg("*%s: Unable to determine the filepath given the file descriptor.\n", fdstr);
} else {
log_filename = filepath;
}
}
thrmgr_setactivetask(fdstr, NULL);
context.filename = fdstr;
context.virsize = 0;
context.scandata = NULL;
ret = cl_scandesc_callback(fd, log_filename, &virname, scanned, engine, options, &context);
thrmgr_setactivetask(NULL, NULL);
if (thrmgr_group_need_terminate(conn->group)) {
logg("*Client disconnected while scanjob was active\n");
ret = ret == CL_ETIMEOUT ? ret : CL_BREAK;
goto done;
}
if (ret == CL_VIRUS) {
if (conn_reply_virus(conn, reply_fdstr, virname) == -1)
ret = CL_ETIMEOUT;
if (context.virsize && optget(opts, "ExtendedDetectionInfo")->enabled)
logg("%s: %s(%s:%llu) FOUND\n", log_filename, virname, context.virhash, context.virsize);
else
logg("%s: %s FOUND\n", log_filename, virname);
virusaction(log_filename, virname, opts);
} else if (ret != CL_CLEAN) {
if (conn_reply(conn, reply_fdstr, cl_strerror(ret), "ERROR") == -1)
ret = CL_ETIMEOUT;
logg("%s: %s ERROR\n", log_filename, cl_strerror(ret));
} else {
if (conn_reply_single(conn, reply_fdstr, "OK") == CL_ETIMEOUT)
ret = CL_ETIMEOUT;
if (logok)
logg("%s: OK\n", log_filename);
}
done:
if (NULL != filepath) {
free(filepath);
}
return ret;
}
int scanstream(
int odesc,
unsigned long int *scanned,
const struct cl_engine *engine,
struct cl_scan_options *options,
const struct optstruct *opts,
char term)
2003-07-29 15:48:06 +00:00
{
int ret, sockfd, acceptd;
int tmpd, bread, retval, firsttimeout, timeout, btread;
unsigned int port = 0, portscan, min_port, max_port;
unsigned long int quota = 0, maxsize = 0;
short bound = 0;
const char *virname = NULL;
char buff[FILEBUFF];
char peer_addr[32];
struct cb_context context;
struct sockaddr_in server;
struct sockaddr_in peer;
socklen_t addrlen;
char *tmpname;
2004-05-01 19:33:05 +00:00
min_port = optget(opts, "StreamMinPort")->numarg;
max_port = optget(opts, "StreamMaxPort")->numarg;
/* search for a free port to bind to */
port = cli_rndnum(max_port - min_port);
bound = 0;
for (portscan = 0; portscan < 1000; portscan++) {
port = (port - 1) % (max_port - min_port + 1);
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(min_port + port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
continue;
if (bind(sockfd, (struct sockaddr *)&server, (socklen_t)sizeof(struct sockaddr_in)) == -1)
closesocket(sockfd);
else {
bound = 1;
break;
}
2003-07-29 15:48:06 +00:00
}
port += min_port;
2004-05-01 19:33:05 +00:00
timeout = optget(opts, "ReadTimeout")->numarg;
firsttimeout = optget(opts, "CommandReadTimeout")->numarg;
2003-07-29 15:48:06 +00:00
if (!bound) {
logg("!ScanStream: Can't find any free port.\n");
mdprintf(odesc, "Can't find any free port. ERROR%c", term);
2013-02-28 14:39:19 -05:00
return -1;
} else {
if (listen(sockfd, 1) == -1) {
logg("!ScanStream: listen() error on socket. Error returned is %s.\n", strerror(errno));
closesocket(sockfd);
return -1;
}
if (mdprintf(odesc, "PORT %u%c", port, term) <= 0) {
logg("!ScanStream: error transmitting port.\n");
closesocket(sockfd);
return -1;
}
2003-07-29 15:48:06 +00:00
}
retval = poll_fd(sockfd, firsttimeout, 0);
if (!retval || retval == -1) {
const char *reason = !retval ? "timeout" : "poll";
mdprintf(odesc, "Accept %s. ERROR%c", reason, term);
logg("!ScanStream %u: accept %s.\n", port, reason);
closesocket(sockfd);
return -1;
}
addrlen = sizeof(peer);
if ((acceptd = accept(sockfd, (struct sockaddr *)&peer, (socklen_t *)&addrlen)) == -1) {
closesocket(sockfd);
mdprintf(odesc, "accept() ERROR%c", term);
logg("!ScanStream %u: accept() failed.\n", port);
return -1;
2003-07-29 15:48:06 +00:00
}
2010-01-28 23:36:37 +01:00
*peer_addr = '\0';
2010-03-06 04:00:14 +01:00
inet_ntop(peer.sin_family, &peer.sin_addr, peer_addr, sizeof(peer_addr));
logg("*Accepted connection from %s on port %u, fd %d\n", peer_addr, port, acceptd);
2003-09-29 11:44:52 +00:00
if (cli_gentempfd(optget(opts, "TemporaryDirectory")->strarg, &tmpname, &tmpd)) {
shutdown(sockfd, 2);
closesocket(sockfd);
closesocket(acceptd);
mdprintf(odesc, "cli_gentempfd() failed. ERROR%c", term);
logg("!ScanStream(%s@%u): Can't create temporary file.\n", peer_addr, port);
return -1;
2004-05-01 19:33:05 +00:00
}
quota = maxsize = optget(opts, "StreamMaxLength")->numarg;
2004-05-01 19:33:05 +00:00
while ((retval = poll_fd(acceptd, timeout, 0)) == 1) {
/* only read up to max */
btread = (maxsize && (quota < sizeof(buff))) ? quota : sizeof(buff);
if (!btread) {
logg("^ScanStream(%s@%u): Size limit reached (max: %lu)\n", peer_addr, port, maxsize);
break; /* Scan what we have */
}
bread = recv(acceptd, buff, btread, 0);
if (bread <= 0)
break;
quota -= bread;
if (writen(tmpd, buff, bread) != bread) {
shutdown(sockfd, 2);
closesocket(sockfd);
closesocket(acceptd);
mdprintf(odesc, "Temporary file -> write ERROR%c", term);
logg("!ScanStream(%s@%u): Can't write to temporary file.\n", peer_addr, port);
close(tmpd);
if (!optget(opts, "LeaveTemporaryFiles")->enabled)
unlink(tmpname);
free(tmpname);
return -1;
}
2004-05-01 19:33:05 +00:00
}
2003-07-29 15:48:06 +00:00
switch (retval) {
case 0: /* timeout */
mdprintf(odesc, "read timeout ERROR%c", term);
logg("!ScanStream(%s@%u): read timeout.\n", peer_addr, port);
break;
case -1:
mdprintf(odesc, "read poll ERROR%c", term);
logg("!ScanStream(%s@%u): read poll failed.\n", peer_addr, port);
break;
2004-05-01 19:33:05 +00:00
}
2003-07-29 15:48:06 +00:00
if (retval == 1) {
lseek(tmpd, 0, SEEK_SET);
thrmgr_setactivetask(peer_addr, NULL);
context.filename = peer_addr;
context.virsize = 0;
context.scandata = NULL;
ret = cl_scandesc_callback(tmpd, tmpname, &virname, scanned, engine, options, &context);
thrmgr_setactivetask(NULL, NULL);
} else {
ret = -1;
}
close(tmpd);
if (!optget(opts, "LeaveTemporaryFiles")->enabled)
unlink(tmpname);
free(tmpname);
2003-07-29 15:48:06 +00:00
closesocket(acceptd);
closesocket(sockfd);
2003-07-29 15:48:06 +00:00
if (ret == CL_VIRUS) {
if (context.virsize && optget(opts, "ExtendedDetectionInfo")->enabled) {
mdprintf(odesc, "stream: %s(%s:%llu) FOUND%c", virname, context.virhash, context.virsize, term);
logg("stream(%s@%u): %s(%s:%llu) FOUND\n", peer_addr, port, virname, context.virhash, context.virsize);
} else {
mdprintf(odesc, "stream: %s FOUND%c", virname, term);
logg("stream(%s@%u): %s FOUND\n", peer_addr, port, virname);
}
virusaction("stream", virname, opts);
} else if (ret != CL_CLEAN) {
if (retval == 1) {
mdprintf(odesc, "stream: %s ERROR%c", cl_strerror(ret), term);
logg("stream(%s@%u): %s ERROR\n", peer_addr, port, cl_strerror(ret));
}
2004-02-01 01:18:57 +00:00
} else {
mdprintf(odesc, "stream: OK%c", term);
if (logok)
logg("stream(%s@%u): OK\n", peer_addr, port);
2004-02-01 01:18:57 +00:00
}
2003-07-29 15:48:06 +00:00
return ret;
}