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
1088 lines
38 KiB
Rust
1088 lines
38 KiB
Rust
use crate::error::{AcauaError, Result};
|
|
use chrono::NaiveDate;
|
|
use serde::{Deserialize, Serialize};
|
|
use sha2::{Digest, Sha256};
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::fs;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct DatasetSummary {
|
|
pub records: u64,
|
|
pub partitions: usize,
|
|
pub ttl_days: u32,
|
|
pub backend: &'static str,
|
|
pub status: &'static str,
|
|
}
|
|
|
|
impl DatasetSummary {
|
|
pub fn empty() -> Self {
|
|
Self {
|
|
records: 0,
|
|
partitions: 0,
|
|
ttl_days: 7,
|
|
backend: "duckdb-parquet",
|
|
status: "empty",
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Default, Serialize)]
|
|
pub struct IngestionStats {
|
|
pub files_seen: usize,
|
|
pub records_ingested: u64,
|
|
pub lines_skipped: u64,
|
|
pub partitions_affected: usize,
|
|
pub files_failed: usize,
|
|
pub failed_errors: Vec<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct TupleTimestamps {
|
|
pub orig_h: String,
|
|
pub resp_h: String,
|
|
pub resp_p: u16,
|
|
pub proto: String,
|
|
pub timestamps: Vec<f64>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct ChainedSession {
|
|
pub orig_h: String,
|
|
pub orig_p: u16,
|
|
pub resp_h: String,
|
|
pub resp_p: u16,
|
|
pub proto: String,
|
|
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)]
|
|
pub struct TupleSessions {
|
|
pub orig_h: String,
|
|
pub resp_h: String,
|
|
pub resp_p: u16,
|
|
pub proto: String,
|
|
pub sessions: Vec<ChainedSession>,
|
|
pub failed_attempts: usize,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Storage {
|
|
root: PathBuf,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct ConnRecord {
|
|
pub ts: f64,
|
|
pub uid: String,
|
|
pub orig_h: String,
|
|
pub orig_p: u16,
|
|
pub resp_h: String,
|
|
pub resp_p: u16,
|
|
pub proto: String,
|
|
pub service: Option<String>,
|
|
pub duration: Option<f64>,
|
|
pub orig_bytes: Option<u64>,
|
|
pub resp_bytes: Option<u64>,
|
|
pub conn_state: Option<String>,
|
|
pub history: Option<String>,
|
|
pub orig_pkts: Option<u64>,
|
|
pub resp_pkts: Option<u64>,
|
|
}
|
|
|
|
impl Storage {
|
|
pub fn open(root: impl AsRef<Path>) -> Result<Self> {
|
|
let root = root.as_ref();
|
|
fs::create_dir_all(root.join("raw").join("conn"))?;
|
|
fs::create_dir_all(root.join("tmp"))?;
|
|
|
|
let canonical_root = fs::canonicalize(root)?;
|
|
|
|
let test_file = canonical_root.join("tmp").join(".write_check");
|
|
fs::write(&test_file, b"ok")?;
|
|
let _ = fs::remove_file(&test_file);
|
|
|
|
Ok(Self {
|
|
root: canonical_root,
|
|
})
|
|
}
|
|
|
|
pub fn root(&self) -> &Path {
|
|
&self.root
|
|
}
|
|
|
|
pub fn open_connection(&self) -> Result<duckdb::Connection> {
|
|
let conn = duckdb::Connection::open_in_memory()?;
|
|
let data_dir_str = self.root.to_string_lossy().replace('\'', "''");
|
|
let tmp_dir_str = self.root.join("tmp").to_string_lossy().replace('\'', "''");
|
|
|
|
conn.execute_batch(&format!(
|
|
"SET TimeZone = 'UTC';
|
|
SET temp_directory = '{tmp_dir_str}';
|
|
SET autoinstall_known_extensions = false;
|
|
SET autoload_known_extensions = false;
|
|
SET allowed_directories = ['{data_dir_str}/'];
|
|
SET enable_external_access = false;
|
|
SET lock_configuration = true;"
|
|
))?;
|
|
|
|
Ok(conn)
|
|
}
|
|
|
|
fn has_parquet_files(&self) -> bool {
|
|
let conn_dir = self.root.join("raw").join("conn");
|
|
if let Ok(entries) = fs::read_dir(conn_dir) {
|
|
for entry in entries.flatten() {
|
|
if let Ok(sub) = fs::read_dir(entry.path()) {
|
|
for f in sub.flatten() {
|
|
if f.path().extension().and_then(|s| s.to_str()) == Some("parquet") {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
pub fn summary(&self) -> Result<DatasetSummary> {
|
|
if !self.has_parquet_files() {
|
|
return Ok(DatasetSummary::empty());
|
|
}
|
|
|
|
let conn = self.open_connection()?;
|
|
let parquet_glob = self
|
|
.root
|
|
.join("raw")
|
|
.join("conn")
|
|
.join("*")
|
|
.join("*.parquet")
|
|
.to_string_lossy()
|
|
.replace('\'', "''");
|
|
|
|
let query = format!(
|
|
"SELECT count(*)::BIGINT, count(DISTINCT date)::BIGINT
|
|
FROM read_parquet('{parquet_glob}', hive_partitioning = true, union_by_name = true);"
|
|
);
|
|
|
|
let row = conn.query_row(&query, [], |r| {
|
|
let records: i64 = r.get(0)?;
|
|
let partitions: i64 = r.get(1)?;
|
|
Ok((records as u64, partitions as usize))
|
|
});
|
|
|
|
match row {
|
|
Ok((records, partitions)) => Ok(DatasetSummary {
|
|
records,
|
|
partitions,
|
|
ttl_days: 7,
|
|
backend: "duckdb-parquet",
|
|
status: "ok",
|
|
}),
|
|
Err(_) => Ok(DatasetSummary::empty()),
|
|
}
|
|
}
|
|
|
|
pub fn prune_expired(&self) -> Result<usize> {
|
|
let conn_dir = self.root.join("raw").join("conn");
|
|
let entries = match fs::read_dir(&conn_dir) {
|
|
Ok(e) => e,
|
|
Err(_) => return Ok(0),
|
|
};
|
|
|
|
let mut dates = Vec::new();
|
|
let mut dirs = Vec::new();
|
|
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
if !path.is_dir() {
|
|
continue;
|
|
}
|
|
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
|
if let Some(date_str) = name.strip_prefix("date=") {
|
|
if let Ok(d) = NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
|
|
dates.push(d);
|
|
dirs.push((d, path));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if dates.is_empty() {
|
|
return Ok(0);
|
|
}
|
|
|
|
let max_date = dates.into_iter().max().unwrap();
|
|
let cutoff = max_date - chrono::Duration::days(7);
|
|
|
|
let mut pruned = 0;
|
|
for (date, path) in dirs {
|
|
if date <= cutoff && fs::remove_dir_all(&path).is_ok() {
|
|
pruned += 1;
|
|
}
|
|
}
|
|
|
|
// Also prune raw/dns if exists
|
|
let dns_dir = self.root.join("raw").join("dns");
|
|
if let Ok(dns_entries) = fs::read_dir(&dns_dir) {
|
|
for entry in dns_entries.flatten() {
|
|
let path = entry.path();
|
|
if !path.is_dir() {
|
|
continue;
|
|
}
|
|
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
|
if let Some(date_str) = name.strip_prefix("date=") {
|
|
if let Ok(d) = NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
|
|
if d <= cutoff && fs::remove_dir_all(&path).is_ok() {
|
|
pruned += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
Ok(pruned)
|
|
}
|
|
|
|
pub fn parse_conn_log(content: &[u8]) -> (Vec<ConnRecord>, u64, HashSet<String>) {
|
|
let mut records = Vec::new();
|
|
let mut skipped = 0;
|
|
let mut dates = HashSet::new();
|
|
|
|
let mut separator = '\t';
|
|
let mut unset_field = String::from("-");
|
|
let mut empty_field = String::from("(empty)");
|
|
let mut fields: Vec<String> = Vec::new();
|
|
|
|
let mut idx_ts = None;
|
|
let mut idx_uid = None;
|
|
let mut idx_orig_h = None;
|
|
let mut idx_orig_p = None;
|
|
let mut idx_resp_h = None;
|
|
let mut idx_resp_p = None;
|
|
let mut idx_proto = None;
|
|
let mut idx_service = None;
|
|
let mut idx_duration = None;
|
|
let mut idx_orig_bytes = None;
|
|
let mut idx_resp_bytes = None;
|
|
let mut idx_conn_state = None;
|
|
let mut idx_history = None;
|
|
let mut idx_orig_pkts = None;
|
|
let mut idx_resp_pkts = None;
|
|
|
|
let text = String::from_utf8_lossy(content);
|
|
|
|
for line in text.lines() {
|
|
let line = line.trim_end_matches(['\r', '\n']);
|
|
if line.is_empty() {
|
|
continue;
|
|
}
|
|
|
|
if line.starts_with('#') {
|
|
if let Some(rest) = line.strip_prefix("#separator ") {
|
|
let sep_str = rest.trim();
|
|
if let Some(hex_code) = sep_str.strip_prefix("\\x") {
|
|
if let Ok(b) = u8::from_str_radix(hex_code, 16) {
|
|
separator = b as char;
|
|
}
|
|
} else if !sep_str.is_empty() {
|
|
separator = sep_str.chars().next().unwrap();
|
|
}
|
|
} else if let Some(rest) = line.strip_prefix("#unset_field") {
|
|
unset_field = rest.trim().to_string();
|
|
} else if let Some(rest) = line.strip_prefix("#empty_field") {
|
|
empty_field = rest.trim().to_string();
|
|
} else if let Some(rest) = line.strip_prefix("#fields") {
|
|
let rest = rest.trim();
|
|
fields = rest
|
|
.split(separator)
|
|
.map(|s| s.trim().to_string())
|
|
.filter(|s| !s.is_empty())
|
|
.collect();
|
|
idx_ts = fields.iter().position(|s| s == "ts");
|
|
idx_uid = fields.iter().position(|s| s == "uid");
|
|
idx_orig_h = fields.iter().position(|s| s == "id.orig_h");
|
|
idx_orig_p = fields.iter().position(|s| s == "id.orig_p");
|
|
idx_resp_h = fields.iter().position(|s| s == "id.resp_h");
|
|
idx_resp_p = fields.iter().position(|s| s == "id.resp_p");
|
|
idx_proto = fields.iter().position(|s| s == "proto");
|
|
idx_service = fields.iter().position(|s| s == "service");
|
|
idx_duration = fields.iter().position(|s| s == "duration");
|
|
idx_orig_bytes = fields.iter().position(|s| s == "orig_bytes");
|
|
idx_resp_bytes = fields.iter().position(|s| s == "resp_bytes");
|
|
idx_conn_state = fields.iter().position(|s| s == "conn_state");
|
|
idx_history = fields.iter().position(|s| s == "history");
|
|
idx_orig_pkts = fields.iter().position(|s| s == "orig_pkts");
|
|
idx_resp_pkts = fields.iter().position(|s| s == "resp_pkts");
|
|
}
|
|
continue;
|
|
}
|
|
|
|
let (i_ts, i_uid, i_oh, i_op, i_rh, i_rp, i_pr) = match (
|
|
idx_ts, idx_uid, idx_orig_h, idx_orig_p, idx_resp_h, idx_resp_p, idx_proto,
|
|
) {
|
|
(Some(a), Some(b), Some(c), Some(d), Some(e), Some(f), Some(g)) => {
|
|
(a, b, c, d, e, f, g)
|
|
}
|
|
_ => {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
};
|
|
|
|
let parts: Vec<&str> = line.split(separator).collect();
|
|
if parts.len() < fields.len() {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
|
|
let ts: f64 = match parts[i_ts].parse() {
|
|
Ok(v) => v,
|
|
Err(_) => {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
};
|
|
|
|
let orig_p: u16 = match parts[i_op].parse() {
|
|
Ok(v) => v,
|
|
Err(_) => {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
};
|
|
|
|
let resp_p: u16 = match parts[i_rp].parse() {
|
|
Ok(v) => v,
|
|
Err(_) => {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
};
|
|
|
|
let get_val = |idx: Option<usize>| -> Option<&str> {
|
|
let i = idx?;
|
|
let val = parts.get(i)?;
|
|
if *val == unset_field.as_str()
|
|
|| *val == "-"
|
|
|| *val == empty_field.as_str()
|
|
|| *val == "(empty)"
|
|
{
|
|
None
|
|
} else {
|
|
Some(*val)
|
|
}
|
|
};
|
|
|
|
let service = get_val(idx_service).map(|s| s.to_string());
|
|
let duration = get_val(idx_duration).and_then(|s| s.parse::<f64>().ok());
|
|
let orig_bytes = get_val(idx_orig_bytes).and_then(|s| s.parse::<u64>().ok());
|
|
let resp_bytes = get_val(idx_resp_bytes).and_then(|s| s.parse::<u64>().ok());
|
|
let conn_state = get_val(idx_conn_state).map(|s| s.to_string());
|
|
let history = get_val(idx_history).map(|s| s.to_string());
|
|
let orig_pkts = get_val(idx_orig_pkts).and_then(|s| s.parse::<u64>().ok());
|
|
let resp_pkts = get_val(idx_resp_pkts).and_then(|s| s.parse::<u64>().ok());
|
|
|
|
let date_ts = chrono::DateTime::from_timestamp(ts.floor() as i64, 0);
|
|
if let Some(dt) = date_ts {
|
|
dates.insert(dt.format("%Y-%m-%d").to_string());
|
|
}
|
|
|
|
records.push(ConnRecord {
|
|
ts,
|
|
uid: parts[i_uid].to_string(),
|
|
orig_h: parts[i_oh].to_string(),
|
|
orig_p,
|
|
resp_h: parts[i_rh].to_string(),
|
|
resp_p,
|
|
proto: parts[i_pr].to_string(),
|
|
service,
|
|
duration,
|
|
orig_bytes,
|
|
resp_bytes,
|
|
conn_state,
|
|
history,
|
|
orig_pkts,
|
|
resp_pkts,
|
|
});
|
|
}
|
|
|
|
(records, skipped, dates)
|
|
}
|
|
|
|
pub fn ingest_file(&self, path: impl AsRef<Path>) -> Result<(u64, u64, HashSet<String>)> {
|
|
let path = path.as_ref();
|
|
let content = fs::read(path)?;
|
|
let mut hasher = Sha256::new();
|
|
hasher.update(&content);
|
|
let hash = hasher.finalize();
|
|
let mut sha16 = String::with_capacity(16);
|
|
for b in &hash[..8] {
|
|
use std::fmt::Write;
|
|
let _ = write!(sha16, "{b:02x}");
|
|
}
|
|
|
|
let (records, skipped, dates) = Self::parse_conn_log(&content);
|
|
if records.is_empty() {
|
|
return Ok((0, skipped, dates));
|
|
}
|
|
|
|
let conn = self.open_connection()?;
|
|
conn.execute_batch(
|
|
"CREATE TEMP TABLE t (
|
|
ts DOUBLE,
|
|
uid VARCHAR,
|
|
orig_h VARCHAR,
|
|
orig_p USMALLINT,
|
|
resp_h VARCHAR,
|
|
resp_p USMALLINT,
|
|
proto VARCHAR,
|
|
service VARCHAR,
|
|
duration DOUBLE,
|
|
orig_bytes UBIGINT,
|
|
resp_bytes UBIGINT,
|
|
conn_state VARCHAR,
|
|
history VARCHAR,
|
|
orig_pkts UBIGINT,
|
|
resp_pkts UBIGINT
|
|
);",
|
|
)?;
|
|
|
|
{
|
|
let mut appender = conn.appender("t")?;
|
|
for r in &records {
|
|
appender.append_row(duckdb::params![
|
|
r.ts,
|
|
r.uid,
|
|
r.orig_h,
|
|
r.orig_p,
|
|
r.resp_h,
|
|
r.resp_p,
|
|
r.proto,
|
|
r.service,
|
|
r.duration,
|
|
r.orig_bytes,
|
|
r.resp_bytes,
|
|
r.conn_state,
|
|
r.history,
|
|
r.orig_pkts,
|
|
r.resp_pkts
|
|
])?;
|
|
}
|
|
}
|
|
|
|
let raw_conn_dir = self
|
|
.root
|
|
.join("raw")
|
|
.join("conn")
|
|
.to_string_lossy()
|
|
.replace('\'', "''");
|
|
|
|
let copy_sql = format!(
|
|
"COPY (
|
|
SELECT *, CAST(to_timestamp(ts) AS DATE) AS date FROM t
|
|
) TO '{raw_conn_dir}' (
|
|
FORMAT parquet,
|
|
PARTITION_BY (date),
|
|
FILENAME_PATTERN 'src_{sha16}_{{i}}',
|
|
OVERWRITE_OR_IGNORE
|
|
);"
|
|
);
|
|
|
|
conn.execute_batch(©_sql)?;
|
|
conn.execute_batch("DROP TABLE t;")?;
|
|
|
|
Ok((records.len() as u64, skipped, dates))
|
|
}
|
|
|
|
pub fn ingest_dir(&self, directory: impl AsRef<Path>) -> Result<IngestionStats> {
|
|
let directory = directory.as_ref();
|
|
if !directory.is_dir() {
|
|
return Err(AcauaError::InvalidInput(format!(
|
|
"{} is not a directory",
|
|
directory.display()
|
|
)));
|
|
}
|
|
|
|
let canonical_dir = fs::canonicalize(directory)?;
|
|
|
|
let mut stats = IngestionStats::default();
|
|
let mut all_dates = HashSet::new();
|
|
|
|
let entries = fs::read_dir(&canonical_dir)?;
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
if let Ok(canon) = fs::canonicalize(&path) {
|
|
if !canon.starts_with(&canonical_dir) {
|
|
continue;
|
|
}
|
|
} else {
|
|
continue;
|
|
}
|
|
|
|
let file_name = match path.file_name().and_then(|n| n.to_str()) {
|
|
Some(n) => n,
|
|
None => continue,
|
|
};
|
|
|
|
if file_name.ends_with(".gz") {
|
|
continue;
|
|
}
|
|
|
|
let is_conn = file_name == "conn.log"
|
|
|| (file_name.starts_with("conn.") && file_name.ends_with(".log"));
|
|
|
|
if is_conn && path.is_file() {
|
|
stats.files_seen += 1;
|
|
match self.ingest_file(&path) {
|
|
Ok((recs, sk, dates)) => {
|
|
stats.records_ingested += recs;
|
|
stats.lines_skipped += sk;
|
|
all_dates.extend(dates);
|
|
}
|
|
Err(e) => {
|
|
stats.files_failed += 1;
|
|
if stats.failed_errors.len() < 10 {
|
|
stats.failed_errors.push(e.to_string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
stats.partitions_affected = all_dates.len();
|
|
Ok(stats)
|
|
}
|
|
|
|
pub fn query_7day_sessions(&self) -> Result<Vec<TupleSessions>> {
|
|
if !self.has_parquet_files() {
|
|
return Ok(Vec::new());
|
|
}
|
|
|
|
let conn = self.open_connection()?;
|
|
let parquet_glob = self
|
|
.root
|
|
.join("raw")
|
|
.join("conn")
|
|
.join("*")
|
|
.join("*.parquet")
|
|
.to_string_lossy()
|
|
.replace('\'', "''");
|
|
|
|
// Find max date present in data
|
|
let max_date_query = format!(
|
|
"SELECT max(date)::VARCHAR
|
|
FROM read_parquet('{parquet_glob}', hive_partitioning = true, union_by_name = true);"
|
|
);
|
|
|
|
let max_date: Option<String> = conn
|
|
.query_row(&max_date_query, [], |r| r.get(0))
|
|
.unwrap_or(None);
|
|
|
|
let max_date_str = match max_date {
|
|
Some(d) if !d.is_empty() => d,
|
|
_ => return Ok(Vec::new()),
|
|
};
|
|
|
|
// Query all conn rows in 7-day window ordered by orig_h, orig_p, resp_h, resp_p, ts
|
|
let query = format!(
|
|
"SELECT ts, orig_h, orig_p, resp_h, resp_p, proto, duration, orig_bytes, resp_bytes, conn_state, history
|
|
FROM read_parquet('{parquet_glob}', hive_partitioning = true, union_by_name = true)
|
|
WHERE date > CAST('{max_date_str}' AS DATE) - INTERVAL 7 DAY
|
|
ORDER BY orig_h, orig_p, resp_h, resp_p, ts;"
|
|
);
|
|
|
|
struct RawRow {
|
|
ts: f64,
|
|
orig_h: String,
|
|
orig_p: u16,
|
|
resp_h: String,
|
|
resp_p: u16,
|
|
proto: String,
|
|
duration: Option<f64>,
|
|
orig_bytes: Option<u64>,
|
|
resp_bytes: Option<u64>,
|
|
conn_state: Option<String>,
|
|
history: Option<String>,
|
|
}
|
|
|
|
let mut stmt = conn.prepare(&query)?;
|
|
let rows = stmt.query_map([], |row| {
|
|
Ok(RawRow {
|
|
ts: row.get(0)?,
|
|
orig_h: row.get(1)?,
|
|
orig_p: row.get(2)?,
|
|
resp_h: row.get(3)?,
|
|
resp_p: row.get(4)?,
|
|
proto: row.get(5)?,
|
|
duration: row.get(6)?,
|
|
orig_bytes: row.get(7)?,
|
|
resp_bytes: row.get(8)?,
|
|
conn_state: row.get(9)?,
|
|
history: row.get(10)?,
|
|
})
|
|
})?;
|
|
|
|
let mut raw_rows = Vec::new();
|
|
let mut failed_map: HashMap<(String, String, u16), usize> = HashMap::new();
|
|
|
|
for r in rows {
|
|
let row = r?;
|
|
if row.proto == "tcp" {
|
|
if let Some(cs) = &row.conn_state {
|
|
if cs == "S0" || cs == "REJ" || cs == "RSTOS0" || cs == "SH" {
|
|
*failed_map
|
|
.entry((row.orig_h.clone(), row.resp_h.clone(), row.resp_p))
|
|
.or_insert(0) += 1;
|
|
}
|
|
}
|
|
}
|
|
raw_rows.push(row);
|
|
}
|
|
|
|
// Group rows by 4-tuple (orig_h, orig_p, resp_h, resp_p, proto)
|
|
// Since rows are already ordered by (orig_h, orig_p, resp_h, resp_p, ts),
|
|
// we can chain sequentially.
|
|
let mut all_sessions: Vec<ChainedSession> = Vec::new();
|
|
let mut current_chain: Option<ChainedSession> = None;
|
|
|
|
for r in raw_rows {
|
|
let row_end = r.ts + r.duration.unwrap_or(0.0);
|
|
if r.proto == "tcp" {
|
|
let matches_current_4tuple = match ¤t_chain {
|
|
Some(curr) => {
|
|
curr.orig_h == r.orig_h
|
|
&& curr.orig_p == r.orig_p
|
|
&& curr.resp_h == r.resp_h
|
|
&& curr.resp_p == r.resp_p
|
|
&& curr.proto == r.proto
|
|
}
|
|
None => false,
|
|
};
|
|
|
|
let is_continuation = if matches_current_4tuple {
|
|
let curr = current_chain.as_ref().unwrap();
|
|
match &r.history {
|
|
Some(h) => !h.contains('S') && (r.ts - curr.end_ts <= 3600.0),
|
|
None => false,
|
|
}
|
|
} else {
|
|
false
|
|
};
|
|
|
|
if is_continuation {
|
|
let curr = current_chain.as_mut().unwrap();
|
|
if row_end > curr.end_ts {
|
|
curr.end_ts = row_end;
|
|
}
|
|
curr.duration = curr.end_ts - curr.start_ts;
|
|
curr.parts += 1;
|
|
curr.orig_bytes += r.orig_bytes.unwrap_or(0);
|
|
curr.resp_bytes += r.resp_bytes.unwrap_or(0);
|
|
} else {
|
|
if let Some(finished) = current_chain.take() {
|
|
all_sessions.push(finished);
|
|
}
|
|
current_chain = Some(ChainedSession {
|
|
orig_h: r.orig_h,
|
|
orig_p: r.orig_p,
|
|
resp_h: r.resp_h,
|
|
resp_p: r.resp_p,
|
|
proto: r.proto,
|
|
start_ts: r.ts,
|
|
end_ts: row_end,
|
|
duration: row_end - r.ts,
|
|
parts: 1,
|
|
orig_bytes: r.orig_bytes.unwrap_or(0),
|
|
resp_bytes: r.resp_bytes.unwrap_or(0),
|
|
});
|
|
}
|
|
} else {
|
|
if let Some(finished) = current_chain.take() {
|
|
all_sessions.push(finished);
|
|
}
|
|
all_sessions.push(ChainedSession {
|
|
orig_h: r.orig_h,
|
|
orig_p: r.orig_p,
|
|
resp_h: r.resp_h,
|
|
resp_p: r.resp_p,
|
|
proto: r.proto,
|
|
start_ts: r.ts,
|
|
end_ts: row_end,
|
|
duration: row_end - r.ts,
|
|
parts: 1,
|
|
orig_bytes: r.orig_bytes.unwrap_or(0),
|
|
resp_bytes: r.resp_bytes.unwrap_or(0),
|
|
});
|
|
}
|
|
}
|
|
if let Some(finished) = current_chain {
|
|
all_sessions.push(finished);
|
|
}
|
|
|
|
// Group sessions by (orig_h, resp_h, resp_p, proto)
|
|
let mut grouped: HashMap<(String, String, u16, String), Vec<ChainedSession>> =
|
|
HashMap::new();
|
|
for session in all_sessions {
|
|
let key = (
|
|
session.orig_h.clone(),
|
|
session.resp_h.clone(),
|
|
session.resp_p,
|
|
session.proto.clone(),
|
|
);
|
|
grouped.entry(key).or_default().push(session);
|
|
}
|
|
|
|
let mut result = Vec::new();
|
|
for ((orig_h, resp_h, resp_p, proto), mut sessions) in grouped {
|
|
sessions.sort_by(|a, b| a.start_ts.partial_cmp(&b.start_ts).unwrap());
|
|
let failed_attempts = failed_map
|
|
.get(&(orig_h.clone(), resp_h.clone(), resp_p))
|
|
.copied()
|
|
.unwrap_or(0);
|
|
result.push(TupleSessions {
|
|
orig_h,
|
|
resp_h,
|
|
resp_p,
|
|
proto,
|
|
sessions,
|
|
failed_attempts,
|
|
});
|
|
}
|
|
|
|
result.sort_by(|a, b| {
|
|
(&a.orig_h, &a.resp_h, a.resp_p, &a.proto)
|
|
.cmp(&(&b.orig_h, &b.resp_h, b.resp_p, &b.proto))
|
|
});
|
|
|
|
Ok(result)
|
|
}
|
|
|
|
pub fn query_7day_tuples(&self) -> Result<Vec<TupleTimestamps>> {
|
|
let tuple_sessions = self.query_7day_sessions()?;
|
|
Ok(tuple_sessions
|
|
.into_iter()
|
|
.map(|ts| TupleTimestamps {
|
|
orig_h: ts.orig_h,
|
|
resp_h: ts.resp_h,
|
|
resp_p: ts.resp_p,
|
|
proto: ts.proto,
|
|
timestamps: ts.sessions.into_iter().map(|s| s.start_ts).collect(),
|
|
})
|
|
.collect())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
const CONN_LOG_SAMPLE_1: &str = "#separator \\x09\n\
|
|
#set_separator\t,\n\
|
|
#empty_field\t(empty)\n\
|
|
#unset_field\t-\n\
|
|
#path\tconn\n\
|
|
#open\t2026-10-31-12-00-00\n\
|
|
#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tservice\tduration\torig_bytes\tresp_bytes\tconn_state\thistory\torig_pkts\tresp_pkts\n\
|
|
#types\ttime\tstring\taddr\tport\taddr\tport\tenum\tstring\tinterval\tcount\tcount\tstring\tstring\tcount\tcount\n\
|
|
1793461200.000000\tCuid1\t192.168.1.10\t45000\t10.0.0.1\t443\ttcp\tssl\t1.234\t100\t200\tSF\tShADadFf\t10\t12\n\
|
|
1793461205.000000\tCuid2\t192.168.1.10\t45001\t10.0.0.1\t443\ttcp\t-\t-\t-\t-\tS0\tS\t1\t0\n\
|
|
#close\t2026-10-31-12-01-00\n";
|
|
|
|
const CONN_LOG_PERMUTED_COLS: &str = "#separator \\x09\n\
|
|
#fields\tid.resp_p\tid.orig_h\tservice\tuid\tduration\tproto\tts\tid.resp_h\tid.orig_p\tconn_state\thistory\n\
|
|
443\t192.168.1.10\thttp\tCuid3\t0.5\ttcp\t1793461210.000000\t10.0.0.1\t45002\tSF\tShAD\n";
|
|
|
|
#[test]
|
|
fn test_parser_extracts_correct_fields_and_unset_as_none() {
|
|
let (records, skipped, dates) = Storage::parse_conn_log(CONN_LOG_SAMPLE_1.as_bytes());
|
|
assert_eq!(skipped, 0);
|
|
assert_eq!(records.len(), 2);
|
|
assert_eq!(dates.len(), 1);
|
|
|
|
assert_eq!(records[0].uid, "Cuid1");
|
|
assert_eq!(records[0].orig_h, "192.168.1.10");
|
|
assert_eq!(records[0].orig_p, 45000);
|
|
assert_eq!(records[0].resp_h, "10.0.0.1");
|
|
assert_eq!(records[0].resp_p, 443);
|
|
assert_eq!(records[0].proto, "tcp");
|
|
assert_eq!(records[0].service.as_deref(), Some("ssl"));
|
|
assert_eq!(records[0].duration, Some(1.234));
|
|
assert_eq!(records[0].orig_bytes, Some(100));
|
|
assert_eq!(records[0].resp_bytes, Some(200));
|
|
assert_eq!(records[0].conn_state.as_deref(), Some("SF"));
|
|
assert_eq!(records[0].history.as_deref(), Some("ShADadFf"));
|
|
assert_eq!(records[0].orig_pkts, Some(10));
|
|
assert_eq!(records[0].resp_pkts, Some(12));
|
|
|
|
assert_eq!(records[1].uid, "Cuid2");
|
|
assert_eq!(records[1].service, None);
|
|
assert_eq!(records[1].duration, None);
|
|
assert_eq!(records[1].orig_bytes, None);
|
|
assert_eq!(records[1].conn_state.as_deref(), Some("S0"));
|
|
assert_eq!(records[1].history.as_deref(), Some("S"));
|
|
}
|
|
|
|
#[test]
|
|
fn test_parser_maps_by_name_not_position() {
|
|
let (records, skipped, _) = Storage::parse_conn_log(CONN_LOG_PERMUTED_COLS.as_bytes());
|
|
assert_eq!(skipped, 0);
|
|
assert_eq!(records.len(), 1);
|
|
let r = &records[0];
|
|
assert_eq!(r.uid, "Cuid3");
|
|
assert_eq!(r.orig_h, "192.168.1.10");
|
|
assert_eq!(r.orig_p, 45002);
|
|
assert_eq!(r.resp_h, "10.0.0.1");
|
|
assert_eq!(r.resp_p, 443);
|
|
assert_eq!(r.proto, "tcp");
|
|
assert_eq!(r.service.as_deref(), Some("http"));
|
|
assert_eq!(r.duration, Some(0.5));
|
|
}
|
|
|
|
#[test]
|
|
fn test_storage_roundtrip_and_idempotence() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let store = Storage::open(temp_dir.path()).unwrap();
|
|
|
|
let log_file = temp_dir.path().join("conn.log");
|
|
fs::write(&log_file, CONN_LOG_SAMPLE_1).unwrap();
|
|
|
|
let (ingested1, skipped1, _) = store.ingest_file(&log_file).unwrap();
|
|
assert_eq!(ingested1, 2);
|
|
assert_eq!(skipped1, 0);
|
|
|
|
let summary1 = store.summary().unwrap();
|
|
assert_eq!(summary1.records, 2);
|
|
assert_eq!(summary1.partitions, 1);
|
|
|
|
let (ingested2, skipped2, _) = store.ingest_file(&log_file).unwrap();
|
|
assert_eq!(ingested2, 2);
|
|
assert_eq!(skipped2, 0);
|
|
|
|
let summary2 = store.summary().unwrap();
|
|
assert_eq!(summary2.records, 2);
|
|
|
|
let log_file_2 = temp_dir.path().join("conn.extra.log");
|
|
fs::write(&log_file_2, CONN_LOG_PERMUTED_COLS).unwrap();
|
|
store.ingest_file(&log_file_2).unwrap();
|
|
|
|
let summary3 = store.summary().unwrap();
|
|
assert_eq!(summary3.records, 3);
|
|
|
|
let tuples = store.query_7day_tuples().unwrap();
|
|
assert_eq!(tuples.len(), 1);
|
|
assert_eq!(tuples[0].orig_h, "192.168.1.10");
|
|
assert_eq!(tuples[0].resp_h, "10.0.0.1");
|
|
assert_eq!(tuples[0].resp_p, 443);
|
|
assert_eq!(tuples[0].proto, "tcp");
|
|
assert_eq!(tuples[0].timestamps.len(), 3);
|
|
assert_eq!(tuples[0].timestamps[0], 1793461200.0);
|
|
assert_eq!(tuples[0].timestamps[1], 1793461205.0);
|
|
assert_eq!(tuples[0].timestamps[2], 1793461210.0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_storage_utc_timezone_partitioning() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let store = Storage::open(temp_dir.path()).unwrap();
|
|
|
|
let log = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\n1793412000.000000\tu1\t10.0.0.1\t1000\t10.0.0.2\t80\ttcp\n";
|
|
let log_file = temp_dir.path().join("conn.log");
|
|
fs::write(&log_file, log).unwrap();
|
|
store.ingest_file(&log_file).unwrap();
|
|
|
|
let partition_dir = temp_dir
|
|
.path()
|
|
.join("raw")
|
|
.join("conn")
|
|
.join("date=2026-10-31");
|
|
assert!(
|
|
partition_dir.is_dir(),
|
|
"partition date=2026-10-31 should exist regardless of local timezone"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_storage_sandbox_blocks_unauthorized_paths() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let store = Storage::open(temp_dir.path()).unwrap();
|
|
let conn = store.open_connection().unwrap();
|
|
|
|
let res = conn.execute_batch("SELECT * FROM read_csv('/etc/passwd');");
|
|
assert!(res.is_err(), "sandbox must block access outside data_dir");
|
|
}
|
|
|
|
#[test]
|
|
fn test_storage_prune_expired() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let store = Storage::open(temp_dir.path()).unwrap();
|
|
|
|
let raw_conn = temp_dir.path().join("raw").join("conn");
|
|
let old_part = raw_conn.join("date=2026-10-01");
|
|
let new_part = raw_conn.join("date=2026-10-11");
|
|
fs::create_dir_all(&old_part).unwrap();
|
|
fs::create_dir_all(&new_part).unwrap();
|
|
|
|
let pruned = store.prune_expired().unwrap();
|
|
assert_eq!(pruned, 1);
|
|
assert!(!old_part.exists());
|
|
assert!(new_part.exists());
|
|
}
|
|
|
|
#[test]
|
|
fn test_union_by_name_v11_and_v12_compatibility() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let store = Storage::open(temp_dir.path()).unwrap();
|
|
let conn = store.open_connection().unwrap();
|
|
|
|
let part_dir = store
|
|
.root()
|
|
.join("raw")
|
|
.join("conn")
|
|
.join("date=2026-10-31");
|
|
fs::create_dir_all(&part_dir).unwrap();
|
|
let part_str = part_dir.to_string_lossy().replace('\'', "''");
|
|
|
|
// Write v1.1 format (no history, no orig_bytes etc.)
|
|
conn.execute_batch(&format!(
|
|
"CREATE TEMP TABLE v11 (ts DOUBLE, uid VARCHAR, orig_h VARCHAR, orig_p USMALLINT, resp_h VARCHAR, resp_p USMALLINT, proto VARCHAR, date DATE);
|
|
INSERT INTO v11 VALUES (1793461200.0, 'u1', '10.0.0.1', 1000, '10.0.0.2', 80, 'tcp', '2026-10-31');
|
|
COPY v11 TO '{part_str}/v11.parquet' (FORMAT parquet);
|
|
DROP TABLE v11;"
|
|
)).unwrap();
|
|
|
|
// Write v1.2 format (with history, orig_bytes)
|
|
conn.execute_batch(&format!(
|
|
"CREATE TEMP TABLE v12 (ts DOUBLE, uid VARCHAR, orig_h VARCHAR, orig_p USMALLINT, resp_h VARCHAR, resp_p USMALLINT, proto VARCHAR, history VARCHAR, orig_bytes UBIGINT, date DATE);
|
|
INSERT INTO v12 VALUES (1793461210.0, 'u2', '10.0.0.1', 1001, '10.0.0.2', 80, 'tcp', 'ShAD', 500, '2026-10-31');
|
|
COPY v12 TO '{part_str}/v12.parquet' (FORMAT parquet);
|
|
DROP TABLE v12;"
|
|
)).unwrap();
|
|
|
|
let parquet_glob = store
|
|
.root()
|
|
.join("raw")
|
|
.join("conn")
|
|
.join("*")
|
|
.join("*.parquet")
|
|
.to_string_lossy()
|
|
.replace('\'', "''");
|
|
|
|
let read_sql = format!(
|
|
"SELECT count(*)::BIGINT, count(history)::BIGINT
|
|
FROM read_parquet('{parquet_glob}', hive_partitioning = true, union_by_name = true);"
|
|
);
|
|
let (total, with_history): (i64, i64) = conn
|
|
.query_row(&read_sql, [], |r| Ok((r.get(0)?, r.get(1)?)))
|
|
.unwrap();
|
|
assert_eq!(total, 2);
|
|
assert_eq!(with_history, 1);
|
|
}
|
|
|
|
#[test]
|
|
fn test_zeek_split_real_fixture_chaining() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let store = Storage::open(temp_dir.path()).unwrap();
|
|
|
|
let fixture_path = Path::new(env!("CARGO_MANIFEST_DIR"))
|
|
.join("tests")
|
|
.join("fixtures")
|
|
.join("zeek_split")
|
|
.join("conn.log");
|
|
|
|
store.ingest_file(&fixture_path).unwrap();
|
|
|
|
let sessions = store.query_7day_sessions().unwrap();
|
|
assert_eq!(sessions.len(), 1);
|
|
assert_eq!(sessions[0].orig_h, "10.0.0.5");
|
|
assert_eq!(sessions[0].resp_h, "203.0.113.9");
|
|
assert_eq!(sessions[0].resp_p, 443);
|
|
assert_eq!(sessions[0].proto, "tcp");
|
|
assert_eq!(sessions[0].sessions.len(), 1);
|
|
|
|
let s = &sessions[0].sessions[0];
|
|
assert_eq!(s.parts, 2);
|
|
assert!(
|
|
(s.duration - 4201.05).abs() < 0.01,
|
|
"duration: expected 4201.05, got {}",
|
|
s.duration
|
|
);
|
|
assert_eq!(s.orig_bytes, 1200);
|
|
assert_eq!(s.resp_bytes, 2400);
|
|
}
|
|
|
|
#[test]
|
|
fn test_chaining_negative_cases() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let store = Storage::open(temp_dir.path()).unwrap();
|
|
|
|
// 1. Second line has 'S' in history -> 2 sessions
|
|
let log_syn = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tduration\thistory\n\
|
|
1793400000.0\tu1\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tShAD\n\
|
|
1793400200.0\tu2\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tShAD\n";
|
|
let f_syn = temp_dir.path().join("conn.syn.log");
|
|
fs::write(&f_syn, log_syn).unwrap();
|
|
store.ingest_file(&f_syn).unwrap();
|
|
|
|
let sess_syn = store.query_7day_sessions().unwrap();
|
|
assert_eq!(
|
|
sess_syn[0].sessions.len(),
|
|
2,
|
|
"history with 'S' must not chain"
|
|
);
|
|
|
|
// 2. Gap of 3601s -> 2 sessions
|
|
let temp_dir2 = tempfile::tempdir().unwrap();
|
|
let store2 = Storage::open(temp_dir2.path()).unwrap();
|
|
let log_gap = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tduration\thistory\n\
|
|
1793400000.0\tu1\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tShAD\n\
|
|
1793403702.0\tu2\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tAD\n";
|
|
let f_gap = temp_dir2.path().join("conn.gap.log");
|
|
fs::write(&f_gap, log_gap).unwrap();
|
|
store2.ingest_file(&f_gap).unwrap();
|
|
|
|
let sess_gap = store2.query_7day_sessions().unwrap();
|
|
assert_eq!(sess_gap[0].sessions.len(), 2, "gap > 3600s must not chain");
|
|
|
|
// 3. history is NULL -> does not chain
|
|
let temp_dir3 = tempfile::tempdir().unwrap();
|
|
let store3 = Storage::open(temp_dir3.path()).unwrap();
|
|
let log_null = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\tduration\thistory\n\
|
|
1793400000.0\tu1\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\tShAD\n\
|
|
1793400200.0\tu2\t10.0.0.1\t40000\t10.0.0.2\t80\ttcp\t100.0\t-\n";
|
|
let f_null = temp_dir3.path().join("conn.null.log");
|
|
fs::write(&f_null, log_null).unwrap();
|
|
store3.ingest_file(&f_null).unwrap();
|
|
|
|
let sess_null = store3.query_7day_sessions().unwrap();
|
|
assert_eq!(
|
|
sess_null[0].sessions.len(),
|
|
2,
|
|
"history NULL must not chain"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn test_partitions_affected_and_files_failed() {
|
|
let temp_dir = tempfile::tempdir().unwrap();
|
|
let store = Storage::open(temp_dir.path()).unwrap();
|
|
|
|
// 2 lines across 2 days (2026-10-30 and 2026-10-31)
|
|
let log = "#separator \\x09\n#fields\tts\tuid\tid.orig_h\tid.orig_p\tid.resp_h\tid.resp_p\tproto\n\
|
|
1793325600.0\tu1\t10.0.0.1\t1000\t10.0.0.2\t80\ttcp\n\
|
|
1793412000.0\tu2\t10.0.0.1\t1000\t10.0.0.2\t80\ttcp\n";
|
|
let f = temp_dir.path().join("conn.log");
|
|
fs::write(&f, log).unwrap();
|
|
|
|
let stats = store.ingest_dir(temp_dir.path()).unwrap();
|
|
assert_eq!(stats.partitions_affected, 2);
|
|
assert_eq!(stats.files_failed, 0);
|
|
}
|
|
}
|