use crate::error::{Result, SecurityError};
use crate::scanning::{Finding, ScanResult, ScanType, Severity};
use sha2::{Digest, Sha256};
use std::collections::HashSet;
const MAX_SCAN_BYTES: usize = 16 * 1024 * 1024;
const HIGH_ENTROPY_THRESHOLD: f64 = 7.5;
const ENTROPY_MIN_SIZE: usize = 256;
const EICAR_SIGNATURE: &[u8] =
br#"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"#;
struct ByteSignature {
name: &'static str,
needle: &'static [u8],
severity: Severity,
}
pub struct MalwareScanner {
hash_blocklist: HashSet<String>,
detect_executables: bool,
detect_high_entropy: bool,
}
impl MalwareScanner {
pub fn new() -> Self {
Self {
hash_blocklist: HashSet::new(),
detect_executables: true,
detect_high_entropy: true,
}
}
pub fn with_blocklisted_sha256(mut self, digest_hex: impl AsRef<str>) -> Self {
self.hash_blocklist
.insert(digest_hex.as_ref().trim().to_ascii_lowercase());
self
}
pub fn detect_executables(mut self, enabled: bool) -> Self {
self.detect_executables = enabled;
self
}
pub fn detect_high_entropy(mut self, enabled: bool) -> Self {
self.detect_high_entropy = enabled;
self
}
pub fn scan_file(&self, file_path: &str) -> Result<ScanResult> {
let metadata = std::fs::metadata(file_path)
.map_err(|e| SecurityError::security_scan(format!("cannot stat '{file_path}': {e}")))?;
let file = std::fs::File::open(file_path)
.map_err(|e| SecurityError::security_scan(format!("cannot open '{file_path}': {e}")))?;
use std::io::Read;
let mut buf = Vec::new();
file.take(MAX_SCAN_BYTES as u64)
.read_to_end(&mut buf)
.map_err(|e| SecurityError::security_scan(format!("cannot read '{file_path}': {e}")))?;
Ok(self.scan_bytes_named(&buf, Some(file_path), metadata.len()))
}
pub fn scan_bytes(&self, data: &[u8]) -> ScanResult {
self.scan_bytes_named(data, None, data.len() as u64)
}
fn scan_bytes_named(&self, data: &[u8], location: Option<&str>, full_size: u64) -> ScanResult {
let mut findings = Vec::new();
for signature in Self::byte_signatures() {
if Self::contains(data, signature.needle) {
findings.push(Finding {
id: Self::finding_id(location, "signature", signature.name),
severity: signature.severity,
description: format!("Malware signature detected: {}", signature.name),
location: location.map(|l| l.to_string()),
});
}
}
if !self.hash_blocklist.is_empty() {
let digest = Self::sha256_hex(data);
if self.hash_blocklist.contains(&digest) {
findings.push(Finding {
id: Self::finding_id(location, "hash", &digest),
severity: Severity::Critical,
description: format!("Content matches blocklisted SHA-256: {digest}"),
location: location.map(|l| l.to_string()),
});
}
}
if self.detect_executables
&& let Some(kind) = Self::executable_kind(data)
{
findings.push(Finding {
id: Self::finding_id(location, "executable", kind),
severity: Severity::Medium,
description: format!(
"Executable content detected ({kind}); unexpected in scanned data"
),
location: location.map(|l| l.to_string()),
});
}
if self.detect_high_entropy && data.len() >= ENTROPY_MIN_SIZE {
let entropy = Self::shannon_entropy(data);
if entropy >= HIGH_ENTROPY_THRESHOLD {
findings.push(Finding {
id: Self::finding_id(location, "entropy", "high"),
severity: Severity::Low,
description: format!(
"High Shannon entropy ({entropy:.2} bits/byte over {} bytes); \
possibly packed or encrypted content",
data.len()
),
location: location.map(|l| l.to_string()),
});
}
}
if full_size > data.len() as u64 {
findings.push(Finding {
id: Self::finding_id(location, "truncated", "scan"),
severity: Severity::Info,
description: format!(
"Only the first {} of {full_size} bytes were scanned",
data.len()
),
location: location.map(|l| l.to_string()),
});
}
ScanResult {
scan_type: ScanType::Malware,
findings,
scanned_at: chrono::Utc::now(),
}
}
fn byte_signatures() -> [ByteSignature; 2] {
[
ByteSignature {
name: "EICAR-Test-File",
needle: EICAR_SIGNATURE,
severity: Severity::Critical,
},
ByteSignature {
name: "Embedded-PE-DOS-stub",
needle: b"This program cannot be run in DOS mode",
severity: Severity::Medium,
},
]
}
fn executable_kind(data: &[u8]) -> Option<&'static str> {
if data.starts_with(b"\x7fELF") {
return Some("ELF");
}
if data.starts_with(b"MZ") {
return Some("PE/MZ");
}
const MACHO: [&[u8]; 5] = [
&[0xFE, 0xED, 0xFA, 0xCE],
&[0xFE, 0xED, 0xFA, 0xCF],
&[0xCE, 0xFA, 0xED, 0xFE],
&[0xCF, 0xFA, 0xED, 0xFE],
&[0xCA, 0xFE, 0xBA, 0xBE],
];
if MACHO.iter().any(|m| data.starts_with(m)) {
return Some("Mach-O");
}
if data.starts_with(b"#!") {
return Some("script-shebang");
}
None
}
fn shannon_entropy(data: &[u8]) -> f64 {
if data.is_empty() {
return 0.0;
}
let mut counts = [0u64; 256];
for &b in data {
counts[b as usize] += 1;
}
let len = data.len() as f64;
let mut entropy = 0.0;
for &count in counts.iter() {
if count == 0 {
continue;
}
let p = count as f64 / len;
entropy -= p * p.log2();
}
entropy
}
fn sha256_hex(data: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(data);
let digest = hasher.finalize();
let mut out = String::with_capacity(64);
for byte in digest {
use std::fmt::Write;
let _ = write!(out, "{byte:02x}");
}
out
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
if needle.is_empty() || needle.len() > haystack.len() {
return needle.is_empty();
}
haystack
.windows(needle.len())
.any(|window| window == needle)
}
fn finding_id(location: Option<&str>, category: &str, detail: &str) -> String {
match location {
Some(loc) => format!("malware:{category}:{detail}:{loc}"),
None => format!("malware:{category}:{detail}"),
}
}
}
impl Default for MalwareScanner {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::io::Write;
#[test]
fn test_clean_text_has_no_findings() {
let scanner = MalwareScanner::new();
let result = scanner.scan_bytes(b"just some perfectly ordinary plain text content");
assert_eq!(result.scan_type, ScanType::Malware);
assert!(
result.findings.is_empty(),
"benign text should produce no findings, got {:?}",
result.findings
);
}
#[test]
fn test_eicar_is_detected_critical() {
let scanner = MalwareScanner::new();
let result = scanner.scan_bytes(EICAR_SIGNATURE);
assert!(
result
.findings
.iter()
.any(|f| f.severity == Severity::Critical && f.description.contains("EICAR")),
"EICAR test file must be detected as Critical, got {:?}",
result.findings
);
}
#[test]
fn test_elf_magic_flagged() {
let scanner = MalwareScanner::new();
let mut data = b"\x7fELF".to_vec();
data.extend_from_slice(&[0u8; 64]);
let result = scanner.scan_bytes(&data);
assert!(
result
.findings
.iter()
.any(|f| f.description.contains("ELF")),
"ELF executable should be flagged"
);
}
#[test]
fn test_hash_blocklist_matches() {
let payload = b"totally benign but blocklisted";
let digest = MalwareScanner::sha256_hex(payload);
let scanner = MalwareScanner::new().with_blocklisted_sha256(&digest);
let result = scanner.scan_bytes(payload);
assert!(
result
.findings
.iter()
.any(|f| f.severity == Severity::Critical && f.description.contains("blocklisted")),
"blocklisted hash must produce a Critical finding"
);
let clean = scanner.scan_bytes(b"different content entirely");
assert!(
clean
.findings
.iter()
.all(|f| !f.description.contains("blocklisted"))
);
}
#[test]
fn test_high_entropy_flagged() {
let scanner = MalwareScanner::new();
let mut data = Vec::with_capacity(4096);
let mut x: u32 = 0x1234_5678;
for _ in 0..4096 {
x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
data.push((x >> 24) as u8);
}
let result = scanner.scan_bytes(&data);
assert!(
result
.findings
.iter()
.any(|f| f.description.contains("entropy")),
"high-entropy content should be flagged"
);
}
#[test]
fn test_scan_file_reads_real_file() {
let mut path = std::env::temp_dir();
path.push(format!(
"oxigeo_malware_scan_test_{}.bin",
std::process::id()
));
{
let mut f = std::fs::File::create(&path).expect("create temp file");
f.write_all(EICAR_SIGNATURE).expect("write");
}
let scanner = MalwareScanner::new();
let result = scanner
.scan_file(path.to_str().expect("path utf8"))
.expect("scan should succeed for a readable file");
assert!(
result
.findings
.iter()
.any(|f| f.description.contains("EICAR")),
"scan_file must actually read and inspect the file"
);
let _ = std::fs::remove_file(&path);
}
#[test]
fn test_scan_file_missing_errors() {
let scanner = MalwareScanner::new();
let mut path = std::env::temp_dir();
path.push(format!(
"oxigeo_definitely_missing_file_{}.bin",
std::process::id()
));
let result = scanner.scan_file(path.to_str().expect("path utf8"));
assert!(
result.is_err(),
"a missing file must produce a typed error, not a fake clean result"
);
}
}