Commit graph

68 commits

Author SHA1 Message Date
Val S.
23c3cc05f1
Windows: fix number of arguments in function call (#1586)
Some checks failed
clang-format / check-16 (push) Has been cancelled
CMake Build / build-windows (push) Has been cancelled
CMake Build / build-macos (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
CMake Build / build-ubuntu (push) Has been cancelled
clang-format / check (push) Has been cancelled
clang-format / check-1 (push) Has been cancelled
clang-format / check-2 (push) Has been cancelled
clang-format / check-3 (push) Has been cancelled
clang-format / check-4 (push) Has been cancelled
clang-format / check-5 (push) Has been cancelled
clang-format / check-6 (push) Has been cancelled
clang-format / check-7 (push) Has been cancelled
clang-format / check-8 (push) Has been cancelled
clang-format / check-9 (push) Has been cancelled
clang-format / check-10 (push) Has been cancelled
clang-format / check-11 (push) Has been cancelled
clang-format / check-12 (push) Has been cancelled
clang-format / check-13 (push) Has been cancelled
clang-format / check-14 (push) Has been cancelled
clang-format / check-15 (push) Has been cancelled
CodeQL / Analyze-1 (push) Has been cancelled
Fix the number of NULL arguments in `scanmem.c` call to `cl_scandesc_ex()`.
2025-10-04 22:33:01 -04:00
Val S.
d4114e0d2c
Fix static analysis code quality issues; Fix old libjson-c support (#1574)
`clamscan/manager.c`: Fix double-free in an error condition in `scanfile()`.

`common/optparser.c`: Fix uninitialized use of the `numarg` variable when
`arg` is `NULL`.

`libclamav/cache.c`: Don't check if `ctx-fmap` is `NULL` when we've
already dereferenced it.

`libclamav/crypto.c`: The `win_exception` variable and associated logic
is Windows-specific and so needs preprocessor platform checks. Otherwise
it generates unused variable warnings.

`libclamav/crypto.c`: Check for `size_t` overflow of the `byte_read`
variable in the `cl_hash_file_fd_ex()` function.

`libclamav/crypto.c`: Fix a memory leak in the `cl_hash_file_fd_ex()`
function.

`libclamav/fmap.c`: Correctly the `name` and `path` pointer if
`fmap_duplicate()` fails. Also need to clear those variables when
duplicating the parent `map` so that on error it does not free the wrong
`name` or `path`.

`libclamav/fmap.c`: Refine error handling for `hash_string` cleanup in
`cl_fmap_get_hash()`. Coverity's complaint was that `hash_string` could
never be non-NULL if `status` is not `CL_SUCCESS`. I.e., the cleanup is
dead code. I don't think my cleanup actually "fixes" that though it is
definitely a better way to do the error handling.
The `if (NULL != hash_string) {` check is still technically dead code.
It safeguards against future changes that may `goto done` between the
allocation and transfering ownership from `hash_string` to `hash_out`.

`libclamav/others.c`: Fix possible memory leak in `cli_recursion_stack_push()`.

`libclamav/others.c`: Refactor an if/else + switch statement inside
`cli_dispatch_scan_callback()` so that the `CL_SCAN_CALLBACK_ALERT` case
is not dead-code. It's also easier to read now.

`libclamav/pdfdecode.c`: For logging, use the `%zu` to format `size_t`
instead of casting to `long long` and using `%llu`. Simiularly use the
`STDu32` format string macro for `uint32_t`.

`libclamav/pdfdecode.c`: Fix a possible double-free for the `decoded`
pointer in `filter_lzwdecode()`.

`libclamav/pdfdecode.c`: Remove the `if (capacity > UINT_MAX) {`
overflow check inside `filter_lzwdecode()`, which didn't do anything.
The `capacity` variable this point is a fixed value and so I also changed
the `avail_out` to be that fixed `INFLATE_CHUNK_SIZE` value rather than
using `capacity`. It is more straightforward and replicates how similar
logic works later in the file.
I also removed the copy-pasted `(Bytef *)` cast which didn't reaaally do
anything, and was a copypaste from a different algorihm. The lzw
implementation interface doesn't use `Bytef`.

`libclamav/readdb.c`: Fix a possible NULL-deref on the `matcher` variable
in the error handling/cleanup code if the function fails.

`libclamav/scanners.c`: Fix an issue where the return value from some of
the parsers may be lost/overridden by the call to
`cli_dispatch_scan_callback()` just after the `done:` label in
`cli_magic_scan()`.

`libclamav/scanners.c`: Silence an unused-return value warning when
calling `cli_basename()`.

`sigtool/sigtool.c` and `unit_tests/check_regex.c`:
Fix possible NULL-derefs of the `ctx.recursion_stack` pointer in the error
handling for several functions.

Also, and this isn't a Coverity thing:

`libclamav/json_api.c` and `libclamav/others.c`:
Fix support for libjson-c version 0.13 and older.
I don't think we *should* be using the old version, but some environments
such as the current OSS-Fuzz base image are older and still use it.
The issue is that `json_object_new_uint64()` was introduced in a later
libjson-c version, so we have to fallback to use `json_object_new_int64()`
with older libjson-c, provided the int were storing isn't too big.

CLAM-2768
2025-09-26 18:26:00 -04:00
Val S.
1d158c13d4
Fix NULL-dereference crash with some command line options (#1567)
It is possible to crash freshclam and probably other programs like this:
```
freshclam --datadir /any/path
```

CLAM-2860
2025-09-15 18:16:09 -04:00
Valerie Snyder
6d9b57eeeb
libclamav: cl_scan*_ex() functions provide verdict separate from errors
It is a shortcoming of existing scan APIs that it is not possible
to return an error without masking a verdict.
We presently work around this limitation by counting up detections at
the end and then overriding the error code with `CL_VIRUS`, if necessary.

The `cl_scanfile_ex()`, `cl_scandesc_ex()`, and `cl_scanmap_ex()` functions
should provide the scan verdict separately from the error code.

This introduces a new enum for recording and reporting a verdict:
`cl_verdict_t` with options:

- `CL_VERDICT_NOTHING_FOUND`
- `CL_VERDICT_TRUSTED`
- `CL_VERDICT_STRONG_INDICATOR`
- `CL_VERDICT_POTENTIALLY_UNWANTED`

Notably, the newer scan APIs may set the verdict to `CL_VERDICT_TRUSTED`
if there is a (hash-based) FP signature for a file, or in the cause where
Authenticode or similar certificate-based verification was performed, or
in the case where an application scan callback returned `CL_VERIFIED`.

CLAM-763
CLAM-865
2025-08-14 22:40:46 -04:00
Valerie Snyder
13c4788f36
FIPS & FIPS-like limits on hash algs for cryptographic uses
ClamAV will not function when using a FIPS-enabled OpenSSL 3.x.
This is because ClamAV uses MD5 and SHA1 algorithms for a variety of
purposes including matching for malware detection, matching to prevent
false positives on known-clean files, and for verification of MD5-based
RSA digital signatures for determining CVD (signature database archive)
authenticity.

Interestingly, FIPS had been intentionally bypassed when creating hashes
based whole buffers and whole files (by descriptor or `FILE`-pointer):
78d4a9985a
Note: this bypassed FIPS the 1.x way with:
`EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);`

It was NOT disabled when using `cl_hash_init()` / `cl_update_hash()` /
`cl_finish_hash()`. That likely worked by coincidence in that the hash
was already calculated most of the time. It certainly would have made
use of those functions if the hash had not been calculated prior:
78d4a9985a/libclamav/matcher.c (L743)

Regardless, bypassing FIPS entirely is not the correct solution.
The FIPS restrictions against using MD5 and SHA1 are valid, particularly
when verifying CVD digital siganatures, but also I think when using a
hash to determine if the file is known-clean (i.e. the "clean cache" and
also MD5-based and SHA1-based FP signatures).

This commit extends the work to bypass FIPS using the newer 3.x method:
`md = EVP_MD_fetch(NULL, alg, "-fips");`

It does this for the legacy `cl_hash*()` functions including
`cl_hash_init()` / `cl_update_hash()` / `cl_finish_hash()`.
It also introduces extended versions that allow the caller to choose if
they want to bypass FIPS:
- `cl_hash_data_ex()`
- `cl_hash_init_ex()`
- `cl_update_hash_ex()`
- `cl_finish_hash_ex()`
- `cl_hash_destroy_ex()`
- `cl_hash_file_fd_ex()`
See the `flags` parameter for each.

Ironically, this commit does NOT use the new functions at this time.
The rational is that ClamAV may need MD5, SHA1, and SHA-256 hashes of
the same files both for determining if the file is malware, and for
determining if the file is clean.

So instead, this commit will do a checks when:

1. Creating a new ClamAV scanning engine. If FIPS-mode enabled, it will
   automatically toggle the "FIPS limits" engine option.
   When loading signatures, if the engine "FIPS limits" option is enabled,
   then MD5 and SHA1 FP signatures will be skipped.

2. Before verifying a CVD (e.g. also for loading, unpacking when
   verification enabled).
   If "FIPS limits" or FIPS-mode are enabled, then the legacy MD5-based RSA
   method is disabled.

   Note: This commit also refactors the interface for `cl_cvdverify_ex()`
   and `cl_cvdunpack_ex()` so they take a `flags` parameters, rather than a
   single `bool`. As these functions are new in this version, it does not
   break the ABI.

The cache was already switched to use SHA2-256, so that's not a concern
for checking FIPS-mode / FIPS limits options.

This adds an option for `freshclam.conf` and `clamd.conf`:

   FIPSCryptoHashLimits yes

And an equivalent command-line option for `clamscan` and `sigtool`:

   --fips-limits

You may programmatically enable FIPS-limits for a ClamAV engine like this:
```C
   cl_engine_set_num(engine, CL_ENGINE_FIPS_LIMITS, 1);
```

CLAM-2792
2025-08-14 22:39:15 -04:00
Valerie Snyder
51adfb8b61
ClamScan & libclamav: improve precision of bytes-scanned, bytes-read
The ClamScan scan summary prints bytes scanned and bytes read in
multiples of 4096 (aka `CL_COUNT_PRECISION`), as is provided by the
`cl_scanfile()`, `cl_scandesc()`, `cl_scanfile_callback()`, and
`cl_scandesc_callback()` functions.

I believe this imprecision was the result of using an `unsigned long int`
which may be 64bit or 32bit, depending on platform. I believe the
intention was to be able to support scanning more than 4 GiB of data.

Since the new `cl_scan*_ex()` functions use a `uint64_t`, which
guarantees a 64bit integer and supports ~16,777,216 terabytes, I find no
reason not to report an accurate count.

For the legacy scan functions (above) I've kept the `CL_COUNT_PRECISION`
behavior to maintain backwards compatibility.

I have also improved the bytes scanned/read output to report GiB, MiB,
KiB, or B as appropriate. Previously, it always report "MB".

CLAM-1433
2025-08-14 22:39:15 -04:00
Valerie Snyder
466c875d69
ClamScan: Add hash & file-type in/out CLI options
Adds the following ClamScan CLI options:

* --hash-hint

  The file hash so that libclamav does not need to calculate it.
  The type of hash must match the '--hash-alg'.

* --log-hash

  Print the file hash after each file scanned.
  The type of hash printed will match the '--hash-alg'.

* --hash-alg

  The hashing algorithm used for either '--hash-hint' or '--log-hash'.
  Supported algorithms are 'md5', 'sha1', 'sha2-256'.
  If not specified, the default is 'sha2-256'.

* --file-type-hint

  The file type hint so that libclamav can optimize scanning.
  E.g. 'pe', 'elf', 'zip', etc.
  You may also use ClamAV type names such as 'CL_TYPE_PE'.
  ClamAV will ignore the hint if it is not familiar with the specified type.
  See also: https://docs.clamav.net/appendix/FileTypes.html#file-types

* --log-file-type

  Print the file type after each file scanned.

Will NOT be adding this for ClamDScan, as we don't have a mechanism
in the ClamD socket API to receive scan options or a way for ClamD
to include scan metadata in the response.
2025-08-14 22:39:12 -04:00
Valerie Snyder
aa7b7e9421
Swap clean cache from MD5 to SHA2-256
Change the clean-cache to use SHA2-256 instead of MD5.
Note that all references are changed to specify "SHA2-256" now instead
of "SHA256", for clarity. But there is no plan to add support for SHA3
algorithms at this time.

Significant code cleanup. E.g.:
- Implemented goto-done error handling.
- Used `uint8_t *` instead of `unsigned char *`.
- Use `bool` for boolean checks, rather than `int.
- Used `#defines` instead of magic numbers.
- Removed duplicate `#defines` for things like hash length.

Add new option to calculate and record additional hash types when the
"generate metadata JSON" feature is enabled:
- libclamav option: `CL_SCAN_GENERAL_STORE_EXTRA_HASHES`
- clamscan option: `--json-store-extra-hashes` (default off)
- clamd.conf option: `JsonStoreExtraHashes` (default 'no')

Renamed the sigtool option `--sha256` to `--sha2-256`.
The original option is still functional, but is deprecated.

For the "generate metadata JSON" feature, the file hash is now stored as
"sha2-256" instead of "FileMD5". If you enable the "extra hashes" option,
then it will also record "md5" and "sha1".

Deprecate and disable the internal "SHA collect" feature.
This option had been hidden behind C #ifdef checks for an option that
wasn't exposed through CMake, so it was basically unavailable anyways.

Changes to calculate file hashes when they're needed and no sooner.

For the FP feature in the matcher module, I have mimiced the
optimization in the FMAP scan routine which makes it so that it can
calculate multiple hashes in a single pass of the file.

The `HandlerType` feature stores a hash of the file in the scan ctx to
prevent retyping the exact same data more than once.
I removed that hash field and replaced it with an attribute flag that is
applied to the new recursion stack layer when retyping a file.
This also closes a minor bug that would prevent retyping a file with an
all-zero hash. :)

The work upgrading cache.c to support SHA2-256 sized hashes thanks to:
https://github.com/m-sola

CLAM-255
CLAM-1858
CLAM-1859
CLAM-1860
2025-08-14 21:23:30 -04:00
Valerie Snyder
18854bf4bc
Windows: Fix filepath basename issue
On Windows, the cli_basename function should treat both '/' and '\' as path
separators. Most Windows APIs also accept both.

On Linux/Unix, it makes sense when using a filepath that is more for
informational purposes or where it may have come from a Windows system,
to treat the '\' as a path separator.
But in situations where the the path is needed for some critical action,
like moving or deleting a file, we can't treat it as a path separator.
2025-08-11 18:14:19 -04:00
ember91
89bacba696
Windows: Fix issue printing unicode filenames (#1461)
On Windows, use CP_UTF8 over CP_OEMCP for output.
2025-07-25 17:42:43 -04:00
Val S.
dd033361fc
Merge pull request #1514 from val-ms/CLAM-2790-missing-JsonStore-clamd-checks
clamd: Add missing scan option checks for PDF and HTML URIs
2025-06-06 16:09:59 -04:00
Valerie Snyder
9d4fcbdb1e
clamd: Add missing scan option checks for PDF and HTML URIs 2025-06-04 14:06:52 -04:00
a3be0d2d45
clamd: Add options to toggle SHUTDOWN, RELOAD, STATS and VERSION (#1502)
The `clamd` protocol lacks authentication or authorization controls
needed to limit access to more administrative commands.
Depending on your use case, disabling some commands like `SHUTDOWN`
may improve the security of the scanning daemon.

This commit adds options to enable/disable the `SHUTDOWN`, `RELOAD`,
`STATS` and `VERSION` commands in `clamd.conf`.
When a client sends one of the following commands but it is disabled,
`clamd` will respond with "COMMAND UNAVAILABLE".

The new `clamd.conf` options are:

- `EnableShutdownCommand`: Enable the `SHUTDOWN` command.
  Setting this to no prevents a client to stop `clamd` via the
  protocol.
  Default: yes

- `EnableReloadCommand` Enable the `RELOAD` command.
  Setting this to no prevents a client to reload the database.
  This disables Freshclam's `NotifyClamd` option. 
  `clamd` monitors for database directory changes, so this should 
  Default: yes

- `EnableStatsCommand` Enable the `STATS` command.
  Setting this to no prevents a client from querying statistics.
  This disables the `clamdtop` program.
  Default: yes

- `EnableVersionCommand` Enable the `VERSION` command.
  Setting this to no prevents a client from querying version
  information.
  This disables the `clamdtop` program and will cause `clamdscan` to
  display a warning when using the `--version` option.
  Default: yes

Resolves: https://github.com/Cisco-Talos/clamav/issues/922
Resolves: https://github.com/Cisco-Talos/clamav/issues/1169
Related: https://github.com/Cisco-Talos/clamav/pull/347
2025-06-04 10:47:57 -04:00
Val S.
e86919789f
Merge pull request #1482 from jhumlick/CLAM-2588-PDF-Urls
Clam 2588 Record PDF URIs if generating scan metadata
2025-05-31 18:57:00 -04:00
John Humlick
e1e3d4c64d
libclamav: Add URI scanning support to PDF parser
Threat Research requests scanning URIs in PDF files and adding them to
the json report file.

This change adds URI scanning support to the PDF parser, including
support for object references to URIs in PDF files.

Jira: CLAM-2588

Fix out-of-order references and other minor improvements.

CLAM-2588, CLAM-2757
2025-05-30 12:41:17 -07:00
Valerie Snyder
7bfe63f639
Extend config inline comment support to exclude leading tabs
E.g. this will also be valid:
```freshclam.conf
DatabaseMirror http://localhost:8000<tab># My private server.
```

Also:
- Fix compile warning regarding unnecessarily const string variable.
- Add parenthesis to resolve inconsistency between clang-format and
  vscode auto-format.
- Add a macro defining the max config line length.
2025-05-24 14:35:36 -04:00
Stiliyan Tonev (Bark)
f4af8b2081
Support for inline comments in clamd, freshclam, clamav-milter config files
The config parser will now treat a '#' character in a config file as an
inline comment, allowing users to write configs like this:
```freshclam.conf
DatabaseMirror http://localhost:8000  # My private server
```
2025-05-24 14:32:08 -04:00
Val Snyder
272e84eaa8
Auto-format with clang-format 2025-03-26 20:00:14 -04:00
Val Snyder
8d485b9bfd
FIPS-compliant CVD signing and verification
Add X509 certificate chain based signing with PKCS7-PEM external
signatures distributed alongside CVD's in a custom .cvd.sign format.
This new signing and verification mechanism is primarily in support
of FIPS compliance.

Fixes: https://github.com/Cisco-Talos/clamav/issues/564

Add a Rust implementation for parsing, verifying, and unpacking CVD
files.

Now installs a 'certs' directory in the app config directory
(e.g. <prefix>/etc/certs). The install location is configurable.
The CMake option to configure the CVD certs directory is:
  `-D CVD_CERTS_DIRECTORY=PATH`

New options to set an alternative CVD certs directory:
- Commandline for freshclam, clamd, clamscan, and sigtool is:
  `--cvdcertsdir PATH`
- Env variable for freshclam, clamd, clamscan, and sigtool is:
  `CVD_CERTS_DIR`
- Config option for freshclam and clamd is:
  `CVDCertsDirectory PATH`

Sigtool:
- Add sign/verify commands.
- Also verify CDIFF external digital signatures when applying CDIFFs.
- Place commonly used commands at the top of --help string.
- Fix up manpage.

Freshclam:
- Will try to download .sign files to verify CVDs and CDIFFs.
- Fix an issue where making a CLD would only include the CFG file for
daily and not if patching any other database.

libclamav.so:
- Bump version to 13:0:1 (aka 12.1.0).
- Also remove libclamav.map versioning.
  Resolves: https://github.com/Cisco-Talos/clamav/issues/1304
- Add two new API's to the public clamav.h header:
  ```c
  extern cl_error_t cl_cvdverify_ex(const char *file,
                                    const char *certs_directory);

  extern cl_error_t cl_cvdunpack_ex(const char *file,
                                    const char *dir,
                                    bool dont_verify,
                                    const char *certs_directory);
  ```
  The original `cl_cvdverify` and `cl_cvdunpack` are deprecated.
- Add `cl_engine_field` enum option `CL_ENGINE_CVDCERTSDIR`.
  You may set this option with `cl_engine_set_str` and get it
  with `cl_engine_get_str`, to override the compiled in default
  CVD certs directory.

libfreshclam.so: Bump version to 4:0:0 (aka 4.0.0).

Add sigtool sign/verify tests and test certs.

Make it so downloadFile doesn't throw a warning if the server
doesn't have the .sign file.

Replace use of md5-based FP signatures in the unit tests with
sha256-based FP signatures because the md5 implementation used
by Python may be disabled in FIPS mode.
Fixes: https://github.com/Cisco-Talos/clamav/issues/1411

CMake: Add logic to enable the Rust openssl-sys / openssl-rs crates
to build against the same OpenSSL library as is used for the C build.
The Rust unit test application must also link directly with libcrypto
and libssl.

Fix some log messages with missing new lines.

Fix missing environment variable notes in --help messages and manpages.

Deconflict CONFDIR/DATADIR/CERTSDIR variable names that are defined in
clamav-config.h.in for libclamav from variable that had the same name
for use in clamav applications that use the optparser.

The 'clamav-test' certs for the unit tests will live for 10 years.
The 'clamav-beta.crt' public cert will only live for 120 days and will
be replaced before the stable release with a production 'clamav.crt'.
2025-03-26 19:33:25 -04:00
Micah Snyder
34bb516748
Windows: code quality improvement for --move and --remove options
When the --move or --remove options are used, ClamAV carefully traverses
the file path one layer at a time so as to avoid following a directory
that is a symlink or reparse point.
We do this for directories, but could also do it for files.
Only an admin should be able to create a reparse point for a file,
but it is better to be consistent.

Thank you to Maxim Suhanov for reporting this issue.
2025-03-19 17:36:05 -04:00
Val Snyder
7ff29b8c37
Bump copyright dates for 2025 2025-02-14 10:24:30 -05:00
Micah Snyder
2e544984f0
Freshclam, Sigtool, Clamconf: fix database line count if has empty lines
Fixes: https://github.com/Cisco-Talos/clamav/issues/1390
2024-10-30 17:45:36 -04:00
Andy Ragusa
666e047f2b
Store URLs from HTML when recording scan metadata json
Store URLs found in HTML `<a>` and `<form>` tags during scan of HTML files
when recording scan metadata.

HTML URL recording will be ON by default, but is a part of the
generate-metadata-json feature.
The generate-metadata-json feature is OFF by default.

This introduces a new general scan option:
- libclamav: `CL_SCAN_GENERAL_STORE_HTML_URLS`.
- ClamD: `JsonStoreHTMLUrls`.
- ClamScan: `--json-store-html-urls`

Thank you Matt Jolly for the helpful comment on the pull request.
2024-09-11 13:40:29 -04:00
Micah Snyder
88efeda2a4
Disable following symlinks when opening log files
The log module used by clamd and freshclam may follow symlinks.
This is a potential security concern since the log may be owned by
the unprivileged service but may be opened by the service running as
root on startup.

For Windows, we'll define O_NOFOLLOW so the code works, though the issue
does not affect Windows.

Issue reported by Detlef.
2024-09-04 13:15:42 -04:00
RainRat
143d23c326
Fix typos and remove duplicate #include 2024-04-10 19:31:46 -04:00
Micah Snyder
e48dfad49a Windows: Fix C/Rust FFI compat issue + Windows compile warnings
Primarily this commit fixes an issue with the size of the parameters
passed to cli_checklimits(). The parameters were "unsigned long", which
varies in size depending on platform.
I've switched them to uint64_t / u64.

While working on this, I observed some concerning warnigns on Windows,
and some less serious ones, primarily regarding inconsistencies with
`const` parameters.

Finally, in `scanmem.c`, there is a warning regarding use of `wchar_t *`
with `GetModuleFileNameEx()` instead of `GetModuleFileNameExW()`.
This made me realize this code assumes we're not defining `UNICODE`,
which would have such macros use the 'A' variant.
I have fixed it the best I can, although I'm still a little
uncomfortable with some of this code that uses `char` or `wchar_t`
instead of TCHAR.

I also remove the `if (GetModuleFileNameEx) {` conditional, because this
macro/function will always be defined. The original code was checking a
function pointer, and so this was a bug when integrating into ClamAV.

Regarding the changes to `rijndael.c`, I found that this module assumes
`unsigned long` == 32bits. It does not.
I have corrected it to use `uint32_t`.
2024-04-09 10:35:22 -04:00
Micah Snyder
73c6d4619a Use regular malloc instead of max_alloc for utf16->8 conversion
Should be safe to allocate a smaller string than one we already have.
2024-03-15 13:18:47 -04:00
Micah Snyder
8e04c25fec Rename clamav memory allocation functions
We have some special functions to wrap malloc, calloc, and realloc to
make sure we don't allocate more than some limit, similar to the
max-filesize and max-scansize limits. Our wrappers are really only
needed when allocating memory for scans based on untrusted user input,
where a scan file could have bytes that claim you need to allocate
some ridiculous amount of memory. Right now they're named:
- cli_malloc
- cli_calloc
- cli_realloc
- cli_realloc2

... and these names do not convey their purpose

This commit renames them to:
- cli_max_malloc
- cli_max_calloc
- cli_max_realloc
- cli_max_realloc2

The realloc ones also have an additional feature in that they will not
free your pointer if you try to realloc to 0 bytes. Freeing the memory
is undefined by the C spec, and only done with some realloc
implementations, so this stabilizes on the behavior of not doing that,
which should prevent accidental double-free's.

So for the case where you may want to realloc and do not need to have a
maximum, this commit adds the following functions:
- cli_safer_realloc
- cli_safer_realloc2

These are used for the MPOOL_REALLOC and MPOOL_REALLOC2 macros when
MPOOL is disabled (e.g. because mmap-support is not found), so as to
match the behavior in the mpool_realloc/2 functions that do not make use
of the allocation-limit.
2024-03-15 13:18:47 -04:00
Micah Snyder
2cc47c83ac Make image fuzzy hashing optional
Image fuzzy hashing is enabled by default. The following options have
been added to allow users to disable it, if desired.

New clamscan options:

  --scan-image[=yes(*)/no]

  --scan-image-fuzzy-hash[=yes(*)/no]

New clamd config options:

  ScanImage yes(*)/no

  ScanImageFuzzyHash yes(*)/no

New libclamav scan options:

  options.parse &= ~CL_SCAN_PARSE_IMAGE;

  options.parse &= ~CL_SCAN_PARSE_IMAGE_FUZZY_HASH;

This commit also changes scan behavior to disable image fuzzy hashing
for specific types when the DCONF (.cfg) signatures disable those types.
That is, if DCONF disables the PNG parser, it should not only disable
the CVE/format checker for PNG files, but also disable image fuzzy
hashing for PNG files.

Also adds a DCONF option to disable image fuzzy hashing:
  OTHER_CONF_IMAGE_FUZZY_HASH

DCONF allows scanning features to be disabled using a configuration
"signature".
2024-03-14 16:57:48 -04:00
Micah Snyder
2f6b71eb98 ClamD: Disable VirusEvent '%f' feature, use environment var instead
The '%f' filename format character has been disabled and will no longer
be replaced with the file name, due to command injection security concerns.
Use the 'CLAM_VIRUSEVENT_FILENAME' environment variable instead.

For the same reason, you should NOT use the environment variables in the
command directly, but should use it carefully from your executed script.
2024-02-05 11:39:02 -05:00
Micah Snyder
9cb28e51e6 Bump copyright dates for 2024 2024-01-22 11:27:17 -05:00
RainRat
1b17e20571
Fix typos (no functional changes) 2024-01-19 09:08:36 -08:00
Lodewyk van der Westhuizen
2e999a196a fix typos in function descriptions 2023-12-14 13:16:21 -05:00
Micah Snyder
3b2f8c044a Support for extracting attachments from OneNote section files
Includes rudimentary support for getting slices from FMap's and for
interacting with libclamav's context structure.

For now will use a Cisco-Talos org fork of the onenote_parser
until the feature to read open a onenote section from a slice (instead
of from a filepath) is added to the upstream.
2023-12-11 15:18:41 -05:00
RainRat
caf324e544
Fix typos (no functional changes) 2023-11-26 18:01:19 -05:00
Micah Snyder
58937087aa Coverity-416448: Improve client certificate error handling 2023-08-08 09:39:37 -07:00
Micah Snyder
eb139c6e7d Extend freshclam client key/cert auth to macOS and Windows
Also:
- Rename to use FRESHCLAM_CLIENT_CERT, FRESHCLAM_CLIENT_KEY instead
  prefixing with "CURL_". Unlike CURL_CA_BUNDLE, these variable names
  are not used by the `curl` program and so do not piggyback on that
  existing functionality.

- Add FRESHCLAM_CLIENT_KEY_PASSWD environment variable to support
  password protected private key PEM files, as described in:
  https://curl.se/libcurl/c/CURLOPT_SSLCERT.html

- Document the new environment variable options in the manpage and in
  the `freshclam --help` message. Also add missing documentation in the
  freshclam and clamsubmit help-messages for CURL_CA_BUNDLE.

- Update the NEWS.md file to credit jedrzej for the new feature.
2023-08-03 19:31:36 -07:00
Jedrzej Jajor
ab288d5136 Allow to use client authentication with certificate in freshclam 2023-08-03 19:31:36 -07:00
ChrisWi
ed630ab5a9 harmonize socket/pid file path to those used in Docker 2023-08-03 09:23:29 -07:00
Matthias Fratz
2962509609 Raise artificial 4G limit for MaxScanSize
This limit is internally "long long", so >=64-bit even on 32-bit platforms.
Also fixes a related issue where limits could have been set to negative
values on 64-bit platforms where setting a "long long" (64-bit signed) can
overflow if assigned from an "unsigned long" (64-bit unsigned).

Resolves: https://github.com/Cisco-Talos/clamav/issues/809
2023-08-03 00:23:38 -07:00
Craig Andrews
e70493cf61 Add options: --cache-size, CacheSize
* Add new clamd and clamscan option --cache-size

This option allows you to set the number of entries the cache can store.

Additionally, introduce CacheSize as a clamd.conf
synonym for --cache-size.

Fixes #867
2023-05-16 19:18:30 -07:00
Andy Ragusa
f683571de5 Sigtool: Add vba macro support for OOXML files
Add a new cl_engine_set_clcb_vba() function to set a cb_vba callback
function and add clcb_generic_data handler prototype to the clamav.h
public API.

The cb_vba callback function will be run whenever VBA is extracted from
office documents. The provided data will be a normalized copy of the
original VBA. This callback is added to support Sigtool so it can use
the same VBA extraction logic as when scanning documents.

Change the Sigtool temp directory creation for any commands that use
temp directories so that you can select a custom temp directory with the
`--tempdir=PATH` option, and can retain the temp files with the
`--leave-temps` option.

Added `--tempdir` and `--leave-temps` to the Sigtool `--help` output.
Added `--tempdir` and `--leave-temps` to the Sigtool manpage.
2023-03-29 22:21:37 -07:00
Răzvan Cojocaru
e4fe6654c1
Add options: --fail-if-cvd-older-than, FailIfCvdOlderThan
* Add a new function cl_cvdgetage() to the libclamav API. 

This function will retrieve the age of the youngest file in a
database directory, or the age of a single CVD (or CLD) file.

* Add new clamscan option --fail-if-cvd-older-than=days

When passed, causes clamscan to exit with a non-zero return code
if the virus database is older than the specified number of days.

* Add new clamd option --fail-if-cvd-older-than=days

When passed, causes clamd to exit on start-up with a non-zero
return code if the virus database is older than the specified
number of days.

Additionally, we introduce FailIfCvdOlderThan as a clamd.conf
synonym for --fail-if-cvd-older-than.

Fixes #820
2023-03-28 14:22:48 -07:00
Micah Snyder
6eebecc303 Bump copyright for 2023 2023-02-12 11:20:22 -08:00
Micah Snyder
289baa1a7b Formatting: work-around for clang-format-14 #ifdef bug 2022-12-02 14:22:31 -08:00
Michael Orlitzky
7374029897 */*: fix invalid prototypes.
Prototypes (or the declarations themselves, if there is no
corresponding prototype) for functions that take no arguments are
required by the C standard to specify (void) as their argument list;
for example,

  regex_pcre.h:79:1: error: function declaration isn't a prototype
  [-Werror=strict-prototypes]
     79 | cl_error_t cli_pcre_init_internal();

Future versions of clang may become strict about this, and there's no
harm in conforming to the standard right now, so we fix all such
instances in this commit.
2022-11-22 23:22:57 -08:00
Micah Snyder
15f9979016 Fix certificate load x509 -> PEM result check
It appears the result from the _x509_to_pem() function was accidentally hardcoded to a `0` (success)
2022-10-19 13:13:57 -07:00
Micah Snyder
89b72cb002
Sigtool: Add --fuzzy-img option to generate image fuzzy hash
Add `sigtool --fuzzy-img` option to generate image fuzzy hash.

Also fix assorted warnings, mostly ensuring enough buffer space so format
strings aren't truncated.

For the dsig change: the returned string is allocated and is not const.
The caller will have to free it.
2022-03-24 16:11:50 -07:00
Micah Snyder
15eef50656 Code cleanup: Refactor to clean up formatting issues
Refactored the clamscan code that determines 'what to scan' in order
to clean up some very messy logic and also to get around a difference in
how vscode and clang-format handle formatting #ifdef blocks in the
middle of an else/if.

In addition to refactoring, there is a slight behavior improvement. With
this change, doing `clamscan blah -` will now scan `blah` and then also
scan `stdin`.  You can even do `clamscan - blah` to now scan `stdin` and
then scan `blah`. Before, The `-` had to be the only "filename" argument
in order to scan from stdin.

In addition, added a bunch of extra empty lines or changing multi-line
function calls to single-line function calls in order to get around a
bug in clang-format with these two options do not playing nice together:
- AlignConsecutiveAssignments: true
- AlignAfterOpenBracket: true

AlignAfterOpenBracket is not taking account the spaces inserted by
AlignConsecutiveAssignments, so you end up with stuff like this:
```c
    bleeblah = 1;
    blah     = function(arg1,
                    arg2,
                    arg3);

                //  ^--- these args 4-left from where they should be.
```

VSCode, meanwhile, somehow fixes this whitespace issue so code that is
correctly formatted by VSCode doesn't have this bug, meaning that:

1. The clang-format check in GH Actions fails.
2. We'd all have to stop using format-on-save in VSCode and accept the
  bug if we wanted those GH Actions tests to pass.

Adding an empty line before variable assignments from multi-line
function calls evades the buggy behavior.

This commit should resolve the clang-format github action test failures,
for now.
2022-03-22 10:42:46 -07:00
Micah Snyder
d1656ee241 Increase default file maximums
MaxFileSize        25M  -> 100M
MaxScanSize        100M -> 400M
StreamMaxLength    25M  -> 100M
MaxEmbeddedPE      10M  -> 40M
MaxHTMLNormalize   10M  -> 40M
MaxHTMLNoTags      2M   -> 8M
MaxScriptNormalize 5M   -> 20M
PCREMaxFileSIze    25M  -> 100M
2022-03-09 16:47:44 -08:00