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

+295 -19
View File
@@ -1,33 +1,309 @@
use crate::error::Result;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionInput {
pub durations_secs: Vec<f64>,
pub bytes: Vec<u64>,
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SessionCandidate {
pub start_ts: f64,
pub end_ts: f64,
pub duration: f64,
pub parts: usize,
pub orig_bytes: u64,
pub resp_bytes: u64,
}
#[derive(Debug, Clone, Serialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionInput {
pub sessions: Vec<SessionCandidate>,
pub failed_attempts: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ChainRuleInfo {
pub max_gap_s: f64,
pub continuation: &'static str,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SessionThresholds {
pub zero_at_s: f64,
pub saturate_at_s: f64,
pub alert_at_s: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SessionScore {
pub score: f64,
pub observations: usize,
pub long_connections: usize,
pub bowley_sentinel: Option<f64>,
pub method: &'static str,
pub status: &'static str,
pub longest_session_seconds: f64,
pub session_start_ts: f64,
pub session_end_ts: f64,
pub parts: usize,
pub orig_bytes: u64,
pub resp_bytes: u64,
pub pcr: f64,
pub bytes_per_hour: f64,
pub failed_attempts: usize,
pub sessions_over_1h: usize,
pub method: &'static str,
pub chain_rule: ChainRuleInfo,
pub thresholds: SessionThresholds,
pub formula_version: &'static str,
}
pub fn score(input: &SessionInput) -> Result<SessionScore> {
let chain_rule = ChainRuleInfo {
max_gap_s: 3600.0,
continuation: "history without 'S'",
};
let thresholds = SessionThresholds {
zero_at_s: 3600.0,
saturate_at_s: 86400.0,
alert_at_s: 7200.0,
};
let valid_sessions: Vec<&SessionCandidate> = input
.sessions
.iter()
.filter(|s| s.duration > 0.0 && !s.duration.is_nan() && !s.duration.is_infinite())
.collect();
if valid_sessions.is_empty() {
return Ok(SessionScore {
score: 0.0,
status: "insufficient_data",
longest_session_seconds: 0.0,
session_start_ts: 0.0,
session_end_ts: 0.0,
parts: 0,
orig_bytes: 0,
resp_bytes: 0,
pcr: 0.0,
bytes_per_hour: 0.0,
failed_attempts: input.failed_attempts,
sessions_over_1h: 0,
method: "chained-tcp-session-duration",
chain_rule,
thresholds,
formula_version: "1.0",
});
}
let longest = valid_sessions
.iter()
.max_by(|a, b| a.duration.partial_cmp(&b.duration).unwrap())
.unwrap();
let l = longest.duration;
let persistence = if l > 3600.0 {
((l / 3600.0).ln() / 24.0_f64.ln()).clamp(0.0, 1.0)
} else {
0.0
};
let tot_bytes = longest.orig_bytes + longest.resp_bytes;
let pcr = if tot_bytes > 0 {
(longest.orig_bytes as f64 - longest.resp_bytes as f64) / (tot_bytes as f64)
} else {
0.0
};
let bytes_per_hour = if l > 0.0 {
(tot_bytes as f64) / (l / 3600.0)
} else {
0.0
};
let sessions_over_1h = input
.sessions
.iter()
.filter(|s| s.duration >= 3600.0)
.count();
Ok(SessionScore {
score: 0.0,
observations: input.durations_secs.len(),
long_connections: input
.durations_secs
.iter()
.filter(|duration| **duration >= 300.0)
.count(),
bowley_sentinel: None,
method: "long-connection-stub",
status: "skeleton",
score: persistence,
status: "ok",
longest_session_seconds: l,
session_start_ts: longest.start_ts,
session_end_ts: longest.end_ts,
parts: longest.parts,
orig_bytes: longest.orig_bytes,
resp_bytes: longest.resp_bytes,
pcr,
bytes_per_hour,
failed_attempts: input.failed_attempts,
sessions_over_1h,
method: "chained-tcp-session-duration",
chain_rule,
thresholds,
formula_version: "1.0",
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1_formula_values() {
let calc = |l: f64| -> f64 {
let input = SessionInput {
sessions: vec![SessionCandidate {
start_ts: 1000.0,
end_ts: 1000.0 + l,
duration: l,
parts: 1,
orig_bytes: 100,
resp_bytes: 100,
}],
failed_attempts: 0,
};
score(&input).unwrap().score
};
assert_eq!(calc(3600.0), 0.0);
let s7200 = calc(7200.0);
assert!((s7200 - 0.218147).abs() < 1e-4, "s7200: {s7200}");
assert_eq!(calc(86400.0), 1.0);
assert_eq!(calc(200000.0), 1.0);
assert_eq!(calc(0.0), 0.0);
assert!(!calc(0.0).is_nan() && !calc(0.0).is_infinite());
}
#[test]
fn test_2_fixture_zeek_split_values() {
// L = 4201.05s (between 1h and 2h)
let input = SessionInput {
sessions: vec![SessionCandidate {
start_ts: 1793400000.0,
end_ts: 1793402401.0 + 1800.05,
duration: 4201.05,
parts: 2,
orig_bytes: 1200,
resp_bytes: 2400,
}],
failed_attempts: 0,
};
let res = score(&input).unwrap();
assert!((res.score - 0.0486).abs() < 1e-4, "score: {}", res.score);
assert!(res.score < 0.2181, "should not trigger alert (< 2h)");
assert_eq!(res.parts, 2);
}
#[test]
fn test_3_c2_persistent_synthetic() {
// 12.3h session in 9 parts + 13 failed attempts
let duration = 12.3 * 3600.0;
let input = SessionInput {
sessions: vec![SessionCandidate {
start_ts: 1000.0,
end_ts: 1000.0 + duration,
duration,
parts: 9,
orig_bytes: 19431,
resp_bytes: 19431,
}],
failed_attempts: 13,
};
let res = score(&input).unwrap();
assert!(res.score >= 0.78, "score: {}", res.score);
assert_eq!(res.failed_attempts, 13);
assert_eq!(res.parts, 9);
assert_eq!(res.status, "ok");
}
#[test]
fn test_4_reverse_shell_synthetic() {
// 2.5h session with PCR < 0 (more received than sent from victim perspective)
let duration = 2.5 * 3600.0;
let input = SessionInput {
sessions: vec![SessionCandidate {
start_ts: 1000.0,
end_ts: 1000.0 + duration,
duration,
parts: 1,
orig_bytes: 5000,
resp_bytes: 50000,
}],
failed_attempts: 0,
};
let res = score(&input).unwrap();
assert!(
res.score >= 0.2181,
"score should alert for 2.5h session: {}",
res.score
);
assert!(res.pcr < 0.0, "PCR should be negative: {}", res.pcr);
}
#[test]
fn test_5_web_browsing_synthetic() {
// 200 HTTPS connections of 5s to 20 min in 3h
let mut sessions = Vec::new();
for i in 0..200 {
let dur = 5.0 + (i as f64 % 1200.0);
sessions.push(SessionCandidate {
start_ts: 1000.0 + (i as f64 * 50.0),
end_ts: 1000.0 + (i as f64 * 50.0) + dur,
duration: dur,
parts: 1,
orig_bytes: 1000,
resp_bytes: 10000,
});
}
let input = SessionInput {
sessions,
failed_attempts: 0,
};
let res = score(&input).unwrap();
assert_eq!(res.score, 0.0);
assert!(res.score < 0.2181);
}
#[test]
fn test_6_ephemeral_port_reuse() {
// Two distinct sessions with SYN on same 4-tuple, separated by 30 min
let s1 = SessionCandidate {
start_ts: 1000.0,
end_ts: 2000.0,
duration: 1000.0,
parts: 1,
orig_bytes: 100,
resp_bytes: 100,
};
let s2 = SessionCandidate {
start_ts: 3800.0,
end_ts: 4800.0,
duration: 1000.0,
parts: 1,
orig_bytes: 100,
resp_bytes: 100,
};
let input = SessionInput {
sessions: vec![s1, s2],
failed_attempts: 0,
};
let res = score(&input).unwrap();
assert_eq!(res.longest_session_seconds, 1000.0);
assert_eq!(res.score, 0.0);
}
#[test]
fn test_7_determinism() {
let input = SessionInput {
sessions: vec![SessionCandidate {
start_ts: 1793400000.123456,
end_ts: 1793444000.654321,
duration: 44000.530865,
parts: 4,
orig_bytes: 12345,
resp_bytes: 67890,
}],
failed_attempts: 3,
};
let s1 = score(&input).unwrap();
let s2 = score(&input).unwrap();
let j1 = serde_json::to_vec(&s1).unwrap();
let j2 = serde_json::to_vec(&s2).unwrap();
assert_eq!(j1, j2);
}
}