diff --git a/README.md b/README.md index 8e732fe..802d9d6 100644 --- a/README.md +++ b/README.md @@ -68,11 +68,16 @@ count: the same finding keeps the same id across ticks, restarts and days. * **State rules** (the six tripwires) describe a *current condition*; they fire once and may re-fire after `STATE_COOLDOWN` (24 h) so "it broke, was fixed, and broke again" is not silently forgotten. -* First run is a **baseline run**: every novelty finding in the retained window - is recorded into `seen` silently instead of dumping weeks of history into - chat — and so is **every distinct egress tuple** in that window, not only the - ones that became findings (a web-port tuple never becomes one on its first - tick). PromQL findings still speak on the first tick — they are current state. +* First run is a **baseline run**: while `seeded` is false at tick start, the + flow-store rules still run (they build the egress counts and beacon history a + warm tick needs) but **every** result is absorbed into `seen` and nothing is + printed — not just the first pass. That covers `--dry-run` too (history is not + news in a dry run either) and it is why the cron's delivery outcome for a seed + tick is `suppressed`. Each seeding tick writes one explanatory line to stderr: + `seed: N tuple(s) absorbed, 0 reported; window Xh from , N file(s)`. The + baseline holds **every distinct egress tuple** in the window, not only the ones + that became findings (a web-port tuple never becomes one on its first tick). + PromQL findings still speak on the first tick — they are current state. * A **warm** state that has never read the gzip archives (i.e. one upgraded to a gzipped store) absorbs its first archive pass the same way: announcing it would print `first-seen … (no prior in ~Xh of observed flows)` for a tuple that is @@ -80,11 +85,12 @@ count: the same finding keeps the same id across ticks, restarts and days. that pass has happened. * Baseline reads are **bounded** (`ARCHIVE_MAX_SECONDS` / `ARCHIVE_MAX_BYTES` / `ARCHIVE_MAX_FILES`). If the budget stops the pass, the state stays - `seeded: false` and the unread archives are listed as `pending` in state and - in the verbose line, so the next tick continues the baseline instead of - alerting from a window that is still being filled. The window quoted in the - alert (`window_h`, derived from the coverage start in the filenames actually - consumed) grows tick by tick until the pass completes. + `seeded: false` and the unread archives are listed as `pending` in state, so + the next tick continues the baseline — and stays silent — instead of alerting + from a window that is still being filled. `seeded` only flips at the end of a + complete pass, so a seed spanning several ticks never announces anything. The + window quoted in the alert (`window_h`, derived from the coverage start in the + filenames actually consumed) grows tick by tick until the pass completes. ## The 8 rules diff --git a/netsec_scan/__main__.py b/netsec_scan/__main__.py index 65682a9..c55f8a5 100644 --- a/netsec_scan/__main__.py +++ b/netsec_scan/__main__.py @@ -43,6 +43,16 @@ def log(msg: str, verbose: bool) -> None: print("netsec-scan: " + msg, file=sys.stderr) +def note(msg: str) -> None: + """Diagnostic that is always printed: it explains a non-obvious silence. + + The seed lines use this. A tick whose stdout is empty must be + distinguishable from a tick whose baseline is still being built, and + `--verbose` is not something a cron job passes. + """ + 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") @@ -115,6 +125,16 @@ def observe_window(st: Dict[str, Any], now: float) -> Optional[float]: return st["window_h"] +def window_text(st: Dict[str, Any], window_h: Optional[float]) -> str: + """The window the baseline actually covers, in the alert's own spelling.""" + if not window_h: + return "no flow history yet" + since = st.get("observed_since") + if not since: + return rules.window_label(window_h) + return "%s from %s" % (rules.window_label(window_h), since) + + 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`. @@ -248,7 +268,7 @@ def consume_flows(store: BaseStore, st: Dict[str, Any], verbose: bool, return stats -def absorb(st: Dict[str, Any], kind: str, entity: str, rule: str, severity: str) -> None: +def absorb(st: Dict[str, Any], kind: str, entity: str, rule: str, severity: str) -> bool: """Add a novelty fingerprint to the baseline without announcing it. Used for history the sensor reads *after* the fact: the cold-start seed and @@ -256,12 +276,19 @@ def absorb(st: Dict[str, Any], kind: str, entity: str, rule: str, severity: str) "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. + + Returns True when the fingerprint was new, so the caller can report how + much history it swallowed instead of leaving the silence unexplained. """ now_iso = datetime.now(timezone.utc).isoformat(timespec="seconds") - st["seen"].setdefault(fingerprint(rule, entity), { + fp = fingerprint(rule, entity) + if fp in st["seen"]: + return False + st["seen"][fp] = { "rule": rule, "kind": kind, "entity": entity, "severity": severity, "first": now_iso, "last_alert": now_iso, "seeded": True, - }) + } + return True def apply_dedupe(findings: List[Finding], seen: Dict[str, Any], now: float, @@ -371,27 +398,54 @@ def main(argv: Optional[List[str]] = None) -> int: # 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) + # `seeded` is false until one complete pass over the store has been + # absorbed: a cold start, and every resume tick after a budget hit. On + # all of those the entire retained window is history, so nothing the + # flow store produces may be announced — see on_batch. `seeded` only + # flips at the very end of a pass, which is what makes a resume tick + # silent instead of a second storm. 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() + baseline = {"seed": 0, "archive": 0} + + def absorb_batch(batch: List, out: List[Finding]) -> int: + """Fold a slice of history into `seen`; returns new fingerprints.""" + added = 0 + # Every tuple counts, not just the findings: a web-port tuple needs + # EGRESS_WEB_MIN_TICKS distinct ticks before it is worth a line, so + # without this it would alert later for traffic that was inside the + # window all along. + for key in rules.egress_keys(batch): + if absorb(st, "novelty", key, "egress-new-dst", "MEDIUM"): + added += 1 + for finding in out: + if absorb(st, finding.kind, finding.entity, finding.rule, + finding.severity): + added += 1 + return added 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: + if seeding: + # Cold start / resume: the rules still run (they build the + # egress counts and beacon history the warm ticks need) but + # every result is absorbed into the baseline. This is the guard + # that keeps a fresh state quiet instead of dumping the retained + # window into chat, and it holds for --dry-run as well: a dry + # run against an unseeded state is reading history, not news. + baseline["seed"] += absorb_batch(batch, out) + return + if source == "archive" and not archive_baseline: # 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) + # nothing. + baseline["archive"] += absorb_batch(batch, out) return flow_findings.extend(out) @@ -417,20 +471,27 @@ def main(argv: Optional[List[str]] = None) -> int: 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. + if baseline["archive"]: + # Not a fault, and not news either: these tuples are inside the + # window the next alert would quote. Say so once, loudly enough to + # be seen without --verbose. + note("archive baseline: %d tuple(s) absorbed, 0 reported; window %s" + % (baseline["archive"], window_text(st, window_h))) + + if seeding: + # Baseline run: every flow-store result was already absorbed in + # on_batch, so nothing from the retained window reaches stdout. + # PromQL findings still speak (they are current state, not history). + # + # Belt and braces: absorb *every* egress tuple the window carried, + # not only the ones this pass turned into findings. A web-port tuple + # needs EGRESS_WEB_MIN_TICKS distinct ticks, so it never becomes a + # finding on the tick it first appears and would otherwise alert on + # tick 3 for traffic that was inside the retained window all along. + # On a resume tick this is a no-op (already absorbed). for key in list(st["egress_counts"]): - absorb(st, "novelty", key, "egress-new-dst", "MEDIUM") + if absorb(st, "novelty", key, "egress-new-dst", "MEDIUM"): + baseline["seed"] += 1 st["seed"] = { "started_at": st.get("seed", {}).get("started_at") or datetime.now(timezone.utc).isoformat(timespec="seconds"), @@ -439,6 +500,7 @@ def main(argv: Optional[List[str]] = None) -> int: "plain": stats["plain"], "flows": stats["flows"], "tuples": len(st["egress_counts"]), "fingerprints": len(st["seen"]), + "absorbed": baseline["seed"], "seconds": stats["seconds"], "bytes": stats["archive_bytes"], "covered_since": st.get("observed_since"), "window_h": window_h, @@ -449,21 +511,22 @@ def main(argv: Optional[List[str]] = None) -> int: "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) + # Not a fault: the budget is the point. Stay unseeded so the + # next tick continues the baseline — and stays silent — instead + # of alerting from a window that is still being filled. + note("seed: %d tuple(s) absorbed, 0 reported; window %s so far, " + "%d archive(s) still pending, next tick continues silently" + % (baseline["seed"], window_text(st, window_h), + len(stats["pending"]))) 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) + if not args.dry_run: + st["seeded"] = True + st["seeded_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds") + note("seed: %d tuple(s) absorbed, 0 reported; window %s, " + "%d file(s) (%d archive(s)) in %.2fs%s" + % (baseline["seed"], window_text(st, window_h), + stats["files_read"], stats["archives"], stats["seconds"], + " (dry run: nothing persisted)" if args.dry_run else "")) flow_findings = [] emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run) diff --git a/netsec_scan/rules.py b/netsec_scan/rules.py index 409a53e..64425ae 100644 --- a/netsec_scan/rules.py +++ b/netsec_scan/rules.py @@ -195,6 +195,9 @@ def _window_label(hours: float) -> str: return "%.1fd" % (hours / 24.0) +window_label = _window_label # public name: the seed summary prints it too + + def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict], counts: Dict[str, dict], now: datetime, window_h: Optional[float] = None, tick: int = 0) -> List[Finding]: diff --git a/tests/test_seed.py b/tests/test_seed.py new file mode 100644 index 0000000..d902176 --- /dev/null +++ b/tests/test_seed.py @@ -0,0 +1,124 @@ +"""A seed is history, not news: it is absorbed, never announced. + +Pins the acceptance of t_cf3e563a: a cold start and *every* resume tick of a +budget-limited seed keep stdout empty (so the cron's delivery outcome is +`suppressed`), `--dry-run` included — a dry run against an unseeded state must +not look like the alert storm it used to print. Silence has to be explained, +so each seeding tick writes one `seed: N tuple(s) absorbed, 0 reported` line +with the window it actually covered. + +The opposite failure is a permanently silent sensor, so the seeded-state +single-fire test lives right next to these (test_archives.py pins it too). +""" + +from __future__ import annotations + +import contextlib +import gzip +import io +import json +import tempfile +import unittest +from pathlib import Path + +from helpers import fixture_lines + +from netsec_scan import __main__ as cli +from netsec_scan import config, state as state_mod + +LIVE = "flows-20261127T070000Z-1.jsonl" +ARCHIVES = ("flows-20261127T060000Z-1.jsonl.gz", + "flows-20261127T050000Z-1.jsonl.gz", + "flows-20261127T040000Z-1.jsonl.gz") +SEED_RE = r"seed: \d+ tuple\(s\) absorbed, 0 reported; window \S+ from 2026-11-27T04:00:00\+00:00" + + +def _store(root: Path) -> None: + lines = fixture_lines("egress-sample.jsonl") + for name in ARCHIVES: + with gzip.open(root / name, "wt", encoding="utf-8") as handle: + handle.write("\n".join(lines) + "\n") + (root / LIVE).write_text("\n".join(lines) + "\n") + + +class TestSeedIsSilent(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.flows = self.root / "flows" + self.flows.mkdir() + _store(self.flows) + self.state = self.root / "state.json" + self.reports = self.root / "reports" + + def tearDown(self): + self.tmp.cleanup() + + def tick(self, *extra: str): + """Returns (stdout, stderr) from one real main() run.""" + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = cli.main(["--flows-dir", str(self.flows), "--no-prom", + "--state", str(self.state), "--reports", str(self.reports), + *extra]) + self.assertEqual(code, 0) + return out.getvalue(), err.getvalue() + + def test_cold_start_is_silent_and_names_the_absorbed_window(self): + out, err = self.tick() + self.assertEqual(out, "", "a cold start must not announce the retained window") + self.assertRegex(err, SEED_RE) + st = state_mod.load(self.state) + self.assertTrue(st["seeded"]) + self.assertEqual(st["seed"]["absorbed"], len(st["seen"])) + self.assertEqual(len(st["seen"]), len(st["egress_counts"])) + self.assertGreater(len(st["seen"]), 0) + self.assertEqual(st["observed_since"], "2026-11-27T04:00:00+00:00") + + def test_dry_run_cold_start_is_silent_and_persists_nothing(self): + out, err = self.tick("--dry-run") + self.assertEqual(out, "", "a dry run over an unseeded state reads history, not news") + self.assertIn("0 reported", err) + self.assertIn("dry run: nothing persisted", err) + self.assertFalse(self.state.exists()) + + def test_resume_tick_is_silent_while_still_unseeded(self): + original = config.ARCHIVE_MAX_FILES + config.ARCHIVE_MAX_FILES = 1 # 1 archive per tick, 3 archives + try: + out1, err1 = self.tick() + st = state_mod.load(self.state) + self.assertEqual(out1, "") + self.assertFalse(st["seeded"], "a partial baseline is not a baseline") + self.assertIn("still pending", err1) + + out2, err2 = self.tick() # the tick t_cf3e563a was filed about + st = state_mod.load(self.state) + self.assertEqual(out2, "", "a resume tick must stay silent too") + self.assertFalse(st["seeded"]) + self.assertIn("still pending", err2) + + out3, _err3 = self.tick() + self.assertEqual(out3, "") + self.assertTrue(state_mod.load(self.state)["seeded"]) + finally: + config.ARCHIVE_MAX_FILES = original + + def test_seeded_state_still_fires_exactly_once(self): + self.tick() + obj = json.loads(fixture_lines("egress-sample.jsonl")[0]) + obj["flow"]["IP"]["destination"] = "203.0.113.77" + proto = next(iter(obj["flow"]["l4"])) + obj["flow"]["l4"][proto]["destination_port"] = 5000 + line = json.dumps(obj) + "\n" + with open(self.flows / LIVE, "a", encoding="utf-8") as handle: + handle.write(line) + first, _err = self.tick() + self.assertEqual(len(first.strip().splitlines()), 1, first) + self.assertIn("203.0.113.77:5000/tcp", first) + second, _err = self.tick() + self.assertEqual(second, "", "a reported tuple does not repeat") + + +if __name__ == "__main__": + unittest.main()