2004-09-05 15:28:10 +00:00
|
|
|
/*
|
2024-01-12 17:03:59 -05:00
|
|
|
* Copyright (C) 2013-2024 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
|
2019-01-25 10:15:50 -05:00
|
|
|
* Copyright (C) 2007-2013 Sourcefire, Inc.
|
2008-04-02 15:24:51 +00:00
|
|
|
*
|
|
|
|
* Authors: Nigel Horne
|
2019-05-04 15:54:54 -04:00
|
|
|
*
|
2018-03-05 16:34:35 -05:00
|
|
|
* Summary: Extract files compressed with TAR compression format.
|
2019-05-04 15:54:54 -04:00
|
|
|
*
|
2018-03-05 16:34:35 -05:00
|
|
|
* Acknowledgements: ClamAV untar code is based on a public domain minitar utility
|
|
|
|
* by Charles G. Waldman.
|
2004-09-05 15:28:10 +00:00
|
|
|
*
|
|
|
|
* This program is free software; you can redistribute it and/or modify
|
2008-04-02 15:24:51 +00:00
|
|
|
* it under the terms of the GNU General Public License version 2 as
|
|
|
|
* published by the Free Software Foundation.
|
2004-09-05 15:28:10 +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
|
2006-04-09 19:59:28 +00:00
|
|
|
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
|
|
|
* MA 02110-1301, USA.
|
2004-09-05 15:28:10 +00:00
|
|
|
*/
|
2008-04-02 15:24:51 +00:00
|
|
|
|
2006-10-15 11:12:09 +00:00
|
|
|
#if HAVE_CONFIG_H
|
|
|
|
#include "clamav-config.h"
|
|
|
|
#endif
|
2004-09-05 18:58:22 +00:00
|
|
|
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include <string.h>
|
2018-12-03 12:40:13 -05:00
|
|
|
#ifdef HAVE_UNISTD_H
|
2004-09-05 18:58:22 +00:00
|
|
|
#include <unistd.h>
|
2006-07-26 09:39:08 +00:00
|
|
|
#endif
|
2004-09-05 18:58:22 +00:00
|
|
|
#include <sys/stat.h>
|
2004-09-06 08:34:47 +00:00
|
|
|
#include <fcntl.h>
|
2018-12-03 12:40:13 -05:00
|
|
|
#ifdef HAVE_SYS_PARAM_H
|
|
|
|
#include <sys/param.h> /* for NAME_MAX */
|
2006-07-26 09:39:08 +00:00
|
|
|
#endif
|
2004-09-05 18:58:22 +00:00
|
|
|
|
|
|
|
#include "clamav.h"
|
|
|
|
#include "others.h"
|
2004-09-06 08:34:47 +00:00
|
|
|
#include "untar.h"
|
2007-04-02 17:49:01 +00:00
|
|
|
#include "mbox.h"
|
|
|
|
#include "blob.h"
|
2008-02-14 15:38:59 +00:00
|
|
|
#include "scanners.h"
|
2010-01-14 23:32:35 +01:00
|
|
|
#include "matcher.h"
|
2004-09-05 18:58:22 +00:00
|
|
|
|
2017-11-01 13:34:20 -06:00
|
|
|
#define TARHEADERSIZE 512
|
|
|
|
/* BLOCKSIZE must be >= TARHEADERSIZE */
|
|
|
|
#define BLOCKSIZE TARHEADERSIZE
|
2012-05-29 17:46:09 -04:00
|
|
|
#define TARSIZEOFFSET 124
|
|
|
|
#define TARSIZELEN 12
|
|
|
|
#define TARCHECKSUMOFFSET 148
|
|
|
|
#define TARCHECKSUMLEN 8
|
|
|
|
#define TARFILETYPEOFFSET 156
|
2004-09-05 18:58:22 +00:00
|
|
|
|
2004-09-06 08:34:47 +00:00
|
|
|
static int
|
|
|
|
octal(const char *str)
|
2004-09-05 18:58:22 +00:00
|
|
|
{
|
2018-12-03 12:40:13 -05:00
|
|
|
int ret;
|
2004-09-05 18:58:22 +00:00
|
|
|
|
2018-12-03 12:40:13 -05:00
|
|
|
if (sscanf(str, "%o", (unsigned int *)&ret) != 1)
|
|
|
|
return -1;
|
|
|
|
return ret;
|
2004-09-05 18:58:22 +00:00
|
|
|
}
|
|
|
|
|
2012-05-29 17:46:09 -04:00
|
|
|
/**
|
|
|
|
* Retrieve checksum values from a tar header block.
|
|
|
|
* @param header Header data block, padded with zeroes to reach BLOCKSIZE
|
|
|
|
* @return int value of checksum, -1 (from octal()) if bad value
|
|
|
|
*/
|
|
|
|
static int
|
|
|
|
getchecksum(const char *header)
|
|
|
|
{
|
2018-12-03 12:40:13 -05:00
|
|
|
char ochecksum[TARCHECKSUMLEN + 1];
|
|
|
|
int checksum = -1;
|
2012-05-29 17:46:09 -04:00
|
|
|
|
2018-12-03 12:40:13 -05:00
|
|
|
strncpy(ochecksum, header + TARCHECKSUMOFFSET, TARCHECKSUMLEN);
|
|
|
|
ochecksum[TARCHECKSUMLEN] = '\0';
|
|
|
|
checksum = octal(ochecksum);
|
|
|
|
return checksum;
|
2012-05-29 17:46:09 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Calculate checksum values for tar header blocks.
|
|
|
|
* @param header Header data block, padded with zeroes to reach BLOCKSIZE
|
|
|
|
* @param targetsum Check value to match (as int not octal!)
|
|
|
|
* @return 0 if checksum matches target, -1 if not
|
|
|
|
*/
|
|
|
|
static int
|
|
|
|
testchecksum(const char *header, int targetsum)
|
|
|
|
{
|
2018-12-03 12:40:13 -05:00
|
|
|
const unsigned char *posix;
|
|
|
|
const signed char *legacy;
|
|
|
|
int posix_sum = 0, legacy_sum = 0;
|
|
|
|
int i;
|
|
|
|
|
|
|
|
// targetsum -1 represents an error from octal()
|
|
|
|
if (targetsum == -1) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Build checksums. POSIX is unsigned; some legacy tars use signed. */
|
|
|
|
posix = (unsigned char *)header;
|
|
|
|
legacy = (signed char *)header;
|
|
|
|
for (i = 0; i < BLOCKSIZE; i++) {
|
|
|
|
if ((i >= TARCHECKSUMOFFSET) && (i < TARCHECKSUMOFFSET + TARCHECKSUMLEN)) {
|
|
|
|
/* Use ascii value of space in place of checksum value */
|
|
|
|
posix_sum += 32;
|
|
|
|
legacy_sum += 32;
|
|
|
|
} else {
|
|
|
|
posix_sum += posix[i];
|
|
|
|
legacy_sum += legacy[i];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if ((targetsum == posix_sum) || (targetsum == legacy_sum)) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
return -1;
|
2012-05-29 17:46:09 -04:00
|
|
|
}
|
|
|
|
|
2019-05-04 15:54:54 -04:00
|
|
|
cl_error_t cli_untar(const char *dir, unsigned int posix, cli_ctx *ctx)
|
2004-09-05 18:58:22 +00:00
|
|
|
{
|
2019-05-04 15:54:54 -04:00
|
|
|
cl_error_t ret;
|
|
|
|
size_t size = 0;
|
|
|
|
int size_int = 0;
|
|
|
|
int fout = -1;
|
2018-12-03 12:40:13 -05:00
|
|
|
int in_block = 0;
|
|
|
|
int last_header_bad = 0;
|
|
|
|
int limitnear = 0;
|
|
|
|
unsigned int files = 0;
|
Improve tmp sub-directory names
At present many parsers create tmp subdirectories to store extracted
files. For parsers like the vba parser, this is required as the
directory is later scanned. For other parsers, these subdirectories are
probably not helpful now that we provide recursive sub-dirs when
--leave-temps is enabled. It's not quite as simple as removing the extra
subdirectories, however. Certain parsers, like autoit, don't create very
unique filenames and would result in file name collisions when
--leave-temps is not enabled.
The best thing to do would be to make sure each parser uses unique
filenames and doesn't rely on cli_magic_scan_dir() to scan extracted
content before removing the extra subdirectory. In the meantime, this
commit gives the extra subdirectories meaningful names to improve
readability.
This commit also:
- Provides the 'bmp' prefix for extracted PE icons.
- Removes empty tmp subdirs when extracting rtf files, to eliminate
clutter.
- The PDF parser sometimes creates tmp files when decompressing streams
before it knows if there is actually any content to decompress. This
resulted in a large number of empty files. While it would be best to
avoid creating empty files in the first place, that's not quite as
as it sounds. This commit does the next best thing and deletes the
tmp files if nothing was actually extracted, even if --leave-temps is
enabled.
- Removes the "scantemp" prefix for unnamed fmaps scanned with
cli_magic_scan(). The 5-character hashes given to tmp files with
prefixes resulted in occasional file name collisions when extracting
certain file types with thousands of embedded files.
- The VBA and TAR parsers mistakenly used NAME_MAX instead of PATH_MAX,
resulting in truncated file paths and failed extraction when
--leave-temps is enabled and a lot of recursion is in play. This commit
switches them from NAME_MAX to PATH_MAX.
2020-03-27 16:06:22 -04:00
|
|
|
char fullname[PATH_MAX + 1];
|
2020-03-19 21:23:54 -04:00
|
|
|
char name[101];
|
2018-12-03 12:40:13 -05:00
|
|
|
size_t pos = 0;
|
|
|
|
size_t currsize = 0;
|
|
|
|
char zero[BLOCKSIZE];
|
|
|
|
|
|
|
|
cli_dbgmsg("In untar(%s)\n", dir);
|
|
|
|
memset(zero, 0, sizeof(zero));
|
|
|
|
|
|
|
|
for (;;) {
|
|
|
|
const char *block;
|
|
|
|
size_t nread;
|
|
|
|
|
libclamav: Fix scan recursion tracking
Scan recursion is the process of identifying files embedded in other
files and then scanning them, recursively.
Internally this process is more complex than it may sound because a file
may have multiple layers of types before finding a new "file".
At present we treat the recursion count in the scanning context as an
index into both our fmap list AND our container list. These two lists
are conceptually a part of the same thing and should be unified.
But what's concerning is that the "recursion level" isn't actually
incremented or decremented at the same time that we add a layer to the
fmap or container lists but instead is more touchy-feely, increasing
when we find a new "file".
To account for this shadiness, the size of the fmap and container lists
has always been a little longer than our "max scan recursion" limit so
we don't accidentally overflow the fmap or container arrays (!).
I've implemented a single recursion-stack as an array, similar to before,
which includes a pointer to each fmap at each layer, along with the size
and type. Push and pop functions add and remove layers whenever a new
fmap is added. A boolean argument when pushing indicates if the new layer
represents a new buffer or new file (descriptor). A new buffer will reset
the "nested fmap level" (described below).
This commit also provides a solution for an issue where we detect
embedded files more than once during scan recursion.
For illustration, imagine a tarball named foo.tar.gz with this structure:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │ └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
But suppose baz.exe embeds a ZIP archive and a 7Z archive, like this:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| baz.exe | PE | 0 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| │ └── hello.txt | ASCII | 2 | 0 |
| └── sfx.7z | 7Z | 1 | 1 |
| └── world.txt | ASCII | 2 | 0 |
(A) If we scan for embedded files at any layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| ├── foo.tar | TAR | 1 | 0 |
| │ ├── bar.zip | ZIP | 2 | 1 |
| │ │ └── hola.txt | ASCII | 3 | 0 |
| │ ├── baz.exe | PE | 2 | 1 |
| │ │ ├── sfx.zip | ZIP | 3 | 1 |
| │ │ │ └── hello.txt | ASCII | 4 | 0 |
| │ │ └── sfx.7z | 7Z | 3 | 1 |
| │ │ └── world.txt | ASCII | 4 | 0 |
| │ ├── sfx.zip | ZIP | 2 | 1 |
| │ │ └── hello.txt | ASCII | 3 | 0 |
| │ └── sfx.7z | 7Z | 2 | 1 |
| │ └── world.txt | ASCII | 3 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| └── sfx.7z | 7Z | 1 | 1 |
(A) is bad because it scans content more than once.
Note that for the GZ layer, it may detect the ZIP and 7Z if the
signature hits on the compressed data, which it might, though
extracting the ZIP and 7Z will likely fail.
The reason the above doesn't happen now is that we restrict embedded
type scans for a bunch of archive formats to include GZ and TAR.
(B) If we scan for embedded files at the foo.tar layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │ └── hola.txt | ASCII | 3 | 0 |
| ├── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 2 | 1 |
| │ └── hello.txt | ASCII | 3 | 0 |
| └── sfx.7z | 7Z | 2 | 1 |
| └── world.txt | ASCII | 3 | 0 |
(B) is almost right. But we can achieve it easily enough only scanning for
embedded content in the current fmap when the "nested fmap level" is 0.
The upside is that it should safely detect all embedded content, even if
it may think the sfz.zip and sfx.7z are in foo.tar instead of in baz.exe.
The biggest risk I can think of affects ZIPs. SFXZIP detection
is identical to ZIP detection, which is why we don't allow SFXZIP to be
detected if insize of a ZIP. If we only allow embedded type scanning at
fmap-layer 0 in each buffer, this will fail to detect the embedded ZIP
if the bar.exe was not compressed in foo.zip and if non-compressed files
extracted from ZIPs aren't extracted as new buffers:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.zip | ZIP | 0 | 0 |
| └── bar.exe | PE | 1 | 1 |
| └── sfx.zip | ZIP | 2 | 2 |
Provided that we ensure all files extracted from zips are scanned in
new buffers, option (B) should be safe.
(C) If we scan for embedded files at the baz.exe layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │ └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 3 | 1 |
| │ └── hello.txt | ASCII | 4 | 0 |
| └── sfx.7z | 7Z | 3 | 1 |
| └── world.txt | ASCII | 4 | 0 |
(C) is right. But it's harder to achieve. For this example we can get it by
restricting 7ZSFX and ZIPSFX detection only when scanning an executable.
But that may mean losing detection of archives embedded elsewhere.
And we'd have to identify allowable container types for each possible
embedded type, which would be very difficult.
So this commit aims to solve the issue the (B)-way.
Note that in all situations, we still have to scan with file typing
enabled to determine if we need to reassign the current file type, such
as re-identifying a Bzip2 archive as a DMG that happens to be Bzip2-
compressed. Detection of DMG and a handful of other types rely on
finding data partway through or near the ned of a file before
reassigning the entire file as the new type.
Other fixes and considerations in this commit:
- The utf16 HTML parser has weak error handling, particularly with respect
to creating a nested fmap for scanning the ascii decoded file.
This commit cleans up the error handling and wraps the nested scan with
the recursion-stack push()/pop() for correct recursion tracking.
Before this commit, each container layer had a flag to indicate if the
container layer is valid.
We need something similar so that the cli_recursion_stack_get_*()
functions ignore normalized layers. Details...
Imagine an LDB signature for HTML content that specifies a ZIP
container. If the signature actually alerts on the normalized HTML and
you don't ignore normalized layers for the container check, it will
appear as though the alert is in an HTML container rather than a ZIP
container.
This commit accomplishes this with a boolean you set in the scan context
before scanning a new layer. Then when the new fmap is created, it will
use that flag to set similar flag for the layer. The context flag is
reset those that anything after this doesn't have that flag.
The flag allows the new recursion_stack_get() function to ignore
normalized layers when iterating the stack to return a layer at a
requested index, negative or positive.
Scanning normalized extracted/normalized javascript and VBA should also
use the 'layer is normalized' flag.
- This commit also fixes Heuristic.Broken.Executable alert for ELF files
to make sure that:
A) these only alert if cli_append_virus() returns CL_VIRUS (aka it
respects the FP check).
B) all broken-executable alerts for ELF only happen if the
SCAN_HEURISTIC_BROKEN option is enabled.
- This commit also cleans up the error handling in cli_magic_scan_dir().
This was needed so we could correctly apply the layer-is-normalized-flag
to all VBA macros extracted to a directory when scanning the directory.
- Also fix an issue where exceeding scan maximums wouldn't cause embedded
file detection scans to abort. Granted we don't actually want to abort
if max filesize or max recursion depth are exceeded... only if max
scansize, max files, and max scantime are exceeded.
Add 'abort_scan' flag to scan context, to protect against depending on
correct error propagation for fatal conditions. Instead, setting this
flag in the scan context should guarantee that a fatal condition deep in
scan recursion isn't lost which result in more stuff being scanned
instead of aborting. This shouldn't be necessary, but some status codes
like CL_ETIMEOUT never used to be fatal and it's easier to do this than
to verify every parser only returns CL_ETIMEOUT and other "fatal
status codes" in fatal conditions.
- Remove duplicate is_tar() prototype from filestypes.c and include
is_tar.h instead.
- Presently we create the fmap hash when creating the fmap.
This wastes a bit of CPU if the hash is never needed.
Now that we're creating fmap's for all embedded files discovered with
file type recognition scans, this is a much more frequent occurence and
really slows things down.
This commit fixes the issue by only creating fmap hashes as needed.
This should not only resolve the perfomance impact of creating fmap's
for all embedded files, but also should improve performance in general.
- Add allmatch check to the zip parser after the central-header meta
match. That way we don't multiple alerts with the same match except in
allmatch mode. Clean up error handling in the zip parser a tiny bit.
- Fixes to ensure that the scan limits such as scansize, filesize,
recursion depth, # of embedded files, and scantime are always reported
if AlertExceedsMax (--alert-exceeds-max) is enabled.
- Fixed an issue where non-fatal alerts for exceeding scan maximums may
mask signature matches later on. I changed it so these alerts use the
"possibly unwanted" alert-type and thus only alert if no other alerts
were found or if all-match or heuristic-precedence are enabled.
- Added the "Heuristics.Limits.Exceeded.*" events to the JSON metadata
when the --gen-json feature is enabled. These will show up once under
"ParseErrors" the first time a limit is exceeded. In the present
implementation, only one limits-exceeded events will be added, so as to
prevent a malicious or malformed sample from filling the JSON buffer
with millions of events and using a tonne of RAM.
2021-09-11 14:15:21 -07:00
|
|
|
block = fmap_need_off_once_len(ctx->fmap, pos, BLOCKSIZE, &nread);
|
2018-12-03 12:40:13 -05:00
|
|
|
cli_dbgmsg("cli_untar: pos = %lu\n", (unsigned long)pos);
|
|
|
|
|
|
|
|
if (!in_block && !nread)
|
|
|
|
break;
|
|
|
|
|
|
|
|
if (!nread)
|
|
|
|
block = zero;
|
|
|
|
|
|
|
|
if (!block) {
|
|
|
|
if (fout >= 0)
|
|
|
|
close(fout);
|
|
|
|
cli_errmsg("cli_untar: block read error\n");
|
|
|
|
return CL_EREAD;
|
|
|
|
}
|
|
|
|
pos += nread;
|
|
|
|
|
|
|
|
if (!in_block) {
|
|
|
|
char type;
|
|
|
|
int directory, skipEntry = 0;
|
|
|
|
int checksum = -1;
|
2020-03-19 21:23:54 -04:00
|
|
|
char magic[7], osize[TARSIZELEN + 1];
|
2018-12-03 12:40:13 -05:00
|
|
|
currsize = 0;
|
|
|
|
|
|
|
|
if (fout >= 0) {
|
|
|
|
lseek(fout, 0, SEEK_SET);
|
2022-03-09 22:26:40 -08:00
|
|
|
ret = cli_magic_scan_desc(fout, fullname, ctx, name, LAYER_ATTRIBUTES_NONE);
|
2018-12-03 12:40:13 -05:00
|
|
|
close(fout);
|
2022-08-27 10:28:39 -07:00
|
|
|
if (!ctx->engine->keeptmp) {
|
|
|
|
if (cli_unlink(fullname)) {
|
|
|
|
return CL_EUNLINK;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (ret != CL_SUCCESS) {
|
|
|
|
return ret;
|
2018-12-03 12:40:13 -05:00
|
|
|
}
|
|
|
|
fout = -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (block[0] == '\0') /* We're done */
|
|
|
|
break;
|
|
|
|
if ((ret = cli_checklimits("cli_untar", ctx, 0, 0, 0)) != CL_CLEAN)
|
|
|
|
return ret;
|
|
|
|
|
|
|
|
if (nread < TARHEADERSIZE) {
|
|
|
|
return CL_CLEAN;
|
|
|
|
}
|
|
|
|
|
|
|
|
checksum = getchecksum(block);
|
|
|
|
cli_dbgmsg("cli_untar: Candidate checksum = %d, [%o in octal]\n", checksum, checksum);
|
|
|
|
if (testchecksum(block, checksum) != 0) {
|
|
|
|
// If checksum is bad, dump and look for next header block
|
|
|
|
cli_dbgmsg("cli_untar: Invalid checksum in tar header. Skip to next...\n");
|
|
|
|
if (last_header_bad == 0) {
|
|
|
|
last_header_bad++;
|
|
|
|
cli_dbgmsg("cli_untar: Invalid checksum found inside archive!\n");
|
|
|
|
}
|
|
|
|
continue;
|
|
|
|
} else {
|
|
|
|
last_header_bad = 0;
|
|
|
|
cli_dbgmsg("cli_untar: Checksum %d is valid.\n", checksum);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (posix) {
|
|
|
|
strncpy(magic, block + 257, 5);
|
|
|
|
magic[5] = '\0';
|
|
|
|
if (strcmp(magic, "ustar") != 0) {
|
|
|
|
cli_dbgmsg("cli_untar: Incorrect magic string '%s' in tar header\n", magic);
|
|
|
|
return CL_EFORMAT;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type = block[TARFILETYPEOFFSET];
|
|
|
|
|
|
|
|
switch (type) {
|
|
|
|
default:
|
|
|
|
cli_dbgmsg("cli_untar: unknown type flag %c\n", type);
|
libclamav: Fix scan recursion tracking
Scan recursion is the process of identifying files embedded in other
files and then scanning them, recursively.
Internally this process is more complex than it may sound because a file
may have multiple layers of types before finding a new "file".
At present we treat the recursion count in the scanning context as an
index into both our fmap list AND our container list. These two lists
are conceptually a part of the same thing and should be unified.
But what's concerning is that the "recursion level" isn't actually
incremented or decremented at the same time that we add a layer to the
fmap or container lists but instead is more touchy-feely, increasing
when we find a new "file".
To account for this shadiness, the size of the fmap and container lists
has always been a little longer than our "max scan recursion" limit so
we don't accidentally overflow the fmap or container arrays (!).
I've implemented a single recursion-stack as an array, similar to before,
which includes a pointer to each fmap at each layer, along with the size
and type. Push and pop functions add and remove layers whenever a new
fmap is added. A boolean argument when pushing indicates if the new layer
represents a new buffer or new file (descriptor). A new buffer will reset
the "nested fmap level" (described below).
This commit also provides a solution for an issue where we detect
embedded files more than once during scan recursion.
For illustration, imagine a tarball named foo.tar.gz with this structure:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │ └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
But suppose baz.exe embeds a ZIP archive and a 7Z archive, like this:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| baz.exe | PE | 0 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| │ └── hello.txt | ASCII | 2 | 0 |
| └── sfx.7z | 7Z | 1 | 1 |
| └── world.txt | ASCII | 2 | 0 |
(A) If we scan for embedded files at any layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| ├── foo.tar | TAR | 1 | 0 |
| │ ├── bar.zip | ZIP | 2 | 1 |
| │ │ └── hola.txt | ASCII | 3 | 0 |
| │ ├── baz.exe | PE | 2 | 1 |
| │ │ ├── sfx.zip | ZIP | 3 | 1 |
| │ │ │ └── hello.txt | ASCII | 4 | 0 |
| │ │ └── sfx.7z | 7Z | 3 | 1 |
| │ │ └── world.txt | ASCII | 4 | 0 |
| │ ├── sfx.zip | ZIP | 2 | 1 |
| │ │ └── hello.txt | ASCII | 3 | 0 |
| │ └── sfx.7z | 7Z | 2 | 1 |
| │ └── world.txt | ASCII | 3 | 0 |
| ├── sfx.zip | ZIP | 1 | 1 |
| └── sfx.7z | 7Z | 1 | 1 |
(A) is bad because it scans content more than once.
Note that for the GZ layer, it may detect the ZIP and 7Z if the
signature hits on the compressed data, which it might, though
extracting the ZIP and 7Z will likely fail.
The reason the above doesn't happen now is that we restrict embedded
type scans for a bunch of archive formats to include GZ and TAR.
(B) If we scan for embedded files at the foo.tar layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │ └── hola.txt | ASCII | 3 | 0 |
| ├── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 2 | 1 |
| │ └── hello.txt | ASCII | 3 | 0 |
| └── sfx.7z | 7Z | 2 | 1 |
| └── world.txt | ASCII | 3 | 0 |
(B) is almost right. But we can achieve it easily enough only scanning for
embedded content in the current fmap when the "nested fmap level" is 0.
The upside is that it should safely detect all embedded content, even if
it may think the sfz.zip and sfx.7z are in foo.tar instead of in baz.exe.
The biggest risk I can think of affects ZIPs. SFXZIP detection
is identical to ZIP detection, which is why we don't allow SFXZIP to be
detected if insize of a ZIP. If we only allow embedded type scanning at
fmap-layer 0 in each buffer, this will fail to detect the embedded ZIP
if the bar.exe was not compressed in foo.zip and if non-compressed files
extracted from ZIPs aren't extracted as new buffers:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.zip | ZIP | 0 | 0 |
| └── bar.exe | PE | 1 | 1 |
| └── sfx.zip | ZIP | 2 | 2 |
Provided that we ensure all files extracted from zips are scanned in
new buffers, option (B) should be safe.
(C) If we scan for embedded files at the baz.exe layer, we may detect:
| description | type | rec level | nested fmap level |
| ------------------------- | ----- | --------- | ----------------- |
| foo.tar.gz | GZ | 0 | 0 |
| └── foo.tar | TAR | 1 | 0 |
| ├── bar.zip | ZIP | 2 | 1 |
| │ └── hola.txt | ASCII | 3 | 0 |
| └── baz.exe | PE | 2 | 1 |
| ├── sfx.zip | ZIP | 3 | 1 |
| │ └── hello.txt | ASCII | 4 | 0 |
| └── sfx.7z | 7Z | 3 | 1 |
| └── world.txt | ASCII | 4 | 0 |
(C) is right. But it's harder to achieve. For this example we can get it by
restricting 7ZSFX and ZIPSFX detection only when scanning an executable.
But that may mean losing detection of archives embedded elsewhere.
And we'd have to identify allowable container types for each possible
embedded type, which would be very difficult.
So this commit aims to solve the issue the (B)-way.
Note that in all situations, we still have to scan with file typing
enabled to determine if we need to reassign the current file type, such
as re-identifying a Bzip2 archive as a DMG that happens to be Bzip2-
compressed. Detection of DMG and a handful of other types rely on
finding data partway through or near the ned of a file before
reassigning the entire file as the new type.
Other fixes and considerations in this commit:
- The utf16 HTML parser has weak error handling, particularly with respect
to creating a nested fmap for scanning the ascii decoded file.
This commit cleans up the error handling and wraps the nested scan with
the recursion-stack push()/pop() for correct recursion tracking.
Before this commit, each container layer had a flag to indicate if the
container layer is valid.
We need something similar so that the cli_recursion_stack_get_*()
functions ignore normalized layers. Details...
Imagine an LDB signature for HTML content that specifies a ZIP
container. If the signature actually alerts on the normalized HTML and
you don't ignore normalized layers for the container check, it will
appear as though the alert is in an HTML container rather than a ZIP
container.
This commit accomplishes this with a boolean you set in the scan context
before scanning a new layer. Then when the new fmap is created, it will
use that flag to set similar flag for the layer. The context flag is
reset those that anything after this doesn't have that flag.
The flag allows the new recursion_stack_get() function to ignore
normalized layers when iterating the stack to return a layer at a
requested index, negative or positive.
Scanning normalized extracted/normalized javascript and VBA should also
use the 'layer is normalized' flag.
- This commit also fixes Heuristic.Broken.Executable alert for ELF files
to make sure that:
A) these only alert if cli_append_virus() returns CL_VIRUS (aka it
respects the FP check).
B) all broken-executable alerts for ELF only happen if the
SCAN_HEURISTIC_BROKEN option is enabled.
- This commit also cleans up the error handling in cli_magic_scan_dir().
This was needed so we could correctly apply the layer-is-normalized-flag
to all VBA macros extracted to a directory when scanning the directory.
- Also fix an issue where exceeding scan maximums wouldn't cause embedded
file detection scans to abort. Granted we don't actually want to abort
if max filesize or max recursion depth are exceeded... only if max
scansize, max files, and max scantime are exceeded.
Add 'abort_scan' flag to scan context, to protect against depending on
correct error propagation for fatal conditions. Instead, setting this
flag in the scan context should guarantee that a fatal condition deep in
scan recursion isn't lost which result in more stuff being scanned
instead of aborting. This shouldn't be necessary, but some status codes
like CL_ETIMEOUT never used to be fatal and it's easier to do this than
to verify every parser only returns CL_ETIMEOUT and other "fatal
status codes" in fatal conditions.
- Remove duplicate is_tar() prototype from filestypes.c and include
is_tar.h instead.
- Presently we create the fmap hash when creating the fmap.
This wastes a bit of CPU if the hash is never needed.
Now that we're creating fmap's for all embedded files discovered with
file type recognition scans, this is a much more frequent occurence and
really slows things down.
This commit fixes the issue by only creating fmap hashes as needed.
This should not only resolve the perfomance impact of creating fmap's
for all embedded files, but also should improve performance in general.
- Add allmatch check to the zip parser after the central-header meta
match. That way we don't multiple alerts with the same match except in
allmatch mode. Clean up error handling in the zip parser a tiny bit.
- Fixes to ensure that the scan limits such as scansize, filesize,
recursion depth, # of embedded files, and scantime are always reported
if AlertExceedsMax (--alert-exceeds-max) is enabled.
- Fixed an issue where non-fatal alerts for exceeding scan maximums may
mask signature matches later on. I changed it so these alerts use the
"possibly unwanted" alert-type and thus only alert if no other alerts
were found or if all-match or heuristic-precedence are enabled.
- Added the "Heuristics.Limits.Exceeded.*" events to the JSON metadata
when the --gen-json feature is enabled. These will show up once under
"ParseErrors" the first time a limit is exceeded. In the present
implementation, only one limits-exceeded events will be added, so as to
prevent a malicious or malformed sample from filling the JSON buffer
with millions of events and using a tonne of RAM.
2021-09-11 14:15:21 -07:00
|
|
|
/* fall-through */
|
2018-12-03 12:40:13 -05:00
|
|
|
case '0': /* plain file */
|
|
|
|
case '\0': /* plain file */
|
|
|
|
case '7': /* contiguous file */
|
|
|
|
case 'M': /* continuation of a file from another volume; might as well scan it. */
|
|
|
|
files++;
|
|
|
|
directory = 0;
|
|
|
|
break;
|
|
|
|
case '1': /* Link to already archived file */
|
|
|
|
case '5': /* directory */
|
|
|
|
case '2': /* sym link */
|
|
|
|
case '3': /* char device */
|
|
|
|
case '4': /* block device */
|
|
|
|
case '6': /* fifo special */
|
|
|
|
case 'V': /* Volume header */
|
|
|
|
directory = 1;
|
|
|
|
break;
|
|
|
|
case 'K':
|
|
|
|
case 'L':
|
|
|
|
/* GNU extension - ././@LongLink
|
2022-02-16 00:13:55 +01:00
|
|
|
* Discard the blocks with the extended filename,
|
|
|
|
* the last header will contain parts of it anyway
|
|
|
|
*/
|
2018-12-03 12:40:13 -05:00
|
|
|
case 'N': /* Old GNU format way of storing long filenames. */
|
|
|
|
case 'A': /* Solaris ACL */
|
|
|
|
case 'E': /* Solaris Extended attribute s*/
|
|
|
|
case 'I': /* Inode only */
|
|
|
|
case 'g': /* Global extended header */
|
|
|
|
case 'x': /* Extended attributes */
|
|
|
|
case 'X': /* Extended attributes (POSIX) */
|
|
|
|
directory = 0;
|
|
|
|
skipEntry = 1;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (directory) {
|
|
|
|
in_block = 0;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
strncpy(osize, block + TARSIZEOFFSET, TARSIZELEN);
|
|
|
|
osize[TARSIZELEN] = '\0';
|
2019-05-04 15:54:54 -04:00
|
|
|
size_int = octal(osize);
|
|
|
|
if (size_int < 0) {
|
2018-12-03 12:40:13 -05:00
|
|
|
cli_dbgmsg("cli_untar: Invalid size in tar header\n");
|
|
|
|
skipEntry++;
|
|
|
|
} else {
|
2019-05-04 15:54:54 -04:00
|
|
|
size = (size_t)size_int;
|
|
|
|
cli_dbgmsg("cli_untar: size = %zu\n", size);
|
2018-12-03 12:40:13 -05:00
|
|
|
ret = cli_checklimits("cli_untar", ctx, size, 0, 0);
|
|
|
|
switch (ret) {
|
|
|
|
case CL_EMAXFILES: // Scan no more files
|
|
|
|
skipEntry++;
|
|
|
|
limitnear = 0;
|
|
|
|
break;
|
|
|
|
case CL_EMAXSIZE: // Either single file limit or total byte limit would be exceeded
|
|
|
|
cli_dbgmsg("cli_untar: would exceed limit, will try up to max");
|
|
|
|
limitnear = 1;
|
|
|
|
break;
|
|
|
|
default: // Ok based on reported content size
|
|
|
|
limitnear = 0;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (skipEntry) {
|
|
|
|
const int nskip = (size % BLOCKSIZE || !size) ? size + BLOCKSIZE - (size % BLOCKSIZE) : size;
|
|
|
|
|
|
|
|
if (nskip < 0) {
|
|
|
|
cli_dbgmsg("cli_untar: got negative skip size, giving up\n");
|
|
|
|
return CL_CLEAN;
|
|
|
|
}
|
|
|
|
cli_dbgmsg("cli_untar: skipping entry\n");
|
|
|
|
pos += nskip;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
strncpy(name, block, 100);
|
|
|
|
name[100] = '\0';
|
|
|
|
if (cli_matchmeta(ctx, name, size, size, 0, files, 0, NULL) == CL_VIRUS) {
|
2022-08-27 10:28:39 -07:00
|
|
|
return CL_VIRUS;
|
2018-12-03 12:40:13 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
snprintf(fullname, sizeof(fullname) - 1, "%s" PATHSEP "tar%02u", dir, files);
|
|
|
|
fullname[sizeof(fullname) - 1] = '\0';
|
|
|
|
fout = open(fullname, O_RDWR | O_CREAT | O_EXCL | O_TRUNC | O_BINARY, 0600);
|
|
|
|
|
|
|
|
if (fout < 0) {
|
|
|
|
char err[128];
|
|
|
|
cli_errmsg("cli_untar: Can't create temporary file %s: %s\n", fullname, cli_strerror(errno, err, sizeof(err)));
|
|
|
|
return CL_ETMPFILE;
|
|
|
|
}
|
|
|
|
|
|
|
|
cli_dbgmsg("cli_untar: extracting to %s\n", fullname);
|
|
|
|
|
|
|
|
in_block = 1;
|
|
|
|
} else { /* write or continue writing file contents */
|
2019-05-04 15:54:54 -04:00
|
|
|
size_t nbytes, nwritten;
|
2018-12-03 12:40:13 -05:00
|
|
|
int skipwrite = 0;
|
|
|
|
char err[128];
|
|
|
|
|
2019-05-04 15:54:54 -04:00
|
|
|
nbytes = (size > 512) ? 512 : size;
|
|
|
|
if (nread && (nread < nbytes))
|
2018-12-03 12:40:13 -05:00
|
|
|
nbytes = nread;
|
|
|
|
|
|
|
|
if (limitnear > 0) {
|
|
|
|
currsize += nbytes;
|
|
|
|
cli_dbgmsg("cli_untar: Approaching limit...\n");
|
|
|
|
if (cli_checklimits("cli_untar", ctx, (unsigned long)currsize, 0, 0) != CL_SUCCESS) {
|
|
|
|
// Limit would be exceeded by this file, suppress writing beyond limit
|
|
|
|
// Need to keep reading to get to end of file chunk
|
|
|
|
skipwrite++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (skipwrite == 0) {
|
2019-05-04 15:54:54 -04:00
|
|
|
nwritten = cli_writen(fout, block, nbytes);
|
2018-12-03 12:40:13 -05:00
|
|
|
|
|
|
|
if (nwritten != nbytes) {
|
2019-05-04 15:54:54 -04:00
|
|
|
cli_errmsg("cli_untar: only wrote %zu bytes to file %s (out of disc space?): %s\n",
|
2018-12-03 12:40:13 -05:00
|
|
|
nwritten, fullname, cli_strerror(errno, err, sizeof(err)));
|
|
|
|
close(fout);
|
|
|
|
return CL_EWRITE;
|
|
|
|
}
|
|
|
|
}
|
2019-05-04 15:54:54 -04:00
|
|
|
if (nbytes > size) {
|
|
|
|
cli_warnmsg("cli_untar: More bytes written than requested!\n");
|
|
|
|
size = 0;
|
|
|
|
} else {
|
|
|
|
size -= nbytes;
|
|
|
|
}
|
2018-12-03 12:40:13 -05:00
|
|
|
if ((size != 0) && (nread == 0)) {
|
|
|
|
// Truncated tar file, so end file content like tar behavior
|
|
|
|
cli_dbgmsg("cli_untar: No bytes read! Forcing end of file content.\n");
|
|
|
|
size = 0;
|
|
|
|
}
|
2011-06-13 11:57:59 +03:00
|
|
|
}
|
2018-12-03 12:40:13 -05:00
|
|
|
if (size == 0)
|
|
|
|
in_block = 0;
|
|
|
|
}
|
|
|
|
if (fout >= 0) {
|
|
|
|
lseek(fout, 0, SEEK_SET);
|
2022-03-09 22:26:40 -08:00
|
|
|
ret = cli_magic_scan_desc(fout, fullname, ctx, name, LAYER_ATTRIBUTES_NONE);
|
2018-12-03 12:40:13 -05:00
|
|
|
close(fout);
|
2022-08-27 10:28:39 -07:00
|
|
|
if (!ctx->engine->keeptmp) {
|
|
|
|
if (cli_unlink(fullname)) {
|
|
|
|
return CL_EUNLINK;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (ret != CL_SUCCESS) {
|
|
|
|
return ret;
|
|
|
|
}
|
2018-12-03 12:40:13 -05:00
|
|
|
}
|
2022-08-27 10:28:39 -07:00
|
|
|
|
2018-12-03 12:40:13 -05:00
|
|
|
return CL_CLEAN;
|
2004-09-05 18:58:22 +00:00
|
|
|
}
|