clamav/libclamav/libmspack.c

671 lines
18 KiB
C
Raw Permalink Normal View History

/*
* Author: Sebastian Andrzej Siewior
* Summary: Glue code for libmspack handling.
*
* Acknowledgements: ClamAV uses Stuart Caie's libmspack to parse as number of
* Microsoft file formats.
* sebastian @ breakpoint ̣cc
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <mspack.h>
#include "clamav.h"
#include "fmap.h"
#include "scanners.h"
#include "others.h"
#include "clamav_rust.h"
enum mspack_type {
FILETYPE_DUNNO,
FILETYPE_FMAP,
FILETYPE_FILENAME,
};
struct mspack_name {
fmap_t *fmap;
off_t org;
};
struct mspack_system_ex {
struct mspack_system ops;
uint64_t max_size;
};
struct mspack_handle {
enum mspack_type type;
fmap_t *fmap;
off_t org;
off_t offset;
FILE *f;
uint64_t max_size;
};
static struct mspack_file *mspack_fmap_open(struct mspack_system *self,
const char *filename, int mode)
{
struct mspack_name *mspack_name;
struct mspack_handle *mspack_handle;
struct mspack_system_ex *self_ex;
const char *fmode;
const struct mspack_system *mptr = self;
if (!filename) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
return NULL;
}
mspack_handle = malloc(sizeof(*mspack_handle));
if (!mspack_handle) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
return NULL;
}
memset(mspack_handle, 0, sizeof(*mspack_handle));
switch (mode) {
case MSPACK_SYS_OPEN_READ:
mspack_handle->type = FILETYPE_FMAP;
mspack_name = (struct mspack_name *)filename;
mspack_handle->fmap = mspack_name->fmap;
mspack_handle->org = mspack_name->org;
mspack_handle->offset = 0;
return (struct mspack_file *)mspack_handle;
case MSPACK_SYS_OPEN_WRITE:
fmode = "wb";
break;
case MSPACK_SYS_OPEN_UPDATE:
fmode = "r+b";
break;
case MSPACK_SYS_OPEN_APPEND:
fmode = "ab";
break;
default:
cli_dbgmsg("%s() wrong mode\n", __func__);
goto out_err;
}
mspack_handle->type = FILETYPE_FILENAME;
mspack_handle->f = fopen(filename, fmode);
if (!mspack_handle->f) {
cli_dbgmsg("%s() failed %d\n", __func__, __LINE__);
goto out_err;
}
self_ex = (struct mspack_system_ex *)((char *)mptr - offsetof(struct mspack_system_ex, ops));
mspack_handle->max_size = self_ex->max_size;
return (struct mspack_file *)mspack_handle;
out_err:
memset(mspack_handle, 0, (sizeof(*mspack_handle)));
free(mspack_handle);
mspack_handle = NULL;
return NULL;
}
static void mspack_fmap_close(struct mspack_file *file)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
if (!mspack_handle)
return;
if (mspack_handle->type == FILETYPE_FILENAME)
if (mspack_handle->f)
fclose(mspack_handle->f);
memset(mspack_handle, 0, (sizeof(*mspack_handle)));
free(mspack_handle);
mspack_handle = NULL;
return;
}
static int mspack_fmap_read(struct mspack_file *file, void *buffer, int bytes)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
Reduce unnecessary scanning of embedded file FPs (#1571) When embedded file type recognition finds a possible embedded file, it is being scanned as a new embedded file even if it turns out it was a false positive and parsing fails. My solution is to pre-parse the file headers as little possible to determine if it is valid. If possible, also determine the file size based on the headers. That will make it so we don't have to scan additional data when the embedded file is not at the very end. This commit adds header checks prior to embedded ZIP, ARJ, and CAB scanning. For these types I was also able to use the header checks to determine the object size so as to prevent excessive pattern matching. TODO: Add the same for RAR, EGG, 7Z, NULSFT, AUTOIT, IShield, and PDF. This commit also removes duplicate matching for embedded MSEXE. The embedded MSEXE detection and scanning logic was accidentally creating an extra duplicate layer in between scanning and detection because of the logic within the `cli_scanembpe()` function. That function was effectively doing the header check which this commit adds for ZIP, ARJ, and CAB but minus the size check. Note: It is unfortunately not possible to get an accurage size from PE file headers. The `cli_scanembpe()` function also used to dump to a temp file for no reason since FMAPs were extended to support windows into other FMAPs. So this commit removes the intermediate layer as well as dropping a temp file for each embedded PE file. Further, this commit adds configuration and DCONF safeguards around all embedded file type scanning. Finally, this commit adds a set of tests to validate proper extraction of embedded ZIP, ARJ, CAB, and MSEXE files. CLAM-2862 Co-authored-by: TheRaynMan <draynor@sourcefire.com>
2025-09-23 15:57:28 -04:00
size_t offset;
size_t count;
int ret;
if (bytes < 0) {
cli_dbgmsg("%s() %d\n", __func__, __LINE__);
return -1;
}
if (!mspack_handle) {
cli_dbgmsg("%s() %d\n", __func__, __LINE__);
return -1;
}
if (mspack_handle->type == FILETYPE_FMAP) {
/* Use fmap */
offset = mspack_handle->offset + mspack_handle->org;
Reduce unnecessary scanning of embedded file FPs (#1571) When embedded file type recognition finds a possible embedded file, it is being scanned as a new embedded file even if it turns out it was a false positive and parsing fails. My solution is to pre-parse the file headers as little possible to determine if it is valid. If possible, also determine the file size based on the headers. That will make it so we don't have to scan additional data when the embedded file is not at the very end. This commit adds header checks prior to embedded ZIP, ARJ, and CAB scanning. For these types I was also able to use the header checks to determine the object size so as to prevent excessive pattern matching. TODO: Add the same for RAR, EGG, 7Z, NULSFT, AUTOIT, IShield, and PDF. This commit also removes duplicate matching for embedded MSEXE. The embedded MSEXE detection and scanning logic was accidentally creating an extra duplicate layer in between scanning and detection because of the logic within the `cli_scanembpe()` function. That function was effectively doing the header check which this commit adds for ZIP, ARJ, and CAB but minus the size check. Note: It is unfortunately not possible to get an accurage size from PE file headers. The `cli_scanembpe()` function also used to dump to a temp file for no reason since FMAPs were extended to support windows into other FMAPs. So this commit removes the intermediate layer as well as dropping a temp file for each embedded PE file. Further, this commit adds configuration and DCONF safeguards around all embedded file type scanning. Finally, this commit adds a set of tests to validate proper extraction of embedded ZIP, ARJ, CAB, and MSEXE files. CLAM-2862 Co-authored-by: TheRaynMan <draynor@sourcefire.com>
2025-09-23 15:57:28 -04:00
count = fmap_readn(mspack_handle->fmap, buffer, offset, (size_t)bytes);
if (count == (size_t)-1) {
cli_dbgmsg("%s() %d requested %d bytes, read failed (-1)\n", __func__, __LINE__, bytes);
return -1;
} else if ((int)count < bytes) {
cli_dbgmsg("%s() %d requested %d bytes, read %zu bytes\n", __func__, __LINE__, bytes, count);
}
mspack_handle->offset += (off_t)count;
return (int)count;
} else {
/* Use file descriptor */
Reduce unnecessary scanning of embedded file FPs (#1571) When embedded file type recognition finds a possible embedded file, it is being scanned as a new embedded file even if it turns out it was a false positive and parsing fails. My solution is to pre-parse the file headers as little possible to determine if it is valid. If possible, also determine the file size based on the headers. That will make it so we don't have to scan additional data when the embedded file is not at the very end. This commit adds header checks prior to embedded ZIP, ARJ, and CAB scanning. For these types I was also able to use the header checks to determine the object size so as to prevent excessive pattern matching. TODO: Add the same for RAR, EGG, 7Z, NULSFT, AUTOIT, IShield, and PDF. This commit also removes duplicate matching for embedded MSEXE. The embedded MSEXE detection and scanning logic was accidentally creating an extra duplicate layer in between scanning and detection because of the logic within the `cli_scanembpe()` function. That function was effectively doing the header check which this commit adds for ZIP, ARJ, and CAB but minus the size check. Note: It is unfortunately not possible to get an accurage size from PE file headers. The `cli_scanembpe()` function also used to dump to a temp file for no reason since FMAPs were extended to support windows into other FMAPs. So this commit removes the intermediate layer as well as dropping a temp file for each embedded PE file. Further, this commit adds configuration and DCONF safeguards around all embedded file type scanning. Finally, this commit adds a set of tests to validate proper extraction of embedded ZIP, ARJ, CAB, and MSEXE files. CLAM-2862 Co-authored-by: TheRaynMan <draynor@sourcefire.com>
2025-09-23 15:57:28 -04:00
count = fread(buffer, (size_t)bytes, 1, mspack_handle->f);
if (count < 1) {
cli_dbgmsg("%s() %d requested %d bytes, read failed (%zu)\n", __func__, __LINE__, bytes, count);
return -1;
}
ret = (int)count;
return ret;
}
}
static int mspack_fmap_write(struct mspack_file *file, void *buffer, int bytes)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
size_t count;
uint64_t max_size;
if (bytes < 0 || !mspack_handle) {
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
if (mspack_handle->type == FILETYPE_FMAP) {
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
if (!bytes)
return 0;
max_size = mspack_handle->max_size;
if (!max_size)
return bytes;
max_size = max_size < (uint64_t)bytes ? max_size : (uint64_t)bytes;
mspack_handle->max_size -= max_size;
count = fwrite(buffer, max_size, 1, mspack_handle->f);
if (count < 1) {
cli_dbgmsg("%s() err %d <%zu %d>\n", __func__, __LINE__, count, bytes);
return -1;
}
return bytes;
}
static int mspack_fmap_seek(struct mspack_file *file, off_t offset, int mode)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
if (!mspack_handle) {
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
if (mspack_handle->type == FILETYPE_FMAP) {
off_t new_pos;
switch (mode) {
case MSPACK_SYS_SEEK_START:
new_pos = offset;
break;
case MSPACK_SYS_SEEK_CUR:
new_pos = mspack_handle->offset + offset;
break;
case MSPACK_SYS_SEEK_END:
new_pos = mspack_handle->fmap->len + offset;
break;
default:
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
if (new_pos < 0 || new_pos > (off_t)mspack_handle->fmap->len) {
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
mspack_handle->offset = new_pos;
return 0;
}
switch (mode) {
case MSPACK_SYS_SEEK_START:
mode = SEEK_SET;
break;
case MSPACK_SYS_SEEK_CUR:
mode = SEEK_CUR;
break;
case MSPACK_SYS_SEEK_END:
mode = SEEK_END;
break;
default:
cli_dbgmsg("%s() err %d\n", __func__, __LINE__);
return -1;
}
return fseek(mspack_handle->f, offset, mode);
}
static off_t mspack_fmap_tell(struct mspack_file *file)
{
struct mspack_handle *mspack_handle = (struct mspack_handle *)file;
if (!mspack_handle)
return -1;
if (mspack_handle->type == FILETYPE_FMAP)
return mspack_handle->offset;
return (off_t)ftell(mspack_handle->f);
}
static void mspack_fmap_message(struct mspack_file *file, const char *fmt, ...)
{
UNUSEDPARAM(file);
if (UNLIKELY(cli_debug_flag)) {
va_list args;
char buff[BUFSIZ];
size_t len = sizeof("LibClamAV debug: ") - 1;
memset(buff, 0, BUFSIZ);
/* Add the prefix */
2023-04-07 19:51:04 -07:00
memcpy(buff, "LibClamAV debug: ", len);
va_start(args, fmt);
vsnprintf(buff + len, sizeof(buff) - len - 2, fmt, args);
va_end(args);
/* Add a newline and a null terminator */
buff[strlen(buff)] = '\n';
buff[strlen(buff) + 1] = '\0';
clrs_eprint(buff);
}
}
static void *mspack_fmap_alloc(struct mspack_system *self, size_t num)
{
UNUSEDPARAM(self);
void *addr = malloc(num);
if (addr) {
memset(addr, 0, num);
}
return addr;
}
static void mspack_fmap_free(void *mem)
{
if (mem) {
free(mem);
mem = NULL;
}
return;
}
static void mspack_fmap_copy(void *src, void *dst, size_t num)
{
memcpy(dst, src, num);
}
static struct mspack_system mspack_sys_fmap_ops = {
.open = mspack_fmap_open,
.close = mspack_fmap_close,
.read = mspack_fmap_read,
.write = mspack_fmap_write,
.seek = mspack_fmap_seek,
.tell = mspack_fmap_tell,
.message = mspack_fmap_message,
.alloc = mspack_fmap_alloc,
.free = mspack_fmap_free,
.copy = mspack_fmap_copy,
};
Reduce unnecessary scanning of embedded file FPs (#1571) When embedded file type recognition finds a possible embedded file, it is being scanned as a new embedded file even if it turns out it was a false positive and parsing fails. My solution is to pre-parse the file headers as little possible to determine if it is valid. If possible, also determine the file size based on the headers. That will make it so we don't have to scan additional data when the embedded file is not at the very end. This commit adds header checks prior to embedded ZIP, ARJ, and CAB scanning. For these types I was also able to use the header checks to determine the object size so as to prevent excessive pattern matching. TODO: Add the same for RAR, EGG, 7Z, NULSFT, AUTOIT, IShield, and PDF. This commit also removes duplicate matching for embedded MSEXE. The embedded MSEXE detection and scanning logic was accidentally creating an extra duplicate layer in between scanning and detection because of the logic within the `cli_scanembpe()` function. That function was effectively doing the header check which this commit adds for ZIP, ARJ, and CAB but minus the size check. Note: It is unfortunately not possible to get an accurage size from PE file headers. The `cli_scanembpe()` function also used to dump to a temp file for no reason since FMAPs were extended to support windows into other FMAPs. So this commit removes the intermediate layer as well as dropping a temp file for each embedded PE file. Further, this commit adds configuration and DCONF safeguards around all embedded file type scanning. Finally, this commit adds a set of tests to validate proper extraction of embedded ZIP, ARJ, CAB, and MSEXE files. CLAM-2862 Co-authored-by: TheRaynMan <draynor@sourcefire.com>
2025-09-23 15:57:28 -04:00
cl_error_t cli_mscab_header_check(cli_ctx *ctx, size_t offset, size_t *size)
{
cl_error_t status = CL_EFORMAT;
struct mscab_decompressor *cab_d = NULL;
struct mscabd_cabinet *cab_h = NULL;
struct mspack_name mspack_fmap = {0};
struct mspack_system_ex ops_ex = {0};
if (NULL == ctx || NULL == size) {
cli_dbgmsg("%s() invalid argument\n", __func__);
status = CL_EARG;
goto done;
}
*size = 0;
mspack_fmap.fmap = ctx->fmap;
if (offset > INT32_MAX) {
cli_dbgmsg("%s() offset too large %zu\n", __func__, offset);
status = CL_EFORMAT;
goto done;
}
mspack_fmap.org = (off_t)offset;
ops_ex.ops = mspack_sys_fmap_ops;
cab_d = mspack_create_cab_decompressor(&ops_ex.ops);
if (NULL == cab_d) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
status = CL_EUNPACK;
goto done;
}
cab_h = cab_d->open(cab_d, (char *)&mspack_fmap);
if (NULL == cab_h) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
status = CL_EFORMAT;
goto done;
}
*size = (size_t)cab_h->length;
cli_dbgmsg("%s(): Successfully read CAB header for CAB of size %zu\n", __func__, *size);
status = CL_SUCCESS;
done:
if (NULL != cab_d) {
if (NULL != cab_h) {
cab_d->close(cab_d, cab_h);
}
mspack_destroy_cab_decompressor(cab_d);
}
return status;
}
cl_error_t cli_scanmscab(cli_ctx *ctx, size_t sfx_offset)
{
cl_error_t ret = CL_SUCCESS;
struct mscab_decompressor *cab_d = NULL;
struct mscabd_cabinet *cab_h = NULL;
struct mscabd_file *cab_f = NULL;
int files;
Reduce unnecessary scanning of embedded file FPs (#1571) When embedded file type recognition finds a possible embedded file, it is being scanned as a new embedded file even if it turns out it was a false positive and parsing fails. My solution is to pre-parse the file headers as little possible to determine if it is valid. If possible, also determine the file size based on the headers. That will make it so we don't have to scan additional data when the embedded file is not at the very end. This commit adds header checks prior to embedded ZIP, ARJ, and CAB scanning. For these types I was also able to use the header checks to determine the object size so as to prevent excessive pattern matching. TODO: Add the same for RAR, EGG, 7Z, NULSFT, AUTOIT, IShield, and PDF. This commit also removes duplicate matching for embedded MSEXE. The embedded MSEXE detection and scanning logic was accidentally creating an extra duplicate layer in between scanning and detection because of the logic within the `cli_scanembpe()` function. That function was effectively doing the header check which this commit adds for ZIP, ARJ, and CAB but minus the size check. Note: It is unfortunately not possible to get an accurage size from PE file headers. The `cli_scanembpe()` function also used to dump to a temp file for no reason since FMAPs were extended to support windows into other FMAPs. So this commit removes the intermediate layer as well as dropping a temp file for each embedded PE file. Further, this commit adds configuration and DCONF safeguards around all embedded file type scanning. Finally, this commit adds a set of tests to validate proper extraction of embedded ZIP, ARJ, CAB, and MSEXE files. CLAM-2862 Co-authored-by: TheRaynMan <draynor@sourcefire.com>
2025-09-23 15:57:28 -04:00
struct mspack_name mspack_fmap = {0};
struct mspack_system_ex ops_ex = {0};
Fix static analysis code quality issues (#1582) `libclamav/libmspack.c`: Initialize variables before first `goto done;` to fix unitialized variable use in an error condition. `libclamav/others.c`: Explicitly ignore return values for calls to add JSON values when subsequent calls don't depend on them. If we were to add error handling here, the only thing we'd do is debug- log it. I don't think it's worth adding the extra lines of code. `libclamav/unarj.c`: Removed dead code. The `status` variable is immediately set afterwards based on whether or not any files may be extracted. `libclamav/unzip.c`: Removed dead code. The `ret` variable is checked immediately after being set, above. This check after the `do`-`while()` loop is dead code. `sigtool/sigtool.c`: Fix potential NULL deref in error handling. This is a fix for the same issue as was fixed in a previous commit. I somehow overlooked this one. Copy/paste bug. `libclamav/pdfdecode.c`: Fix leaked `stream` memory when `filter_lzwdecode()` fails. `clamdtop/clamdtop.c`: Fix possible NULL dereference if `strchr` returns NULL in `read_version()` and `check_stats_available()`. `libclamav/rtf.c`: Fix memory leak in `rtf_object_process()` if `cli_gentemp_with_prefix()` fails. Also change empty for-loop to resolve clang-format weirdness and make it more obvious the for-loop has no body. `libclamav/aspack.c`: Ensure that `endoff - old` is not negative in `build_decrypt_array()` before passing to `CLI_ISCONTAINED()` which expects unsigned values. `libclamav/upx.c`: Fix integer overflow checks in multiple functions. `libclamav/vba_extract.c`: Set `entries` pointer back to NULL after free in `word_read_macro_entry()` error condition. `libclamav/unzip.c`: Remove logic to return `CL_EMAXFILES` from `index_local_file_headers()`. It seems it only overwrote the status when not `CL_SUCCESS` in which case it could be overriding a more serious failure. Further, updates to the how the ZIP parser works has made it so this needs to return `CL_SUCCESS` in order for the caller to at least scan the files found so far. Finally, the calling function has checks of its own to make sure we don't exceeds the max-files limit. `libclamav/unzip.c`: Fix issue where `cli_append_potentially_unwanted()` in `index_local_file_headers()` might overwrite an error in `status` with `CL_CLEAN`. Instead, it now checks the return value and only overwrites the `CL_EFORMAT` status with a different value if not `CL_SUCCESS`. `libclamav/unzip.c`: Fix a potential leak with `combined_catalogue` and `temp_catalogue` in an error condition. We should always free them if not NULL, not just if the function failed. And to make this safe, we must set `combined_catalogue` to NULL when we give ownership to `*catalogue`. `libclamav/scanners.c`: Fix a potential leak in error handling for the `cli_ole2_tempdir_scan_vba()` function. CLAM-2768
2025-10-02 11:46:14 -04:00
char *tmp_fname = NULL;
bool tempfile_exists = false;
Reduce unnecessary scanning of embedded file FPs (#1571) When embedded file type recognition finds a possible embedded file, it is being scanned as a new embedded file even if it turns out it was a false positive and parsing fails. My solution is to pre-parse the file headers as little possible to determine if it is valid. If possible, also determine the file size based on the headers. That will make it so we don't have to scan additional data when the embedded file is not at the very end. This commit adds header checks prior to embedded ZIP, ARJ, and CAB scanning. For these types I was also able to use the header checks to determine the object size so as to prevent excessive pattern matching. TODO: Add the same for RAR, EGG, 7Z, NULSFT, AUTOIT, IShield, and PDF. This commit also removes duplicate matching for embedded MSEXE. The embedded MSEXE detection and scanning logic was accidentally creating an extra duplicate layer in between scanning and detection because of the logic within the `cli_scanembpe()` function. That function was effectively doing the header check which this commit adds for ZIP, ARJ, and CAB but minus the size check. Note: It is unfortunately not possible to get an accurage size from PE file headers. The `cli_scanembpe()` function also used to dump to a temp file for no reason since FMAPs were extended to support windows into other FMAPs. So this commit removes the intermediate layer as well as dropping a temp file for each embedded PE file. Further, this commit adds configuration and DCONF safeguards around all embedded file type scanning. Finally, this commit adds a set of tests to validate proper extraction of embedded ZIP, ARJ, CAB, and MSEXE files. CLAM-2862 Co-authored-by: TheRaynMan <draynor@sourcefire.com>
2025-09-23 15:57:28 -04:00
mspack_fmap.fmap = ctx->fmap;
if (sfx_offset > INT32_MAX) {
cli_dbgmsg("%s() offset too large %zu\n", __func__, sfx_offset);
ret = CL_EFORMAT;
goto done;
}
mspack_fmap.org = (off_t)sfx_offset;
memset(&ops_ex, 0, sizeof(struct mspack_system_ex));
ops_ex.ops = mspack_sys_fmap_ops;
cab_d = mspack_create_cab_decompressor(&ops_ex.ops);
if (!cab_d) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
ret = CL_EUNPACK;
goto done;
}
cab_d->set_param(cab_d, MSCABD_PARAM_FIXMSZIP, 1);
#if MSCABD_PARAM_SALVAGE
cab_d->set_param(cab_d, MSCABD_PARAM_SALVAGE, 1);
#endif
cab_h = cab_d->open(cab_d, (char *)&mspack_fmap);
if (NULL == cab_h) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
ret = CL_EFORMAT;
goto done;
}
files = 0;
for (cab_f = cab_h->files; cab_f; cab_f = cab_f->next) {
uint64_t max_size;
ret = cli_matchmeta(ctx, cab_f->filename, 0, cab_f->length, 0,
files, 0);
if (CL_SUCCESS != ret) {
goto done;
}
if (ctx->engine->maxscansize) {
if (ctx->scansize >= ctx->engine->maxscansize) {
ret = CL_CLEAN;
goto done;
}
}
if (ctx->engine->maxfilesize > 0) {
// max filesize has been set
if ((ctx->engine->maxscansize > 0) &&
(ctx->scansize + ctx->engine->maxfilesize >= ctx->engine->maxscansize)) {
// ... but would exceed max scansize, shrink it.
max_size = ctx->engine->maxscansize - ctx->scansize;
} else {
// ... and will work
max_size = ctx->engine->maxfilesize;
}
} else {
// max filesize not specified
if ((ctx->engine->maxscansize > 0) &&
(ctx->scansize + UINT32_MAX >= ctx->engine->maxscansize)) {
// ... but UINT32_MAX would exceed max scansize, shrink it.
max_size = ctx->engine->maxscansize - ctx->scansize;
} else {
// ... use UINT32_MAX
max_size = UINT32_MAX;
}
}
libclamav: Add engine option to toggle temp directory recursion Temp directory recursion in ClamAV is when each layer of a scan gets its own temp directory in the parent layer's temp directory. In addition to temp directory recursion, ClamAV has been creating a new subdirectory for each file scan as a risk-adverse method to ensure no temporary file leaks fill up the disk. Creating a directory is relatively slow on Windows in particular if scanning a lot of very small files. This commit: 1. Separates the temp directory recursion feature from the leave-temps feature so that libclamav can leave temp files without making subdirectories for each file scanned. 2. Makes it so that when temp directory recursion is off, libclamav will just use the configure temp directory for all files. The new option to enable temp directory recursion is for libclamav-only at this time. It is off by default, and you can enable it like this: ```c cl_engine_set_num(engine, CL_ENGINE_TMPDIR_RECURSION, 1); ``` For the `clamscan` and `clamd` programs, temp directory recursion will be enabled when `--leave-temps` / `LeaveTemporaryFiles` is enabled. The difference is that when disabled, it will return to using the configured temp directory without making a subdirectory for each file scanned, so as to improve scan performance for small files, mostly on Windows. Under the hood, this commit also: 1. Cleans up how we keep track of tmpdirs for each layer. The goal here is to align how we keep track of layer-specific stuff using the scan_layer structure. 2. Cleans up how we record metadata JSON for embedded files. Note: Embedded files being different from Contained files, as they are extracted not with a parser, but by finding them with file type magic signatures. CLAM-1583
2025-06-09 20:42:31 -04:00
tmp_fname = cli_gentemp(ctx->this_layer_tmpdir);
if (!tmp_fname) {
ret = CL_EMEM;
goto done;
}
ops_ex.max_size = max_size;
/* scan */
ret = cab_d->extract(cab_d, cab_f, tmp_fname);
if (ret) {
/* Failed to extract. Try to scan what is there */
cli_dbgmsg("%s() failed to extract %d\n", __func__, ret);
}
tempfile_exists = true; // probably
ret = cli_magic_scan_file(tmp_fname, ctx, cab_f->filename, LAYER_ATTRIBUTES_NONE);
Record names of extracted files A way is needed to record scanned file names for two purposes: 1. File names (and extensions) must be stored in the json metadata properties recorded when using the --gen-json clamscan option. Future work may use this to compare file extensions with detected file types. 2. File names are useful when interpretting tmp directory output when using the --leave-temps option. This commit enables file name retention for later use by storing file names in the fmap header structure, if a file name exists. To store the names in fmaps, an optional name argument has been added to any internal scan API's that create fmaps and every call to these APIs has been modified to pass a file name or NULL if a file name is not required. The zip and gpt parsers required some modification to record file names. The NSIS and XAR parsers fail to collect file names at all and will require future work to support file name extraction. Also: - Added recursive extraction to the tmp directory when the --leave-temps option is enabled. When not enabled, the tmp directory structure remains flat so as to prevent the likelihood of exceeding MAX_PATH. The current tmp directory is stored in the scan context. - Made the cli_scanfile() internal API non-static and added it to scanners.h so it would be accessible outside of scanners.c in order to remove code duplication within libmspack.c. - Added function comments to scanners.h and matcher.h - Converted a TDB-type macros and LSIG-type macros to enums for improved type safey. - Converted more return status variables from `int` to `cl_error_t` for improved type safety, and corrected ooxml file typing functions so they use `cli_file_t` exclusively rather than mixing types with `cl_error_t`. - Restructured the magic_scandesc() function to use goto's for error handling and removed the early_ret_from_magicscan() macro and magic_scandesc_cleanup() function. This makes the code easier to read and made it easier to add the recursive tmp directory cleanup to magic_scandesc(). - Corrected zip, egg, rar filename extraction issues. - Removed use of extra sub-directory layer for zip, egg, and rar file extraction. For Zip, this also involved changing the extracted filenames to be randomly generated rather than using the "zip.###" file name scheme.
2020-03-19 21:23:54 -04:00
if (CL_EOPEN == ret) {
// okay so the file didn't actually get extracted. That's okay, we'll move on.
tempfile_exists = false;
ret = CL_SUCCESS;
} else if (CL_SUCCESS != ret) {
goto done;
Record names of extracted files A way is needed to record scanned file names for two purposes: 1. File names (and extensions) must be stored in the json metadata properties recorded when using the --gen-json clamscan option. Future work may use this to compare file extensions with detected file types. 2. File names are useful when interpretting tmp directory output when using the --leave-temps option. This commit enables file name retention for later use by storing file names in the fmap header structure, if a file name exists. To store the names in fmaps, an optional name argument has been added to any internal scan API's that create fmaps and every call to these APIs has been modified to pass a file name or NULL if a file name is not required. The zip and gpt parsers required some modification to record file names. The NSIS and XAR parsers fail to collect file names at all and will require future work to support file name extraction. Also: - Added recursive extraction to the tmp directory when the --leave-temps option is enabled. When not enabled, the tmp directory structure remains flat so as to prevent the likelihood of exceeding MAX_PATH. The current tmp directory is stored in the scan context. - Made the cli_scanfile() internal API non-static and added it to scanners.h so it would be accessible outside of scanners.c in order to remove code duplication within libmspack.c. - Added function comments to scanners.h and matcher.h - Converted a TDB-type macros and LSIG-type macros to enums for improved type safey. - Converted more return status variables from `int` to `cl_error_t` for improved type safety, and corrected ooxml file typing functions so they use `cli_file_t` exclusively rather than mixing types with `cl_error_t`. - Restructured the magic_scandesc() function to use goto's for error handling and removed the early_ret_from_magicscan() macro and magic_scandesc_cleanup() function. This makes the code easier to read and made it easier to add the recursive tmp directory cleanup to magic_scandesc(). - Corrected zip, egg, rar filename extraction issues. - Removed use of extra sub-directory layer for zip, egg, and rar file extraction. For Zip, this also involved changing the extracted filenames to be randomly generated rather than using the "zip.###" file name scheme.
2020-03-19 21:23:54 -04:00
}
if (!ctx->engine->keeptmp && tempfile_exists) {
if (cli_unlink(tmp_fname)) {
ret = CL_EUNLINK;
goto done;
}
}
free(tmp_fname);
tmp_fname = NULL;
files++;
}
done:
if (NULL != tmp_fname) {
if (!ctx->engine->keeptmp && tempfile_exists) {
(void)cli_unlink(tmp_fname);
}
free(tmp_fname);
}
if (NULL != cab_d) {
if (NULL != cab_h) {
cab_d->close(cab_d, cab_h);
}
mspack_destroy_cab_decompressor(cab_d);
}
return ret;
}
cl_error_t cli_scanmschm(cli_ctx *ctx)
{
cl_error_t ret = CL_SUCCESS;
struct mschm_decompressor *mschm_d = NULL;
struct mschmd_header *mschm_h = NULL;
struct mschmd_file *mschm_f = NULL;
int files;
struct mspack_name mspack_fmap = {
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
.fmap = ctx->fmap,
};
struct mspack_system_ex ops_ex;
char *tmp_fname = NULL;
bool tempfile_exists = false;
memset(&ops_ex, 0, sizeof(struct mspack_system_ex));
ops_ex.ops = mspack_sys_fmap_ops;
mschm_d = mspack_create_chm_decompressor(&ops_ex.ops);
if (!mschm_d) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
ret = CL_EUNPACK;
goto done;
}
mschm_h = mschm_d->open(mschm_d, (char *)&mspack_fmap);
if (!mschm_h) {
cli_dbgmsg("%s() failed at %d\n", __func__, __LINE__);
ret = CL_EFORMAT;
goto done;
}
files = 0;
for (mschm_f = mschm_h->files; mschm_f; mschm_f = mschm_f->next) {
uint64_t max_size;
ret = cli_matchmeta(ctx, mschm_f->filename, 0, mschm_f->length,
0, files, 0);
if (CL_SUCCESS != ret) {
goto done;
}
if (ctx->engine->maxscansize) {
if (ctx->scansize >= ctx->engine->maxscansize) {
ret = CL_CLEAN;
goto done;
}
}
if (ctx->engine->maxfilesize > 0) {
// max filesize has been set
if ((ctx->engine->maxscansize > 0) &&
(ctx->scansize + ctx->engine->maxfilesize >= ctx->engine->maxscansize)) {
// ... but would exceed max scansize, shrink it.
max_size = ctx->engine->maxscansize - ctx->scansize;
} else {
// ... and will work
max_size = ctx->engine->maxfilesize;
}
} else {
// max filesize not specified
if ((ctx->engine->maxscansize > 0) &&
(ctx->scansize + UINT32_MAX >= ctx->engine->maxscansize)) {
// ... but UINT32_MAX would exceed max scansize, shrink it.
max_size = ctx->engine->maxscansize - ctx->scansize;
} else {
// ... use UINT32_MAX
max_size = UINT32_MAX;
}
}
libclamav: Add engine option to toggle temp directory recursion Temp directory recursion in ClamAV is when each layer of a scan gets its own temp directory in the parent layer's temp directory. In addition to temp directory recursion, ClamAV has been creating a new subdirectory for each file scan as a risk-adverse method to ensure no temporary file leaks fill up the disk. Creating a directory is relatively slow on Windows in particular if scanning a lot of very small files. This commit: 1. Separates the temp directory recursion feature from the leave-temps feature so that libclamav can leave temp files without making subdirectories for each file scanned. 2. Makes it so that when temp directory recursion is off, libclamav will just use the configure temp directory for all files. The new option to enable temp directory recursion is for libclamav-only at this time. It is off by default, and you can enable it like this: ```c cl_engine_set_num(engine, CL_ENGINE_TMPDIR_RECURSION, 1); ``` For the `clamscan` and `clamd` programs, temp directory recursion will be enabled when `--leave-temps` / `LeaveTemporaryFiles` is enabled. The difference is that when disabled, it will return to using the configured temp directory without making a subdirectory for each file scanned, so as to improve scan performance for small files, mostly on Windows. Under the hood, this commit also: 1. Cleans up how we keep track of tmpdirs for each layer. The goal here is to align how we keep track of layer-specific stuff using the scan_layer structure. 2. Cleans up how we record metadata JSON for embedded files. Note: Embedded files being different from Contained files, as they are extracted not with a parser, but by finding them with file type magic signatures. CLAM-1583
2025-06-09 20:42:31 -04:00
tmp_fname = cli_gentemp(ctx->this_layer_tmpdir);
if (!tmp_fname) {
ret = CL_EMEM;
break;
}
ops_ex.max_size = max_size;
/* scan */
ret = mschm_d->extract(mschm_d, mschm_f, tmp_fname);
if (ret) {
/* Failed to extract. Try to scan what is there */
cli_dbgmsg("%s() failed to extract %d\n", __func__, ret);
}
tempfile_exists = true; // probably
ret = cli_magic_scan_file(tmp_fname, ctx, mschm_f->filename, LAYER_ATTRIBUTES_NONE);
Record names of extracted files A way is needed to record scanned file names for two purposes: 1. File names (and extensions) must be stored in the json metadata properties recorded when using the --gen-json clamscan option. Future work may use this to compare file extensions with detected file types. 2. File names are useful when interpretting tmp directory output when using the --leave-temps option. This commit enables file name retention for later use by storing file names in the fmap header structure, if a file name exists. To store the names in fmaps, an optional name argument has been added to any internal scan API's that create fmaps and every call to these APIs has been modified to pass a file name or NULL if a file name is not required. The zip and gpt parsers required some modification to record file names. The NSIS and XAR parsers fail to collect file names at all and will require future work to support file name extraction. Also: - Added recursive extraction to the tmp directory when the --leave-temps option is enabled. When not enabled, the tmp directory structure remains flat so as to prevent the likelihood of exceeding MAX_PATH. The current tmp directory is stored in the scan context. - Made the cli_scanfile() internal API non-static and added it to scanners.h so it would be accessible outside of scanners.c in order to remove code duplication within libmspack.c. - Added function comments to scanners.h and matcher.h - Converted a TDB-type macros and LSIG-type macros to enums for improved type safey. - Converted more return status variables from `int` to `cl_error_t` for improved type safety, and corrected ooxml file typing functions so they use `cli_file_t` exclusively rather than mixing types with `cl_error_t`. - Restructured the magic_scandesc() function to use goto's for error handling and removed the early_ret_from_magicscan() macro and magic_scandesc_cleanup() function. This makes the code easier to read and made it easier to add the recursive tmp directory cleanup to magic_scandesc(). - Corrected zip, egg, rar filename extraction issues. - Removed use of extra sub-directory layer for zip, egg, and rar file extraction. For Zip, this also involved changing the extracted filenames to be randomly generated rather than using the "zip.###" file name scheme.
2020-03-19 21:23:54 -04:00
if (CL_EOPEN == ret) {
// okay so the file didn't actually get extracted. That's okay, we'll move on.
tempfile_exists = false;
ret = CL_SUCCESS;
} else if (CL_SUCCESS != ret) {
goto done;
Record names of extracted files A way is needed to record scanned file names for two purposes: 1. File names (and extensions) must be stored in the json metadata properties recorded when using the --gen-json clamscan option. Future work may use this to compare file extensions with detected file types. 2. File names are useful when interpretting tmp directory output when using the --leave-temps option. This commit enables file name retention for later use by storing file names in the fmap header structure, if a file name exists. To store the names in fmaps, an optional name argument has been added to any internal scan API's that create fmaps and every call to these APIs has been modified to pass a file name or NULL if a file name is not required. The zip and gpt parsers required some modification to record file names. The NSIS and XAR parsers fail to collect file names at all and will require future work to support file name extraction. Also: - Added recursive extraction to the tmp directory when the --leave-temps option is enabled. When not enabled, the tmp directory structure remains flat so as to prevent the likelihood of exceeding MAX_PATH. The current tmp directory is stored in the scan context. - Made the cli_scanfile() internal API non-static and added it to scanners.h so it would be accessible outside of scanners.c in order to remove code duplication within libmspack.c. - Added function comments to scanners.h and matcher.h - Converted a TDB-type macros and LSIG-type macros to enums for improved type safey. - Converted more return status variables from `int` to `cl_error_t` for improved type safety, and corrected ooxml file typing functions so they use `cli_file_t` exclusively rather than mixing types with `cl_error_t`. - Restructured the magic_scandesc() function to use goto's for error handling and removed the early_ret_from_magicscan() macro and magic_scandesc_cleanup() function. This makes the code easier to read and made it easier to add the recursive tmp directory cleanup to magic_scandesc(). - Corrected zip, egg, rar filename extraction issues. - Removed use of extra sub-directory layer for zip, egg, and rar file extraction. For Zip, this also involved changing the extracted filenames to be randomly generated rather than using the "zip.###" file name scheme.
2020-03-19 21:23:54 -04:00
}
if (!ctx->engine->keeptmp && tempfile_exists) {
if (cli_unlink(tmp_fname)) {
ret = CL_EUNLINK;
goto done;
}
}
free(tmp_fname);
tmp_fname = NULL;
files++;
}
done:
if (NULL != tmp_fname) {
if (!ctx->engine->keeptmp && tempfile_exists) {
(void)cli_unlink(tmp_fname);
}
free(tmp_fname);
}
if (NULL != mschm_d) {
if (NULL != mschm_h) {
mschm_d->close(mschm_d, mschm_h);
}
mspack_destroy_chm_decompressor(mschm_d);
}
return ret;
}