Skip to content

Commit

Permalink
fix: issue with math.entropy when input was an empty string
Browse files Browse the repository at this point in the history
In such cases `math.entropy` must return 0.0 instead of undefined.
  • Loading branch information
plusvic committed Mar 25, 2024
1 parent e2a4877 commit ed6d9f1
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/src/modules/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,12 @@ fn entropy_data(ctx: &ScanContext, offset: i64, length: i64) -> Option<f64> {
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<f64> {
entropy(s.as_bstr(ctx).as_bytes())
Some(entropy(s.as_bstr(ctx).as_bytes()))
}

#[module_export(name = "deviation")]
Expand Down Expand Up @@ -206,9 +206,9 @@ fn monte_carlo_pi_string(ctx: &ScanContext, s: RuntimeString) -> Option<f64> {
monte_carlo_pi(s.as_bstr(ctx).as_bytes())
}

fn entropy(data: &[u8]) -> Option<f64> {
fn entropy(data: &[u8]) -> f64 {
if data.is_empty() {
return None;
return 0.0;
}

let mut distribution = [0u64; 256];
Expand All @@ -224,7 +224,7 @@ fn entropy(data: &[u8]) -> Option<f64> {
}
}

Some(entropy)
entropy
}

fn deviation(data: &[u8], mean: f64) -> Option<f64> {
Expand Down Expand Up @@ -460,6 +460,16 @@ mod tests {
&[]
);

rule_true!(
r#"
import "math"
rule test {
condition:
math.entropy("") == 0.0
}"#,
&[]
);

rule_true!(
r#"
import "math"
Expand Down

0 comments on commit ed6d9f1

Please sign in to comment.