Silent ticks (empty stdout, exit 0), one line per stable fingerprint, cumulative union-only seen-set at ~/.hermes/cron/netsec-scan-state.json, memoized sensor- degradation line, daily baseline report. Stdlib only; reads the collector's JSONL over SSH with per-file byte offsets and Prometheus via the k8s API proxy. 40 unit tests against fixtures recorded from the live collector.
122 lines
4.5 KiB
Python
122 lines
4.5 KiB
Python
"""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}
|
|
"egress": {}, # tuple -> first_seen iso (cumulative)
|
|
"beacon": {}, # tuple -> {socket: ts}
|
|
"files": {}, # name -> {offset, carry, size}
|
|
"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)
|
|
for key in ("seen", "egress", "beacon", "files", "degraded"):
|
|
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)
|
|
egress = state["egress"]
|
|
if len(egress) > config.MAX_EGRESS:
|
|
ordered = sorted(egress.items(), key=lambda kv: kv[1])
|
|
for key, _ in ordered[: len(ordered) - config.MAX_EGRESS + 2000]:
|
|
egress.pop(key, None)
|
|
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)
|
|
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()
|