diff --git a/README.md b/README.md index acdfa9b..8e732fe 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,21 @@ count: the same finding keeps the same id across ticks, restarts and days. 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. PromQL findings still speak on the first tick — they are current state. + 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. +* 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 + demonstrably inside those X hours. `archive_baseline: true` in state means + 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. ## The 8 rules @@ -143,8 +157,9 @@ promq 'count by (port) (hubble_port_distribution_total)' promq 'sum(rate(hubble_http_requests_total[15m]))' # rule 6 promq 'sum(rate(hubble_http_requests_total{status=~"4..|5.."}[15m]))' # rule 6 -# rules 7-8: what the flow store says this window -ssh -i ~/.ssh/lancelot_priv Lancelot@10.10.0.2 'sudo -n cat /var/log/netsec/flows-*.jsonl' \ +# rules 7-8: what the flow store says this window (archives are gzip+immutable) +ssh -i ~/.ssh/lancelot_priv Lancelot@10.10.0.2 \ + 'sudo -n sh -c "zcat -f /var/log/netsec/flows-*.jsonl /var/log/netsec/flows-*.jsonl.gz"' \ | python3 -c 'import sys,json,collections c=collections.Counter() for l in sys.stdin: @@ -165,18 +180,42 @@ UTC day rollover. No alert is ever raised from it. * **Flows**: the `netsec/hubble-flow-collector` DaemonSet on siriussec writes filtered JSONL to the host's `/var/log/netsec` (drops, policy verdicts, all L7, and `trace:to-network` whose peer is outside `10.244.0.0/16` + `10.10.0.0/24`). - This sensor reads it over SSH as `Lancelot@10.10.0.2` with `sudo -n`, using a - **per-file byte offset** kept in state — a tick pulls only new bytes. It never + This sensor reads it over SSH as `Lancelot@10.10.0.2` with `sudo -n`. It never polls `hubble observe`: the agent ring buffer is ~28 s at 148 flows/s, so a poll is lossy by design. +* **The store is two shapes and both are read.** The collector gzips a file the + moment it rotates, so `flows--.jsonl` is the single live file and + every closed file is `….jsonl.gz`. `FLOW_PATTERN` is `flows-*.jsonl*`: + * plain files are appended to → read from a **per-file byte offset**, so a + tick pulls only new bytes (a trailing partial line is carried in state); + * archives are **immutable** → read once, whole, `gzip.open(…, "rt")`, and + recorded in `state["archives"]` so they are never re-read. Reading only + `*.jsonl` would leave every rotated file invisible: measured 2026-11-27, + `find -name 'flows-*.jsonl'` = **1** file, `find -name 'flows-*.jsonl*'` = + **5**, i.e. 1/72 of the retained window. + * `*.jsonl*` also matches the collector's in-flight `…jsonl.gz.tmp.` + marker; those are filtered out by name, never read. +* **Archive reads are bounded** (`config.ARCHIVE_MAX_*`): newest first, stop when + the time/byte/file budget is spent, leave the rest unread and reported as + pending. Unbounded is not an option — the 960 MiB cap is ~16 GB of JSON at the + measured 17.5× ratio, and holding it as `Flow` objects would exhaust memory + long before it finished, so flows are handed to the rules in batches + (`FLOW_BATCH`). Measured throughput on the admin host: **~140 MB/s** of + decompressed JSON through `json.loads` + `parse_flow` + egress-key extraction. +* **A torn archive costs a note, not the tick.** A `.gz` that cannot be + decompressed to the end (`EOFError: Compressed file ended before the + end-of-stream marker was reached`) yields the readable prefix, records + `archives[name].error`, is listed in `seed.failed`, and is not retried until + its size changes. * **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 + carries a 37.5 MB startup burst), lower in steady state; ~226 MB/h raw → + ~310 MB/day compressed → 960 MiB ≈ **74 h**. A "not seen before" judgement + therefore comes from this sensor's own cumulative seen-set (which outlives the + files) *plus* the retained window it has actually consumed, and the alert says + which (`window_h`). +* Only collector files (`flows-*.jsonl`, `flows-*.jsonl.gz`) are read; a + rotation tombstone or an in-flight `…gz.tmp.` in the directory is + 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). @@ -214,12 +253,33 @@ credentials, no LLM call, no secret reads. ## Verified behaviour (2026-11-27) -* 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. +* 56 unit tests pass against recorded fixtures (`tests/test_archives.py` covers + the gz path: read-once, torn archive, budget/pending, cold seed, warm-state + archive absorption, single-fire). +* **Cold start on the live store** (state moved aside, `--no-prom --verbose`): + `5 file(s) (4 archive(s), 1 plain), 150225 flows, 116 tuple(s), 116 + fingerprint(s), window 2.06h, 7.34s`, **stdout 0 bytes**, exit 0. The window is + the retained one (the collector was restarted onto the gzip layout at 05:04Z, + so 2.06 h is all that exists today; the same pass scales to the full 74 h cap). +* **Warm tick**: 0.34 s / 0.50 s over two runs (before the change: 0.28 s / + 0.32 s on identical state), stdout empty, exit 0 — archives are not re-read + (`state["archives"][name].read_at` unchanged). +* **Single fire, live, over SSH** against an isolated copy of the store: a + synthetic `203.0.113.77:5000/tcp` line fired exactly one line + (`HIGH … egress-new-dst … (no prior in ~2.1h of observed flows)`) and the next + two ticks were empty; deleting that `seen` entry re-armed exactly one more + line, then silence. +* **Torn archive**: a `.gz` truncated mid-file was noted + (`EOFError: Compressed file ended before the end-of-stream marker was + reached`, prefix of 2628 lines kept), the tick exited 0, and the next tick was + silent. +* **Budget**: `ARCHIVE_MAX_FILES=1` against 3 archives → `pending 2`, `seeded + false`, window 1.14 h; the next tick `pending 1`, 1.98 h; the third completes + at 2.14 h and seeds. The alert window grows with the evidence instead of + claiming the full retention up front. +* Baseline tick seeded the retained window silently and wrote the state file and + `reports/2026-11-27.json` (which now carries `window_h`, `covered_since`, + `seed`, and per-shape file counts). * 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 diff --git a/netsec_scan/__main__.py b/netsec_scan/__main__.py index 98320fe..65682a9 100644 --- a/netsec_scan/__main__.py +++ b/netsec_scan/__main__.py @@ -17,14 +17,19 @@ import time import traceback from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple +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, ) @@ -69,14 +74,107 @@ def render(finding: Finding) -> str: return line -def collect_flows(store: BaseStore, st: Dict[str, Any], verbose: bool) -> Tuple[List, int, int]: - """Read every un-consumed byte of every collector file; parse complete lines.""" +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() - parsed = [] - malformed = 0 - live = set() - for name, size in files: - live.add(name) + 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 @@ -84,60 +182,102 @@ def collect_flows(store: BaseStore, st: Dict[str, Any], verbose: bool) -> Tuple[ 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: - line = line.strip() - if not line: - continue - try: - obj = json.loads(line) - except ValueError: - malformed += 1 - continue - flow = parse_flow(obj) - if flow is None: - malformed += 1 - continue - parsed.append(flow) + 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) - # Forget files the collector rotated away (their bytes are already consumed). + + 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) - return parsed, malformed, len(files) + for name in list(known): + if name not in live: + known.pop(name, None) + + stats["seconds"] = round(time.monotonic() - started, 2) + return stats -def track_window(st: Dict[str, Any], flows: List) -> Optional[float]: - """Hours of flow history this sensor has actually observed. +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. - 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 ". + 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. """ - 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"] + 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.""" + """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) @@ -227,9 +367,44 @@ def main(argv: Optional[List[str]] = None) -> int: return 2 try: - flows, malformed, file_count = collect_flows(store, st, args.verbose) - log("parsed %d flows from %d file(s), %d malformed" - % (len(flows), file_count, malformed), args.verbose) + # 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: @@ -242,36 +417,58 @@ 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)) - seeding = not st.get("seeded") - window_h = track_window(st, flows) - 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 - 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: - st["seen"].setdefault(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"), - "seeded": True, - }) - st["seeded"] = True - st["seeded_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds") - log("seed run: %d flow findings recorded silently" % len(flow_findings), - args.verbose) + 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, len(flows), emitted, rules.egress_keys(flows), malformed) + record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"]) state_mod.prune(st) if not args.dry_run: diff --git a/netsec_scan/config.py b/netsec_scan/config.py index d73233e..355205d 100644 --- a/netsec_scan/config.py +++ b/netsec_scan/config.py @@ -32,9 +32,31 @@ SSH_HOST = os.environ.get("NETSEC_SCAN_SSH_HOST", "Lancelot@10.10.0.2") SSH_KEY = os.environ.get("NETSEC_SCAN_SSH_KEY", str(HOME / ".ssh" / "lancelot_priv")) SSH_TIMEOUT = int(os.environ.get("NETSEC_SCAN_SSH_TIMEOUT", "60")) FLOW_DIR = os.environ.get("NETSEC_SCAN_FLOW_DIR", "/var/log/netsec") -FLOW_PATTERN = os.environ.get("NETSEC_SCAN_FLOW_PATTERN", "flows-*.jsonl") +# The collector gzips a file the moment it rotates (t_cfea18ac), so the store is +# `flows--.jsonl` (the live file) plus `flows--.jsonl.gz` +# (closed, immutable). Without the trailing `*` the sensor can only see the live +# file — i.e. minutes of the ~74 h the 960 MiB cap actually retains. +FLOW_PATTERN = os.environ.get("NETSEC_SCAN_FLOW_PATTERN", "flows-*.jsonl*") FLOW_GLOB = FLOW_DIR + "/" + FLOW_PATTERN +# ------------------------------------------------- archival seed budget ---- +# Archives are read once, whole, and only at cold start / right after a +# rotation. Unbounded is not an option: 960 MiB of gzip is ~16 GB of JSON at the +# measured 17.5x ratio, and holding that as Flow objects would exhaust memory +# long before it finished. Measured on the admin host 2026-11-27: json.loads + +# parse_flow + egress-key extraction runs at ~140 MB/s of decompressed JSON, so +# these defaults are sized for a one-time seed of ~12 GB (~55 h of current +# volume) and a warm tick, which reads zero or one archive, finishes in ~1 s. +# Whichever budget binds first wins; the window actually covered is printed and +# persisted, never implied. +ARCHIVE_MAX_SECONDS = float(os.environ.get("NETSEC_SCAN_ARCHIVE_SECONDS", "90")) +ARCHIVE_MAX_BYTES = int(os.environ.get("NETSEC_SCAN_ARCHIVE_BYTES", str(8 * 1024 ** 3))) +ARCHIVE_MAX_FILES = int(os.environ.get("NETSEC_SCAN_ARCHIVE_FILES", "40")) + +# Flows are consumed in batches so a seed never holds the whole window in RAM as +# Flow objects (16 GB of JSON is millions of them). +FLOW_BATCH = int(os.environ.get("NETSEC_SCAN_FLOW_BATCH", "20000")) + # ----------------------------------------------------- prometheus ---- PROM_PROXY = ( "/api/v1/namespaces/monitoring/services/" diff --git a/netsec_scan/flows.py b/netsec_scan/flows.py index 7dd108b..703c84e 100644 --- a/netsec_scan/flows.py +++ b/netsec_scan/flows.py @@ -1,29 +1,36 @@ """Flow-store access and parsing. -Two sources, one parser: +Three sources, one parser: -* `RemoteFlowStore` reads the collector's JSONL on siriussec over SSH with a - per-file byte offset, so a 5-minute tick pulls only the new bytes (the whole - retained window is <= 1 GiB, but 900 MiB every tick would be absurd). +* `RemoteFlowStore` reads the collector's JSONL on siriussec over SSH. Plain + `.jsonl` files are appended to by the collector, so they are read with a + per-file byte offset and only new bytes are pulled each tick. `.jsonl.gz` + archives are immutable once renamed into place (the collector gzips to a + temp name and renames), so each one is read once, in full. * `LocalFlowStore` reads a directory (tests, fixtures, dev). +* `SingleFileStore` reads one fixture file (the `--fixture` path). -Only complete lines are consumed; a trailing partial line is carried in state -and re-parented to the next tick. +Only complete lines are consumed; a trailing partial line in a live file is +carried in state and re-parented to the next tick. """ from __future__ import annotations +import gzip import hashlib +import io import ipaddress import json import os +import re import shlex import shutil import subprocess +import zlib from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path -from typing import Dict, Iterable, List, Optional, Tuple +from typing import Dict, Iterable, Iterator, List, Optional, Tuple from . import config from .prom import SensorError @@ -188,6 +195,70 @@ def iter_lines(data: bytes) -> Tuple[List[str], bytes]: return complete.split("\n"), data[idx + 1:] +# ------------------------------------------------------- archive names ---- +# The collector's own naming contract (apps/base/netsec/collect.sh): +# flows--.jsonl live, appended to +# flows--.jsonl.gz closed, immutable +# flows--.jsonl.gz.tmp. gzip in flight +# is the moment the file was *opened*, so it is the start of that +# file's coverage — min(stamps) is exactly "how far back these files go". +_STAMP_RE = re.compile(r"^flows-(\d{8}T\d{6}Z)-\d+\.jsonl(?:\.gz)?$") + + +def is_archive(name: str) -> bool: + return name.endswith(".jsonl.gz") + + +def is_plain(name: str) -> bool: + return name.endswith(".jsonl") + + +def is_usable(name: str) -> bool: + """A file the sensor may read: not in flight, not half-named. + + `.jsonl*` also matches the collector's `…jsonl.gz.tmp.` marker, which + is an in-progress gzip — reading it would be a torn stream every rotation. + """ + base = os.path.basename(name) + if ".tmp" in base or not base.startswith("flows-"): + return False + return is_archive(base) or is_plain(base) + + +def flow_stamp(name: str) -> Optional[datetime]: + """Coverage start of a collector file, from its name (UTC).""" + match = _STAMP_RE.match(os.path.basename(name)) + if not match: + return None + try: + return datetime.strptime(match.group(1), "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc) + except ValueError: + return None + + +class ArchiveTruncated(Exception): + """A `.gz` that could not be decompressed to the end. + + Raised *after* the readable prefix has been yielded, so a torn archive + costs the tail of one file and never the tick. + """ + + +def iter_archive(store: "BaseStore", name: str) -> Iterator[str]: + """Yield decoded lines from an immutable archive, decompressing lazily. + + Whole-file reads into a list are avoided on purpose: one live file is up to + 150 MB and a seed walks many of them. + """ + data = store.read_from(name, 0) + try: + with gzip.open(io.BytesIO(data), mode="rt", encoding="utf-8", errors="replace") as handle: + for line in handle: + yield line + except (EOFError, gzip.BadGzipFile, zlib.error, OSError) as exc: + raise ArchiveTruncated("%s: %s" % (type(exc).__name__, exc)) + + # --------------------------------------------------------------- stores ---- class BaseStore: def list_files(self) -> List[Tuple[str, int]]: @@ -251,7 +322,10 @@ class RemoteFlowStore(BaseStore): parts = line.rsplit(" ", 1) if len(parts) != 2 or not parts[1].isdigit(): continue - files.append((os.path.basename(parts[0]), int(parts[1]))) + name = os.path.basename(parts[0]) + if not is_usable(name): # in-flight gzip and the like + continue + files.append((name, int(parts[1]))) if not files: raise SensorError("no-flows-file", "collector directory is empty on %s" % self.host) return files @@ -275,10 +349,12 @@ class LocalFlowStore(BaseStore): def list_files(self) -> List[Tuple[str, int]]: files = [] - for path in sorted(self.directory.glob("flows-*.jsonl")): + for path in sorted(self.directory.glob(config.FLOW_PATTERN.split("/")[-1])): + if not is_usable(path.name): + continue files.append((path.name, path.stat().st_size)) if not files: - raise SensorError("no-flows-file", "no flows-*.jsonl in %s" % self.directory) + raise SensorError("no-flows-file", "no %s in %s" % (config.FLOW_PATTERN, self.directory)) return files def read_from(self, name: str, offset: int) -> bytes: diff --git a/netsec_scan/report.py b/netsec_scan/report.py index eb93735..3b77228 100644 --- a/netsec_scan/report.py +++ b/netsec_scan/report.py @@ -32,6 +32,14 @@ def build(state: Dict[str, Any]) -> Dict[str, Any]: "egress_tuples": sorted(egress), "top_new_destinations": new_dsts[-10:], "seen_fingerprints_cumulative": len(state.get("seen", {})), + # The baseline this sensor actually holds: which files it consumed and + # the window they cover. "no prior in ~Xh" comes from this, never from a + # guess. + "window_h": state.get("window_h"), + "covered_since": state.get("observed_since"), + "seed": state.get("seed") or {}, + "files": {"plain": len(state.get("files") or {}), + "archives": len(state.get("archives") or {})}, "state_totals": state.get("totals", {}), } diff --git a/netsec_scan/rules.py b/netsec_scan/rules.py index 473ee17..409a53e 100644 --- a/netsec_scan/rules.py +++ b/netsec_scan/rules.py @@ -197,7 +197,7 @@ def _window_label(hours: float) -> str: def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict], counts: Dict[str, dict], now: datetime, - window_h: float = None, tick: int = 0) -> List[Finding]: + window_h: Optional[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), diff --git a/netsec_scan/state.py b/netsec_scan/state.py index f693ac0..1a33f07 100644 --- a/netsec_scan/state.py +++ b/netsec_scan/state.py @@ -36,7 +36,10 @@ def empty() -> Dict[str, Any]: "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} + "files": {}, # name -> {offset, carry, size} (plain, appended to) + "archives": {}, # name -> {size, read_at, lines} (.jsonl.gz, read once) + "archive_baseline": False, # archives have been baselined once (absorbed silently) + "seed": {}, # summary of the baseline run: window, files, tuples "degraded": {}, # failure class -> iso of last announcement "day": {"date": datetime.now(timezone.utc).strftime("%Y-%m-%d"), "flows": 0, "rules": {}, "egress": [], "new_dsts": []}, @@ -57,7 +60,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", "egress_counts", "files", "degraded"): + for key in ("seen", "beacon", "egress_counts", "files", "archives", "degraded"): if not isinstance(data.get(key), dict): data[key] = {} return data diff --git a/tests/test_archives.py b/tests/test_archives.py new file mode 100644 index 0000000..a872425 --- /dev/null +++ b/tests/test_archives.py @@ -0,0 +1,226 @@ +"""Archive handling: `.jsonl.gz` is read once, bounded, and never fatal. + +The collector gzips a file when it rotates, so the retained window is archives +plus one live plain file. These tests pin the three properties that matter: +a cold start baselines from the archives, a torn archive costs a note and not +the tick, and the seed budget leaves the rest unread instead of pretending to a +window it never examined. +""" + +from __future__ import annotations + +import contextlib +import gzip +import io +import json +import shutil +import tempfile +import unittest +from pathlib import Path + +from helpers import FIXTURES, fixture_lines + +from netsec_scan import __main__ as cli +from netsec_scan import config, state as state_mod +from netsec_scan.flows import ( + ArchiveTruncated, + LocalFlowStore, + flow_stamp, + is_usable, + iter_archive, +) + +LIVE = "flows-20261127T060000Z-1.jsonl" +ARCH_NEW = "flows-20261127T050000Z-1.jsonl.gz" +ARCH_OLD = "flows-20261127T040000Z-2.jsonl.gz" + + +def _adopted_dir(root: Path) -> None: + """Two archives and one live file, all built from the real egress fixture.""" + lines = fixture_lines("egress-sample.jsonl") + for name in (ARCH_OLD, ARCH_NEW): + 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") + + +def _synthetic_flow(dst="203.0.113.77", port=5000) -> str: + """One workload->world line on a non-web port (fires on the first tick).""" + obj = json.loads(fixture_lines("egress-sample.jsonl")[0]) + obj["flow"]["IP"]["destination"] = dst + proto = next(iter(obj["flow"]["l4"])) + obj["flow"]["l4"][proto]["destination_port"] = port + return json.dumps(obj) + + +class TestArchiveNames(unittest.TestCase): + def test_stamp_is_the_coverage_start(self): + new = flow_stamp(ARCH_NEW) + live = flow_stamp("/var/log/netsec/" + LIVE) + self.assertIsNotNone(new) + self.assertIsNotNone(live) + assert new is not None and live is not None + self.assertEqual(new.isoformat(), "2026-11-27T05:00:00+00:00") + self.assertEqual(live.isoformat(), "2026-11-27T06:00:00+00:00") + self.assertIsNone(flow_stamp("flows-nonsense.jsonl")) + + def test_inflight_gzip_and_foreign_names_are_not_usable(self): + self.assertTrue(is_usable(ARCH_NEW)) + self.assertTrue(is_usable(LIVE)) + self.assertFalse(is_usable("flows-20261127T050000Z-1.jsonl.gz.tmp.4242")) + self.assertFalse(is_usable("notes.jsonl")) + + def test_listing_covers_archives_and_skips_inflight(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _adopted_dir(root) + (root / "flows-20261127T070000Z-1.jsonl.gz.tmp.7").write_bytes(b"marker") + names = sorted(name for name, _size in LocalFlowStore(tmp).list_files()) + self.assertEqual(names, sorted([ARCH_NEW, ARCH_OLD, LIVE])) + + +class TestArchiveReader(unittest.TestCase): + def test_reads_a_gzip_archive(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _adopted_dir(root) + store = LocalFlowStore(tmp) + lines = list(iter_archive(store, ARCH_NEW)) + self.assertEqual(len([ln for ln in lines if ln.strip()]), + len(fixture_lines("egress-sample.jsonl"))) + + def test_truncated_archive_yields_what_it_can_then_raises(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _adopted_dir(root) + whole = (root / ARCH_NEW).read_bytes() + (root / ARCH_NEW).write_bytes(whole[: len(whole) // 2]) + seen = 0 + with self.assertRaises(ArchiveTruncated): + for _line in iter_archive(LocalFlowStore(tmp), ARCH_NEW): + seen += 1 + self.assertGreaterEqual(seen, 0) # prefix is kept, tick survives + + +class TestColdStart(unittest.TestCase): + """End-to-end through main(): the state file is the only thing that matters.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.flows = self.root / "flows" + self.flows.mkdir() + _adopted_dir(self.flows) + self.state = self.root / "state.json" + self.reports = self.root / "reports" + + def tearDown(self): + self.tmp.cleanup() + + def tick(self) -> str: + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer), contextlib.redirect_stderr(io.StringIO()): + code = cli.main(["--flows-dir", str(self.flows), "--no-prom", + "--state", str(self.state), "--reports", str(self.reports)]) + self.assertEqual(code, 0) + return buffer.getvalue() + + def test_seed_reads_archives_silently_and_the_next_tick_is_quiet(self): + self.assertEqual(self.tick(), "") # no alert storm + st = state_mod.load(self.state) + self.assertTrue(st["seeded"]) + self.assertEqual(set(st["archives"]), {ARCH_NEW, ARCH_OLD}) + self.assertEqual(st["observed_since"], "2026-11-27T04:00:00+00:00") + self.assertGreater(len(st["egress_counts"]), 0) + # Every distinct tuple in the window is in the baseline, including the + # web-port ones the 3-tick gate never turns into a finding. + self.assertEqual(len(st["seen"]), len(st["egress_counts"])) + self.assertEqual(st["seed"]["archives"], 2) + self.assertEqual(self.tick(), "") # warm tick, still quiet + + def test_warm_state_meeting_archives_for_the_first_time_absorbs_them(self): + """The upgrade case: a seeded sensor whose baseline was the live file only. + + The archives hold tuples that are *inside* the window the alert would + quote, so announcing them would state a falsehood ("no prior in ~Xh") + and produce a burst. They are absorbed instead; the live file still + alerts normally. + """ + st = state_mod.empty() + st["seeded"] = True # baseline built before archives existed + state_mod.save(self.state, st) + self.assertEqual(self.tick(), "") # archives absorbed, nothing announced + after = state_mod.load(self.state) + self.assertTrue(after["archive_baseline"]) + self.assertGreaterEqual(len(after["seen"]), len(after["egress_counts"])) + # A genuinely new live destination still speaks. + with open(self.flows / LIVE, "a", encoding="utf-8") as handle: + handle.write(_synthetic_flow() + "\n") + out = self.tick() + self.assertEqual(len(out.strip().splitlines()), 1, out) + self.assertIn("203.0.113.77:5000/tcp", out) + + def test_archive_is_not_reread_on_a_warm_tick(self): + self.tick() + before = state_mod.load(self.state)["archives"][ARCH_NEW]["read_at"] + self.tick() + after = state_mod.load(self.state)["archives"][ARCH_NEW]["read_at"] + self.assertEqual(before, after) + + def test_synthetic_destination_fires_once_and_only_once(self): + self.tick() + with open(self.flows / LIVE, "a", encoding="utf-8") as handle: + handle.write(_synthetic_flow() + "\n") + first = self.tick() + self.assertEqual(len(first.strip().splitlines()), 1, first) + self.assertIn("203.0.113.77:5000/tcp", first) + self.assertIn("egress-new-dst", first) + self.assertEqual(self.tick(), "") # exactly once + + def test_deleting_the_fingerprint_re_arms_one_line(self): + self.tick() + with open(self.flows / LIVE, "a", encoding="utf-8") as handle: + handle.write(_synthetic_flow() + "\n") + first = self.tick().strip() + st = state_mod.load(self.state) + fp = first.split()[1] + del st["seen"][fp] + state_mod.save(self.state, st) + with open(self.flows / LIVE, "a", encoding="utf-8") as handle: + handle.write(_synthetic_flow() + "\n") + again = self.tick() + self.assertEqual(len(again.strip().splitlines()), 1, again) + self.assertEqual(again.split()[1], fp) + self.assertEqual(self.tick(), "") + + def test_truncated_archive_is_noted_not_fatal(self): + whole = (self.flows / ARCH_NEW).read_bytes() + (self.flows / ARCH_NEW).write_bytes(whole[: len(whole) // 2]) + self.assertEqual(self.tick(), "") # tick survives + st = state_mod.load(self.state) + self.assertIn(ARCH_NEW, st["archives"]) + self.assertIn("EOFError", st["archives"][ARCH_NEW]["error"]) + self.assertIn(ARCH_NEW, st["seed"]["failed"]) + self.assertEqual(self.tick(), "") + + def test_budget_leaves_archives_pending_instead_of_narrowing_silently(self): + original = config.ARCHIVE_MAX_FILES + config.ARCHIVE_MAX_FILES = 1 + try: + self.assertEqual(self.tick(), "") + st = state_mod.load(self.state) + self.assertFalse(st["seeded"], "a partial baseline is not a baseline") + self.assertEqual(len(st["archives"]), 1) + self.assertEqual(st["seed"]["pending"], 1) + # The next tick continues; once nothing is pending it seeds. + self.tick() + st = state_mod.load(self.state) + self.assertTrue(st["seeded"]) + self.assertEqual(st["seed"]["pending"], 0) + self.assertEqual(len(st["archives"]), 2) + finally: + config.ARCHIVE_MAX_FILES = original + + +if __name__ == "__main__": + unittest.main()