clamav/clamdscan/client.c

433 lines
12 KiB
C
Raw Normal View History

2003-07-29 15:48:06 +00:00
/*
2020-01-03 15:44:07 -05:00
* Copyright (C) 2013-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2009-2013 Sourcefire, Inc.
*
* Authors: Tomasz Kojm, aCaB
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>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
2009-02-12 17:31:09 +00:00
#endif
#include <string.h>
2003-07-29 15:48:06 +00:00
#include <sys/types.h>
2004-03-29 00:00:58 +00:00
#include <sys/stat.h>
#ifdef HAVE_SYS_LIMITS_H
#include <sys/limits.h>
#endif
2009-09-24 16:08:52 +02:00
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
2009-09-24 16:08:52 +02:00
#endif
2009-09-24 19:23:21 +02:00
#ifndef _WIN32
#include <sys/socket.h>
2003-07-29 15:48:06 +00:00
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <utime.h>
2009-09-24 19:23:21 +02:00
#endif
#include <errno.h>
#include <dirent.h>
#include <fcntl.h>
2003-07-29 15:48:06 +00:00
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
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 "str.h"
#include "others.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
// shared
#include "optparser.h"
#include "output.h"
#include "misc.h"
#include "actions.h"
#include "clamdcom.h"
#include "client.h"
#include "proto.h"
2003-07-29 15:48:06 +00:00
unsigned long int maxstream;
2009-09-24 19:23:21 +02:00
#ifndef _WIN32
struct sockaddr_un nixsock;
2009-09-24 19:23:21 +02:00
#endif
extern struct optstruct *clamdopts;
/* Inits the communication layer
* Returns 0 if clamd is local, non zero if clamd is remote */
static int isremote(const struct optstruct *opts)
{
int s, ret;
const struct optstruct *opt;
2014-01-26 14:58:21 -05:00
char *ipaddr, port[10];
struct addrinfo hints, *info, *p;
int res;
UNUSEDPARAM(opts);
2009-09-24 16:08:52 +02:00
#ifndef _WIN32
if ((opt = optget(clamdopts, "LocalSocket"))->enabled) {
2014-01-25 21:50:33 -05:00
memset((void *)&nixsock, 0, sizeof(nixsock));
nixsock.sun_family = AF_UNIX;
strncpy(nixsock.sun_path, opt->strarg, sizeof(nixsock.sun_path));
nixsock.sun_path[sizeof(nixsock.sun_path) - 1] = '\0';
2014-01-25 21:50:33 -05:00
return 0;
}
2009-09-24 16:08:52 +02:00
#endif
if (!(opt = optget(clamdopts, "TCPSocket"))->enabled)
2014-01-25 21:50:33 -05:00
return 0;
2014-01-26 14:58:21 -05:00
snprintf(port, sizeof(port), "%lld", optget(clamdopts, "TCPSocket")->numarg);
2014-01-25 21:50:33 -05:00
opt = optget(clamdopts, "TCPAddr");
while (opt) {
ipaddr = NULL;
if (opt->strarg)
2014-01-26 14:58:21 -05:00
ipaddr = (!strcmp(opt->strarg, "any") ? NULL : opt->strarg);
memset(&hints, 0x00, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
2014-01-26 14:58:21 -05:00
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
2014-01-26 14:58:21 -05:00
if ((res = getaddrinfo(ipaddr, port, &hints, &info))) {
logg("!Can't lookup clamd hostname: %s\n", gai_strerror(res));
opt = opt->nextarg;
2014-01-26 14:58:21 -05:00
continue;
2014-01-25 21:50:33 -05:00
}
2014-01-26 14:58:21 -05:00
for (p = info; p != NULL; p = p->ai_next) {
if ((s = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) {
2014-01-26 14:58:21 -05:00
logg("isremote: socket() returning: %s.\n", strerror(errno));
continue;
}
switch (p->ai_family) {
case AF_INET:
((struct sockaddr_in *)(p->ai_addr))->sin_port = htons(INADDR_ANY);
break;
case AF_INET6:
((struct sockaddr_in6 *)(p->ai_addr))->sin6_port = htons(INADDR_ANY);
break;
default:
break;
}
ret = bind(s, p->ai_addr, p->ai_addrlen);
2014-01-26 14:58:21 -05:00
if (ret) {
if (errno == EADDRINUSE) {
2020-01-03 15:44:07 -05:00
/*
* If we can't bind, then either we're attempting to listen on an IP that isn't
* ours or that clamd is already listening on.
*/
closesocket(s);
freeaddrinfo(info);
return 0;
}
closesocket(s);
2014-01-26 14:58:21 -05:00
freeaddrinfo(info);
return 1;
}
closesocket(s);
2014-01-25 21:50:33 -05:00
}
2014-01-26 14:58:21 -05:00
freeaddrinfo(info);
2014-01-25 21:50:33 -05:00
opt = opt->nextarg;
}
2014-01-26 14:58:21 -05:00
return 0;
}
/* pings clamd at the specified interval the number of time specified
* return 0 on a succesful connection, 1 upon timeout, -1 on error */
int16_t ping_clamd(const struct optstruct *opts)
{
uint64_t attempts = 0;
uint64_t interval = 0;
char *attempt_str = NULL;
char *interval_str = NULL;
char *errchk = NULL;
uint64_t i = 0;
const struct optstruct *opt = NULL;
int64_t sockd;
struct RCVLN rcv;
uint16_t ret = 0;
if (opts == NULL) {
logg("!null parameter was passed\n");
ret = -1;
goto done;
}
/* ping command takes the form --ping [attempts[:interval]] */
if (NULL != (opt = optget(opts, "ping"))) {
if (NULL != opt->strarg) {
if (NULL == (attempt_str = cli_strdup(opt->strarg))) {
logg("!could not allocate memory for string\n");
ret = -1;
goto done;
}
interval_str = strchr(attempt_str, ':');
if (interval_str[0] != '\0') {
interval_str[0] = '\0';
interval_str++;
interval = cli_strntoul(interval_str, strlen(interval_str), &errchk, 10);
if (interval_str + strlen(interval_str) > errchk) {
logg("^interval_str would go past end of buffer\n");
ret = -1;
goto done;
}
} else {
interval = CLAMDSCAN_DEFAULT_PING_INTERVAL;
}
attempts = cli_strntoul(attempt_str, strlen(attempt_str), &errchk, 10);
if (attempt_str + strlen(attempt_str) > errchk) {
logg("^attmept_str would go past end of buffer\n");
ret = -1;
goto done;
}
} else {
attempts = CLAMDSCAN_DEFAULT_PING_ATTEMPTS;
interval = CLAMDSCAN_DEFAULT_PING_INTERVAL;
}
}
isremote(opts);
do {
if ((sockd = dconnect()) >= 0) {
recvlninit(&rcv, sockd);
if (sendln(sockd, "zPING", 5)) {
logg("*PING failed...\n");
closesocket(sockd);
} else {
if (!optget(opts, "wait")->enabled) {
logg("PONG\n");
}
ret = 0;
goto done;
}
}
if (i + 1 < attempts) {
logg("*PINGing again in %" PRIu64 " seconds\n", interval);
sleep(interval);
}
i++;
} while (i < attempts);
ret = 1;
done:
if (attempt_str) {
free(attempt_str);
}
attempt_str = NULL;
interval_str = NULL;
errchk = NULL;
return ret;
}
/* Turns a relative path into an absolute one
2020-01-03 15:44:07 -05:00
* Returns a pointer to the path (which must be
* freed by the caller) or NULL on error */
static char *makeabs(const char *basepath)
{
int namelen;
char *ret;
if (!(ret = malloc(PATH_MAX + 1))) {
logg("^Can't make room for fullpath.\n");
return NULL;
}
if (!cli_is_abspath(basepath)) {
if (!getcwd(ret, PATH_MAX)) {
logg("^Can't get absolute pathname of current working directory.\n");
free(ret);
return NULL;
}
#ifdef _WIN32
if (*basepath == '\\') {
namelen = 2;
basepath++;
} else
#endif
namelen = strlen(ret);
snprintf(&ret[namelen], PATH_MAX - namelen, PATHSEP "%s", basepath);
2003-07-29 15:48:06 +00:00
} else {
strncpy(ret, basepath, PATH_MAX);
2003-07-29 15:48:06 +00:00
}
ret[PATH_MAX] = '\0';
return ret;
}
2003-07-29 15:48:06 +00:00
/* Recursively scans a path with the given scantype
* Returns non zero for serious errors, zero otherwise */
static int client_scan(const char *file, int scantype, int *infected, int *err, int maxlevel, int session, int flags)
{
int ret;
char *fullpath = makeabs(file);
if (!fullpath)
return 0;
if (!session)
ret = serial_client_scan(fullpath, scantype, infected, err, maxlevel, flags);
else
ret = parallel_client_scan(fullpath, scantype, infected, err, maxlevel, flags);
free(fullpath);
return ret;
}
2003-07-29 15:48:06 +00:00
int get_clamd_version(const struct optstruct *opts)
{
char *buff;
int len, sockd;
struct RCVLN rcv;
isremote(opts);
if ((sockd = dconnect()) < 0) return 2;
recvlninit(&rcv, sockd);
if (sendln(sockd, "zVERSION", 9)) {
closesocket(sockd);
return 2;
}
while ((len = recvln(&rcv, &buff, NULL))) {
if (len == -1) {
logg("!Error occurred while receiving version information.\n");
break;
}
printf("%s\n", buff);
}
2009-09-24 16:21:51 +02:00
closesocket(sockd);
return 0;
}
int reload_clamd_database(const struct optstruct *opts)
{
char *buff;
int len, sockd;
struct RCVLN rcv;
isremote(opts);
if ((sockd = dconnect()) < 0) return 2;
recvlninit(&rcv, sockd);
if (sendln(sockd, "zRELOAD", 8)) {
closesocket(sockd);
return 2;
}
if (!(len = recvln(&rcv, &buff, NULL)) || len < 10 || memcmp(buff, "RELOADING", 9)) {
logg("!Clamd did not reload the database\n");
closesocket(sockd);
return 2;
}
2009-09-24 16:21:51 +02:00
closesocket(sockd);
return 0;
}
2010-02-03 18:23:30 +01:00
int client(const struct optstruct *opts, int *infected, int *err)
{
int remote, scantype, session = 0, errors = 0, scandash = 0, maxrec, flags = 0;
const char *fname;
if (optget(opts, "wait")->enabled) {
if (ping_clamd(opts) != 0) {
return 2;
}
}
scandash = (opts->filename && opts->filename[0] && !strcmp(opts->filename[0], "-") && !optget(opts, "file-list")->enabled && !opts->filename[1]);
remote = isremote(opts) | optget(opts, "stream")->enabled;
#ifdef HAVE_FD_PASSING
if (!remote && optget(clamdopts, "LocalSocket")->enabled && (optget(opts, "fdpass")->enabled || scandash)) {
scantype = FILDES;
session = optget(opts, "multiscan")->enabled;
} else
#endif
if (remote || scandash) {
scantype = STREAM;
session = optget(opts, "multiscan")->enabled;
} else if (optget(opts, "multiscan")->enabled)
scantype = MULTI;
else if (optget(opts, "allmatch")->enabled)
scantype = ALLMATCH;
else
scantype = CONT;
maxrec = optget(clamdopts, "MaxDirectoryRecursion")->numarg;
maxstream = optget(clamdopts, "StreamMaxLength")->numarg;
if (optget(clamdopts, "FollowDirectorySymlinks")->enabled)
flags |= CLI_FTW_FOLLOW_DIR_SYMLINK;
if (optget(clamdopts, "FollowFileSymlinks")->enabled)
flags |= CLI_FTW_FOLLOW_FILE_SYMLINK;
flags |= CLI_FTW_TRIM_SLASHES;
2003-07-29 15:48:06 +00:00
*infected = 0;
2004-03-29 00:00:58 +00:00
if (scandash) {
int sockd, ret;
STATBUF sb;
if (FSTAT(0, &sb) < 0) {
logg("client.c: fstat failed for file name \"%s\", with %s\n.",
opts->filename[0], strerror(errno));
return 2;
}
if ((sb.st_mode & S_IFMT) != S_IFREG) scantype = STREAM;
if ((sockd = dconnect()) >= 0 && (ret = dsresult(sockd, scantype, NULL, &ret, NULL)) >= 0)
*infected = ret;
else
errors = 1;
if (sockd >= 0) closesocket(sockd);
} else if (opts->filename || optget(opts, "file-list")->enabled) {
if (opts->filename && optget(opts, "file-list")->enabled)
logg("^Only scanning files from --file-list (files passed at cmdline are ignored)\n");
while ((fname = filelist(opts, NULL))) {
if (!strcmp(fname, "-")) {
logg("!Scanning from standard input requires \"-\" to be the only file argument\n");
continue;
}
errors += client_scan(fname, scantype, infected, err, maxrec, session, flags);
/* this may be too strict
2010-02-03 18:23:30 +01:00
if(errors >= 10) {
logg("!Too many errors\n");
break;
}
*/
}
} else {
errors = client_scan("", scantype, infected, err, maxrec, session, flags);
2003-07-29 15:48:06 +00:00
}
return *infected ? 1 : (errors ? 2 : 0);
2003-07-29 15:48:06 +00:00
}