use crate::error::Result; use serde::{Deserialize, Serialize}; #[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, Default, Serialize, Deserialize)] pub struct SessionInput { pub sessions: Vec, 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 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 { 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: 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); } }