From ed6d9f1d24e01463050061ea02276cc177197bb8 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Mon, 25 Mar 2024 10:50:12 +0100 Subject: [PATCH] fix: issue with `math.entropy` when input was an empty string In such cases `math.entropy` must return 0.0 instead of undefined. --- lib/src/modules/math.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/src/modules/math.rs b/lib/src/modules/math.rs index 1e5254696..2e0a4ad71 100644 --- a/lib/src/modules/math.rs +++ b/lib/src/modules/math.rs @@ -126,12 +126,12 @@ fn entropy_data(ctx: &ScanContext, offset: i64, length: i64) -> Option { let length: usize = length.try_into().ok()?; let start: usize = offset.try_into().ok()?; let end = cmp::min(ctx.scanned_data().len(), start.saturating_add(length)); - entropy(ctx.scanned_data().get(start..end)?) + Some(entropy(ctx.scanned_data().get(start..end)?)) } #[module_export(name = "entropy")] fn entropy_string(ctx: &ScanContext, s: RuntimeString) -> Option { - entropy(s.as_bstr(ctx).as_bytes()) + Some(entropy(s.as_bstr(ctx).as_bytes())) } #[module_export(name = "deviation")] @@ -206,9 +206,9 @@ fn monte_carlo_pi_string(ctx: &ScanContext, s: RuntimeString) -> Option { monte_carlo_pi(s.as_bstr(ctx).as_bytes()) } -fn entropy(data: &[u8]) -> Option { +fn entropy(data: &[u8]) -> f64 { if data.is_empty() { - return None; + return 0.0; } let mut distribution = [0u64; 256]; @@ -224,7 +224,7 @@ fn entropy(data: &[u8]) -> Option { } } - Some(entropy) + entropy } fn deviation(data: &[u8], mean: f64) -> Option { @@ -460,6 +460,16 @@ mod tests { &[] ); + rule_true!( + r#" + import "math" + rule test { + condition: + math.entropy("") == 0.0 + }"#, + &[] + ); + rule_true!( r#" import "math"