"""Entry point: one tick of the deterministic sensor. Contract (see README): * calm tick -> empty stdout, exit 0 * hit -> one line per fingerprint, `SEV ` (<= 200 chars) * degradation-> one memoized line naming the failure class, exit non-zero, state file untouched """ from __future__ import annotations import argparse import json import os import sys import time import traceback from datetime import datetime, timezone from pathlib import Path from typing import Any, Dict, List, Optional from . import config, report, rules, state as state_mod from .flows import ( ArchiveTruncated, BaseStore, LocalFlowStore, RemoteFlowStore, SingleFileStore, flow_stamp, fingerprint, is_archive, iter_archive, iter_lines, parse_flow, ) from .prom import SensorError from .rules import SEVERITY_ORDER, Finding # ------------------------------------------------------------- helpers ---- def log(msg: str, verbose: bool) -> None: if verbose: print("netsec-scan: " + msg, file=sys.stderr) def memo_path(state_path: Path) -> Path: """Degradation memo lives beside the state file, never inside it.""" return state_path.with_name(state_path.stem + ".memo.json") def load_memo(path: Path) -> Dict[str, str]: try: data = json.loads(path.read_text()) return data if isinstance(data, dict) else {} except (OSError, ValueError): return {} def save_memo(path: Path, memo: Dict[str, str]) -> None: try: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(memo, indent=2, sort_keys=True) + "\n") os.replace(tmp, path) except OSError: pass def render(finding: Finding) -> str: line = "%s %s %s %s" % (finding.severity, finding.fingerprint, finding.rule, finding.detail) if len(line) > config.MAX_LINE: line = line[: config.MAX_LINE - 1] + "\u2026" return line def mark_coverage(st: Dict[str, Any], name: str) -> None: """Widen `observed_since` to the coverage start of a consumed file. The filename stamp is the moment the collector opened that file, so it is the exact start of the coverage (not an estimate), and the minimum over every file ever consumed is the honest answer to "how far back have I looked". Monotone: it only ever moves earlier. """ stamp = flow_stamp(name) if stamp is None: return prev = st.get("observed_since") if prev: try: if datetime.fromisoformat(prev) <= stamp: return except (TypeError, ValueError): pass st["observed_since"] = stamp.isoformat(timespec="seconds") def observe_window(st: Dict[str, Any], now: float) -> Optional[float]: """Hours of flow history this sensor has actually consumed. `observed_since` tracks consumed files, not just the live one, so this is the number the alert quotes: "no prior in ~Xh of observed flows". Computed before a tick reads anything, which is exact for every warm tick because new files are always newer than the oldest thing already consumed. """ since = st.get("observed_since") if not since: return None try: start = datetime.fromisoformat(since) except (TypeError, ValueError): return None hours = max(0.0, (now - start.timestamp()) / 3600.0) st["window_h"] = round(hours, 2) return st["window_h"] def consume_flows(store: BaseStore, st: Dict[str, Any], verbose: bool, on_batch, now: Optional[float] = None) -> Dict[str, Any]: """Walk the collector's store once, handing parsed flows to `on_batch`. * Plain `.jsonl` is being appended to, so it is read from the last consumed byte (a trailing partial line is carried in state, as before). * `.jsonl.gz` is immutable once the collector renames it into place, so each archive is decompressed once, in full, and its name recorded — never re-read. This is what lets a cold start baseline against the retained window instead of the live file's minutes. * Archives are bounded (`config.ARCHIVE_MAX_*`): newest first, stop when the time/byte/file budget is spent, leave the rest **unread** and report them as pending so the next tick continues rather than silently narrowing the baseline. Flows are handed over in batches so a multi-GB seed never exists as a list of Flow objects. """ started = time.monotonic() now = now if now is not None else started budget = {"seconds": config.ARCHIVE_MAX_SECONDS, "bytes": config.ARCHIVE_MAX_BYTES, "files": config.ARCHIVE_MAX_FILES} stats: Dict[str, Any] = { "flows": 0, "malformed": 0, "lines": 0, "plain": 0, "archives": 0, "archive_bytes": 0, "pending": [], "failed": {}, "files_read": 0, "budget_hit": False, "seconds": 0.0, } batch: List = [] source_of_batch = {"value": "plain"} def flush() -> None: nonlocal batch if batch: on_batch(batch, source_of_batch["value"]) batch = [] def feed(line: str, source: str) -> None: line = line.strip() if not line: return try: obj = json.loads(line) except ValueError: stats["malformed"] += 1 return flow = parse_flow(obj) if flow is None: stats["malformed"] += 1 return stats["flows"] += 1 source_of_batch["value"] = source batch.append(flow) if len(batch) >= config.FLOW_BATCH: flush() files = store.list_files() live = {name for name, _size in files} plain = [(name, size) for name, size in files if not is_archive(name)] archives = [(name, size) for name, size in files if is_archive(name)] for name, size in plain: entry = st["files"].get(name) or {"offset": 0, "size": 0} offset = int(entry.get("offset", 0) or 0) if size < offset: # truncated or replaced under us log("file %s shrank (%d < %d); restarting at 0" % (name, size, offset), verbose) offset = 0 if size == offset: st["files"][name] = {"offset": offset, "size": size} mark_coverage(st, name) continue data = store.read_from(name, offset) lines, partial = iter_lines(data) consumed = offset + len(data) - len(partial) for line in lines: feed(line, "plain") st["files"][name] = {"offset": consumed, "size": size} mark_coverage(st, name) stats["plain"] += 1 stats["files_read"] += 1 stats["lines"] += len(lines) log("read %s: %d bytes, %d lines" % (name, len(data), len(lines)), verbose) known = st.setdefault("archives", {}) unread = sorted((name for name, _size in archives if name not in known), reverse=True) sizes = dict(archives) for name in unread: spent = time.monotonic() - started if stats["archives"] and (spent > budget["seconds"] or stats["archive_bytes"] > budget["bytes"] or stats["archives"] >= budget["files"]): stats["budget_hit"] = True stats["pending"].append(name) continue lines = 0 error = None try: for line in iter_archive(store, name): lines += 1 stats["archive_bytes"] += len(line) feed(line, "archive") except ArchiveTruncated as exc: # Torn/partial archive: keep the readable prefix, note it, move on. error = str(exc)[:160] stats["failed"][name] = error log("archive %s unreadable (%s); read %d line(s), skipped rest" % (name, error, lines), verbose) except SensorError: raise known[name] = {"size": sizes.get(name, 0), "read_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "lines": lines} if error: known[name]["error"] = error mark_coverage(st, name) stats["archives"] += 1 stats["files_read"] += 1 stats["lines"] += lines log("archive %s: %d line(s), %d bytes decompressed, %.1fs" % (name, lines, stats["archive_bytes"], time.monotonic() - started), verbose) flush() # Forget entries the collector rotated/pruned away; their bytes are consumed # and a collector filename can never come back. for name in list(st["files"]): if name not in live: st["files"].pop(name, None) for name in list(known): if name not in live: known.pop(name, None) stats["seconds"] = round(time.monotonic() - started, 2) return stats def absorb(st: Dict[str, Any], kind: str, entity: str, rule: str, severity: str) -> None: """Add a novelty fingerprint to the baseline without announcing it. Used for history the sensor reads *after* the fact: the cold-start seed and the first pass over pre-existing archives. Announcing those would print "first-seen … (no prior in ~Xh of observed flows)" for a tuple that is demonstrably inside that X hours — a false statement, and the alert storm the state file exists to prevent. """ now_iso = datetime.now(timezone.utc).isoformat(timespec="seconds") st["seen"].setdefault(fingerprint(rule, entity), { "rule": rule, "kind": kind, "entity": entity, "severity": severity, "first": now_iso, "last_alert": now_iso, "seeded": True, }) def apply_dedupe(findings: List[Finding], seen: Dict[str, Any], now: float, dry_run: bool) -> List[Finding]: """Emit each fingerprint once; state rules may re-fire after the cooldown. Batched consumption can surface the same finding from two batches (a beacon is re-derived per batch), so a fingerprint already emitted in *this* tick is dropped here as well — one line per finding per tick, always. """ emit: List[Finding] = [] this_tick = set() for finding in findings: if finding.fingerprint in this_tick: continue this_tick.add(finding.fingerprint) prev = seen.get(finding.fingerprint) if dry_run: emit.append(finding) continue if prev is None: seen[finding.fingerprint] = { "rule": finding.rule, "kind": finding.kind, "entity": finding.entity, "severity": finding.severity, "first": datetime.now(timezone.utc).isoformat(timespec="seconds"), "last_alert": datetime.now(timezone.utc).isoformat(timespec="seconds"), } emit.append(finding) continue if finding.kind == "state": try: last = datetime.fromisoformat(prev.get("last_alert", "")).timestamp() except (TypeError, ValueError): last = 0.0 if now - last >= config.STATE_COOLDOWN: prev["last_alert"] = datetime.now(timezone.utc).isoformat(timespec="seconds") emit.append(finding) return emit def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding], egress_tick: List[str], malformed: int) -> None: state_mod.roll_day(st) day = st["day"] day["flows"] = int(day.get("flows", 0)) + flows for finding in emitted: day["rules"][finding.rule] = int(day["rules"].get(finding.rule, 0)) + 1 if finding.rule == "egress-new-dst": day["new_dsts"].append( {"tuple": finding.entity, "first_seen": datetime.now(timezone.utc).isoformat(timespec="seconds")}) # `egress_tuples_seen` is the day's distinct external tuples, whether or not # they were novel: it is the baseline rule 7 gets tuned from. known = day.setdefault("egress", []) for key in egress_tick: if key not in known: known.append(key) known.sort() st["totals"]["ticks"] = int(st["totals"].get("ticks", 0)) + 1 st["totals"]["flows"] = int(st["totals"].get("flows", 0)) + flows st["totals"]["findings"] = int(st["totals"].get("findings", 0)) + len(emitted) st["totals"]["malformed"] = int(st["totals"].get("malformed", 0)) + malformed # ----------------------------------------------------------------- main ---- def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace: parser = argparse.ArgumentParser( prog="netsec-scan", description="Deterministic netsec sensor: silent when calm, one line per hit.") parser.add_argument("--fixture", help="read this JSONL file instead of the live collector") parser.add_argument("--flows-dir", help="read flows-*.jsonl from this local directory") parser.add_argument("--dry-run", action="store_true", help="print findings without writing state/report and without seen-set dedupe") parser.add_argument("--no-prom", action="store_true", help="skip the PromQL tripwires") parser.add_argument("--state", help="state file path (default ~/.hermes/cron/netsec-scan-state.json)") parser.add_argument("--reports", help="report directory (default ~/Projects/netsec-agent/reports)") parser.add_argument("--verbose", action="store_true", help="debug lines on stderr") return parser.parse_args(argv) def main(argv: Optional[List[str]] = None) -> int: args = parse_args(argv) state_path = Path(args.state or config.STATE_FILE) reports_dir = Path(args.reports or config.REPORT_DIR) now = time.time() if args.fixture: store: BaseStore = SingleFileStore(args.fixture) prom_enabled = False elif args.flows_dir: store = LocalFlowStore(args.flows_dir) prom_enabled = not args.no_prom else: store = RemoteFlowStore() prom_enabled = not args.no_prom try: st = state_mod.load(state_path) except SensorError as exc: print("SENSOR %s netsec-scan: %s" % (exc.cls, exc.detail or exc.cls)) return 2 try: # Exact for any warm tick: `observed_since` is a monotone minimum over # consumed files and everything read this tick is newer, so the number # the findings quote cannot go stale mid-tick. window_h = observe_window(st, now) seeding = not st.get("seeded") archive_baseline = bool(st.get("archive_baseline")) tick = int(st["totals"].get("ticks", 0)) + 1 flow_findings: List[Finding] = [] tick_egress = set() def on_batch(batch: List, source: str) -> None: tick_egress.update(rules.egress_keys(batch)) out = rules.rule_egress_first_seen( batch, st["seen"], st["egress_counts"], _utcnow(), window_h, tick) out += rules.rule_beacon(batch, st["beacon"], now) if source == "archive" and not archive_baseline and not seeding: # Archives this sensor has never read, while its baseline came # from the live file only: absorb the whole batch, announce # nothing. Every tuple counts, not just the findings — a web-port # tuple never becomes a finding on its first tick. for key in rules.egress_keys(batch): absorb(st, "novelty", key, "egress-new-dst", "MEDIUM") for finding in out: absorb(st, finding.kind, finding.entity, finding.rule, finding.severity) return flow_findings.extend(out) stats = consume_flows(store, st, args.verbose, on_batch, now) window_h = observe_window(st, now) rules.prune_beacon(st["beacon"], now) if stats["archives"] and not stats["pending"]: st["archive_baseline"] = True log("consumed %d flows from %d file(s) (%d archive(s), %d plain), %d malformed, " "%d pending, %.2fs; window %sh" % (stats["flows"], stats["files_read"], stats["archives"], stats["plain"], stats["malformed"], len(stats["pending"]), stats["seconds"], window_h), args.verbose) findings: List[Finding] = [] if prom_enabled: for rule in rules.PROM_RULES: try: findings.extend(rule(_prommod())) except SensorError: raise except Exception as exc: # a broken rule must not eat the tick log("rule %s failed: %s" % (rule.__name__, exc), args.verbose) raise SensorError("prom-error", "%s: %s" % (rule.__name__, exc)) if seeding and not args.dry_run: # Baseline run: record history silently instead of dumping the # retained window into chat. PromQL findings still speak (they are # current state, not history). for finding in flow_findings: absorb(st, finding.kind, finding.entity, finding.rule, finding.severity) # The baseline must absorb *every* egress tuple in the window, not # only the ones that became findings. A web-port tuple needs # EGRESS_WEB_MIN_TICKS distinct ticks before it is worth a line, so # it never becomes a finding on the one seeding tick — and would then # alert on tick 3 for traffic that was in the retained window all # along. That is the alert storm this file exists to prevent. for key in list(st["egress_counts"]): absorb(st, "novelty", key, "egress-new-dst", "MEDIUM") st["seed"] = { "started_at": st.get("seed", {}).get("started_at") or datetime.now(timezone.utc).isoformat(timespec="seconds"), "at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "files": stats["files_read"], "archives": stats["archives"], "plain": stats["plain"], "flows": stats["flows"], "tuples": len(st["egress_counts"]), "fingerprints": len(st["seen"]), "seconds": stats["seconds"], "bytes": stats["archive_bytes"], "covered_since": st.get("observed_since"), "window_h": window_h, "pending": len(stats["pending"]), "failed": stats["failed"], "budget": {"seconds": config.ARCHIVE_MAX_SECONDS, "bytes": config.ARCHIVE_MAX_BYTES, "files": config.ARCHIVE_MAX_FILES}, } if stats["pending"]: # Not a fault: the budget is the point. Stay unseeded so the next # tick continues the baseline instead of alerting from a window # that is still being filled. log("seed: budget hit with %d archive(s) pending (%s); baseline " "covers %sh so far, continuing next tick" % (len(stats["pending"]), ", ".join(sorted(stats["pending"])[:3]), window_h), args.verbose) else: st["seeded"] = True st["seeded_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds") log("seed run: %d file(s) (%d archive(s)), window %sh, %d tuple(s), " "%d fingerprint(s) recorded silently in %.2fs" % (stats["files_read"], stats["archives"], window_h, len(st["egress_counts"]), len(st["seen"]), stats["seconds"]), args.verbose) flow_findings = [] emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run) record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"]) state_mod.prune(st) if not args.dry_run: state_mod.save(state_path, st) report.write(st, reports_dir) except SensorError as exc: return degrade(state_path, exc, args.verbose) except Exception as exc: # never fail silently traceback.print_exc(file=sys.stderr) return degrade(state_path, SensorError("internal-error", str(exc)[:160]), args.verbose) emitted.sort(key=lambda f: (SEVERITY_ORDER.get(f.severity, 9), f.rule, f.entity)) for finding in emitted: print(render(finding)) return 0 def _utcnow() -> datetime: return datetime.now(timezone.utc) def _prommod(): from . import prom return prom def degrade(state_path: Path, exc: SensorError, verbose: bool) -> int: """One memoized line per failure class; state file is never touched.""" memo_file = memo_path(state_path) memo = load_memo(memo_file) now = time.time() last = memo.get(exc.cls) announce = True if last: try: announce = (now - datetime.fromisoformat(last).timestamp()) >= config.DEGRADED_MEMO except (TypeError, ValueError): announce = True if announce: detail = exc.detail or exc.cls print("SENSOR %s netsec-scan: sensor input unavailable (%s)" % (exc.cls, detail)) memo[exc.cls] = datetime.now(timezone.utc).isoformat(timespec="seconds") save_memo(memo_file, memo) if verbose: print("netsec-scan: degraded class=%s detail=%s" % (exc.cls, exc.detail), file=sys.stderr) return 1 if __name__ == "__main__": sys.exit(main())