diff --git a/.gitignore b/.gitignore index a4eefe62f4..ace0d03b1c 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/clamscan/clamscan.c b/clamscan/clamscan.c index ea4378c1af..89ad945859 100644 --- a/clamscan/clamscan.c +++ b/clamscan/clamscan.c @@ -42,6 +42,7 @@ // libclamav #include "clamav.h" +#include "json_report.h" #include "others.h" #include "str.h" @@ -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)) { @@ -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()); @@ -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; @@ -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"); diff --git a/clamscan/global.h b/clamscan/global.h index cbe05faf2c..8dfdc750b8 100644 --- a/clamscan/global.h +++ b/clamscan/global.h @@ -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; diff --git a/clamscan/manager.c b/clamscan/manager.c index c85248577f..3fb8ef5704 100644 --- a/clamscan/manager.c +++ b/clamscan/manager.c @@ -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"); @@ -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"); diff --git a/common/actions.c b/common/actions.c index d94ccaa433..817e24f270 100644 --- a/common/actions.c +++ b/common/actions.c @@ -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; @@ -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; } diff --git a/common/actions.h b/common/actions.h index 0c6d2b1483..dbd2003b20 100644 --- a/common/actions.h +++ b/common/actions.h @@ -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. * diff --git a/common/optparser.c b/common/optparser.c index 66217f3931..6171e0d56e 100644 --- a/common/optparser.c +++ b/common/optparser.c @@ -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"}, @@ -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"}, diff --git a/etc/clamd.conf.sample b/etc/clamd.conf.sample index 116822c4d8..e08f6b96c3 100644 --- a/etc/clamd.conf.sample +++ b/etc/clamd.conf.sample @@ -900,3 +900,134 @@ Example # # Default: 10000 # BytecodeTimeout 1000 + + +## +## Network Firewall & Threat Protection +## + +# Enable the advanced network firewall and threat protection module. +# When enabled, ClamAV will perform network-level analysis including port scan +# detection, DDoS/brute-force protection, IP reputation checks, geolocation +# blocking, URL homograph detection, protocol anomaly analysis, and C2 +# communication detection. +# Default: no +#NetworkFirewall yes + +# Allow port scanning activity. When set to 'no', ClamAV will detect and alert +# on rapid multi-port connection patterns (Nmap, Masscan, Zmap, Shodan, etc.). +# Default: yes +#AllowPortScanning no + +# Number of distinct destination ports that trigger a port-scan alert within +# the observation window defined by PortScanTimeout. +# Default: 10 +#PortScanThreshold 10 + +# Observation window in seconds for port-scan detection. +# Default: 300 +#PortScanTimeout 300 + +# Automatically block source IPs detected as performing a port scan. +# Default: no +#BlockScannedPorts yes + +# Maximum simultaneous connections from a single IP before a DDoS alert fires. +# Default: 50 +#MaxConnectionsPerIP 50 + +# Maximum HTTP requests per second from a single IP before an HTTP flood +# alert is triggered. +# Default: 100 +#MaxRequestsPerSecond 100 + +# Number of consecutive failed authentication attempts from the same IP that +# triggers a brute-force alert and temporary lockout. +# Default: 5 +#MaxFailedLogins 5 + +# Duration in seconds for which a source IP is blocked after exceeding the +# brute-force or DDoS threshold. +# Default: 300 +#LockoutDuration 300 + +# Enable IP reputation checking. Source IPs are scored against known malicious +# ranges and threat-intelligence feeds: +# Score >= 85 -> BLOCK (Malicious) +# Score 50-84 -> WARN (Suspicious) +# Score 20-49 -> MONITOR +# Score < 20 -> ALLOW +# Default: no +#EnableIPReputation yes + +# Path to the IP reputation database file. +# Default: /etc/clamav/ip_reputation.db +#IPReputationDatabase /etc/clamav/ip_reputation.db + +# Enable geolocation-based connection blocking. +# Requires AllowedCountries or DenyCountries to be configured. +# Default: no +#GeoBlockingEnabled yes + +# Comma-separated list of ISO 3166-1 alpha-2 country codes that are allowed to +# connect. All other countries are blocked when this option is set and +# GeoBlockingEnabled is yes. +# Example: US,GB,CA,DE,FR,JP,SG +#AllowedCountries US,GB,CA,DE,FR + +# Comma-separated list of ISO 3166-1 alpha-2 country codes that are explicitly +# denied. Takes effect when GeoBlockingEnabled is yes. +# Example: KP,IR,SY +#DenyCountries KP,IR + +# Enable detection of homograph and Unicode-spoofing attacks in URLs and domain +# names. Detects mixed-script domains, Punycode abuse, emoji domains, and +# RTL-override attacks. +# Default: no +#PhishingHomographDetection yes + +# Sensitivity level for homograph detection. +# normal - warn on suspicious domains (default) +# strict - block mixed-script and Punycode domains +# Default: normal +#PhishingHomographLevel strict + +# Detect DNS tunneling and covert-channel abuse (oversized queries, high-entropy +# subdomains, TXT record abuse). +# Default: no +#DNSTunnelingDetection yes + +# Enable HTTP header inspection for anomalies such as missing User-Agent, +# path traversal sequences, and X-Forwarded-For loops. +# Default: no +#HTTPInspection yes + +# Enable TLS cipher suite and protocol version validation. Alerts on weak +# ciphers (RC4, NULL, EXPORT, DES, 3DES, anonymous DH) and deprecated +# protocol versions (SSLv2, SSLv3, TLS 1.0, TLS 1.1). +# Default: no +#ValidateSSLCertificate yes + +# Alert when a TLS downgrade to an insecure protocol version is detected. +# Requires ValidateSSLCertificate to be enabled. +# Default: no +#DetectTLSDowngrade yes + +# Enable detection of Command & Control (C2) communication patterns. Analyses +# connection timing and payload size regularity to identify beaconing behaviour +# characteristic of malware C2 channels, ransomware callbacks, and botnet +# coordination traffic. +# Default: no +#DetectC2Communication yes + +# Enable machine-learning-based anomaly detection models for identifying +# malicious domains, botnet C2, phishing URLs, ransomware traffic patterns, +# and cryptomining pool connections. +# Default: no +#EnableMLModels yes + +# Minimum confidence threshold (0-100) for ML-model detections to generate an +# alert. The integer value is treated as a percentage: 85 means 85% confidence +# (0.85 internally). Higher values reduce false positives. +# Default: 85 +#MLConfidenceThreshold 85 diff --git a/libclamav/CMakeLists.txt b/libclamav/CMakeLists.txt index bcee81b7cf..d9fba92160 100644 --- a/libclamav/CMakeLists.txt +++ b/libclamav/CMakeLists.txt @@ -208,6 +208,7 @@ set(LIBCLAMAV_SOURCES fpu.c fpu.h hashtab.c hashtab.h iowrap.c iowrap.h + json_report.c json_report.h json_api.c json_api.h jsparse/textbuf.h others_common.c others.h @@ -358,6 +359,8 @@ set(LIBCLAMAV_SOURCES phish_domaincheck_db.c phish_domaincheck_db.h phish_allow_list.c phish_allow_list.h phishcheck.c phishcheck.h + # network firewall & threat protection + network_firewall.c network_firewall.h regex_list.c regex_list.h regex_suffix.c regex_suffix.h # sis diff --git a/libclamav/json_report.c b/libclamav/json_report.c new file mode 100644 index 0000000000..9087f213a6 --- /dev/null +++ b/libclamav/json_report.c @@ -0,0 +1,141 @@ +/* + * Shared JSON report helpers + * + * Copyright (C) 2013-2026 Cisco Systems, Inc. and/or its affiliates. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#if HAVE_CONFIG_H +#include "clamav-config.h" +#endif + +#include +#include + +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifndef _WIN32 +#include +#else +#include +#endif + +#include "json_report.h" +#include "others.h" + +void cl_json_fwrite_string(FILE *fp, const char *s) +{ + if (!s) { + fputs("null", fp); + return; + } + + fputc('"', fp); + for (; *s; s++) { + unsigned char c = (unsigned char)*s; + if (c == '"') { + fputs("\\\"", fp); + } else if (c == '\\') { + fputs("\\\\", fp); + } else if (c == '\n') { + fputs("\\n", fp); + } else if (c == '\r') { + fputs("\\r", fp); + } else if (c == '\t') { + fputs("\\t", fp); + } else if (c < 0x20) { + fprintf(fp, "\\u%04x", c); + } else { + fputc(c, fp); + } + } + fputc('"', fp); +} + +int cl_json_history_open_daily_file(time_t event_time, + const char *suffix, + char *report_file, + size_t report_file_size, + FILE **fp) +{ + char report_dir[1024]; + char date_str[16]; + struct tm tmp; + + if (!suffix || !report_file || !fp || report_file_size == 0) { + return -1; + } + +#ifdef _WIN32 + if (0 != localtime_s(&tmp, &event_time)) { +#else + if (!localtime_r(&event_time, &tmp)) { +#endif + cli_warnmsg("json-report-history: Failed to get local event time.\n"); + return -1; + } + + strftime(date_str, sizeof(date_str), "%d-%m-%Y", &tmp); + snprintf(report_dir, sizeof(report_dir), "history/reports"); + +#ifndef _WIN32 + if (mkdir("history", 0755) != 0 && errno != EEXIST) { + cli_warnmsg("json-report-history: Failed to create directory 'history': %s\n", strerror(errno)); + return -1; + } + if (mkdir(report_dir, 0755) != 0 && errno != EEXIST) { + cli_warnmsg("json-report-history: Failed to create directory '%s': %s\n", report_dir, strerror(errno)); + return -1; + } +#else + if (_mkdir("history") != 0 && errno != EEXIST) { + cli_warnmsg("json-report-history: Failed to create directory 'history': %s\n", strerror(errno)); + return -1; + } + if (_mkdir(report_dir) != 0 && errno != EEXIST) { + cli_warnmsg("json-report-history: Failed to create directory '%s': %s\n", report_dir, strerror(errno)); + return -1; + } +#endif + + snprintf(report_file, report_file_size, "%s/%s-%s.jsonl", report_dir, date_str, suffix); + + *fp = fopen(report_file, "a"); + if (*fp == NULL) { + cli_warnmsg("json-report-history: Failed to open '%s' for appending: %s\n", report_file, strerror(errno)); + return -1; + } + + return 0; +} + +int cl_json_history_append_daily_json(time_t event_time, + const char *suffix, + const char *json, + char *report_file, + size_t report_file_size) +{ + FILE *fp; + + if (!json) { + return -1; + } + + if (0 != cl_json_history_open_daily_file(event_time, + suffix, + report_file, + report_file_size, + &fp)) { + return -1; + } + + fprintf(fp, "%s\n", json); + fclose(fp); + + return 0; +} diff --git a/libclamav/json_report.h b/libclamav/json_report.h new file mode 100644 index 0000000000..d70626f70e --- /dev/null +++ b/libclamav/json_report.h @@ -0,0 +1,49 @@ +/* + * Shared JSON report helpers + * + * Copyright (C) 2013-2026 Cisco Systems, Inc. and/or its affiliates. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#ifndef __JSON_REPORT_H +#define __JSON_REPORT_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Write a JSON string value, escaping special characters. */ +void cl_json_fwrite_string(FILE *fp, const char *s); + +/* + * Open history/reports/DD-MM-YYYY-.jsonl in append mode. + * Returns 0 on success, -1 on failure. + */ +int cl_json_history_open_daily_file(time_t event_time, + const char *suffix, + char *report_file, + size_t report_file_size, + FILE **fp); + +/* + * Append one JSON object line to history/reports/DD-MM-YYYY-.jsonl. + * Returns 0 on success, -1 on failure. + */ +int cl_json_history_append_daily_json(time_t event_time, + const char *suffix, + const char *json, + char *report_file, + size_t report_file_size); + +#ifdef __cplusplus +} +#endif + +#endif /* __JSON_REPORT_H */ diff --git a/libclamav/network_firewall.c b/libclamav/network_firewall.c new file mode 100644 index 0000000000..19255a259f --- /dev/null +++ b/libclamav/network_firewall.c @@ -0,0 +1,1203 @@ +/* + * ClamAV Advanced Network Firewall & Threat Protection Module + * + * Copyright (C) 2013-2026 Cisco Systems, Inc. and/or its affiliates. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#if HAVE_CONFIG_H +#include "clamav-config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_UNISTD_H +#include +#endif + +#include "network_firewall.h" +#include "json_report.h" +#include "others.h" + +/* ------------------------------------------------------------------------- + * Internal constants + * ------------------------------------------------------------------------- */ + +/* SYN flood: alert if > this many SYNs per second */ +#define NFW_SYN_FLOOD_THRESHOLD 1000 +/* UDP flood: alert if > this many UDP packets per second */ +#define NFW_UDP_FLOOD_THRESHOLD 5000 +/* HTTP flood: alert if > this many requests per second */ +#define NFW_HTTP_FLOOD_THRESHOLD 100 + +/* DNS tunneling: alert if query name exceeds this length */ +#define NFW_DNS_QUERY_MAX_SAFE 64 +/* DNS tunneling: alert if payload exceeds 512 bytes */ +#define NFW_DNS_PAYLOAD_MAX_SAFE 512 + +/* Minimum label entropy (bits) to flag as likely base64/hex encoded tunnel */ +#define NFW_DNS_ENTROPY_THRESHOLD 3.8 + +/* C2 beaconing: maximum jitter ratio still considered "regular" */ +#define NFW_C2_JITTER_MAX 0.10 + +/* Number of connections to sample before deciding on beaconing */ +#define NFW_C2_MIN_SAMPLES 5 + +/* Maximum C2 destination entries tracked per state */ +#define NFW_MAX_C2_ENTRIES 1024 + +/* ------------------------------------------------------------------------- + * Internal types + * ------------------------------------------------------------------------- */ + +/* Per-destination C2 beaconing tracker */ +typedef struct { + char src_ip[NFW_MAX_IP_LEN]; + char dst_ip[NFW_MAX_IP_LEN]; + uint16_t dst_port; + time_t last_seen[NFW_C2_MIN_SAMPLES + 2]; + size_t payload_lens[NFW_C2_MIN_SAMPLES + 2]; + int sample_count; +} nfw_c2_entry_t; + +/* Known weak / deprecated TLS cipher suite prefixes */ +static const char *nfw_weak_ciphers[] = { + "RC4", + "NULL", + "EXPORT", + "DES-", + "3DES", + "ADH-", + "AECDH-", + "MD5", + NULL +}; + +/* Known bad TLS protocol versions */ +static const char *nfw_bad_tls_versions[] = { + "SSLv2", + "SSLv3", + "TLSv1.0", + "TLSv1.1", + NULL +}; + +/* ------------------------------------------------------------------------- + * Module state + * ------------------------------------------------------------------------- */ +struct nfw_state { + nfw_config_t cfg; + nfw_ip_record_t ip_table[NFW_MAX_TRACKED_IPS]; + uint32_t ip_table_count; + nfw_c2_entry_t c2_table[NFW_MAX_C2_ENTRIES]; + uint32_t c2_table_count; +}; + +/* ------------------------------------------------------------------------- + * Helpers + * ------------------------------------------------------------------------- */ + +static nfw_ip_record_t *nfw_find_or_create_ip(nfw_state_t *state, + const char *ip) +{ + uint32_t i; + time_t now = time(NULL); + + /* Search for existing entry */ + for (i = 0; i < state->ip_table_count; i++) { + if (strcmp(state->ip_table[i].ip, ip) == 0) { + state->ip_table[i].last_seen = now; + return &state->ip_table[i]; + } + } + + /* Create new entry (evict oldest if full) */ + if (state->ip_table_count >= NFW_MAX_TRACKED_IPS) { + /* Find oldest entry */ + uint32_t oldest_idx = 0; + time_t oldest_time = state->ip_table[0].last_seen; + for (i = 1; i < NFW_MAX_TRACKED_IPS; i++) { + if (state->ip_table[i].last_seen < oldest_time) { + oldest_time = state->ip_table[i].last_seen; + oldest_idx = i; + } + } + memset(&state->ip_table[oldest_idx], 0, + sizeof(nfw_ip_record_t)); + strncpy(state->ip_table[oldest_idx].ip, ip, + NFW_MAX_IP_LEN - 1); + state->ip_table[oldest_idx].ip[NFW_MAX_IP_LEN - 1] = '\0'; + state->ip_table[oldest_idx].first_seen = now; + state->ip_table[oldest_idx].last_seen = now; + return &state->ip_table[oldest_idx]; + } + + nfw_ip_record_t *rec = &state->ip_table[state->ip_table_count++]; + memset(rec, 0, sizeof(*rec)); + strncpy(rec->ip, ip, NFW_MAX_IP_LEN - 1); + rec->ip[NFW_MAX_IP_LEN - 1] = '\0'; + rec->first_seen = now; + rec->last_seen = now; + return rec; +} + +/* Reset per-IP counters if the observation window has expired */ +static void nfw_maybe_reset_counters(nfw_ip_record_t *rec, + const nfw_config_t *cfg) +{ + time_t now = time(NULL); + if ((now - rec->first_seen) >= (time_t)cfg->port_scan_timeout) { + uint32_t prev_failed = rec->failed_login_count; + char ip_copy[NFW_MAX_IP_LEN]; + strncpy(ip_copy, rec->ip, NFW_MAX_IP_LEN - 1); + ip_copy[NFW_MAX_IP_LEN - 1] = '\0'; + memset(rec, 0, sizeof(*rec)); + strncpy(rec->ip, ip_copy, NFW_MAX_IP_LEN - 1); + rec->ip[NFW_MAX_IP_LEN - 1] = '\0'; + rec->first_seen = now; + rec->last_seen = now; + rec->failed_login_count = prev_failed; /* carry across windows */ + } +} + +static void nfw_fill_log_defaults(nfw_threat_log_t *log, + const char *src_ip) +{ + if (!log) return; + memset(log, 0, sizeof(*log)); + /* ISO 8601 timestamp */ + time_t now = time(NULL); + struct tm *tm_info = gmtime(&now); + if (tm_info) { + strftime(log->timestamp, sizeof(log->timestamp), + "%Y-%m-%dT%H:%M:%SZ", tm_info); + } + if (src_ip) + strncpy(log->source_ip, src_ip, NFW_MAX_IP_LEN - 1); +} + +/* Shannon entropy of a string (used for DNS tunneling detection) */ +static double nfw_string_entropy(const char *s, size_t len) +{ + if (!s || len == 0) return 0.0; + int freq[256] = {0}; + size_t i; + for (i = 0; i < len; i++) { + freq[(unsigned char)s[i]]++; + } + double entropy = 0.0; + for (i = 0; i < 256; i++) { + if (freq[i] > 0) { + double p = (double)freq[i] / (double)len; + entropy -= p * log2(p); + } + } + return entropy; +} + +/* ------------------------------------------------------------------------- + * Public API – lifecycle + * ------------------------------------------------------------------------- */ + +void nfw_config_init_defaults(nfw_config_t *cfg) +{ + if (!cfg) return; + memset(cfg, 0, sizeof(*cfg)); + + cfg->enabled = false; + cfg->allow_port_scanning = true; + cfg->port_scan_threshold = 10; + cfg->port_scan_timeout = 300; + cfg->block_scanned_ports = false; + cfg->max_connections_per_ip = 50; + cfg->max_requests_per_second = 100; + cfg->max_failed_logins = 5; + cfg->lockout_duration = 300; + cfg->grace_period = 10; + cfg->enable_ip_reputation = false; + cfg->geo_blocking_enabled = false; + cfg->detect_impossible_travel = false; + cfg->detect_unusual_location = false; + cfg->homograph_detection = false; + cfg->homograph_strict = false; + cfg->dnssec_enabled = false; + cfg->detect_dns_rebinding = false; + cfg->detect_dns_tunneling = false; + cfg->http_inspection = false; + cfg->validate_ssl_certificate = false; + cfg->detect_tls_downgrade = false; + cfg->detect_c2_communication = false; + cfg->enable_ml_models = false; + cfg->ml_confidence_threshold = 0.85; +} + +nfw_state_t *nfw_init(const nfw_config_t *cfg) +{ + nfw_state_t *state = (nfw_state_t *)calloc(1, sizeof(nfw_state_t)); + if (!state) { + cli_errmsg("nfw_init: failed to allocate firewall state structure\n"); + return NULL; + } + if (cfg) + memcpy(&state->cfg, cfg, sizeof(nfw_config_t)); + else + nfw_config_init_defaults(&state->cfg); + + return state; +} + +void nfw_free(nfw_state_t *state) +{ + if (state) + free(state); +} + +/* ------------------------------------------------------------------------- + * Detection – port scanning + * ------------------------------------------------------------------------- */ + +bool nfw_check_port_scan(nfw_state_t *state, + const char *src_ip, + uint16_t dst_port, + nfw_threat_log_t *log) +{ + if (!state || !state->cfg.enabled || !src_ip) + return false; + + nfw_ip_record_t *rec = nfw_find_or_create_ip(state, src_ip); + nfw_maybe_reset_counters(rec, &state->cfg); + + rec->connection_count++; + + /* Track distinct ports */ + bool port_known = false; + uint32_t i; + for (i = 0; i < rec->ports_seen_count; i++) { + if (rec->ports_seen[i] == dst_port) { + port_known = true; + break; + } + } + if (!port_known && + rec->ports_seen_count < NFW_MAX_PORTS_TRACKED) { + rec->ports_seen[rec->ports_seen_count++] = dst_port; + rec->port_count++; + } + + /* Check if port-scan threshold is exceeded */ + if (!state->cfg.allow_port_scanning && + rec->port_count >= state->cfg.port_scan_threshold) { + + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->severity = NFW_SEV_HIGH; + log->threat_type = "Port Scanning"; + log->threat_name = NFW_ALERT_PORT_SCAN_DETECTED; + log->port = dst_port; + log->protocol = "TCP"; + log->action = state->cfg.block_scanned_ports + ? NFW_ACTION_BLOCK + : NFW_ACTION_WARN; + log->confidence = 0.95; + } + + if (state->cfg.block_scanned_ports) + rec->blocked = true; + + return true; + } + + /* Fast port sequence: many connections in a very short time */ + time_t now = time(NULL); + double elapsed = difftime(now, rec->first_seen); + if (elapsed > 0 && + ((double)rec->port_count / elapsed) > (double)state->cfg.port_scan_threshold) { + + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->severity = NFW_SEV_MEDIUM; + log->threat_type = "Port Scanning"; + log->threat_name = NFW_ALERT_FAST_PORT_SEQUENCE; + log->port = dst_port; + log->protocol = "TCP"; + log->action = NFW_ACTION_WARN; + log->confidence = 0.80; + } + return true; + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Detection – DDoS / brute force + * ------------------------------------------------------------------------- */ + +bool nfw_check_ddos(nfw_state_t *state, + const char *src_ip, + bool failed_login, + bool is_syn, + bool is_udp, + bool is_http, + nfw_threat_log_t *log) +{ + if (!state || !state->cfg.enabled || !src_ip) + return false; + + nfw_ip_record_t *rec = nfw_find_or_create_ip(state, src_ip); + nfw_maybe_reset_counters(rec, &state->cfg); + + if (is_syn) rec->syn_count++; + if (is_udp) rec->udp_count++; + if (is_http) rec->http_request_count++; + if (failed_login) rec->failed_login_count++; + rec->connection_count++; + + time_t now = time(NULL); + double elapsed = difftime(now, rec->first_seen); + if (elapsed < 1.0) elapsed = 1.0; + + /* Check if IP is locked out */ + if (rec->blocked && now < rec->blocked_until) + return false; /* already blocked, caller handles */ + + /* SYN flood detection */ + if (is_syn && + ((double)rec->syn_count / elapsed) > NFW_SYN_FLOOD_THRESHOLD) { + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->severity = NFW_SEV_CRITICAL; + log->threat_type = "DDoS"; + log->threat_name = NFW_ALERT_SYN_FLOOD; + log->protocol = "TCP"; + log->action = NFW_ACTION_BLOCK; + log->confidence = 0.92; + } + rec->blocked = true; + rec->blocked_until = now + (time_t)state->cfg.lockout_duration; + return true; + } + + /* UDP flood detection */ + if (is_udp && + ((double)rec->udp_count / elapsed) > NFW_UDP_FLOOD_THRESHOLD) { + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->severity = NFW_SEV_CRITICAL; + log->threat_type = "DDoS"; + log->threat_name = NFW_ALERT_UDP_FLOOD; + log->protocol = "UDP"; + log->action = NFW_ACTION_BLOCK; + log->confidence = 0.90; + } + rec->blocked = true; + rec->blocked_until = now + (time_t)state->cfg.lockout_duration; + return true; + } + + /* HTTP flood detection */ + if (is_http && + ((double)rec->http_request_count / elapsed) > + (double)state->cfg.max_requests_per_second) { + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->severity = NFW_SEV_HIGH; + log->threat_type = "DDoS"; + log->threat_name = NFW_ALERT_HTTP_FLOOD; + log->protocol = "HTTP"; + log->action = NFW_ACTION_BLOCK; + log->confidence = 0.88; + } + rec->blocked = true; + rec->blocked_until = now + (time_t)state->cfg.lockout_duration; + return true; + } + + /* Brute force / credential stuffing */ + if (failed_login && + rec->failed_login_count >= state->cfg.max_failed_logins) { + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->severity = NFW_SEV_HIGH; + log->threat_type = "Brute Force"; + log->threat_name = NFW_ALERT_BRUTE_FORCE; + log->protocol = "TCP"; + log->action = NFW_ACTION_BLOCK; + log->confidence = 0.85; + } + rec->blocked = true; + rec->blocked_until = now + (time_t)state->cfg.lockout_duration; + return true; + } + + /* Concurrent connection limit */ + if (rec->connection_count > state->cfg.max_connections_per_ip) { + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->severity = NFW_SEV_MEDIUM; + log->threat_type = "DDoS"; + log->threat_name = NFW_ALERT_POSSIBLE_DDOS; + log->protocol = "TCP"; + log->action = NFW_ACTION_WARN; + log->confidence = 0.70; + } + return true; + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Detection – IP reputation + * + * This implementation provides the scoring framework. In a production + * deployment the score would be loaded from the ip_reputation_db file + * or queried from threat-intelligence feeds (Spamhaus ZEN, AbuseIPDB, + * etc.). Here a simple internal lookup table of well-known malicious + * ranges (RFC 5737 documentation ranges used as examples) is provided + * for illustration. + * ------------------------------------------------------------------------- */ + +/* Example: reserved / documentation prefixes that should never appear as + * real source traffic. Real deployments would have a much richer list. */ +static const struct { + const char *prefix; + int score; + const char *label; +} nfw_known_bad_prefixes[] = { + { "192.0.2.", 95, NFW_ALERT_BLACKLISTED_IP }, /* TEST-NET-1 */ + { "198.51.100.", 95, NFW_ALERT_BLACKLISTED_IP }, /* TEST-NET-2 */ + { "203.0.113.", 95, NFW_ALERT_BLACKLISTED_IP }, /* TEST-NET-3 */ + { "0.0.0.0", 90, NFW_ALERT_BLACKLISTED_IP }, /* Unspecified */ + { NULL, 0, NULL } +}; + +bool nfw_check_ip_reputation(nfw_state_t *state, + const char *src_ip, + int *score_out, + nfw_threat_log_t *log) +{ + if (!state || !state->cfg.enable_ip_reputation || !src_ip) + return false; + + int score = 0; + const char *label = NULL; + int i; + + /* Check known-bad prefix table */ + for (i = 0; nfw_known_bad_prefixes[i].prefix; i++) { + if (strncmp(src_ip, nfw_known_bad_prefixes[i].prefix, + strlen(nfw_known_bad_prefixes[i].prefix)) == 0) { + score = nfw_known_bad_prefixes[i].score; + label = nfw_known_bad_prefixes[i].label; + break; + } + } + + if (score_out) *score_out = score; + + if (score >= NFW_REPUTATION_WARN) { + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->ip_reputation = score; + log->threat_name = label ? label : NFW_ALERT_BLACKLISTED_IP; + log->threat_type = "IP Reputation"; + log->action = (score >= NFW_REPUTATION_BLOCK) + ? NFW_ACTION_BLOCK + : NFW_ACTION_WARN; + log->severity = (score >= NFW_REPUTATION_BLOCK) + ? NFW_SEV_CRITICAL + : NFW_SEV_HIGH; + log->confidence = score / 100.0; + } + return true; + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Detection – geolocation + * ------------------------------------------------------------------------- */ + +/* Check if a 2-letter country code appears in a comma-separated list */ +static bool nfw_country_in_list(const char *country_code, + const char *list) +{ + if (!country_code || !list || !*list) return false; + + const char *p = list; + while (*p) { + /* skip spaces */ + while (*p == ' ' || *p == ',') p++; + if (!*p) break; + + if (strncasecmp(p, country_code, 2) == 0) { + char next = *(p + 2); + if (next == '\0' || next == ',' || next == ' ') + return true; + } + /* advance to next token */ + while (*p && *p != ',') p++; + } + return false; +} + +bool nfw_check_geolocation(nfw_state_t *state, + const char *country_code, + nfw_threat_log_t *log) +{ + if (!state || !state->cfg.geo_blocking_enabled || !country_code) + return false; + + bool denied = nfw_country_in_list(country_code, + state->cfg.deny_countries); + + /* If allowed_countries is set, only those are permitted */ + if (!denied && state->cfg.allowed_countries[0] != '\0') { + denied = !nfw_country_in_list(country_code, + state->cfg.allowed_countries); + } + + if (denied) { + nfw_fill_log_defaults(log, NULL); + if (log) { + log->severity = NFW_SEV_HIGH; + log->threat_type = "Geolocation"; + log->threat_name = NFW_ALERT_RESTRICTED_GEO; + log->action = NFW_ACTION_BLOCK; + log->confidence = 1.0; + log->geo_source = country_code; + } + return true; + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Detection – URL homograph / Unicode spoofing + * ------------------------------------------------------------------------- */ + +/* Unicode script block ranges (simplified – covers the most-abused blocks) */ +typedef struct { + unsigned int start; + unsigned int end; + const char *name; +} nfw_unicode_block_t; + +static const nfw_unicode_block_t nfw_unicode_blocks[] = { + { 0x0000, 0x007F, "Basic Latin" }, + { 0x0080, 0x00FF, "Latin-1 Supplement" }, + { 0x0400, 0x04FF, "Cyrillic" }, + { 0x0370, 0x03FF, "Greek" }, + { 0x0600, 0x06FF, "Arabic" }, + { 0x0900, 0x097F, "Devanagari" }, + { 0x4E00, 0x9FFF, "CJK Unified" }, + { 0, 0, NULL } +}; + +/* Decode a single UTF-8 codepoint from *s, advance *s */ +static unsigned int nfw_utf8_next(const unsigned char **s) +{ + unsigned int cp = 0; + unsigned char c = **s; + if (!c) return 0; + + if ((c & 0x80) == 0) { + cp = c; + (*s)++; + } else if ((c & 0xE0) == 0xC0) { + /* 2-byte sequence: need 1 continuation byte */ + cp = (c & 0x1F) << 6; + (*s)++; + if (**s == '\0') return 0; + cp |= (**s & 0x3F); (*s)++; + } else if ((c & 0xF0) == 0xE0) { + /* 3-byte sequence: need 2 continuation bytes */ + cp = (c & 0x0F) << 12; + (*s)++; + if (**s == '\0') return 0; + cp |= ((**s) & 0x3F) << 6; (*s)++; + if (**s == '\0') return 0; + cp |= ((**s) & 0x3F); (*s)++; + } else if ((c & 0xF8) == 0xF0) { + /* 4-byte sequence: need 3 continuation bytes */ + cp = (c & 0x07) << 18; + (*s)++; + if (**s == '\0') return 0; + cp |= ((**s) & 0x3F) << 12; (*s)++; + if (**s == '\0') return 0; + cp |= ((**s) & 0x3F) << 6; (*s)++; + if (**s == '\0') return 0; + cp |= ((**s) & 0x3F); (*s)++; + } else { + (*s)++; /* invalid byte – skip */ + } + return cp; +} + +static const char *nfw_unicode_block_name(unsigned int cp) +{ + int i; + for (i = 0; nfw_unicode_blocks[i].name; i++) { + if (cp >= nfw_unicode_blocks[i].start && + cp <= nfw_unicode_blocks[i].end) + return nfw_unicode_blocks[i].name; + } + return "Other"; +} + +bool nfw_check_homograph(nfw_state_t *state, + const char *domain, + nfw_threat_log_t *log) +{ + if (!state || !state->cfg.homograph_detection || !domain) + return false; + + /* Check for Punycode labels (xn--) */ + if (strncasecmp(domain, "xn--", 4) == 0 || + strstr(domain, ".xn--") != NULL) { + + nfw_fill_log_defaults(log, NULL); + if (log) { + log->severity = NFW_SEV_MEDIUM; + log->threat_type = "Homograph Attack"; + log->threat_name = NFW_ALERT_PUNYCODE_ABUSE; + log->action = state->cfg.homograph_strict + ? NFW_ACTION_BLOCK + : NFW_ACTION_WARN; + log->confidence = 0.70; + } + return true; + } + + /* Scan for non-ASCII / mixed-script characters */ + const unsigned char *p = (const unsigned char *)domain; + const char *first_block = NULL; + bool mixed = false; + bool has_emoji = false; + bool has_rtl = false; + + while (*p) { + unsigned int cp = nfw_utf8_next(&p); + if (cp == 0) break; + + /* Emoji range (simplified) */ + if (cp >= 0x1F300 && cp <= 0x1FAFF) { + has_emoji = true; + break; + } + + /* RTL override (U+202E) */ + if (cp == 0x202E) { + has_rtl = true; + break; + } + + if (cp <= 0x007F) continue; /* pure ASCII is fine */ + + const char *block = nfw_unicode_block_name(cp); + if (!first_block) { + first_block = block; + } else if (strcmp(block, first_block) != 0 && + strcmp(block, "Basic Latin") != 0 && + strcmp(first_block, "Basic Latin") != 0) { + mixed = true; + break; + } + } + + if (has_emoji || has_rtl || mixed) { + nfw_fill_log_defaults(log, NULL); + if (log) { + log->severity = NFW_SEV_HIGH; + log->threat_type = "Homograph Attack"; + log->threat_name = has_emoji || has_rtl + ? NFW_ALERT_HOMOGRAPH_DOMAIN + : NFW_ALERT_MIXED_SCRIPT_DOMAIN; + log->action = state->cfg.homograph_strict + ? NFW_ACTION_BLOCK + : NFW_ACTION_WARN; + log->confidence = 0.85; + } + return true; + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Detection – DNS tunneling + * ------------------------------------------------------------------------- */ + +bool nfw_check_dns_tunneling(nfw_state_t *state, + const char *query_name, + const char *query_type, + size_t payload_len, + nfw_threat_log_t *log) +{ + if (!state || !state->cfg.detect_dns_tunneling || !query_name) + return false; + + bool suspicious = false; + double confidence = 0.0; + + /* Oversized payload */ + if (payload_len > NFW_DNS_PAYLOAD_MAX_SAFE) { + suspicious = true; + confidence = 0.75; + } + + /* Very long query name */ + size_t qlen = strlen(query_name); + if (qlen > NFW_DNS_QUERY_MAX_SAFE) { + suspicious = true; + confidence = (confidence > 0.80) ? confidence : 0.80; + } + + /* High entropy in the leftmost label (base64/hex-encoded data) */ + if (qlen > 0) { + /* Isolate the first label */ + const char *dot = strchr(query_name, '.'); + size_t label_len = dot ? (size_t)(dot - query_name) : qlen; + if (label_len >= 8) { + double entropy = nfw_string_entropy(query_name, label_len); + if (entropy >= NFW_DNS_ENTROPY_THRESHOLD) { + suspicious = true; + confidence = (confidence > 0.85) ? confidence : 0.85; + } + } + } + + /* TXT records used to carry arbitrary data */ + if (query_type && strcasecmp(query_type, "TXT") == 0) { + confidence += 0.05; + if (confidence > 1.0) confidence = 1.0; + } + + if (suspicious) { + nfw_fill_log_defaults(log, NULL); + if (log) { + log->severity = NFW_SEV_HIGH; + log->threat_type = "DNS Tunneling"; + log->threat_name = NFW_ALERT_DNS_TUNNELING; + log->protocol = "DNS"; + log->action = NFW_ACTION_BLOCK; + log->confidence = confidence; + } + return true; + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Detection – C2 beaconing + * ------------------------------------------------------------------------- */ + +static nfw_c2_entry_t *nfw_find_or_create_c2(nfw_state_t *state, + const char *src_ip, + const char *dst_ip, + uint16_t dst_port) +{ + uint32_t i; + for (i = 0; i < state->c2_table_count; i++) { + nfw_c2_entry_t *e = &state->c2_table[i]; + if (strcmp(e->src_ip, src_ip) == 0 && + strcmp(e->dst_ip, dst_ip) == 0 && + e->dst_port == dst_port) + return e; + } + + if (state->c2_table_count >= NFW_MAX_C2_ENTRIES) { + /* Evict entry 0 (FIFO) */ + memmove(&state->c2_table[0], &state->c2_table[1], + sizeof(nfw_c2_entry_t) * (NFW_MAX_C2_ENTRIES - 1)); + state->c2_table_count = NFW_MAX_C2_ENTRIES - 1; + } + + nfw_c2_entry_t *e = &state->c2_table[state->c2_table_count++]; + memset(e, 0, sizeof(*e)); + strncpy(e->src_ip, src_ip, NFW_MAX_IP_LEN - 1); + strncpy(e->dst_ip, dst_ip, NFW_MAX_IP_LEN - 1); + e->dst_port = dst_port; + return e; +} + +bool nfw_check_c2_beaconing(nfw_state_t *state, + const char *src_ip, + const char *dst_ip, + uint16_t dst_port, + size_t payload_len, + nfw_threat_log_t *log) +{ + if (!state || !state->cfg.detect_c2_communication || !src_ip || !dst_ip) + return false; + + nfw_c2_entry_t *e = nfw_find_or_create_c2(state, src_ip, + dst_ip, dst_port); + + time_t now = time(NULL); + int sc = e->sample_count; + int n; + int i; + double intervals[NFW_C2_MIN_SAMPLES]; + double sum; + double mean; + double sq_sum; + double stddev; + double jitter; + double d; + bool payload_consistent; + bool beaconing; + + if (sc < NFW_C2_MIN_SAMPLES) { + e->last_seen[sc] = now; + e->payload_lens[sc] = payload_len; + e->sample_count++; + return false; /* not enough data yet */ + } + + /* Compute inter-arrival intervals */ + n = NFW_C2_MIN_SAMPLES; + for (i = 0; i < n - 1; i++) { + intervals[i] = difftime(e->last_seen[i + 1], e->last_seen[i]); + } + intervals[n - 1] = difftime(now, e->last_seen[n - 1]); + + /* Mean interval */ + sum = 0; + for (i = 0; i < n; i++) sum += intervals[i]; + mean = sum / n; + + if (mean <= 0) return false; + + /* Standard deviation */ + sq_sum = 0; + for (i = 0; i < n; i++) { + d = intervals[i] - mean; + sq_sum += d * d; + } + stddev = sqrt(sq_sum / n); + jitter = stddev / mean; + + /* Consistent payload sizes are another indicator */ + payload_consistent = true; + for (i = 1; i < n; i++) { + size_t a = e->payload_lens[i]; + size_t b = e->payload_lens[0]; + size_t diff = (a > b) ? (a - b) : (b - a); + if (diff > 64) { + payload_consistent = false; + break; + } + } + + beaconing = (jitter <= NFW_C2_JITTER_MAX) && payload_consistent; + + /* Slide the window */ + memmove(e->last_seen, e->last_seen + 1, + sizeof(time_t) * (NFW_C2_MIN_SAMPLES - 1)); + e->last_seen[NFW_C2_MIN_SAMPLES - 1] = now; + memmove(e->payload_lens, e->payload_lens + 1, + sizeof(size_t) * (NFW_C2_MIN_SAMPLES - 1)); + e->payload_lens[NFW_C2_MIN_SAMPLES - 1] = payload_len; + + if (beaconing) { + nfw_fill_log_defaults(log, src_ip); + if (log) { + log->severity = NFW_SEV_CRITICAL; + log->threat_type = "C2 Communication"; + log->threat_name = NFW_ALERT_C2_BEACONING; + strncpy(log->dest_ip, dst_ip, NFW_MAX_IP_LEN - 1); + log->port = dst_port; + log->protocol = "TCP"; + log->action = NFW_ACTION_BLOCK; + log->confidence = 1.0 - jitter; + if (log->confidence < 0.0) log->confidence = 0.0; + } + return true; + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Detection – HTTP header anomalies + * ------------------------------------------------------------------------- */ + +bool nfw_check_http_headers(nfw_state_t *state, + const char *headers, + size_t headers_len, + nfw_threat_log_t *log) +{ + bool suspicious = false; + const char *xff; + const char *p; + int commas; + + if (!state || !state->cfg.http_inspection || !headers || !headers_len) + return false; + + /* Missing User-Agent */ + if (strstr(headers, "User-Agent:") == NULL && + strstr(headers, "user-agent:") == NULL) { + suspicious = true; + } + + /* Path traversal in request line – check the most common patterns */ + if (strstr(headers, "../") != NULL || + strstr(headers, "%2e%2e/") != NULL || + strstr(headers, "%2E%2E/") != NULL) { + suspicious = true; + } + + /* X-Forwarded-For loop detection */ + xff = strstr(headers, "X-Forwarded-For:"); + if (xff) { + /* Count commas – many hops suggest loop or spoofing */ + commas = 0; + p = xff; + while (*p && *p != '\r' && *p != '\n') { + if (*p == ',') commas++; + p++; + } + if (commas > 8) suspicious = true; + } + + if (suspicious) { + nfw_fill_log_defaults(log, NULL); + if (log) { + log->severity = NFW_SEV_MEDIUM; + log->threat_type = "Protocol Anomaly"; + log->threat_name = NFW_ALERT_HTTP_HEADER_ANOMALY; + log->protocol = "HTTP"; + log->action = NFW_ACTION_WARN; + log->confidence = 0.70; + } + return true; + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Detection – TLS cipher suite + * ------------------------------------------------------------------------- */ + +bool nfw_check_tls_cipher(nfw_state_t *state, + const char *cipher_suite, + const char *tls_version, + nfw_threat_log_t *log) +{ + if (!state || !state->cfg.validate_ssl_certificate || !cipher_suite) + return false; + + int i; + + /* Check for known-weak cipher prefixes */ + for (i = 0; nfw_weak_ciphers[i]; i++) { + if (strncasecmp(cipher_suite, nfw_weak_ciphers[i], + strlen(nfw_weak_ciphers[i])) == 0) { + nfw_fill_log_defaults(log, NULL); + if (log) { + log->severity = NFW_SEV_HIGH; + log->threat_type = "TLS Security"; + log->threat_name = NFW_ALERT_WEAK_CIPHER; + log->protocol = "TLS"; + log->action = NFW_ACTION_BLOCK; + log->confidence = 0.95; + } + return true; + } + } + + /* Check for deprecated TLS versions */ + if (tls_version && state->cfg.detect_tls_downgrade) { + for (i = 0; nfw_bad_tls_versions[i]; i++) { + if (strcasecmp(tls_version, nfw_bad_tls_versions[i]) == 0) { + nfw_fill_log_defaults(log, NULL); + if (log) { + log->severity = NFW_SEV_HIGH; + log->threat_type = "TLS Downgrade"; + log->threat_name = NFW_ALERT_TLS_DOWNGRADE; + log->protocol = "TLS"; + log->action = NFW_ACTION_WARN; + log->confidence = 0.90; + } + return true; + } + } + } + + return false; +} + +/* ------------------------------------------------------------------------- + * Logging + * ------------------------------------------------------------------------- */ + +const char *nfw_severity_str(nfw_severity_t severity) +{ + switch (severity) { + case NFW_SEV_LOW: return "LOW"; + case NFW_SEV_MEDIUM: return "MEDIUM"; + case NFW_SEV_HIGH: return "HIGH"; + case NFW_SEV_CRITICAL: return "CRITICAL"; + default: return "UNKNOWN"; + } +} + +const char *nfw_action_str(nfw_action_t action) +{ + switch (action) { + case NFW_ACTION_ALLOW: return "ALLOW"; + case NFW_ACTION_MONITOR: return "MONITOR"; + case NFW_ACTION_WARN: return "WARN"; + case NFW_ACTION_BLOCK: return "BLOCK"; + default: return "UNKNOWN"; + } +} + +char *nfw_log_to_json(const nfw_threat_log_t *log) +{ + if (!log) return NULL; + + /* Estimate a generous buffer size */ + size_t buf_size = 1024; + char *buf = (char *)malloc(buf_size); + if (!buf) return NULL; + + int n = snprintf(buf, buf_size, + "{" + "\"timestamp\":\"%s\"," + "\"severity\":\"%s\"," + "\"threat_type\":\"%s\"," + "\"threat_name\":\"%s\"," + "\"source_ip\":\"%s\"," + "\"dest_ip\":\"%s\"," + "\"port\":%u," + "\"protocol\":\"%s\"," + "\"action\":\"%s\"," + "\"confidence\":%.2f," + "\"geo_source\":\"%s\"," + "\"ip_reputation\":%d" + "}", + log->timestamp, + nfw_severity_str(log->severity), + log->threat_type ? log->threat_type : "", + log->threat_name ? log->threat_name : "", + log->source_ip, + log->dest_ip, + (unsigned)log->port, + log->protocol ? log->protocol : "", + nfw_action_str(log->action), + log->confidence, + log->geo_source ? log->geo_source : "", + log->ip_reputation); + + if (n < 0 || (size_t)n >= buf_size) { + /* Truncated or encoding error – try a larger buffer */ + free(buf); + if (n < 0) { + /* snprintf encoding error: fall back to a fixed large size */ + buf_size = 2048; + } else { + buf_size = (size_t)n + 2; + } + buf = (char *)malloc(buf_size); + if (!buf) return NULL; + snprintf(buf, buf_size, + "{" + "\"timestamp\":\"%s\"," + "\"severity\":\"%s\"," + "\"threat_type\":\"%s\"," + "\"threat_name\":\"%s\"," + "\"source_ip\":\"%s\"," + "\"dest_ip\":\"%s\"," + "\"port\":%u," + "\"protocol\":\"%s\"," + "\"action\":\"%s\"," + "\"confidence\":%.2f," + "\"geo_source\":\"%s\"," + "\"ip_reputation\":%d" + "}", + log->timestamp, + nfw_severity_str(log->severity), + log->threat_type ? log->threat_type : "", + log->threat_name ? log->threat_name : "", + log->source_ip, + log->dest_ip, + (unsigned)log->port, + log->protocol ? log->protocol : "", + nfw_action_str(log->action), + log->confidence, + log->geo_source ? log->geo_source : "", + log->ip_reputation); + } + + return buf; +} + +void nfw_log_write(const nfw_threat_log_t *log, FILE *out) +{ + if (!log || !out) return; + char *json = nfw_log_to_json(log); + if (json) { + fprintf(out, "%s\n", json); + free(json); + } +} + +bool nfw_log_write_history(const nfw_threat_log_t *log) +{ + char report_file[1105]; + time_t now; + char *json; + + if (!log) { + return false; + } + + json = nfw_log_to_json(log); + if (!json) { + return false; + } + + now = time(NULL); + if (0 != cl_json_history_append_daily_json(now, + "network-reports", + json, + report_file, + sizeof(report_file))) { + free(json); + return false; + } + free(json); + + cli_dbgmsg("nfw_log_write_history: JSON history report saved: %s\n", report_file); + + return true; +} diff --git a/libclamav/network_firewall.h b/libclamav/network_firewall.h new file mode 100644 index 0000000000..b304e82cfe --- /dev/null +++ b/libclamav/network_firewall.h @@ -0,0 +1,433 @@ +/* + * ClamAV Advanced Network Firewall & Threat Protection Module + * + * Copyright (C) 2013-2026 Cisco Systems, Inc. and/or its affiliates. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#ifndef __NETWORK_FIREWALL_H +#define __NETWORK_FIREWALL_H + +#include +#include +#include + +#include "clamav.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------------------------------------------------------------- + * Threat alert names emitted by the network firewall module + * ------------------------------------------------------------------------- */ + +/* Port scanning */ +#define NFW_ALERT_PORT_SCAN_DETECTED "Heuristics.Network.PortScanDetected" +#define NFW_ALERT_FAST_PORT_SEQUENCE "Heuristics.Network.FastPortSequence" +#define NFW_ALERT_SUSPICIOUS_FINGERPRINT "Heuristics.Network.SuspiciousFingerprint" +#define NFW_ALERT_NMAP_SCAN "Heuristics.Network.NmapScan" +#define NFW_ALERT_MASSCAN_ACTIVITY "Heuristics.Network.MasscanActivity" + +/* DDoS / brute force */ +#define NFW_ALERT_POSSIBLE_DDOS "Heuristics.Network.PossibleDDoS" +#define NFW_ALERT_SYN_FLOOD "Heuristics.Network.SYNFlood" +#define NFW_ALERT_UDP_FLOOD "Heuristics.Network.UDPFlood" +#define NFW_ALERT_HTTP_FLOOD "Heuristics.Network.HTTPFlood" +#define NFW_ALERT_BRUTE_FORCE "Heuristics.Network.BruteForceAttempt" +#define NFW_ALERT_CREDENTIAL_STUFFING "Heuristics.Network.CredentialStuffing" + +/* IP reputation */ +#define NFW_ALERT_BLACKLISTED_IP "Heuristics.Network.BlacklistedIP" +#define NFW_ALERT_HIGH_RISK_ISP "Heuristics.Network.HighRiskISP" +#define NFW_ALERT_KNOWN_BOTNET_C2 "Heuristics.Network.KnownBotnetC2" +#define NFW_ALERT_SPAM_NETWORK "Heuristics.Network.SpamNetwork" +#define NFW_ALERT_MALWARE_DISTRIBUTION "Heuristics.Network.MalwareDistribution" + +/* Geolocation */ +#define NFW_ALERT_IMPOSSIBLE_TRAVEL "Heuristics.Network.ImpossibleTravel" +#define NFW_ALERT_UNUSUAL_COUNTRY "Heuristics.Network.UnusualCountry" +#define NFW_ALERT_RESTRICTED_GEO "Heuristics.Network.RestrictedGeolocation" +#define NFW_ALERT_TOR_EXIT_NODE "Heuristics.Network.TorExitNode" +#define NFW_ALERT_VPN_DETECTED "Heuristics.Network.VPNDetected" +#define NFW_ALERT_PROXY_DETECTED "Heuristics.Network.ProxyDetected" + +/* URL / domain */ +#define NFW_ALERT_HOMOGRAPH_DOMAIN "Heuristics.Network.HomographDomain" +#define NFW_ALERT_PUNYCODE_ABUSE "Heuristics.Network.PunycodeAbuse" +#define NFW_ALERT_MIXED_SCRIPT_DOMAIN "Heuristics.Network.MixedScriptDomain" +#define NFW_ALERT_NEW_DOMAIN "Heuristics.Network.NewDomain" +#define NFW_ALERT_DNS_REBINDING "Heuristics.Network.DNSRebinding" +#define NFW_ALERT_DNS_TUNNELING "Heuristics.Network.DNSTunneling" +#define NFW_ALERT_DNSSEC_FAILURE "Heuristics.Network.DNSSECFailure" + +/* Protocol anomalies */ +#define NFW_ALERT_HTTP_HEADER_ANOMALY "Heuristics.Network.HTTPHeaderAnomaly" +#define NFW_ALERT_TLS_DOWNGRADE "Heuristics.Network.TLSDowngrade" +#define NFW_ALERT_WEAK_CIPHER "Heuristics.Network.WeakCipherSuite" +#define NFW_ALERT_PATH_TRAVERSAL "Heuristics.Network.PathTraversal" + +/* Behavioral / threat-specific */ +#define NFW_ALERT_C2_BEACONING "Heuristics.Network.C2Beaconing" +#define NFW_ALERT_C2_COMMUNICATION "Heuristics.Network.C2Communication" +#define NFW_ALERT_RANSOMWARE_C2 "Heuristics.Network.RansomwareC2" +#define NFW_ALERT_CRYPTOMINER "Heuristics.Network.CryptominerPool" +#define NFW_ALERT_COVERT_CHANNEL "Heuristics.Network.CovertChannel" + +/* ------------------------------------------------------------------------- + * Severity levels for threat logging + * ------------------------------------------------------------------------- */ +typedef enum nfw_severity { + NFW_SEV_LOW = 0, + NFW_SEV_MEDIUM = 1, + NFW_SEV_HIGH = 2, + NFW_SEV_CRITICAL = 3 +} nfw_severity_t; + +/* ------------------------------------------------------------------------- + * Action taken when a threat is detected + * ------------------------------------------------------------------------- */ +typedef enum nfw_action { + NFW_ACTION_ALLOW = 0, + NFW_ACTION_MONITOR = 1, + NFW_ACTION_WARN = 2, + NFW_ACTION_BLOCK = 3 +} nfw_action_t; + +/* ------------------------------------------------------------------------- + * IP reputation score thresholds + * ------------------------------------------------------------------------- */ +#define NFW_REPUTATION_BLOCK 85 /* Score >= 85: BLOCK */ +#define NFW_REPUTATION_WARN 50 /* Score 50-84: WARN */ +#define NFW_REPUTATION_MONITOR 20 /* Score 20-49: MONITOR */ + /* Score < 20: ALLOW */ + +/* ------------------------------------------------------------------------- + * Per-IP connection tracking entry (for port scan / DDoS detection) + * ------------------------------------------------------------------------- */ +#define NFW_MAX_TRACKED_IPS 4096 +#define NFW_MAX_IP_LEN 46 /* IPv6 string max length */ +#define NFW_MAX_PORTS_TRACKED 256 + +typedef struct nfw_ip_record { + char ip[NFW_MAX_IP_LEN]; + time_t first_seen; + time_t last_seen; + uint32_t port_count; /* distinct ports contacted */ + uint32_t connection_count; /* total connections in window */ + uint32_t failed_login_count; /* failed authentication attempts */ + uint16_t ports_seen[NFW_MAX_PORTS_TRACKED]; + uint32_t ports_seen_count; + uint32_t syn_count; /* SYN packets in window */ + uint32_t udp_count; /* UDP packets in window */ + uint32_t http_request_count; /* HTTP requests in window */ + bool blocked; /* currently blocked */ + time_t blocked_until; +} nfw_ip_record_t; + +/* ------------------------------------------------------------------------- + * Threat log entry (JSON-serialisable) + * ------------------------------------------------------------------------- */ +typedef struct nfw_threat_log { + char timestamp[32]; /* ISO 8601 */ + nfw_severity_t severity; + const char *threat_type; + const char *threat_name; + char source_ip[NFW_MAX_IP_LEN]; + char dest_ip[NFW_MAX_IP_LEN]; + uint16_t port; + const char *protocol; + nfw_action_t action; + double confidence; /* 0.0 – 1.0 */ + const char *geo_source; /* country name / code */ + int ip_reputation; /* 0–100 */ +} nfw_threat_log_t; + +/* ------------------------------------------------------------------------- + * Firewall configuration (mirrors clamd.conf options) + * ------------------------------------------------------------------------- */ +typedef struct nfw_config { + /* General */ + bool enabled; + + /* Port scan */ + bool allow_port_scanning; + uint32_t port_scan_threshold; /* connections in observation window */ + uint32_t port_scan_timeout; /* observation window seconds */ + bool block_scanned_ports; + + /* DDoS / rate limiting */ + uint32_t max_connections_per_ip; + uint32_t max_requests_per_second; + uint32_t max_failed_logins; + uint32_t lockout_duration; /* seconds */ + uint32_t grace_period; /* seconds */ + + /* IP reputation */ + bool enable_ip_reputation; + char ip_reputation_db[256]; + + /* Geolocation */ + bool geo_blocking_enabled; + char allowed_countries[512]; /* comma-separated ISO codes */ + char deny_countries[512]; + bool detect_impossible_travel; + bool detect_unusual_location; + + /* URL / domain */ + bool homograph_detection; + bool homograph_strict; /* strict = block mixed-script */ + bool dnssec_enabled; + bool detect_dns_rebinding; + bool detect_dns_tunneling; + + /* Protocol */ + bool http_inspection; + bool validate_ssl_certificate; + bool detect_tls_downgrade; + + /* Behavioral */ + bool detect_c2_communication; + bool enable_ml_models; + double ml_confidence_threshold; /* 0.0 – 1.0 */ +} nfw_config_t; + +/* ------------------------------------------------------------------------- + * Module state (opaque from outside) + * ------------------------------------------------------------------------- */ +typedef struct nfw_state nfw_state_t; + +/* ------------------------------------------------------------------------- + * Public API + * ------------------------------------------------------------------------- */ + +/** + * @brief Allocate and initialise the network firewall state. + * + * @param cfg Populated configuration structure. + * @return Pointer to the new state on success, NULL on failure. + */ +nfw_state_t *nfw_init(const nfw_config_t *cfg); + +/** + * @brief Release all resources held by the firewall state. + * + * @param state State returned by nfw_init(). + */ +void nfw_free(nfw_state_t *state); + +/** + * @brief Initialise a firewall config with safe defaults. + * + * @param cfg Output config structure. + */ +void nfw_config_init_defaults(nfw_config_t *cfg); + +/* ---- Detection functions ------------------------------------------------ */ + +/** + * @brief Check whether the given source IP is performing a port scan. + * + * @param state Firewall state. + * @param src_ip Source IP address string. + * @param dst_port Destination port being contacted. + * @param log Output: populated if a threat is detected (may be NULL). + * @return True if a port-scan pattern was detected. + */ +bool nfw_check_port_scan(nfw_state_t *state, + const char *src_ip, + uint16_t dst_port, + nfw_threat_log_t *log); + +/** + * @brief Check connection rates for DDoS / brute-force patterns. + * + * @param state Firewall state. + * @param src_ip Source IP address string. + * @param failed_login True if this event is a failed authentication attempt. + * @param is_syn True if this is a SYN packet. + * @param is_udp True if this is a UDP packet. + * @param is_http True if this is an HTTP request. + * @param log Output: populated if a threat is detected (may be NULL). + * @return True if a DDoS / brute-force pattern was detected. + */ +bool nfw_check_ddos(nfw_state_t *state, + const char *src_ip, + bool failed_login, + bool is_syn, + bool is_udp, + bool is_http, + nfw_threat_log_t *log); + +/** + * @brief Evaluate IP reputation score. + * + * @param state Firewall state. + * @param src_ip Source IP address string. + * @param score_out Output: reputation score 0–100 (higher = more malicious). + * @param log Output: populated if a threat is detected (may be NULL). + * @return True if the IP should be blocked or warned about. + */ +bool nfw_check_ip_reputation(nfw_state_t *state, + const char *src_ip, + int *score_out, + nfw_threat_log_t *log); + +/** + * @brief Check whether the source country is blocked by geolocation policy. + * + * @param state Firewall state. + * @param country_code Two-letter ISO 3166-1 alpha-2 country code (e.g. "US"). + * @param log Output: populated if blocked (may be NULL). + * @return True if the country is denied. + */ +bool nfw_check_geolocation(nfw_state_t *state, + const char *country_code, + nfw_threat_log_t *log); + +/** + * @brief Detect homograph / Unicode spoofing attacks in a domain name. + * + * Checks for: + * - Mixed Unicode scripts (e.g. Cyrillic + Latin) + * - Punycode abuse (xn-- labels that resemble ASCII domains) + * - Emoji domains + * - RTL override characters + * + * @param state Firewall state. + * @param domain Domain name to inspect (UTF-8 or ACE form). + * @param log Output: populated if an attack is detected (may be NULL). + * @return True if a homograph attack pattern was detected. + */ +bool nfw_check_homograph(nfw_state_t *state, + const char *domain, + nfw_threat_log_t *log); + +/** + * @brief Check a DNS query for tunneling / covert-channel patterns. + * + * @param state Firewall state. + * @param query_name Full DNS query name (FQDN). + * @param query_type DNS record type (e.g. "TXT", "A"). + * @param payload_len Length of the DNS payload in bytes. + * @param log Output: populated if detected (may be NULL). + * @return True if DNS tunneling was detected. + */ +bool nfw_check_dns_tunneling(nfw_state_t *state, + const char *query_name, + const char *query_type, + size_t payload_len, + nfw_threat_log_t *log); + +/** + * @brief Detect C2 beaconing patterns in outbound connections. + * + * Analyses the timing and payload characteristics of a series of + * connections from the same source to the same destination to + * identify regular heartbeat (beaconing) behaviour. + * + * @param state Firewall state. + * @param src_ip Source IP address. + * @param dst_ip Destination IP address. + * @param dst_port Destination port. + * @param payload_len Payload size of this connection. + * @param log Output: populated if C2 beaconing is detected. + * @return True if beaconing pattern detected. + */ +bool nfw_check_c2_beaconing(nfw_state_t *state, + const char *src_ip, + const char *dst_ip, + uint16_t dst_port, + size_t payload_len, + nfw_threat_log_t *log); + +/** + * @brief Detect HTTP header anomalies. + * + * @param state Firewall state. + * @param headers Raw HTTP headers string. + * @param headers_len Length of headers string. + * @param log Output: populated if anomaly detected (may be NULL). + * @return True if an HTTP anomaly was detected. + */ +bool nfw_check_http_headers(nfw_state_t *state, + const char *headers, + size_t headers_len, + nfw_threat_log_t *log); + +/** + * @brief Check TLS cipher suite for weak or deprecated algorithms. + * + * @param state Firewall state. + * @param cipher_suite TLS cipher suite name string. + * @param tls_version TLS protocol version string (e.g. "TLSv1.2"). + * @param log Output: populated if a weak cipher is detected. + * @return True if a weak or deprecated cipher was found. + */ +bool nfw_check_tls_cipher(nfw_state_t *state, + const char *cipher_suite, + const char *tls_version, + nfw_threat_log_t *log); + +/* ---- Logging ------------------------------------------------------------ */ + +/** + * @brief Serialise a threat log entry to a JSON string. + * + * The returned buffer is allocated with malloc() and must be freed by + * the caller. + * + * @param log Threat log entry to serialise. + * @return Heap-allocated JSON string, or NULL on error. + */ +char *nfw_log_to_json(const nfw_threat_log_t *log); + +/** + * @brief Write a threat log entry to the given FILE stream as JSON. + * + * @param log Threat log entry. + * @param out Output stream (e.g. a log file opened with fopen). + */ +void nfw_log_write(const nfw_threat_log_t *log, FILE *out); + +/** + * @brief Append a threat log entry to the JSON history report directory. + * + * Writes one JSON object line to: + * history/reports/DD-MM-YYYY-network-reports.jsonl + * + * @param log Threat log entry. + * @return True on success, false on failure. + */ +bool nfw_log_write_history(const nfw_threat_log_t *log); + +/* ---- Utility ------------------------------------------------------------ */ + +/** + * @brief Convert an nfw_severity_t value to a human-readable string. + */ +const char *nfw_severity_str(nfw_severity_t severity); + +/** + * @brief Convert an nfw_action_t value to a human-readable string. + */ +const char *nfw_action_str(nfw_action_t action); + +#ifdef __cplusplus +} +#endif + +#endif /* __NETWORK_FIREWALL_H */