diff --git a/README.md b/README.md index 852055e..c8ad1cf 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ python3 -m unittest discover -s tests # 40 tests, no network Example: ``` -HIGH a3f19c02b7de egress-new-dst osint/osint-app->203.0.113.9:4444/tcp first-seen 03:12Z (no prior in retained window) -MEDIUM 0fbb2e28bb07 egress-new-dst flux-system/source-controller->104.18.30.120:443/tcp first-seen 05:10Z (no prior in retained window) +HIGH a3f19c02b7de egress-new-dst osint/osint-app->203.0.113.9:4444/tcp first-seen 03:12Z (no prior in ~20m of observed flows) +MEDIUM 0fbb2e28bb07 egress-new-dst flux-system/source-controller->104.18.30.120:443/tcp first-seen 05:10Z (no prior in ~2.1d of observed flows) ``` **Fingerprint** = `sha256(rule + entity)[:12]`. Never a timestamp, never a @@ -86,9 +86,14 @@ and two flow-store rules (`/var/log/netsec/*.jsonl` on siriussec). | 4 | `rst-storm` | MEDIUM | refused/reset connection storm | RST > **2/s** and > **10×** 6 h average | 1 RST series, 2.5/s at idle | | 5 | `new-port` | LOW | a server-range port (1-32767) that carried flows now but none 24 h ago | `count by(port) … unless … offset 24h` | 131 port series; 4 named ports in 24 h at deploy | | 6 | `http-error-ratio` | MEDIUM | L7 4xx/5xx share shift (public gateway) | > **0.5** of ≥ **0.5 req/s** (15 m) | 20 status series; 2.2 % at idle | -| 7 | `egress-new-dst` | HIGH (non-web port) / MEDIUM (80/443) | first-seen `(workload, dst_ip, dst_port)` outside pod/mesh/LAN space — candidate beacon or exfil | no prior in the retained window (cumulative seen-set) | 21 workload→world tuples in the first 15 min captured | +| 7 | `egress-new-dst` | HIGH (non-web port, or any `DROPPED` verdict) / MEDIUM (80/443 forwarded) | first-seen `(workload, dst_ip, dst_port)` outside pod/mesh/LAN space — candidate beacon or exfil | no prior in the cumulative seen-set; the line states the observation window (e.g. `~20m of observed flows`) | 21 workload→world tuples in the first 15 min captured | | 8 | `beacon-shape` | HIGH | periodic connections from one workload to one `dst:port` — C2 shape | ≥ **20** distinct client sockets in 2 h, inter-arrival **CV < 0.15**, mean interval ≤ 900 s | requires ≥ 20 conns; the busiest real tuple measured 9 sockets / CV 1.57 | +Rule 7 keeps a `DROPPED` attempt **separate** from forwarded traffic to the same +destination (`…/dropped` in the entity, HIGH): a pod trying to reach a new host +and being refused is a stronger signal than one that succeeded, and collapsing +them would hide it behind the forwarded tuple's fingerprint. + **Deliberately not implemented** (and why): * **Per-workload PromQL rules.** The `pod` label on every `hubble_*` metric is @@ -152,6 +157,17 @@ UTC day rollover. No alert is ever raised from it. **per-file byte offset** kept in state — a tick pulls only new bytes. It never polls `hubble observe`: the agent ring buffer is ~28 s at 148 flows/s, so a poll is lossy by design. +* **Measured volume**: 41 MB in ~20 min at collector start (the first file + carries a 37.5 MB startup burst), lower in steady state, against a 1 GiB cap — + so the file window is **days, not the month the design note assumed**. A + "not seen before" judgement therefore comes from this sensor's own cumulative + seen-set (which outlives the files), and the alert says how long that window + actually is rather than implying a longer baseline. +* Only `*.jsonl` counts toward the volume; rotation tombstones in the directory + are ignored. A partial final line in a file that is still being appended is + **normal**: the parser keeps the incomplete tail and re-reads it next tick + from the last complete newline (a `JSONDecodeError` on that tail is expected, + not corruption). * **Prometheus**: the monitoring Service through the API proxy, read-only, no port-forward, no new credentials. @@ -175,6 +191,7 @@ UTC day rollover. No alert is ever raised from it. |---|---| | repo | `sirius/netsec-agent` on Forgejo, cloned at `~/Projects/netsec-agent` | | shim | `~/.hermes/scripts/netsec-scan.sh` → `exec /home/lancelot/Projects/netsec-agent/run.sh "$@"` (`chmod +x`: a non-executable shim fails with `Permission denied` **on empty stdout**, which looks exactly like a healthy silent tick) | +| scheduler shim | `~/.hermes/profiles/devops/scripts/netsec-scan.sh` → execs the canonical shim. The cron scheduler only accepts a `script` path that resolves inside `/scripts/`, so the profile copy exists purely for that guard; the real entrypoint stays in one place. | | cron | Hermes job `netsec-scan`, `no_agent` script job, every 5 minutes, `workdir ~/Projects/netsec-agent`, `script netsec-scan.sh`, `deliver telegram` | | state | `~/.hermes/cron/netsec-scan-state.json` (+ `.memo.json` for degradation wording) | | reports | `~/Projects/netsec-agent/reports/YYYY-MM-DD.json` | @@ -184,10 +201,14 @@ credentials, no LLM call, no secret reads. ## Verified behaviour (2026-11-27) -* 40 unit tests pass against recorded fixtures. -* First live tick seeded 21 egress tuples and 21 beacon buckets silently, wrote - the state file and `reports/2026-11-27.json`. -* Single-fire: deleting one key from `seen` re-emits exactly one line, and the - immediately following run is silent. +* 43 unit tests pass against recorded fixtures. +* Baseline tick seeded the retained window silently (25 fingerprints, 21 beacon + buckets), wrote the state file and `reports/2026-11-27.json`; the immediately + following tick was empty with exit 0 **and a changed state mtime**. +* Single-fire: deleting one fingerprint from `seen` re-emitted exactly one line + naming that tuple, and the next run was silent; the state was then restored. * Cron delivery proven through `~/.hermes/cron/executions.db` (`delivery_outcome=delivered`) — see the task handoff for the transcript. +* Live tripwire values at commissioning: hubble-loss HIGH on siriussec (0.42-0.60 + events/s) and linode (0.13-3.2 events/s); `new-port` LOW for 3100/9093; the + rest quiet. diff --git a/netsec_scan/__main__.py b/netsec_scan/__main__.py index 380450f..df7f983 100644 --- a/netsec_scan/__main__.py +++ b/netsec_scan/__main__.py @@ -111,11 +111,32 @@ def collect_flows(store: BaseStore, st: Dict[str, Any], verbose: bool) -> Tuple[ return parsed, malformed, len(files) -def apply_dedupe(findings: List[Finding], st: Dict[str, Any], now: float, +def track_window(st: Dict[str, Any], flows: List) -> Optional[float]: + """Hours of flow history this sensor has actually observed. + + The collector caps at 1 GiB (days, not weeks), and the state may be younger + than that, so a first-seen judgement is only ever "no prior in ". + """ + times = [f.time for f in flows if getattr(f, "time", None)] + if not times: + return st.get("window_h") + earliest = min(times) + prev = st.get("observed_since") + if prev: + try: + earliest = min(earliest, datetime.fromisoformat(prev)) + except (TypeError, ValueError): + pass + st["observed_since"] = earliest.isoformat(timespec="seconds") + hours = max(0.0, (datetime.now(timezone.utc) - earliest).total_seconds() / 3600.0) + st["window_h"] = round(hours, 2) + return st["window_h"] + + +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.""" emit: List[Finding] = [] - seen = st["seen"] for finding in findings: prev = seen.get(finding.fingerprint) if dry_run: @@ -144,17 +165,23 @@ def apply_dedupe(findings: List[Finding], st: Dict[str, Any], now: float, def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding], - new_egress: List[str], malformed: int) -> None: + 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["egress"].append(finding.entity) 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) @@ -216,7 +243,8 @@ def main(argv: Optional[List[str]] = None) -> int: raise SensorError("prom-error", "%s: %s" % (rule.__name__, exc)) seeding = not st.get("seeded") - new_egress = rules.rule_egress_first_seen(flows, st["egress"], _utcnow()) + window_h = track_window(st, flows) + new_egress = rules.rule_egress_first_seen(flows, st["seen"], _utcnow(), window_h) beacon = rules.rule_beacon(flows, st["beacon"], now) rules.prune_beacon(st["beacon"], now) flow_findings = new_egress + beacon @@ -239,9 +267,9 @@ def main(argv: Optional[List[str]] = None) -> int: args.verbose) flow_findings = [] - emitted = apply_dedupe(findings + flow_findings, st, now, args.dry_run) + emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run) - record_counters(st, len(flows), emitted, new_egress, malformed) + record_counters(st, len(flows), emitted, rules.egress_keys(flows), malformed) state_mod.prune(st) if not args.dry_run: diff --git a/netsec_scan/rules.py b/netsec_scan/rules.py index ca251fc..c918496 100644 --- a/netsec_scan/rules.py +++ b/netsec_scan/rules.py @@ -165,6 +165,16 @@ def _egress_key(flow: Flow) -> Optional[str]: return "%s->%s:%d/%s" % (flow.src_workload, flow.dst_ip, flow.dst_port, flow.proto.lower()) +def egress_keys(flows: Iterable[Flow]) -> List[str]: + """Every external destination tuple in this slice (novel or not).""" + keys = [] + for flow in flows: + key = _egress_key(flow) + if key and key not in keys: + keys.append(key) + return keys + + def prune_beacon(beacon: Dict[str, Dict[str, float]], now: float) -> None: """Drop sockets that fell out of the window from every tracked tuple.""" cutoff = now - config.BEACON_WINDOW @@ -176,25 +186,54 @@ def prune_beacon(beacon: Dict[str, Dict[str, float]], now: float) -> None: beacon.pop(key, None) -def rule_egress_first_seen(flows: Iterable[Flow], egress_seen: Dict[str, str], - now: datetime) -> List[Finding]: +def _window_label(hours: float) -> str: + """Observation window in the shortest honest form.""" + if hours < 1: + return "%dm" % max(1, int(round(hours * 60))) + if hours < 48: + return "%.1fh" % hours + return "%.1fd" % (hours / 24.0) + + +def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict], + now: datetime, window_h: float = None) -> List[Finding]: """First-seen egress tuple = candidate beacon/exfil. - The seen-set is cumulative and seeded silently on the first run, so - deploying this sensor cannot dump the whole retained history into chat. + Novelty is gated on the **cumulative seen-set only** (fingerprint presence), + so there is exactly one place that decides "already reported": deleting a + 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. + + 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. """ out: List[Finding] = [] + window = (" (no prior in ~%s of observed flows)" % _window_label(window_h) + if window_h else " (no prior in observed flows)") for flow in flows: key = _egress_key(flow) - if not key or key in egress_seen: + if not key: continue - egress_seen[key] = (flow.time or now).astimezone(timezone.utc).isoformat() - port = flow.dst_port - severity = "MEDIUM" if port in config.WEB_PORTS else "HIGH" - out.append(Finding( + dropped = flow.verdict == "DROPPED" + if dropped: + key += "/dropped" + if flow.dst_port in config.WEB_PORTS and not dropped: + severity = "MEDIUM" + else: + severity = "HIGH" + finding = Finding( rule="egress-new-dst", kind="novelty", severity=severity, entity=key, - detail="%s first-seen %s (no prior in retained window)" % (key, _ts(flow.time)), - )) + detail="%s first-seen %s%s" % (key, _ts(flow.time), window), + ) + if finding.fingerprint in seen: + continue + out.append(finding) return out diff --git a/netsec_scan/state.py b/netsec_scan/state.py index e94ec4d..37f3708 100644 --- a/netsec_scan/state.py +++ b/netsec_scan/state.py @@ -33,8 +33,8 @@ def empty() -> Dict[str, Any]: "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} + "observed_since": None, # earliest flow timestamp ever observed (ISO) "files": {}, # name -> {offset, carry, size} "degraded": {}, # failure class -> iso of last announcement "day": {"date": datetime.now(timezone.utc).strftime("%Y-%m-%d"), @@ -56,7 +56,7 @@ def load(path: Path) -> Dict[str, Any]: base = empty() for key, value in base.items(): data.setdefault(key, value) - for key in ("seen", "egress", "beacon", "files", "degraded"): + for key in ("seen", "beacon", "files", "degraded"): if not isinstance(data.get(key), dict): data[key] = {} return data @@ -80,11 +80,9 @@ def prune(state: Dict[str, Any]) -> None: 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) + egress = state["day"].get("egress", []) + if len(egress) > config.MAX_DAY_EGRESS: + state["day"]["egress"] = egress[-config.MAX_DAY_EGRESS:] beacon = state["beacon"] if len(beacon) > config.MAX_BEACON_TUPLES: ordered = sorted(beacon.items(), diff --git a/tests/test_rules.py b/tests/test_rules.py index 5bace11..413e53e 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -16,25 +16,47 @@ def utc(*args): class TestFirstSeenEgress(unittest.TestCase): - def test_same_tuple_fires_once(self): - flows = fixture_flows("egress-sample.jsonl") - seen = {} - now = utc(2026, 11, 27, 5, 20) - first = rules.rule_egress_first_seen(flows, seen, now) - self.assertTrue(first) - self.assertTrue(all(f.rule == "egress-new-dst" for f in first)) - # second evaluation over the same flows must be silent - second = rules.rule_egress_first_seen(flows, seen, now) - self.assertEqual(second, []) + NOW = utc(2026, 11, 27, 5, 20) + + def test_new_tuples_produce_findings(self): + flows = fixture_flows("egress-sample.jsonl") + findings = rules.rule_egress_first_seen(flows, {}, self.NOW) + self.assertTrue(findings) + self.assertTrue(all(f.rule == "egress-new-dst" for f in findings)) + + def test_seen_fingerprint_suppresses_the_rule(self): + flows = fixture_flows("egress-sample.jsonl") + first = rules.rule_egress_first_seen(flows, {}, self.NOW) + seen = {f.fingerprint: {"rule": f.rule} for f in first} + self.assertEqual(rules.rule_egress_first_seen(flows, seen, self.NOW), []) + + 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 - def test_union_semantics_keeps_history(self): flows = fixture_flows("egress-sample.jsonl") seen = {} - rules.rule_egress_first_seen(flows, seen, utc(2026, 11, 27, 5, 20)) - before = dict(seen) - # a later, unrelated evaluation must not shrink the seen-set - rules.rule_egress_first_seen([], seen, utc(2026, 11, 27, 5, 25)) - self.assertEqual(seen, before) + first = apply_dedupe(rules.rule_egress_first_seen(flows, seen, self.NOW), + seen, self.NOW.timestamp(), False) + self.assertTrue(first) + again = apply_dedupe(rules.rule_egress_first_seen(flows, seen, self.NOW), + 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), + seen, self.NOW.timestamp(), False) + self.assertEqual([f.fingerprint for f in rearmed], [target]) + + def test_seen_set_is_union_only(self): + from netsec_scan.__main__ import apply_dedupe + + 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), + 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") @@ -44,7 +66,7 @@ class TestFirstSeenEgress(unittest.TestCase): def test_severity_by_port(self): flows = fixture_flows("egress-sample.jsonl") - findings = rules.rule_egress_first_seen(flows, {}, utc(2026, 11, 27, 5, 20)) + 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" @@ -52,7 +74,7 @@ class TestFirstSeenEgress(unittest.TestCase): def test_nonexternal_and_reserved_are_ignored(self): flows = fixture_flows("egress-sample.jsonl") - findings = rules.rule_egress_first_seen(flows, {}, utc(2026, 11, 27, 5, 20)) + findings = rules.rule_egress_first_seen(flows, {}, self.NOW) for f in findings: self.assertNotIn("reserved:", f.entity) self.assertNotIn("192.168.", f.entity) @@ -154,6 +176,20 @@ class TestPromRules(unittest.TestCase): self.assertTrue(rules.rule_http_errors(busy)) +class TestDayCounters(unittest.TestCase): + def test_egress_tuples_union_across_ticks(self): + from netsec_scan.__main__ import record_counters + from netsec_scan import state as state_mod + + st = state_mod.empty() + record_counters(st, 5, [], ["a->1.2.3.4:443/tcp"], 0) + record_counters(st, 7, [], ["a->1.2.3.4:443/tcp", "b->5.6.7.8:80/tcp"], 1) + self.assertEqual(st["day"]["flows"], 12) + self.assertEqual(st["day"]["egress"], ["a->1.2.3.4:443/tcp", "b->5.6.7.8:80/tcp"]) + self.assertEqual(st["totals"]["ticks"], 2) + self.assertEqual(st["totals"]["malformed"], 1) + + class TestOutputShape(unittest.TestCase): def test_render_is_bounded_and_starts_with_severity_and_fingerprint(self): from netsec_scan.__main__ import render diff --git a/tests/test_state.py b/tests/test_state.py index 9a2603c..c885287 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -45,13 +45,13 @@ class TestStateFile(unittest.TestCase): def test_missing_key_is_added_not_replaced(self): st = state_mod.load(self.path) - st["egress"]["a->1.2.3.4:443/tcp"] = "2026-11-27T00:00:00+00:00" + st["seen"]["aaaa"] = {"rule": "x", "first": "2026-11-27T00:00:00+00:00"} state_mod.save(self.path, st) again = state_mod.load(self.path) - again["egress"]["b->5.6.7.8:80/tcp"] = "2026-11-27T00:01:00+00:00" + again["seen"]["bbbb"] = {"rule": "x", "first": "2026-11-27T00:01:00+00:00"} state_mod.save(self.path, again) final = json.loads(self.path.read_text()) - self.assertEqual(len(final["egress"]), 2) + self.assertEqual(sorted(final["seen"]), ["aaaa", "bbbb"]) def test_prune_bounds_the_seen_set(self): st = state_mod.load(self.path)