feat: implement Pillars 2-4 and fix a production false-positive in Pillar 1

Pillar 1 v1.1 (shipped earlier) flagged benign browsing bursts as
beaconing: on short captures, grid periods longer than the observed
span never complete a cycle, so significance saturates to 1 and the
score sticks at exactly 0.5. v1.2 caps the grid at a third of the
observed span, requires a minimum number of completed cycles, and
excludes protocols that are periodic by nature (NTP, DNS, mDNS,
ICMP). Validated against 300 seeds per scenario: false positives on
bursty traffic drop from the 290-300/300 that v1.1 produced to 0/300,
with every beacon-detection scenario scoring unchanged.

Add Pillar 2 (persistent/long-lived sessions, with Zeek's fragmented
TCP sessions rejoined after a 5-minute gap), Pillar 3 (DNS tunneling
via Shannon-entropy information volume per subdomain per hour; the
Jensen-Shannon divergence was measured and does not separate tunnels
from benign CDN subdomains, so it stays in the evidence at zero
weight instead of in the score), and Pillar 4 (deterministic
noisy-OR fusion across the three pillars).

The fusion formula was validated against 8 labeled real-traffic
vectors (IoT-23, CTU-Normal) with tolerance <= 1e-4. A known
limitation is kept, not hidden: a benign Philips HUE bulb's strict
periodic polling and a 21.9h session score it above three real C2
hosts. No weight or threshold was tuned to mask this; it is
documented in the architecture docs instead.

Also fixes real bugs found along the way: ingest_dir's partition
count summed file names instead of distinct dates, DuckDB errors
were counted as bad rows, /api/alerts always returned an empty list
regardless of the last analysis, and the dashboard still claimed
every pillar was unimplemented.

Restores four design corrections that were missing from
docs/architecture.md (KL to Jensen-Shannon, the persistent-session
detector, the JA4 licensing boundary, and deterministic reduction
order), and catalogs the public datasets used for validation
(IoT-23, CTU-Normal, Mendeley DTQBC) with their licenses and SHA-256
checksums under research/validation/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8d7HuAdUGB6aA5xmDD
This commit is contained in:
Lucas RayanandClaude Sonnet 5 committed 2026-11-01 00:28:54 -03:00
1 parent 8a80504c45
commit c64bbbf775
41 files changed
+4034 -348

No files matched your search

+337 -45
View File
@@ -4,6 +4,8 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BeaconingInput {
pub timestamps: Vec<f64>,
#[serde(default)]
pub proto: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -34,6 +36,13 @@ pub struct BeaconingScore {
pub weights: WeightsInfo,
pub formula_version: &'static str,
pub status: &'static str,
pub span_seconds: f64,
pub min_cycles: usize,
pub significance: f64,
pub regularity: f64,
pub significance_gate: f64,
pub gate_regularity: f64,
pub proto: String,
}
fn quantile_cont(sorted: &[f64], q: f64) -> f64 {
@@ -55,18 +64,24 @@ fn quantile_cont(sorted: &[f64], q: f64) -> f64 {
}
pub fn score(input: &BeaconingInput) -> Result<BeaconingScore> {
let grid_info = GridInfo {
min_period_s: 600.0,
max_period_s: 43200.0,
points: 200,
};
let n = input.timestamps.len();
let min_cycles = 3;
let gate_regularity = 0.25;
let weights_info = WeightsInfo {
significance: 0.5,
regularity: 0.5,
};
let n = input.timestamps.len();
if n < 20 {
let span = if n >= 2 {
let mut sorted = input.timestamps.clone();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
sorted[n - 1] - sorted[0]
} else {
0.0
};
return Ok(BeaconingScore {
score: 0.0,
observations: n,
@@ -77,16 +92,29 @@ pub fn score(input: &BeaconingInput) -> Result<BeaconingScore> {
skew_bowley: 0.0,
degenerate_quartiles: false,
method: "rayleigh-schuster",
grid: grid_info,
grid: GridInfo {
min_period_s: 600.0,
max_period_s: 43200.0,
points: 0,
},
weights: weights_info,
formula_version: "1.1",
formula_version: "1.2",
status: "insufficient_data",
span_seconds: span,
min_cycles,
significance: 0.0,
regularity: 0.0,
significance_gate: 0.0,
gate_regularity,
proto: input.proto.clone(),
});
}
let mut ts = input.timestamps.clone();
ts.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let span = ts[n - 1] - ts[0];
let mut deltas = Vec::with_capacity(n - 1);
for i in 1..n {
deltas.push(ts[i] - ts[i - 1]);
@@ -110,21 +138,85 @@ pub fn score(input: &BeaconingInput) -> Result<BeaconingScore> {
abs_devs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let madm = quantile_cont(&abs_devs, 0.50);
let (madm_normalized, degenerate_deltas) = if q2 <= EPSILON {
(0.0, true)
} else {
(madm / q2, false)
};
// Step 2: degenerate deltas check
if q2 <= EPSILON {
return Ok(BeaconingScore {
score: 0.0,
observations: n,
period_detected_seconds: 0.0,
p_value: 1.0,
peak_power: 0.0,
madm_normalized: 0.0,
skew_bowley,
degenerate_quartiles,
method: "rayleigh-schuster",
grid: GridInfo {
min_period_s: 600.0,
max_period_s: 0.0,
points: 0,
},
weights: weights_info,
formula_version: "1.2",
status: "degenerate_deltas",
span_seconds: span,
min_cycles,
significance: 0.0,
regularity: 0.0,
significance_gate: 0.0,
gate_regularity,
proto: input.proto.clone(),
});
}
// Rayleigh/Schuster periodogram with M = 200 log-spaced periods from 600s to 43200s
let t0 = ts[0];
let num_periods = 200;
let mut periods = Vec::with_capacity(num_periods);
let mut powers = Vec::with_capacity(num_periods);
let madm_normalized = madm / q2;
for j in 0..num_periods {
// Step 3: Effective grid (periods <= span / min_cycles)
let max_allowed_period = span / (min_cycles as f64);
let num_grid_points = 200;
let mut periods = Vec::new();
for j in 0..num_grid_points {
let period = 600.0 * 72.0_f64.powf(j as f64 / 199.0);
periods.push(period);
if period <= max_allowed_period {
periods.push(period);
}
}
let m_eff = periods.len();
if m_eff == 0 {
let regularity = (1.0 - 2.0 * madm_normalized).clamp(0.0, 1.0);
return Ok(BeaconingScore {
score: 0.0,
observations: n,
period_detected_seconds: 0.0,
p_value: 1.0,
peak_power: 0.0,
madm_normalized,
skew_bowley,
degenerate_quartiles,
method: "rayleigh-schuster",
grid: GridInfo {
min_period_s: 600.0,
max_period_s: 0.0,
points: 0,
},
weights: weights_info,
formula_version: "1.2",
status: "insufficient_span",
span_seconds: span,
min_cycles,
significance: 0.0,
regularity,
significance_gate: 0.0,
gate_regularity,
proto: input.proto.clone(),
});
}
// Step 4: Rayleigh/Schuster periodogram on effective grid
let t0 = ts[0];
let mut powers = Vec::with_capacity(m_eff);
for &period in &periods {
let f = 1.0 / period;
let mut sum_cos = 0.0;
let mut sum_sin = 0.0;
@@ -144,35 +236,37 @@ pub fn score(input: &BeaconingInput) -> Result<BeaconingScore> {
}
}
// Harmonic resistance: largest period in the grid with P >= 0.5 * P_max
// Step 9: Harmonic resistance: largest period in effective grid with P >= 0.5 * P_max
let threshold_power = 0.5 * p_max;
let mut detected_period = periods[0];
for j in (0..num_periods).rev() {
for j in (0..m_eff).rev() {
if powers[j] >= threshold_power {
detected_period = periods[j];
break;
}
}
let m_points = num_periods as f64;
let p_value = (m_points * (-p_max).exp()).min(1.0);
let m_eff_f64 = m_eff as f64;
let p_value = (m_eff_f64 * (-p_max).exp()).min(1.0);
// Formula v1.1
let ln_m = m_points.ln();
// Step 5: Significance
let ln_m = m_eff_f64.ln();
let six_ln_10 = 6.0 * 10.0_f64.ln();
let sig = ((p_max - ln_m) / six_ln_10).clamp(0.0, 1.0);
// Step 6: Regularity
let regularity = (1.0 - 2.0 * madm_normalized).clamp(0.0, 1.0);
let status = if degenerate_deltas {
"degenerate_deltas"
} else {
"ok"
};
// Step 7: Gate
let gate = (regularity / gate_regularity).min(1.0);
let score = if degenerate_deltas {
0.5 * sig
} else {
0.5 * sig + 0.5 * regularity
// Step 8: Score
let score = 0.5 * sig * gate + 0.5 * regularity;
let grid_info = GridInfo {
min_period_s: periods[0],
max_period_s: periods[m_eff - 1],
points: m_eff,
};
Ok(BeaconingScore {
@@ -187,8 +281,15 @@ pub fn score(input: &BeaconingInput) -> Result<BeaconingScore> {
method: "rayleigh-schuster",
grid: grid_info,
weights: weights_info,
formula_version: "1.1",
status,
formula_version: "1.2",
status: "ok",
span_seconds: span,
min_cycles,
significance: sig,
regularity,
significance_gate: gate,
gate_regularity,
proto: input.proto.clone(),
})
}
@@ -233,7 +334,11 @@ mod tests {
for k in 0..42 {
timestamps.push(k as f64 * 14400.0);
}
let res = score(&BeaconingInput { timestamps }).unwrap();
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert!(res.score >= 0.99, "score: {}", res.score);
let rel_err = (res.period_detected_seconds - 14400.0).abs() / 14400.0;
assert!(
@@ -243,6 +348,7 @@ mod tests {
rel_err
);
assert_eq!(res.status, "ok");
assert_eq!(res.formula_version, "1.2");
}
#[test]
@@ -257,7 +363,11 @@ mod tests {
let jitter = rng.uniform(-0.18, 0.18) * 14400.0;
timestamps.push(t0 + k as f64 * 14400.0 + jitter);
}
let res = score(&BeaconingInput { timestamps }).unwrap();
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert!(res.score >= 0.80, "seed {seed} score {} < 0.80", res.score);
if res.score < min_score {
min_score = res.score;
@@ -284,7 +394,11 @@ mod tests {
curr += 14400.0 * (1.0 + rng.uniform(-0.18, 0.18));
timestamps.push(curr);
}
let res = score(&BeaconingInput { timestamps }).unwrap();
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert!(res.score >= 0.40, "seed {seed} score {} < 0.40", res.score);
if res.score < min_score {
min_score = res.score;
@@ -320,7 +434,11 @@ mod tests {
curr += rng.exponential(mean);
timestamps.push(curr);
}
let res = score(&BeaconingInput { timestamps }).unwrap();
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert!(res.score < 0.30, "seed {seed} score {} >= 0.30", res.score);
if res.score < min_score {
min_score = res.score;
@@ -338,7 +456,11 @@ mod tests {
for k in 0..25 {
timestamps.push(k as f64 * 1000.0);
}
let res = score(&BeaconingInput { timestamps }).unwrap();
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert_eq!(res.skew_bowley, 0.0);
assert!(res.degenerate_quartiles);
assert!(!res.score.is_nan() && !res.score.is_infinite());
@@ -347,15 +469,24 @@ mod tests {
#[test]
fn test_6_median_delta_zero() {
let timestamps = vec![1000.0; 25];
let res = score(&BeaconingInput { timestamps }).unwrap();
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert_eq!(res.status, "degenerate_deltas");
assert_eq!(res.score, 0.0);
assert!(!res.score.is_nan() && !res.score.is_infinite());
}
#[test]
fn test_7_insufficient_data() {
let timestamps: Vec<f64> = (0..19).map(|k| k as f64 * 1000.0).collect();
let res = score(&BeaconingInput { timestamps }).unwrap();
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert_eq!(res.status, "insufficient_data");
assert_eq!(res.score, 0.0);
}
@@ -365,11 +496,172 @@ mod tests {
let timestamps: Vec<f64> = (0..42).map(|k| k as f64 * 14400.0).collect();
let s1 = score(&BeaconingInput {
timestamps: timestamps.clone(),
proto: "tcp".to_string(),
})
.unwrap();
let s2 = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
let s2 = score(&BeaconingInput { timestamps }).unwrap();
let j1 = serde_json::to_vec(&s1).unwrap();
let j2 = serde_json::to_vec(&s2).unwrap();
assert_eq!(j1, j2);
}
fn generate_bursty(rng: &mut SplitMix64, span: f64) -> Vec<f64> {
let mut out = Vec::new();
let mut t = 1_790_000_000.0;
let end = t + span;
loop {
t += rng.exponential(900.0);
if t > end {
break;
}
let mut k = 1;
while rng.next_f64() < 0.8 {
k += 1;
}
let mut u = t;
for _ in 0..k {
out.push(u);
u += rng.exponential(2.0);
}
}
out
}
#[test]
fn test_9_bursty_3h() {
let mut max_score = f64::MIN;
for seed in 1..=50 {
let mut rng = SplitMix64::new(seed);
let timestamps = generate_bursty(&mut rng, 3.0 * 3600.0);
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert!(
res.score < 0.05,
"seed {seed} bursty3h score {} >= 0.05 (status: {})",
res.score,
res.status
);
if res.score > max_score {
max_score = res.score;
}
}
println!("Test 9 (bursty 3h) 50 seeds: max={max_score:.4}");
}
#[test]
fn test_10_bursty_24h() {
let mut max_score = f64::MIN;
for seed in 1..=50 {
let mut rng = SplitMix64::new(seed);
let timestamps = generate_bursty(&mut rng, 86400.0);
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert!(
res.score < 0.05,
"seed {seed} bursty24h score {} >= 0.05 (status: {})",
res.score,
res.status
);
if res.score > max_score {
max_score = res.score;
}
}
println!("Test 10 (bursty 24h) 50 seeds: max={max_score:.4}");
}
#[test]
fn test_11_fast_short() {
let mut min_score = f64::MAX;
let mut max_score = f64::MIN;
let mut period_within_10pct = 0;
for seed in 1..=50 {
let mut rng = SplitMix64::new(seed);
let mut timestamps = Vec::new();
let mut t = 1_790_000_000.0;
let end = t + 86400.0;
while t < end {
timestamps.push(t);
t += 900.0 * (1.0 + rng.uniform(-0.1, 0.1));
}
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert!(
res.score >= 0.40,
"seed {seed} fast_short score {} < 0.40",
res.score
);
if res.score < min_score {
min_score = res.score;
}
if res.score > max_score {
max_score = res.score;
}
let rel_err = (res.period_detected_seconds - 900.0).abs() / 900.0;
if rel_err < 0.10 {
period_within_10pct += 1;
}
}
println!(
"Test 11 (fast short) 50 seeds: min={min_score:.4}, max={max_score:.4}, period_hits={period_within_10pct}/50"
);
assert!(
period_within_10pct >= 45,
"period hits: {period_within_10pct}/50"
);
}
#[test]
fn test_12_dropout_30pct() {
let mut hits = 0;
for seed in 1..=50 {
let mut rng = SplitMix64::new(seed);
let mut timestamps = Vec::new();
let mut t = 1_790_000_000.0;
for _ in 0..60 {
if rng.next_f64() > 0.3 {
timestamps.push(t);
}
t += 14400.0 * (1.0 + rng.uniform(-0.1, 0.1));
}
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
if res.score >= 0.40 {
hits += 1;
}
}
println!("Test 12 (dropout 30%) 50 seeds: hits={hits}/50");
assert!(hits >= 48, "dropout hits {hits} < 48");
}
#[test]
fn test_13_insufficient_span() {
// 30 events in 25 min (1500s < 1800s)
let timestamps: Vec<f64> = (0..30).map(|k| 1000.0 + k as f64 * 50.0).collect();
let res = score(&BeaconingInput {
timestamps,
proto: "tcp".to_string(),
})
.unwrap();
assert_eq!(res.status, "insufficient_span");
assert_eq!(res.score, 0.0);
}
}