Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,6 @@ target/

# These are backup files generated by rustfmt
**/*.rs.bk

# ClamAV JSON report history (generated by --json-report-history)
history/reports/
135 changes: 129 additions & 6 deletions clamscan/clamscan.c
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@

// libclamav
#include "clamav.h"
#include "json_report.h"
#include "others.h"
#include "str.h"

Expand All @@ -56,10 +57,125 @@

void help(void);

static void write_json_report_history(time_t date_start, time_t date_end, int duration_s, int duration_us)
{
char report_file[1105];
char start_buf[26];
char end_buf[26];
struct tm tmp;
FILE *fp;
double duration_sec;

#ifdef _WIN32
if (0 != localtime_s(&tmp, &date_start)) {
#else
if (!localtime_r(&date_start, &tmp)) {
#endif
logg(LOGG_WARNING, "json-report-history: Failed to get local start time.\n");
return;
}
strftime(start_buf, sizeof(start_buf), "%Y:%m:%d %H:%M:%S", &tmp);

#ifdef _WIN32
if (0 != localtime_s(&tmp, &date_end)) {
#else
if (!localtime_r(&date_end, &tmp)) {
#endif
logg(LOGG_WARNING, "json-report-history: Failed to get local end time.\n");
return;
}
strftime(end_buf, sizeof(end_buf), "%Y:%m:%d %H:%M:%S", &tmp);

duration_sec = (double)duration_s + duration_us / 1000000.0;

if (0 != cl_json_history_open_daily_file(date_start,
"reports",
report_file,
sizeof(report_file),
&fp)) {
return;
}

fprintf(fp,
"{\"start_time\":\"%s\","
"\"end_time\":\"%s\","
"\"duration_seconds\":%.3f,"
"\"engine_version\":\"%s\","
"\"known_viruses\":%u,"
"\"scanned_directories\":%u,"
"\"scanned_files\":%u,"
"\"infected_files\":%u,"
"\"errors\":%u,"
"\"data_scanned_bytes\":%" PRIu64 ","
"\"data_read_bytes\":%" PRIu64 ","
"\"threats\":[",
start_buf, end_buf,
duration_sec,
get_version(),
info.sigs,
info.dirs,
info.files,
info.ifiles,
info.errors,
info.bytes_scanned,
info.bytes_read);

{
unsigned int i;
for (i = 0; i < infected_list_count; i++) {
if (i > 0) fputc(',', fp);
fputs("{\"file\":", fp);
cl_json_fwrite_string(fp, infected_list[i].path);
fputs(",\"virus\":", fp);
cl_json_fwrite_string(fp, infected_list[i].virus_name);
fputs(",\"action\":", fp);
cl_json_fwrite_string(fp, action_type_name);
fputs("}", fp);
}
}

fputs("]}\n", fp);

fclose(fp);
free_infected_list();

logg(LOGG_INFO, "JSON history report saved: %s\n", report_file);
}

struct s_info info;
struct s_infected_record *infected_list = NULL;
unsigned int infected_list_count = 0;
unsigned int infected_list_capacity = 0;
short recursion = 0, bell = 0;
short printinfected = 0, printclean = 1;

void record_infected_file(const char *path, const char *virus_name)
{
if (infected_list_count >= infected_list_capacity) {
unsigned int new_cap = infected_list_capacity ? infected_list_capacity * 2 : 8;
struct s_infected_record *tmp = realloc(infected_list, new_cap * sizeof(*tmp));
if (!tmp) return;
infected_list = tmp;
infected_list_capacity = new_cap;
}
infected_list[infected_list_count].path = path ? strdup(path) : NULL;
infected_list[infected_list_count].virus_name = virus_name ? strdup(virus_name) : NULL;
infected_list_count++;
}

void free_infected_list(void)
{
unsigned int i;
for (i = 0; i < infected_list_count; i++) {
free(infected_list[i].path);
free(infected_list[i].virus_name);
}
free(infected_list);
infected_list = NULL;
infected_list_count = 0;
infected_list_capacity = 0;
}

static void loggBytes(uint64_t bytes)
{
if (bytes >= (1024 * 1024 * 1024)) {
Expand Down Expand Up @@ -184,15 +300,16 @@ int main(int argc, char **argv)

ret = scanmanager(opts);

date_end = time(NULL);
gettimeofday(&t2, NULL);
ds = t2.tv_sec - t1.tv_sec;
dms = t2.tv_usec - t1.tv_usec;
ds -= (dms < 0) ? (1) : (0);
dms += (dms < 0) ? (1000000) : (0);

if (!optget(opts, "no-summary")->enabled) {
struct tm tmp;

date_end = time(NULL);
gettimeofday(&t2, NULL);
ds = t2.tv_sec - t1.tv_sec;
dms = t2.tv_usec - t1.tv_usec;
ds -= (dms < 0) ? (1) : (0);
dms += (dms < 0) ? (1000000) : (0);
logg(LOGG_INFO, "\n----------- SCAN SUMMARY -----------\n");
logg(LOGG_INFO, "Known viruses: %u\n", info.sigs);
logg(LOGG_INFO, "Engine version: %s\n", get_version());
Expand Down Expand Up @@ -239,6 +356,10 @@ int main(int argc, char **argv)
logg(LOGG_INFO, "End Date: %s\n", buffer);
}

if (optget(opts, "json-report-history")->enabled) {
write_json_report_history(date_start, date_end, ds, dms);
}

optfree(opts);

return ret;
Expand Down Expand Up @@ -278,6 +399,8 @@ void help(void)
mprintf(LOGG_INFO, " --json-store-pdf-uris[=yes(*)/no] Store pdf URIs in metadata.\n");
mprintf(LOGG_INFO, " URIs will be written to the metadata.json file in an array called 'URIs'.\n");
mprintf(LOGG_INFO, " --json-store-extra-hashes[=yes(*)/no] Store md5 and sha1 in addition to sha2-256 in metadata.\n");
mprintf(LOGG_INFO, " --json-report-history[=yes/no(*)] Save a JSON Lines summary of each scan to history/reports/DD-MM-yyyy-reports.jsonl.\n");
mprintf(LOGG_INFO, " Multiple scans on the same day are appended to the same file.\n");
mprintf(LOGG_INFO, " --database=FILE/DIR -d FILE/DIR Load virus database from FILE or load all supported db files from DIR.\n");
mprintf(LOGG_INFO, " --official-db-only[=yes/no(*)] Only load official signatures.\n");
mprintf(LOGG_INFO, " --fail-if-cvd-older-than=days Return with a nonzero error code if virus database outdated.\n");
Expand Down
19 changes: 19 additions & 0 deletions clamscan/global.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,26 @@ struct s_info {
uint64_t bytes_read; /* number of *read* bytes */
};

struct s_infected_record {
char *path;
char *virus_name;
};

extern struct s_info info;
extern struct s_infected_record *infected_list;
extern unsigned int infected_list_count;
extern unsigned int infected_list_capacity;

/**
* @brief Record an infected file path and virus name for later inclusion in the JSON report.
*/
void record_infected_file(const char *path, const char *virus_name);

/**
* @brief Free all entries in the infected file list and reset it.
*/
void free_infected_list(void);

extern short recursion, bell;
extern short printinfected, printclean;

Expand Down
2 changes: 2 additions & 0 deletions clamscan/manager.c
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,7 @@ static void scanfile(const char *filename, struct cl_engine *engine, const struc
}
info.files++;
info.ifiles++;
record_infected_file(filename, alert_name);

if (bell) {
fprintf(stderr, "\007");
Expand Down Expand Up @@ -763,6 +764,7 @@ static int scanstdin(const struct cl_engine *engine, const struct optstruct *opt
case CL_VERDICT_STRONG_INDICATOR:
case CL_VERDICT_POTENTIALLY_UNWANTED: {
info.ifiles++;
record_infected_file("stdin", alert_name);

if (bell) {
fprintf(stderr, "\007");
Expand Down
10 changes: 7 additions & 3 deletions common/actions.c
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
#include "actions.h"

void (*action)(const char *) = NULL;
const char *action_type_name = "none";
unsigned int notmoved = 0, notremoved = 0;

static char *actarget;
Expand Down Expand Up @@ -714,9 +715,12 @@ int actsetup(const struct optstruct *opts)
}
#endif
if (!isdir()) return 1;
action = move ? action_move : action_copy;
action = move ? action_move : action_copy;
action_type_name = move ? "moved" : "copied";
targlen = strlen(actarget);
} else if (optget(opts, "remove")->enabled)
action = action_remove;
} else if (optget(opts, "remove")->enabled) {
action = action_remove;
action_type_name = "removed";
}
return 0;
}
6 changes: 6 additions & 0 deletions common/actions.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@
*/
extern void (*action)(const char *);

/**
* @brief Human-readable name of the action that will be taken on infected files.
* Set by actsetup(). Values: "none", "moved", "copied", "removed".
*/
extern const char *action_type_name;

/**
* @brief Select the appropriate callback function based on the configuration options.
*
Expand Down
49 changes: 49 additions & 0 deletions common/optparser.c
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,8 @@ const struct clam_option __clam_options[] = {

{"JsonStoreExtraHashes", "json-store-extra-hashes", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "When GenerateMetadataJson enabled: calculate and store each type of supported file hash.", "yes"},

{NULL, "json-report-history", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMSCAN, "Save a JSON Lines summary of each scan to history/reports/DD-MM-yyyy-reports.jsonl.", ""},

{"User", NULL, 0, CLOPT_TYPE_STRING, NULL, -1, NULL, 0, OPT_CLAMD | OPT_MILTER, "Run the daemon as a specified user (the process must be started by root).", "clamav"},

{"FIPSCryptoHashLimits", "fips-limits", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_FRESHCLAM | OPT_CLAMSCAN | OPT_CLAMD | OPT_SIGTOOL | OPT_CLAMONACC, "Apply FIPS-like limitations on which hash algorithms may be used for cryptographic purposes. This essentially disables the legacy CVD digital signature verfication method, and also disables support for MD5 and SHA1 false positive signatures ('.fp' and '.sfp' signatures using MD5 or SHA1).", "yes"},
Expand Down Expand Up @@ -466,6 +468,53 @@ const struct clam_option __clam_options[] = {

{"AlertPartitionIntersection", "alert-partition-intersection", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Alert on raw DMG image files containing partition intersections.", "yes"},

/* Network Firewall & Threat Protection */
{"NetworkFirewall", "network-firewall", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Enable the advanced network firewall and threat protection module.\nWhen enabled, ClamAV will perform network-level analysis including\nport scan detection, DDoS/brute-force protection, IP reputation\nchecks, geolocation blocking, URL homograph detection, protocol\nanomaly analysis, and C2 communication detection.", "no"},

{"AllowPortScanning", "allow-port-scanning", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 1, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Allow port scanning activity. When set to 'no', ClamAV will detect\nand alert on rapid multi-port connection patterns (Nmap, Masscan, etc.).", "yes"},

{"PortScanThreshold", "port-scan-threshold", 0, CLOPT_TYPE_NUMBER, MATCH_NUMBER, 10, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Number of distinct destination ports contacted within the observation\nwindow that triggers a port-scan alert.", "10"},

{"PortScanTimeout", "port-scan-timeout", 0, CLOPT_TYPE_NUMBER, MATCH_NUMBER, 300, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Observation window in seconds for port-scan detection.", "300"},

{"BlockScannedPorts", "block-scanned-ports", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Automatically block source IPs detected as performing a port scan.", "no"},

{"MaxConnectionsPerIP", "max-connections-per-ip", 0, CLOPT_TYPE_NUMBER, MATCH_NUMBER, 50, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Maximum number of simultaneous connections allowed from a single IP\nbefore a DDoS alert is triggered.", "50"},

{"MaxRequestsPerSecond", "max-requests-per-second", 0, CLOPT_TYPE_NUMBER, MATCH_NUMBER, 100, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Maximum number of HTTP requests per second allowed from a single IP\nbefore an HTTP flood alert is triggered.", "100"},

{"MaxFailedLogins", "max-failed-logins", 0, CLOPT_TYPE_NUMBER, MATCH_NUMBER, 5, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Number of consecutive failed authentication attempts that triggers\na brute-force alert and temporary lockout.", "5"},

{"LockoutDuration", "lockout-duration", 0, CLOPT_TYPE_NUMBER, MATCH_NUMBER, 300, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Duration in seconds for which a source IP is blocked after\nexceeding the brute-force or DDoS threshold.", "300"},

{"EnableIPReputation", "enable-ip-reputation", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Enable IP reputation checking. Source IPs are scored against known\nmalicious ranges and threat-intelligence feeds. IPs scoring >= 85\nare blocked; scores 50-84 generate a warning.", "no"},

{"IPReputationDatabase", "ip-reputation-database", 0, CLOPT_TYPE_STRING, NULL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Path to the IP reputation database file.", "/etc/clamav/ip_reputation.db"},

{"GeoBlockingEnabled", "geo-blocking", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Enable geolocation-based connection blocking. Requires AllowedCountries\nor DenyCountries to be configured.", "no"},

{"AllowedCountries", "allowed-countries", 0, CLOPT_TYPE_STRING, NULL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Comma-separated list of ISO 3166-1 alpha-2 country codes that are\nallowed to connect. All other countries are blocked when this option\nis set and GeoBlockingEnabled is yes.\nExample: US,GB,CA,DE,FR,JP", ""},

{"DenyCountries", "deny-countries", 0, CLOPT_TYPE_STRING, NULL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Comma-separated list of ISO 3166-1 alpha-2 country codes that are\nexplicitly denied when GeoBlockingEnabled is yes.\nExample: KP,IR,SY", ""},

{"PhishingHomographDetection", "homograph-detection", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Enable detection of homograph and Unicode-spoofing attacks in URLs\nand domain names. Detects mixed-script domains, Punycode abuse,\nemoji domains, and RTL-override attacks.", "no"},

{"PhishingHomographLevel", "homograph-level", 0, CLOPT_TYPE_STRING, NULL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Sensitivity level for homograph detection.\n'normal' - warn on suspicious domains.\n'strict' - block mixed-script and Punycode domains.", "normal"},

{"DNSTunnelingDetection", "dns-tunneling-detection", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Detect DNS tunneling and covert-channel abuse (oversized queries,\nhigh-entropy subdomains, TXT record abuse).", "no"},

{"HTTPInspection", "http-inspection", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Enable HTTP header inspection for anomalies such as missing\nUser-Agent, path traversal sequences, and X-Forwarded-For loops.", "no"},

{"ValidateSSLCertificate", "validate-ssl", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Enable TLS cipher suite and protocol version validation. Alerts on\nweak ciphers (RC4, NULL, EXPORT, DES, 3DES, anonymous DH) and\ndeprecated protocol versions (SSLv2, SSLv3, TLS 1.0, TLS 1.1).", "no"},

{"DetectTLSDowngrade", "detect-tls-downgrade", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Alert when a TLS downgrade to an insecure protocol version is\ndetected (requires ValidateSSLCertificate to be enabled).", "no"},

{"DetectC2Communication", "detect-c2", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Enable detection of Command & Control (C2) communication patterns.\nAnalyses connection timing and payload size regularity to identify\nbeaconing behaviour characteristic of malware C2 channels.", "no"},

{"EnableMLModels", "enable-ml-models", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 0, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Enable machine-learning-based anomaly detection models for\nidentifying malicious domains, botnet C2, phishing URLs,\nransomware traffic patterns, and cryptomining pool connections.", "no"},

{"MLConfidenceThreshold", "ml-confidence", 0, CLOPT_TYPE_NUMBER, MATCH_NUMBER, 85, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "Minimum confidence threshold (0-100) for ML-model detections to\ngenerate an alert. The value is a percentage (85 = 85% = 0.85 internally).\nHigher values reduce false positives.", "85"},

{"ScanPDF", "scan-pdf", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 1, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "This option enables scanning within PDF files.\nIf you turn off this option, the original files will still be scanned, but\nwithout decoding and additional processing.", "yes"},

{"ScanSWF", "scan-swf", 0, CLOPT_TYPE_BOOL, MATCH_BOOL, 1, NULL, 0, OPT_CLAMD | OPT_CLAMSCAN, "This option enables scanning within SWF files.\nIf you turn off this option, the original files will still be scanned, but\nwithout decoding and additional processing.", "yes"},
Expand Down
Loading
Loading