Commit graph

51 commits

Author SHA1 Message Date
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
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
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
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
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
Andy Ragusa
29987c0eeb
Limit the max-recursion scan option to 100
There is presently no limit for the max-recursion scan option.
Selecting a max-recursion limit that is too high will cause confusing
errors. E.g.:

/home/aragusa/install.alz/bin/clamscan -d clamav.hdb . --max-recursion=9999999999

LibClamAV Error: fmap_fd: Attempted to get fd for NULL fmap
/home/aragusa/issue/clamav.hdb: Can't allocate memory ERROR
LibClamAV Error: fmap_fd: Attempted to get fd for NULL fmap
/home/aragusa/issue/test.sh: Can't allocate memory ERROR

This commit prevents setting the max-recursion limit higher than 100.
2024-09-09 12:32:29 -04:00
Micah Snyder
48393b67b8 clamscan: Add options missing from manpage and --help
The --force-to-disk option is missing from the clamscan --help and
clamscan manpage documentation.

Also change clamd.conf.sample suggestions to differ the from default
settings so that the sample is easier to use.
2024-03-14 16:57:48 -04:00
Andy Ragusa
ff8652bf2e Fix usage for --datadir option
Make the usage clear to the user that the option specified by
'--datadir' must be an absolute path to a directory that already exists,
and is writeable by freshclam and readable by clamscan/clamd.
2024-03-14 15:49:37 -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
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
Micah Snyder
4161986c25
Missing command line option documentation
The clamd and clamav-milter `--help` message and manpages do
not mention the `--pid` (`-p`) option.

The clamd `--help` message and manpage do not mention the
`--datadir` option.

Also corrected minor punctuation issues, and removed the meaningless
jargon about the "main thread" which has nothing to do with the PID.
2023-05-31 17:38:00 -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
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
Ben Bodenmiller
4f3fd4e417
Fix default BytecodeTimeout value in sample config 2022-07-11 12:10:42 -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
Micah Snyder
0a24f70218 Rename Heuristics.Email.ExceedsMax alerts
Rename Heuristics.Email.ExceedsMax alerts to start with
Heuristics.Limits.Exceeded.Email instead, so that all heuristic alerts
for exceeded scan limits have the same prefix.
2021-10-29 15:01:25 -07:00
Micah Snyder
db013a2bfd 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-10-25 16:02:29 -07:00
Micah Snyder
d8dc3f00f9 ClamD: Add GenerateMetadataJson option, like clamscan --gen-json
Adds an equivalent functionality to ClamScan's --gen-json option to
ClamD.

Behavior for GenerateMetadataJson is the same as with --gen-json.
If Debug is enabled, it will print out the JSON after each scan.
If LeaveTemporaryFiles is enabled, it will drop a metadat.json file
in the scan temp directory, which of course may be customized using
the TemporaryDirectory option.
2021-10-11 11:32:06 -07:00
Simon Arlott
1b276dbe93 Change ReceiveTimeout to use CURLOPT_LOW_SPEED_TIME
Currently ReceiveTimeout sets CURLOPT_TIMEOUT which is an absolute timeout
on the HTTP download and not particularly useful without knowing the size
of the file or the throughput available to download it.

Change it to use CURLOPT_LOW_SPEED_TIME instead, and set the related low
speed limit (CURLOPT_LOW_SPEED_LIMIT) to 1 byte per second. This will allow
the ReceiveTimeout to abort the attempt if the download is not making
any significant progress.

Restore the documentation, default and sample options back to before
2fd28e1d09 and
f5d465a864.

This fixes #266 and avoids problems caused by the Ubuntu default
ReceiveTimeout of 30 seconds.
2021-08-26 16:17:17 -07:00
Micah Snyder
e0e0c8f955 CMake: Support to build deb, rpm, & macOS pkg packages
CMake/CPack is already used to build:
- TGZ source tarball
- WiX-based installer (Windows)
- ZIP install packages (Windows)

This commit adds support for building:
- macOS PKG installer
- DEB package
- RPM package

This should also enable building FreeBSD packages, but while I was able
to build all of the static dependencies using Mussels, CMake/CPack 3.20
doesn't appear to have the the FreeBSD generator despite being in the
documentation.

The package names are will be in this format:
  clamav-<version><suffix>.<os>.<arch>.<extension>

This includes changing the Windows .zip and .msi installer names.

E.g.:
- clamav-0.104.0-rc.macos.x86_64.pkg
- clamav-0.104.0-rc.win.win32.msi
- clamav-0.104.0-rc.win.win32.zip
- clamav-0.104.0-rc.win.x64.msi
- clamav-0.104.0-rc.linux.x86_64.deb
- clamav-0.104.0-rc.linux.x86_64.rpm

Notes about building the packages:

I've only tested this with building ClamAV using static dependencies that
I build using the clamav_deps "host-static" recipes from the "clamav"
Mussels cookbook. Eg:

  msl build clamav_deps -t host-static

Here's an example configuration to build clam in this way, installing to
/usr/local/clamav:

```sh
cmake .. \
  -D CMAKE_FIND_PACKAGE_PREFER_CONFIG=TRUE \
  -D CMAKE_PREFIX_PATH=$HOME/.mussels/install/host-static \
  -D CMAKE_INSTALL_PREFIX="/usr/local/clamav" \
  -D CMAKE_MODULE_PATH=$HOME/.mussels/install/host-static/lib/cmake \
  -D CMAKE_BUILD_TYPE=RelWithDebInfo \
  -D ENABLE_EXAMPLES=OFF \
  -D JSONC_INCLUDE_DIR="$HOME/.mussels/install/host-static/include/json-c" \
  -D JSONC_LIBRARY="$HOME/.mussels/install/host-static/lib/libjson-c.a" \
  -D ENABLE_JSON_SHARED=OFF \
  -D BZIP2_INCLUDE_DIR="$HOME/.mussels/install/host-static/include" \
  -D BZIP2_LIBRARY_RELEASE="$HOME/.mussels/install/host-static/lib/libbz2_static.a" \
  -D OPENSSL_ROOT_DIR="$HOME/.mussels/install/host-static" \
  -D OPENSSL_INCLUDE_DIR="$HOME/.mussels/install/host-static/include" \
  -D OPENSSL_CRYPTO_LIBRARY="$HOME/.mussels/install/host-static/lib/libcrypto.a" \
  -D OPENSSL_SSL_LIBRARY="$HOME/.mussels/install/host-static/lib/libssl.a" \
  -D LIBXML2_INCLUDE_DIR="$HOME/.mussels/install/host-static/include/libxml2" \
  -D LIBXML2_LIBRARY="$HOME/.mussels/install/host-static/lib/libxml2.a" \
  -D PCRE2_INCLUDE_DIR="$HOME/.mussels/install/host-static/include" \
  -D PCRE2_LIBRARY="$HOME/.mussels/install/host-static/lib/libpcre2-8.a" \
  -D CURSES_INCLUDE_DIR="$HOME/.mussels/install/host-static/include" \
  -D CURSES_LIBRARY="$HOME/.mussels/install/host-static/lib/libncurses.a" \
  -D ZLIB_INCLUDE_DIR="$HOME/.mussels/install/host-static/include" \
  -D ZLIB_LIBRARY="$HOME/.mussels/install/host-static/lib/libz.a" \
  -D LIBCHECK_INCLUDE_DIR="$HOME/.mussels/install/host-static/include" \
  -D LIBCHECK_LIBRARY="$HOME/.mussels/install/host-static/lib/libcheck.a"
```

Set CPACK_PACKAGING_INSTALL_PREFIX to customize the resulting package's
install location. This can be different than the install prefix. E.g.:
```sh
  -D CMAKE_INSTALL_PREFIX="/usr/local/clamav" \
  -D CPACK_PACKAGING_INSTALL_PREFIX="/usr/local/clamav" \
```

Then `make` and then one of these, depending on the platform:
```sh
cpack        # macOS: productbuild is default
cpack -G DEB # Debian-based
cpack -G RPM # RPM-based
```

On macOS you'll need to `pip3 install markdown` so that the NEWS.md file can
be converted to html so it will render in the installer.

On RPM-based systems, you'll need rpmbuild (install rpm-build)

This commit also fixes an issue where the html manual (if present) was
not correctly added to the Windows (or now other) install packages.

Fix num to hex function for Windows installer guid

Fix win32 cpack build

Fix macOS cpack build
2021-08-18 13:53:34 -07:00
Micah Snyder
270724c642 FreshClam: Disable HTTPUserAgent if using clamav.net
Disable the HTTPUserAgent config option if the DatabaseMirror uses
clamav.net. This will prevent users from being inadvertently blocked and
will ensure that we can keep better metrics on which clamav versions are
being used.

This change is needed because we observed some users being blocked by
the new CDN rules when they set custom user-agents.
2021-06-01 18:19:12 -07:00
Micah Snyder (micasnyd)
4f51994fad FreshClam: Fix tests, configs for IPv6-only systems
Some config settings and some tests hardcoded 127.0.0.1. This switches
to localhost, they'll work for systems that don't support IPv4.
2021-05-27 16:52:58 -07:00
Micah Snyder
0255f29a72 Blacklist & Whitelist verbiage
Improvements to use modern block list and allow list verbiage.

blacklist -> block list
whitelist -> allow listed
blacklisted -> blocked
whitelisted -> allowed

In the case of certificate verification, use "trust" or "verify" when
something is allowed.

Also changed domainlist -> domain list (or DomainList) to match.
2021-05-27 14:16:00 -07:00
Micah Snyder
46fd3f631a FreshClam: Error handling fixes per code review 2021-04-05 12:29:03 -07:00
Micah Snyder
03449219da FreshClam: Improved HTTP 304, 403, & 429 handling
Added special warning messages for 403 and 429 HTTP codes.
For 403, FreshClam will fail (non-zero exit code) if not in daemon-mode.
For 429, FreshClam will succeed (exit 0) if not in daemon-mode.

Adds If-Modified-Since header for CVD downloads (not just CVD-head)
which should reduce data usage if DNS is advertising a newer version
than is actually available, which seems to happen sometimes due to
caching issues, it should still fail out when this happens - it just
won't have to download the older CVD, and should detect the HTTP 304
(Not-Modified) response instead.

Also replaced "Freshclam" with "FreshClam" in a few places, for
consistency.
2021-04-05 12:29:02 -07:00
Micah Snyder
fc3f6f604c FreshClam: Deprecate SafeBrowsing config option
The SafeBrowsing option will no longer do anything.

For more details, see:
https://blog.clamav.net/2020/06/the-future-of-clamav-safebrowsing.html

If generating your own safebrowing.gdb database, use the
DatabaseCustomURL option in freshclam.conf to download it.
2021-04-05 12:29:02 -07:00
Micah Snyder (micasnyd)
861153a656 Fix errors when scanning files > 4G
This commit resolves https://bugzilla.clamav.net/show_bug.cgi?id=12673

Changes in 0.103 to order of operations for creating fmaps and
performaing hashes of fmaps resulted errors when scanning files that are
4096M and a different (but related) error when scanning files > 4096M.
This is despite the fact that scanning is supposed to be limited to
--max-scansize (MaxScanSize) and was also apparently limited to
INT_MAX - 2 (aka ~1.999999G) back in 2014 to alleviate reported crashes
for a few large file formats.
(see https://bugzilla.clamav.net/show_bug.cgi?id=10960)
This last limitation was not documented, so I added it to the sample
clamd.conf.

Anyways, the main issue is that the fmap module was using "unsigned int"
and was then enforcing a limitation (verbose error messages) when that
a map length exceeded the capapacity of an unsigned int. This commit
switches the associated variables over to uint64_t, and while fmaps are
still limited to size_t in other places, the fmap module will at least
work with files > 4G on 64bit systems.

In testing this, I found that the time to hash a file, particularly when
hashing a file on an NTFS partition from Linux was really slow because
we were hashing in FILEBUFF chunks (about 8K) at a time.  Increasing
this to 10MB chunks speeds up scanning of large files.

Finally, now that hashing is performed immediately when an fmap is
created for a file, hashing of files larger than max-scansize was
occuring. This commit adds checks to bail out early if the file size
exceeds the maximum before creating an fmap. It will alert with the
Heuristics.Limits.Exceeded name if the heuristic is enabled.

Also fixed CheckFmapFeatures.cmake module that detects if
sysconf(_SC_PAGESIZE) is available.
2021-03-31 12:16:41 -07:00
Micah Snyder
a8e8c344eb Make new CMake Win32 install paths match old installer
And include the user manual, if present.
2021-02-25 11:41:28 -08:00
Vasile Papp
46e8dbbc45 clamd: Add %f to VirusEvent
VirusEvent commands may use %v to get the signature name (virus name)
for the alert but do not have a format option to get the file name.
This commit adds %f to get the file name.

The VirusEvent feature does provide two environment variables,
$CLAM_VIRUSEVENT_FILENAME and $CLAM_VIRUSEVENT_VIRUSNAME which provide
file and virus names, but they weren't documented in the sample configs.
This commit also adds these environment variables to the sample configs.
2021-02-17 13:43:06 -08:00
Micah Snyder
4cce1fcd20 GIF, PNG bugfixes; Add AlertBrokenMedia option
Added a new scan option to alert on broken media (graphics) file
formats. This feature mitigates the risk of malformed media files
intended to exploit vulnerabilities in other software. At present
media validation exists for JPEG, TIFF, PNG, and GIF files.

To enable this feature, set `AlertBrokenMedia yes` in clamd.conf, or
use the `--alert-broken-media` option when using `clamscan`.
These options are disabled by default for now.

Application developers may enable this scan option by enabling
`CL_SCAN_HEURISTIC_BROKEN_MEDIA` for the `heuristic` scan option bit
field.

Fixed PNG parser logic bugs that caused an excess of parsing errors
and fixed a stack exhaustion issue affecting some systems when
scanning PNG files. PNG file type detection was disabled via
signature database update for 0.103.0 to mitigate effects from these
bugs.

Fixed an issue where PNG and GIF files no longer work with Target:5
(graphics) signatures if detected as CL_TYPE_PNG/GIF rather than as
CL_TYPE_GRAPHICS. Target types now support up to 10 possible file
types to make way for additional graphics types in future releases.

Scanning JPEG, TIFF, PNG, and GIF files will no longer return "parse"
errors when file format validation fails. Instead, the scan will alert
with the "Heuristics.Broken.Media" signature prefix and a descriptive
suffix to indicate the issue, provided that the "alert broken media"
feature is enabled.

GIF format validation will no longer fail if the GIF image is missing
the trailer byte, as this appears to be a relatively common issue in
otherwise functional GIF files.

Added a TIFF dynamic configuration (DCONF) option, which was missing.
This will allow us to disable TIFF format validation via signature
database update in the event that it proves to be problematic.
This feature already exists for many other file types.

Added CL_TYPE_JPEG and CL_TYPE_TIFF types.
2021-01-28 12:54:47 -08:00
Micah Snyder (micasnyd)
6b08dda088 bb12620: freshclam clean up tmp dir with EXIT_1
When using --on-update-execute=EXIT_1 freshclam doesn't clean up the
temporary directory where it downloaded and tested the new database.

This patch moves the command execution to happen after temp-cleanup.
2021-01-12 12:05:30 -08:00
Micah Snyder
045bde3b42 Minor documentation corrections 2020-09-10 19:58:31 -07:00
Micah Snyder (micasnyd)
9e20cdf6ea Add CMake build tooling
This patch adds experimental-quality CMake build tooling.

The libmspack build required a modification to use "" instead of <> for
header #includes. This will hopefully be included in the libmspack
upstream project when adding CMake build tooling to libmspack.

Removed use of libltdl when using CMake.

Flex & Bison are now required to build.

If -DMAINTAINER_MODE, then GPERF is also required, though it currently
doesn't actually do anything.  TODO!

I found that the autotools build system was generating the lexer output
but not actually compiling it, instead using previously generated (and
manually renamed) lexer c source. As a consequence, changes to the .l
and .y files weren't making it into the build. To resolve this, I
removed generated flex/bison files and fixed the tooling to use the
freshly generated files. Flex and bison are now required build tools.
On Windows, this adds a dependency on the winflexbison package,
which can be obtained using Chocolatey or may be manually installed.

CMake tooling only has partial support for building with external LLVM
library, and no support for the internal LLVM (to be removed in the
future). I.e. The CMake build currently only supports the bytecode
interpreter.

Many files used include paths relative to the top source directory or
relative to the current project, rather than relative to each build
target. Modern CMake support requires including internal dependency
headers the same way you would external dependency headers (albeit
with "" instead of <>). This meant correcting all header includes to
be relative to the build targets and not relative to the workspace.

For example, ...

```c
include "../libclamav/clamav.h"
include "clamd/clamd_others.h"
```

... becomes:

```c
// libclamav
include "clamav.h"

// clamd
include "clamd_others.h"
```

Fixes header name conflicts by renaming a few of the files.

Converted the "shared" code into a static library, which depends on
libclamav. The ironically named "shared" static library provides
features common to the ClamAV apps which are not required in
libclamav itself and are not intended for use by downstream projects.
This change was required for correct modern CMake practices but was
also required to use the automake "subdir-objects" option.
This eliminates warnings when running autoreconf which, in the next
version of autoconf & automake are likely to break the build.

libclamav used to build in multiple stages where an earlier stage is
a static library containing utils required by the "shared" code.
Linking clamdscan and clamdtop with this libclamav utils static lib
allowed these two apps to function without libclamav. While this is
nice in theory, the practical gains are minimal and it complicates
the build system. As such, the autotools and CMake tooling was
simplified for improved maintainability and this feature was thrown
out. clamdtop and clamdscan now require libclamav to function.

Removed the nopthreads version of the autotools
libclamav_internal_utils static library and added pthread linking to
a couple apps that may have issues building on some platforms without
it, with the intention of removing needless complexity from the
source. Kept the regular version of libclamav_internal_utils.la
though it is no longer used anywhere but in libclamav.

Added an experimental doxygen build option which attempts to build
clamav.h and libfreshclam doxygen html docs.

The CMake build tooling also may build the example program(s), which
isn't a feature in the Autotools build system.

Changed C standard to C90+ due to inline linking issues with socket.h
when linking libfreshclam.so on Linux.

Generate common.rc for win32.

Fix tabs/spaces in shared Makefile.am, and remove vestigial ifndef
from misc.c.

Add CMake files to the automake dist, so users can try the new
CMake tooling w/out having to build from a git clone.

clamonacc changes:
- Renamed FANOTIFY macro to HAVE_SYS_FANOTIFY_H to better match other
  similar macros.
- Added a new clamav-clamonacc.service systemd unit file, based on
  the work of ChadDevOps & Aaron Brighton.
- Added missing clamonacc man page.

Updates to clamdscan man page, add missing options.

Remove vestigial CL_NOLIBCLAMAV definitions (all apps now use
libclamav).

Rename Windows mspack.dll to libmspack.dll so all ClamAV-built
libraries have the lib-prefix with Visual Studio as with CMake.
2020-08-13 00:25:34 -07:00
Micah Snyder
cd2f2975b9 Docs: Warn against running untrusted bytecode
Add notices to man pages and help strings cautioning against running
bytecode signatures from untrusted sources.

Also adds missing BytecodeUnsigned option to clamd.conf.sample files.
2020-07-09 15:38:15 -07:00
Micah Snyder
dac084fb91 bb10979: clamd multi-threaded database reload #2
Add clamd config option to force blocking clamd database reload to
conserve RAM. Users may set `ConcurrentDatabaseReload no` in their
clamd.conf config file to force a blocking reload.

The blocking mode will still perform the reload in a new thread, but
will first free the current database, wait for scans targeting that
database to complete, and then load the new database in the new thread
and wait (`pthread_join()`) on that thread. Once loaded, any pending
scans will continue. This is effectively the same behavior as how
clamd reloads worked before the multi-threaded database reload feature
was added.
2020-07-01 22:06:15 -07:00
Mickey Sola
9da15ce163 Add DLP CC-only option to win32 clamd.conf
Add the credit card-only DLP option "StructuredCCOnly" to the win32
sample clamd config.

Also update NEWS.md to credit John Schember and Alexander Sulfrian for
the DLP CC-only mode contribution.
2020-04-29 13:55:25 -07:00
Micah Snyder (micasnyd)
f5d465a864 bb12500: [docs] freshclam ReceiveTimeout clarity 2020-03-13 09:26:13 -07:00
Tuomo Soini
2fd28e1d09 freshclam: change default of ReceiveTimeout to 0
This fixes issues in cvd download when network speed is slow.
Setting is passed to libcurl CURLOPT_TIMEOUT. Original default of 60s
was not enough if network speed is limited. Curl handles this as
total time for http(s) transfer.

https://curl.haxx.se/libcurl/c/CURLOPT_TIMEOUT.html

Also change commented out setting of ReceiveTimeout on example configs
to somewhat sensible value (1800s).

Signed-off-by: Tuomo Soini <tis@foobar.fi>
2020-01-28 08:15:11 -08:00
Tuomo Soini
aa9112dfdf configs: synchronize etc/ and win32/conf_examples/
Signed-off-by: Tuomo Soini <tis@foobar.fi>
2019-10-02 16:08:31 -04:00
Micah Snyder (micasnyd)
6a0abb897a Adds --max-scantime clamscan option and MaxScanTime clamd config option.
--max-scantime replaces the --timelimit clamscan option that had been experimental.
Default max-scantime set to 2 minutes (120000 milliseconds).
2019-10-02 16:08:29 -04:00
Micah Snyder (micasnyd)
cb9b09afa9 bb12043, bb12302: Adds --foreground freshclam option to help and manpage, some other documentation tweaks. 2019-10-02 16:08:23 -04:00
Micah Snyder
2c1f820095 Old-style db.XY.clamav.net and db.XY.ipv6.clamav.net entries now redirect to https://database.clamav.net. 2019-10-02 16:08:23 -04:00
Micah Snyder
06e3c1c896 Increased default freshclam receive timeout from 30 sec to 60 sec. Set default DatabaseMirror back to database.clamav.net, now that TLS/SSL is enabled on the mirrors that back the CDN. Some other updates to the man pages that were missing from previous changes. 2019-10-02 16:08:23 -04:00
Micah Snyder
cef54eaf8f Freshclam refresh. This update makes libcurl a hard requirement for ClamAV.
New features added to freshclam:
- Update signature definitions over HTTPS.
- Support for HTTP protocol v1.1 (formerly v1.0).
- New libfreshclam library with an all new API and versioning separate from libclamav (v2.0.0). This library is now build and installed alongside libclamav as a hard dependency of freshclam.
- The ability to opt-in and opt-out of standard and optional official ClamAV databases (ExtraDatabase, ExcludeDatabase)
- The option to specify the protocol and port number of official and private mirror servers.
- Support for additional types of proxy servers beyond plain HTTP (SOCKS 4, SOCKS 5).

Features removed from freshclam:
- Mirror management (mirrors.dat) file. This feature is no longer needed as official signature databases are distributed using a paid content delivery network (Cloudflare).

This commit also adds the following features for Windows users:
- The clamsubmit tool.
- The json-c library dependency, which will enable the --gen-json option in clamscan.
- Third party libraries under the win32/3rdparty directory have been removed. Developers will need to build the libraries separately from ClamAV and provide the headers and lib/dll library files the same way they do for OpenSSL. This includes libxml2, pthread-win32, bzip2, zlib, pcre2 as well as new dependencies: curl, json-c. Developers are encouraged to use the build tool Mussels to simplify this task.
2019-10-02 16:08:22 -04:00
Micah Snyder (micasnyd)
f61e92da8f Changing numerous scan options' names, primarily those of heuristic signatature alert options. Original options (command line and clamd) will remain as deprecated & undocumented for a couple releases. Added 2 extra scan options to allow users to differentiate between alerting on encrypted archives vs encrypted documents (bb11911). 2018-12-02 23:06:59 -05:00
Micah Snyder
d7979d4ff7 Restructured scan options flags from a single bitflag field to a structure containing multiple bitflag fields. This also required adding a new function to the bytecode API to get scan options a la carte, and modifying the existing function to hand back scan options in the old/deprecated uint32_t bitflag format. Re-generated bytecode iface header files.
Updated libclamav documentation detailing new scan options structure.
Renamed references to 'algorithmic' detection to 'heuristic' detection. Renaming references to 'properties' to 'collect metadata'.
Renamed references to 'scan all' to 'scan all match'.
Renamed a couple of 'Hueristic.*' signature names as 'Heuristics.*' signatures (plural) to match majority of other heuristics.
2018-12-02 23:06:59 -05:00
Micah Snyder
f67a9b7508 bb12118: Lowering the default PCRERecMatchLimit from 5000 to 2000, to minimize risk of segfault due to bug in older versions of libpcre/libpcrev2. 2018-12-02 23:06:58 -05:00
Micah Snyder
964a1e7321 Converting http urls to https urls. Primary focus was on clamav.net urls. I updated a couple others and fixes a few broken links as well. There are many (non-clamav.net) urls I didn't address, especially in 3rd party or contrib code. 2018-04-02 07:58:33 -04:00