From be60d74159c579a28f6aa8ec54605e1a0814aa02 Mon Sep 17 00:00:00 2001 From: sirius Date: Fri, 27 Nov 2026 00:32:25 -0500 Subject: [PATCH] netsec-scan: second-tick gate for web-port egress novelty (kill CDN churn) One CI run produced 20 one-shot AWS/GitHub CDN destinations in a single 5-minute tick (21-line message, nothing reached the operator only because delivery was unresolved). First-seen tuples now carry per-tick observation counts in state: web ports (80/443/8080/8443) need two distinct ticks before alerting, non-web ports and any DROPPED verdict still alert on first sight. A beacon/exfil destination is retried; CDN rotation is not. Also: cron deliver switched to local because this profile has platforms.telegram.enabled=false (deliver=telegram errors 'no delivery target resolved'), and the README now documents that constraint. --- README.md | 9 ++++++ netsec_scan/__main__.py | 4 ++- netsec_scan/config.py | 7 +++++ netsec_scan/rules.py | 33 +++++++++++++-------- netsec_scan/state.py | 8 ++++- tests/test_rules.py | 66 +++++++++++++++++++++++++++++------------ 6 files changed, 94 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index c8ad1cf..07b7356 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,15 @@ destination (`…/dropped` in the entity, HIGH): a pod trying to reach a new hos and being refused is a stronger signal than one that succeeded, and collapsing them would hide it behind the forwarded tuple's fingerprint. +Rule 7 also keeps **web-port novelty** (80/443/8080/8443) on a second-tick gate: +a first-seen web destination is only worth a line once it appears in **two** +distinct ticks. Measured 2026-11-27: one CI run produced 20 one-shot AWS/GitHub +CDN destinations inside a single 5-minute window, which is a 20-line message and +exactly how a channel gets muted. CDN rotation is one-shot by nature; a beacon or +an exfil destination is retried, so it still fires — a tick later. Non-web ports +and any `DROPPED` verdict alert on first sight, and a `DROPPED` web-port tuple is +HIGH. Rationale and the two-tick evidence live in `config.EGRESS_WEB_MIN_TICKS`. + **Deliberately not implemented** (and why): * **Per-workload PromQL rules.** The `pod` label on every `hubble_*` metric is diff --git a/netsec_scan/__main__.py b/netsec_scan/__main__.py index df7f983..98320fe 100644 --- a/netsec_scan/__main__.py +++ b/netsec_scan/__main__.py @@ -244,7 +244,9 @@ def main(argv: Optional[List[str]] = None) -> int: seeding = not st.get("seeded") window_h = track_window(st, flows) - new_egress = rules.rule_egress_first_seen(flows, st["seen"], _utcnow(), window_h) + tick = int(st["totals"].get("ticks", 0)) + 1 + new_egress = rules.rule_egress_first_seen( + flows, st["seen"], st["egress_counts"], _utcnow(), window_h, tick) beacon = rules.rule_beacon(flows, st["beacon"], now) rules.prune_beacon(st["beacon"], now) flow_findings = new_egress + beacon diff --git a/netsec_scan/config.py b/netsec_scan/config.py index e5db2ca..7120cb1 100644 --- a/netsec_scan/config.py +++ b/netsec_scan/config.py @@ -81,6 +81,13 @@ BEACON_MAX_INTERVAL = 900.0 # mean interval ceiling; 30s beacons fit, 1h cron-i # Severity for a first-seen egress tuple: standard web ports are common CDN # churn, everything else is a much stronger beacon/exfil signal. WEB_PORTS = frozenset({80, 443, 8080, 8443}) +# A first-seen *web-port* tuple must also be observed in a second tick before it +# alerts. Measured 2026-11-27: one CI run produced 20 one-shot AWS/GitHub CDN +# destinations in a single 5-minute window, which is a 20-line message and +# exactly how a channel gets muted. CDN rotation is one-shot; a beacon or an +# exfil destination is retried. Non-web ports still alert on first sight. +EGRESS_WEB_MIN_TICKS = 2 +MAX_EGRESS_COUNTS = 20000 # Re-alert cooldown for *state* tripwires (current-condition rules). Flow # novelty is permanent: a tuple fires exactly once, ever. A state rule gets to diff --git a/netsec_scan/rules.py b/netsec_scan/rules.py index c918496..473ee17 100644 --- a/netsec_scan/rules.py +++ b/netsec_scan/rules.py @@ -196,7 +196,8 @@ def _window_label(hours: float) -> str: def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict], - now: datetime, window_h: float = None) -> List[Finding]: + counts: Dict[str, dict], now: datetime, + window_h: float = None, tick: int = 0) -> List[Finding]: """First-seen egress tuple = candidate beacon/exfil. Novelty is gated on the **cumulative seen-set only** (fingerprint presence), @@ -204,14 +205,14 @@ def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict], fingerprint from `seen` re-arms the rule, which is what the acceptance procedure exercises. - The alert says how long this sensor has actually been watching - (`window_h`): the collector caps at 1 GiB, which at the measured ~2 MB/min - is days, not the month the design note assumed. Never imply a longer - baseline than was observed. + `counts` (tuple -> {n, first, last_tick}) exists only to separate one-shot + CDN rotation from a repeat destination: a web-port tuple must be seen in + `EGRESS_WEB_MIN_TICKS` distinct ticks before it is worth a line. Non-web + ports alert immediately, and a `DROPPED` verdict is always HIGH. - A `DROPPED` verdict on a new to-world tuple is its own signal (the pod tried - something that policy refused), so it is keyed and graded separately from - the forwarded traffic for the same destination. + The alert says how long this sensor has actually been watching + (`window_h`): the collector caps at 1 GiB, which is days, not the month the + design note assumed. Never imply a longer baseline than was observed. """ out: List[Finding] = [] window = (" (no prior in ~%s of observed flows)" % _window_label(window_h) @@ -220,13 +221,21 @@ def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict], key = _egress_key(flow) if not key: continue + entry = counts.get(key) + if entry is None: + entry = {"n": 1, "first": (flow.time or now).isoformat(timespec="seconds"), + "last_tick": tick} + counts[key] = entry + elif entry.get("last_tick") != tick: + entry["n"] = int(entry.get("n", 1)) + 1 + entry["last_tick"] = tick dropped = flow.verdict == "DROPPED" if dropped: key += "/dropped" - if flow.dst_port in config.WEB_PORTS and not dropped: - severity = "MEDIUM" - else: - severity = "HIGH" + web = flow.dst_port in config.WEB_PORTS + if web and not dropped and int(entry.get("n", 1)) < config.EGRESS_WEB_MIN_TICKS: + continue # one-shot CDN destination: not worth a line yet + severity = "MEDIUM" if web and not dropped else "HIGH" finding = Finding( rule="egress-new-dst", kind="novelty", severity=severity, entity=key, detail="%s first-seen %s%s" % (key, _ts(flow.time), window), diff --git a/netsec_scan/state.py b/netsec_scan/state.py index 37f3708..f693ac0 100644 --- a/netsec_scan/state.py +++ b/netsec_scan/state.py @@ -34,6 +34,7 @@ def empty() -> Dict[str, Any]: "seeded": False, # flow novelty has been baselined once "seen": {}, # fp -> {rule, kind, entity, severity, first, last_alert} "beacon": {}, # tuple -> {socket: ts} + "egress_counts": {}, # tuple -> {n ticks seen, first, last_tick} "observed_since": None, # earliest flow timestamp ever observed (ISO) "files": {}, # name -> {offset, carry, size} "degraded": {}, # failure class -> iso of last announcement @@ -56,7 +57,7 @@ def load(path: Path) -> Dict[str, Any]: base = empty() for key, value in base.items(): data.setdefault(key, value) - for key in ("seen", "beacon", "files", "degraded"): + for key in ("seen", "beacon", "egress_counts", "files", "degraded"): if not isinstance(data.get(key), dict): data[key] = {} return data @@ -89,6 +90,11 @@ def prune(state: Dict[str, Any]) -> None: 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) + 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) day = state["day"] if len(day.get("egress", [])) > config.MAX_DAY_EGRESS: day["egress"] = day["egress"][-config.MAX_DAY_EGRESS:] diff --git a/tests/test_rules.py b/tests/test_rules.py index 413e53e..9a654d5 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -18,33 +18,69 @@ def utc(*args): class TestFirstSeenEgress(unittest.TestCase): NOW = utc(2026, 11, 27, 5, 20) - def test_new_tuples_produce_findings(self): + def evaluate(self, flows, seen, counts=None, tick=1, now=None): + return rules.rule_egress_first_seen( + flows, seen, counts if counts is not None else {}, + now or self.NOW, 0.5, tick) + + def warmed(self, flows): + """Baseline tick: populates counts, emits nothing for web ports.""" + counts = {} + self.assertEqual(self.evaluate(flows, {}, counts, tick=1), []) + return counts + + def test_web_port_tuple_needs_a_second_tick(self): + """One-shot CDN destinations must not produce a line on first sight.""" flows = fixture_flows("egress-sample.jsonl") - findings = rules.rule_egress_first_seen(flows, {}, self.NOW) + counts = {} + self.assertEqual(self.evaluate(flows, {}, counts, tick=1), []) + findings = self.evaluate(flows, {}, counts, tick=2) self.assertTrue(findings) self.assertTrue(all(f.rule == "egress-new-dst" for f in findings)) + self.assertTrue(all(f.severity == "MEDIUM" for f in findings)) + + def test_non_web_port_alerts_on_first_sight(self): + flows = fixture_flows("egress-sample.jsonl") + for flow in flows[:1]: + flow.dst_port = 4444 + findings = self.evaluate(flows[:1], {}, {}, tick=1) + self.assertEqual(len(findings), 1) + self.assertEqual(findings[0].severity, "HIGH") + self.assertIn(":4444/", findings[0].entity) + + def test_dropped_verdict_is_keyed_and_high(self): + flows = fixture_flows("egress-sample.jsonl") + flows = flows[:1] + flows[0].verdict = "DROPPED" + findings = self.evaluate(flows, {}, {}, tick=1) + self.assertEqual(len(findings), 1) + self.assertEqual(findings[0].severity, "HIGH") + self.assertTrue(findings[0].entity.endswith("/dropped")) def test_seen_fingerprint_suppresses_the_rule(self): flows = fixture_flows("egress-sample.jsonl") - first = rules.rule_egress_first_seen(flows, {}, self.NOW) + counts = self.warmed(flows) + first = self.evaluate(flows, {}, counts, tick=2) + self.assertTrue(first) seen = {f.fingerprint: {"rule": f.rule} for f in first} - self.assertEqual(rules.rule_egress_first_seen(flows, seen, self.NOW), []) + self.assertEqual(self.evaluate(flows, seen, counts, tick=3), []) def test_single_fire_then_rearm_when_one_key_is_deleted(self): """The acceptance procedure: delete exactly one fp -> exactly one line.""" from netsec_scan.__main__ import apply_dedupe flows = fixture_flows("egress-sample.jsonl") + counts = self.warmed(flows) seen = {} - first = apply_dedupe(rules.rule_egress_first_seen(flows, seen, self.NOW), + first = apply_dedupe(self.evaluate(flows, seen, counts, tick=2), seen, self.NOW.timestamp(), False) self.assertTrue(first) - again = apply_dedupe(rules.rule_egress_first_seen(flows, seen, self.NOW), + again = apply_dedupe(self.evaluate(flows, seen, counts, tick=3), seen, self.NOW.timestamp(), False) self.assertEqual(again, []) target = first[0].fingerprint del seen[target] - rearmed = apply_dedupe(rules.rule_egress_first_seen(flows, seen, self.NOW), + rearmed = apply_dedupe(self.evaluate(flows, seen, counts, tick=4), seen, self.NOW.timestamp(), False) self.assertEqual([f.fingerprint for f in rearmed], [target]) @@ -53,28 +89,20 @@ class TestFirstSeenEgress(unittest.TestCase): flows = fixture_flows("egress-sample.jsonl") seen = {"deadbeef0000": {"rule": "egress-new-dst", "kind": "novelty"}} - apply_dedupe(rules.rule_egress_first_seen(flows, seen, self.NOW), + apply_dedupe(self.evaluate(flows, seen, self.warmed(flows), tick=2), seen, self.NOW.timestamp(), False) self.assertIn("deadbeef0000", seen) self.assertGreater(len(seen), 1) def test_fingerprint_is_stable_across_runs(self): flows = fixture_flows("egress-sample.jsonl") - a = rules.rule_egress_first_seen(flows, {}, utc(2026, 11, 27, 5, 20)) - b = rules.rule_egress_first_seen(flows, {}, utc(2027, 1, 2, 9, 0)) + a = self.evaluate(flows, {}, self.warmed(flows), tick=2, now=utc(2026, 11, 27, 5, 20)) + b = self.evaluate(flows, {}, self.warmed(flows), tick=2, now=utc(2027, 1, 2, 9, 0)) self.assertEqual([f.fingerprint for f in a], [f.fingerprint for f in b]) - def test_severity_by_port(self): - flows = fixture_flows("egress-sample.jsonl") - findings = rules.rule_egress_first_seen(flows, {}, self.NOW) - for f in findings: - port = int(f.entity.rsplit(":", 1)[1].split("/")[0]) - want = "MEDIUM" if port in config.WEB_PORTS else "HIGH" - self.assertEqual(f.severity, want, f.entity) - def test_nonexternal_and_reserved_are_ignored(self): flows = fixture_flows("egress-sample.jsonl") - findings = rules.rule_egress_first_seen(flows, {}, self.NOW) + findings = self.evaluate(flows, {}, self.warmed(flows), tick=2) for f in findings: self.assertNotIn("reserved:", f.entity) self.assertNotIn("192.168.", f.entity)