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.
This commit is contained in:
sirius 2026-11-27 00:32:25 -05:00
commit be60d74159
6 changed files with 94 additions and 33 deletions

View file

@ -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 and being refused is a stronger signal than one that succeeded, and collapsing
them would hide it behind the forwarded tuple's fingerprint. 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): **Deliberately not implemented** (and why):
* **Per-workload PromQL rules.** The `pod` label on every `hubble_*` metric is * **Per-workload PromQL rules.** The `pod` label on every `hubble_*` metric is

View file

@ -244,7 +244,9 @@ def main(argv: Optional[List[str]] = None) -> int:
seeding = not st.get("seeded") seeding = not st.get("seeded")
window_h = track_window(st, flows) 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) beacon = rules.rule_beacon(flows, st["beacon"], now)
rules.prune_beacon(st["beacon"], now) rules.prune_beacon(st["beacon"], now)
flow_findings = new_egress + beacon flow_findings = new_egress + beacon

View file

@ -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 # Severity for a first-seen egress tuple: standard web ports are common CDN
# churn, everything else is a much stronger beacon/exfil signal. # churn, everything else is a much stronger beacon/exfil signal.
WEB_PORTS = frozenset({80, 443, 8080, 8443}) 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 # Re-alert cooldown for *state* tripwires (current-condition rules). Flow
# novelty is permanent: a tuple fires exactly once, ever. A state rule gets to # novelty is permanent: a tuple fires exactly once, ever. A state rule gets to

View file

@ -196,7 +196,8 @@ def _window_label(hours: float) -> str:
def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict], 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. """First-seen egress tuple = candidate beacon/exfil.
Novelty is gated on the **cumulative seen-set only** (fingerprint presence), 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 fingerprint from `seen` re-arms the rule, which is what the acceptance
procedure exercises. procedure exercises.
The alert says how long this sensor has actually been watching `counts` (tuple -> {n, first, last_tick}) exists only to separate one-shot
(`window_h`): the collector caps at 1 GiB, which at the measured ~2 MB/min CDN rotation from a repeat destination: a web-port tuple must be seen in
is days, not the month the design note assumed. Never imply a longer `EGRESS_WEB_MIN_TICKS` distinct ticks before it is worth a line. Non-web
baseline than was observed. 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 The alert says how long this sensor has actually been watching
something that policy refused), so it is keyed and graded separately from (`window_h`): the collector caps at 1 GiB, which is days, not the month the
the forwarded traffic for the same destination. design note assumed. Never imply a longer baseline than was observed.
""" """
out: List[Finding] = [] out: List[Finding] = []
window = (" (no prior in ~%s of observed flows)" % _window_label(window_h) 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) key = _egress_key(flow)
if not key: if not key:
continue 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" dropped = flow.verdict == "DROPPED"
if dropped: if dropped:
key += "/dropped" key += "/dropped"
if flow.dst_port in config.WEB_PORTS and not dropped: web = flow.dst_port in config.WEB_PORTS
severity = "MEDIUM" if web and not dropped and int(entry.get("n", 1)) < config.EGRESS_WEB_MIN_TICKS:
else: continue # one-shot CDN destination: not worth a line yet
severity = "HIGH" severity = "MEDIUM" if web and not dropped else "HIGH"
finding = Finding( finding = Finding(
rule="egress-new-dst", kind="novelty", severity=severity, entity=key, rule="egress-new-dst", kind="novelty", severity=severity, entity=key,
detail="%s first-seen %s%s" % (key, _ts(flow.time), window), detail="%s first-seen %s%s" % (key, _ts(flow.time), window),

View file

@ -34,6 +34,7 @@ def empty() -> Dict[str, Any]:
"seeded": False, # flow novelty has been baselined once "seeded": False, # flow novelty has been baselined once
"seen": {}, # fp -> {rule, kind, entity, severity, first, last_alert} "seen": {}, # fp -> {rule, kind, entity, severity, first, last_alert}
"beacon": {}, # tuple -> {socket: ts} "beacon": {}, # tuple -> {socket: ts}
"egress_counts": {}, # tuple -> {n ticks seen, first, last_tick}
"observed_since": None, # earliest flow timestamp ever observed (ISO) "observed_since": None, # earliest flow timestamp ever observed (ISO)
"files": {}, # name -> {offset, carry, size} "files": {}, # name -> {offset, carry, size}
"degraded": {}, # failure class -> iso of last announcement "degraded": {}, # failure class -> iso of last announcement
@ -56,7 +57,7 @@ def load(path: Path) -> Dict[str, Any]:
base = empty() base = empty()
for key, value in base.items(): for key, value in base.items():
data.setdefault(key, value) 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): if not isinstance(data.get(key), dict):
data[key] = {} data[key] = {}
return data 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) key=lambda kv: max(kv[1].values()) if kv[1] else 0)
for key, _ in ordered[: len(ordered) - config.MAX_BEACON_TUPLES + 200]: for key, _ in ordered[: len(ordered) - config.MAX_BEACON_TUPLES + 200]:
beacon.pop(key, None) 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"] day = state["day"]
if len(day.get("egress", [])) > config.MAX_DAY_EGRESS: if len(day.get("egress", [])) > config.MAX_DAY_EGRESS:
day["egress"] = day["egress"][-config.MAX_DAY_EGRESS:] day["egress"] = day["egress"][-config.MAX_DAY_EGRESS:]

View file

@ -18,33 +18,69 @@ def utc(*args):
class TestFirstSeenEgress(unittest.TestCase): class TestFirstSeenEgress(unittest.TestCase):
NOW = utc(2026, 11, 27, 5, 20) 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") 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(findings)
self.assertTrue(all(f.rule == "egress-new-dst" for f in 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): def test_seen_fingerprint_suppresses_the_rule(self):
flows = fixture_flows("egress-sample.jsonl") 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} 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): def test_single_fire_then_rearm_when_one_key_is_deleted(self):
"""The acceptance procedure: delete exactly one fp -> exactly one line.""" """The acceptance procedure: delete exactly one fp -> exactly one line."""
from netsec_scan.__main__ import apply_dedupe from netsec_scan.__main__ import apply_dedupe
flows = fixture_flows("egress-sample.jsonl") flows = fixture_flows("egress-sample.jsonl")
counts = self.warmed(flows)
seen = {} 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) seen, self.NOW.timestamp(), False)
self.assertTrue(first) 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) seen, self.NOW.timestamp(), False)
self.assertEqual(again, []) self.assertEqual(again, [])
target = first[0].fingerprint target = first[0].fingerprint
del seen[target] 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) seen, self.NOW.timestamp(), False)
self.assertEqual([f.fingerprint for f in rearmed], [target]) self.assertEqual([f.fingerprint for f in rearmed], [target])
@ -53,28 +89,20 @@ class TestFirstSeenEgress(unittest.TestCase):
flows = fixture_flows("egress-sample.jsonl") flows = fixture_flows("egress-sample.jsonl")
seen = {"deadbeef0000": {"rule": "egress-new-dst", "kind": "novelty"}} 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) seen, self.NOW.timestamp(), False)
self.assertIn("deadbeef0000", seen) self.assertIn("deadbeef0000", seen)
self.assertGreater(len(seen), 1) self.assertGreater(len(seen), 1)
def test_fingerprint_is_stable_across_runs(self): def test_fingerprint_is_stable_across_runs(self):
flows = fixture_flows("egress-sample.jsonl") flows = fixture_flows("egress-sample.jsonl")
a = rules.rule_egress_first_seen(flows, {}, utc(2026, 11, 27, 5, 20)) a = self.evaluate(flows, {}, self.warmed(flows), tick=2, now=utc(2026, 11, 27, 5, 20))
b = rules.rule_egress_first_seen(flows, {}, utc(2027, 1, 2, 9, 0)) 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]) 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): def test_nonexternal_and_reserved_are_ignored(self):
flows = fixture_flows("egress-sample.jsonl") 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: for f in findings:
self.assertNotIn("reserved:", f.entity) self.assertNotIn("reserved:", f.entity)
self.assertNotIn("192.168.", f.entity) self.assertNotIn("192.168.", f.entity)