2026-11-27 00:20:46 -05:00
|
|
|
"""State file: cumulative seen-set, per-file read offsets, report counters.
|
|
|
|
|
|
|
|
|
|
Rules of the house:
|
|
|
|
|
* the seen-set is UNIONED, never replaced — a transiently-empty read must not
|
|
|
|
|
re-alert history;
|
|
|
|
|
* a write is atomic (tmp + rename) and 0600;
|
|
|
|
|
* a corrupt file is a hard failure (exit non-zero, nothing touched), not a
|
|
|
|
|
silent reset that re-alerts everything.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import json
|
|
|
|
|
import os
|
|
|
|
|
import time
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
from typing import Any, Dict, List, Tuple
|
|
|
|
|
|
|
|
|
|
from . import config
|
|
|
|
|
from .prom import SensorError
|
|
|
|
|
|
|
|
|
|
VERSION = 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _now_iso() -> str:
|
|
|
|
|
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def empty() -> Dict[str, Any]:
|
|
|
|
|
return {
|
|
|
|
|
"version": VERSION,
|
|
|
|
|
"created_at": _now_iso(),
|
|
|
|
|
"seeded": False, # flow novelty has been baselined once
|
|
|
|
|
"seen": {}, # fp -> {rule, kind, entity, severity, first, last_alert}
|
|
|
|
|
"beacon": {}, # tuple -> {socket: ts}
|
2026-11-27 00:32:25 -05:00
|
|
|
"egress_counts": {}, # tuple -> {n ticks seen, first, last_tick}
|
2026-11-27 00:24:22 -05:00
|
|
|
"observed_since": None, # earliest flow timestamp ever observed (ISO)
|
netsec-scan: read flows-*.jsonl.gz so a cold start baselines the retained window, not the live file
The collector gzips on rotation, so FLOW_PATTERN 'flows-*.jsonl' saw 1 of 5
files (measured: 1/72 of the retained window). Archives are immutable, so each
is read once, whole, decrypted lazily and recorded in state['archives'].
- archives are bounded (ARCHIVE_MAX_SECONDS/BYTES/FILES, newest first) and
flows are consumed in batches; a partial pass leaves state seeded=false and
reports the unread files as pending, so the next tick continues instead of
alerting from a window it has not examined
- the alert window comes from the coverage start in the consumed filenames
(monotone), so 'no prior in ~Xh of observed flows' is now verifiable
- the seed absorbs every egress tuple in the window, not just findings (a
web-port tuple never becomes one on its first tick); a warm state meeting
archives for the first time absorbs them the same way
- a torn .gz keeps its readable prefix, is noted in state/seed.failed, and does
not abort the tick; in-flight *.gz.tmp.* markers are never read
- report.json carries window_h/covered_since/seed; 12 new tests
2026-11-27 02:09:51 -05:00
|
|
|
"files": {}, # name -> {offset, carry, size} (plain, appended to)
|
|
|
|
|
"archives": {}, # name -> {size, read_at, lines} (.jsonl.gz, read once)
|
|
|
|
|
"archive_baseline": False, # archives have been baselined once (absorbed silently)
|
|
|
|
|
"seed": {}, # summary of the baseline run: window, files, tuples
|
2026-11-27 00:20:46 -05:00
|
|
|
"degraded": {}, # failure class -> iso of last announcement
|
|
|
|
|
"day": {"date": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
|
|
|
"flows": 0, "rules": {}, "egress": [], "new_dsts": []},
|
|
|
|
|
"totals": {"ticks": 0, "flows": 0, "findings": 0},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load(path: Path) -> Dict[str, Any]:
|
|
|
|
|
path = Path(path)
|
|
|
|
|
if not path.exists():
|
|
|
|
|
return empty()
|
|
|
|
|
try:
|
|
|
|
|
data = json.loads(path.read_text())
|
|
|
|
|
except (OSError, ValueError) as exc:
|
|
|
|
|
raise SensorError("state-corrupt", "%s: %s" % (path, exc))
|
|
|
|
|
if not isinstance(data, dict) or data.get("version") != VERSION:
|
|
|
|
|
raise SensorError("state-corrupt", "unexpected schema in %s" % path)
|
|
|
|
|
base = empty()
|
|
|
|
|
for key, value in base.items():
|
|
|
|
|
data.setdefault(key, value)
|
netsec-scan: read flows-*.jsonl.gz so a cold start baselines the retained window, not the live file
The collector gzips on rotation, so FLOW_PATTERN 'flows-*.jsonl' saw 1 of 5
files (measured: 1/72 of the retained window). Archives are immutable, so each
is read once, whole, decrypted lazily and recorded in state['archives'].
- archives are bounded (ARCHIVE_MAX_SECONDS/BYTES/FILES, newest first) and
flows are consumed in batches; a partial pass leaves state seeded=false and
reports the unread files as pending, so the next tick continues instead of
alerting from a window it has not examined
- the alert window comes from the coverage start in the consumed filenames
(monotone), so 'no prior in ~Xh of observed flows' is now verifiable
- the seed absorbs every egress tuple in the window, not just findings (a
web-port tuple never becomes one on its first tick); a warm state meeting
archives for the first time absorbs them the same way
- a torn .gz keeps its readable prefix, is noted in state/seed.failed, and does
not abort the tick; in-flight *.gz.tmp.* markers are never read
- report.json carries window_h/covered_since/seed; 12 new tests
2026-11-27 02:09:51 -05:00
|
|
|
for key in ("seen", "beacon", "egress_counts", "files", "archives", "degraded"):
|
2026-11-27 00:20:46 -05:00
|
|
|
if not isinstance(data.get(key), dict):
|
|
|
|
|
data[key] = {}
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def save(path: Path, state: Dict[str, Any]) -> None:
|
|
|
|
|
path = Path(path)
|
|
|
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
|
|
|
payload = json.dumps(state, separators=(",", ":"), sort_keys=True)
|
|
|
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
|
|
|
with os.fdopen(fd, "w") as handle:
|
|
|
|
|
handle.write(payload)
|
|
|
|
|
os.replace(tmp, path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def prune(state: Dict[str, Any]) -> None:
|
|
|
|
|
"""Bound every cumulative structure so a long-lived sensor stays small."""
|
|
|
|
|
seen = state["seen"]
|
|
|
|
|
if len(seen) > config.MAX_SEEN:
|
|
|
|
|
ordered = sorted(seen.items(), key=lambda kv: kv[1].get("first", ""))
|
|
|
|
|
for key, _ in ordered[: len(ordered) - config.MAX_SEEN + 2000]:
|
|
|
|
|
seen.pop(key, None)
|
2026-11-27 00:24:22 -05:00
|
|
|
egress = state["day"].get("egress", [])
|
|
|
|
|
if len(egress) > config.MAX_DAY_EGRESS:
|
|
|
|
|
state["day"]["egress"] = egress[-config.MAX_DAY_EGRESS:]
|
2026-11-27 00:20:46 -05:00
|
|
|
beacon = state["beacon"]
|
|
|
|
|
if len(beacon) > config.MAX_BEACON_TUPLES:
|
|
|
|
|
ordered = sorted(beacon.items(),
|
|
|
|
|
key=lambda kv: max(kv[1].values()) if kv[1] else 0)
|
|
|
|
|
for key, _ in ordered[: len(ordered) - config.MAX_BEACON_TUPLES + 200]:
|
|
|
|
|
beacon.pop(key, None)
|
2026-11-27 00:32:25 -05:00
|
|
|
counts = state.get("egress_counts") or {}
|
|
|
|
|
if len(counts) > config.MAX_EGRESS_COUNTS:
|
|
|
|
|
ordered = sorted(counts.items(), key=lambda kv: int(kv[1].get("last_tick", 0)))
|
|
|
|
|
for key, _ in ordered[: len(ordered) - config.MAX_EGRESS_COUNTS + 2000]:
|
|
|
|
|
counts.pop(key, None)
|
2026-11-27 00:20:46 -05:00
|
|
|
day = state["day"]
|
|
|
|
|
if len(day.get("egress", [])) > config.MAX_DAY_EGRESS:
|
|
|
|
|
day["egress"] = day["egress"][-config.MAX_DAY_EGRESS:]
|
|
|
|
|
if len(day.get("new_dsts", [])) > config.MAX_DAY_EGRESS:
|
|
|
|
|
day["new_dsts"] = day["new_dsts"][-config.MAX_DAY_EGRESS:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def roll_day(state: Dict[str, Any]) -> None:
|
|
|
|
|
"""Carry report counters into a fresh UTC day (old day stays on disk)."""
|
|
|
|
|
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
|
|
|
day = state.get("day") or {}
|
|
|
|
|
if day.get("date") != today:
|
|
|
|
|
state["day"] = {"date": today, "flows": 0, "rules": {}, "egress": [], "new_dsts": []}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def degraded_memo(state: Dict[str, Any], cls: str, now: float) -> bool:
|
|
|
|
|
"""True when this failure class was already announced inside the window."""
|
|
|
|
|
last = state.get("degraded", {}).get(cls)
|
|
|
|
|
if last is None:
|
|
|
|
|
return False
|
|
|
|
|
try:
|
|
|
|
|
stamp = datetime.fromisoformat(last).timestamp()
|
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
|
return False
|
|
|
|
|
return (now - stamp) < config.DEGRADED_MEMO
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def note_degraded(state: Dict[str, Any], cls: str) -> None:
|
|
|
|
|
state.setdefault("degraded", {})[cls] = _now_iso()
|