Deterministic network-security sensor for the Sirius homelab: PromQL tripwires + Hubble flow-store novelty rules, run by a 5-minute Hermes cron tick (silent when calm).
  • Python 99.8%
  • Shell 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Sirius DevOps ba1bef3814 netsec-scan: read flows-*.jsonl.gz so a cold start baselines the retained window, not the live file
The collector gzips on rotation, so FLOW_PATTERN 'flows-*.jsonl' saw 1 of 5
files (measured: 1/72 of the retained window). Archives are immutable, so each
is read once, whole, decrypted lazily and recorded in state['archives'].

- archives are bounded (ARCHIVE_MAX_SECONDS/BYTES/FILES, newest first) and
  flows are consumed in batches; a partial pass leaves state seeded=false and
  reports the unread files as pending, so the next tick continues instead of
  alerting from a window it has not examined
- the alert window comes from the coverage start in the consumed filenames
  (monotone), so 'no prior in ~Xh of observed flows' is now verifiable
- the seed absorbs every egress tuple in the window, not just findings (a
  web-port tuple never becomes one on its first tick); a warm state meeting
  archives for the first time absorbs them the same way
- a torn .gz keeps its readable prefix, is noted in state/seed.failed, and does
  not abort the tick; in-flight *.gz.tmp.* markers are never read
- report.json carries window_h/covered_since/seed; 12 new tests
2026-11-27 02:09:51 -05:00
netsec_scan netsec-scan: read flows-*.jsonl.gz so a cold start baselines the retained window, not the live file 2026-11-27 02:09:51 -05:00
reports netsec-scan: deterministic sensor (6 PromQL tripwires + 2 flow-store novelty rules) 2026-11-27 00:20:46 -05:00
tests netsec-scan: read flows-*.jsonl.gz so a cold start baselines the retained window, not the live file 2026-11-27 02:09:51 -05:00
.gitignore netsec-scan: deterministic sensor (6 PromQL tripwires + 2 flow-store novelty rules) 2026-11-27 00:20:46 -05:00
README.md netsec-scan: read flows-*.jsonl.gz so a cold start baselines the retained window, not the live file 2026-11-27 02:09:51 -05:00
run.sh netsec-scan: deterministic sensor (6 PromQL tripwires + 2 flow-store novelty rules) 2026-11-27 00:20:46 -05:00

netsec-agent

Deterministic network-security sensor for the Sirius homelab cluster.

The LLM never decides whether something is odd. This program decides, in code, cheaply, and emits one line per fingerprint. A Hermes cron job runs it every 5 minutes; its stdout is the alert (the gateway owns delivery). Waking an investigator agent on a hit is a separate, deliberate step — not done here.

                  ┌──────────────────────────────┐
 Prometheus ─────▶│                              │──▶ stdout: nothing (calm)
 (kubectl get     │        netsec_scan           │    or 1 line per fingerprint
  --raw, read-only)│                              │
 /var/log/netsec ─▶│  (SSH + sudo -n, byte-offset │──▶ state: cumulative seen-set
  (collector JSONL)│   incremental reads)         │──▶ reports/YYYY-MM-DD.json
                  └──────────────────────────────┘

Layout

Path What
netsec_scan/ the program (Python 3, stdlib only — no pip install on the host)
netsec_scan/config.py every tunable, next to the measurement it came from
netsec_scan/rules.py the 8 rules
netsec_scan/flows.py collector access (remote byte-offset reads) + Cilium flow parsing
netsec_scan/prom.py PromQL through the k8s API proxy
netsec_scan/state.py cumulative seen-set, offsets, report counters
netsec_scan/report.py daily baseline report
run.sh entrypoint (exec python3 -m netsec_scan "$@" from the repo root)
tests/ unit tests + 3 small fixtures recorded from the live collector

Run it by hand:

cd ~/Projects/netsec-agent && ./run.sh            # silent tick, exit 0
./run.sh --verbose                                # same, diagnostics on stderr
./run.sh --fixture tests/fixtures/beacon-shaped.jsonl --dry-run   # what-would-I-say
python3 -m unittest discover -s tests             # 40 tests, no network

Output contract

Situation stdout exit
calm tick empty — no "monitoring N flows" line, ever 0
hit one line per fingerprint, SEV <fp12> <rule> <detail>, ≤ 200 chars 0
sensor input unavailable one memoized line naming the class (HTTP 503, timeout, no-flows-file, …) non-zero, state file untouched

Example:

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 count: the same finding keeps the same id across ticks, restarts and days.

Dedupe model

  • seen is a cumulative, union-only map fp -> {rule, kind, entity, severity, first, last_alert}, persisted at ~/.hermes/cron/netsec-scan-state.json (not inside a {job_id} directory — the scheduler reclaims those). It is never replaced by the current tick's findings, so a transiently-empty read cannot re-alert history.
  • Novelty rules (egress-new-dst, beacon-shape) fire once, ever per fp.
  • 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.
  • 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

Six PromQL tripwires (read-only, via kubectl get --raw /api/v1/namespaces/monitoring/services/http:kube-prometheus-stack-prometheus:9090/proxy/api/v1/query) and two flow-store rules (/var/log/netsec/*.jsonl on siriussec).

# Rule Severity What it detects Threshold Backing series (2026-11-27)
1 hubble-loss HIGH Hubble ring-buffer loss — the rule that says the other rules are blind sum by(node)(rate(hubble_lost_events_total[15m])) > 0.05/s 3 (siriussec 0.60, linode 0.13, rpi 0.00)
2 drop-spike MEDIUM TCP/UDP drop-rate spike vs a 1 h baseline (ICMPv6 neighbour-discovery noise excluded) > 0.05/s and > 3× 1 h baseline 4 series by reason/protocol; TCP/ICMPv6 split measured
3 syn-sweep MEDIUM connects that never complete (SYN without SYN-ACK) SYN > 1/s and ratio > 3 4 (SYN 10.6/s, SYN-ACK 6.7/s → ratio 1.59 at idle)
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, 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.

Rule 7 also keeps web-port novelty (80/443/8080/8443) on a three-tick (~15 min) persistence gate: a first-seen web destination is only worth a line once it appears in three distinct ticks. Measured 2026-11-27: one CI run produced 20 one-shot AWS/GitHub CDN destinations inside a single 5-minute window (a 20-line message) and a two-tick gate still let ~2 per build through. CDN rotation is one-shot or short-lived; a beacon or an exfil destination persists. Stated cost: a smash-and-grab that contacts a brand-new host twice and stops is not alerted on 80/443/8080/8443 — it is on any other port and on any DROPPED verdict, and periodic C2 is rule 8's job (beacon-shape, ≥ 20 conns in 2 h). Non-web ports alert on first sight; a DROPPED web-port tuple is HIGH. Rationale and the measured numbers live in config.EGRESS_WEB_MIN_TICKS.

Deliberately not implemented (and why):

  • Per-workload PromQL rules. The pod label on every hubble_* metric is the Cilium agent pod (pod="cilium-vs7sb"), not the workload. A rule by (pod) measures agents and is permanently flat. Workload attribution comes from the flow JSONL instead. No by (pod) exists anywhere in this code.
  • hubble_dns_* / DNS response codes. The metric family does not exist in this build (0 series).
  • HTTP attack-shape text rules (../, union select, .env probes, scanner UAs). cilium-envoy emits no access log (audit finding F7, card t_e662b03a), so there is no data source. When that card lands, this is where the parser goes.
  • verdict != FORWARDED as its own rule. It fires permanently at rest (constant ICMPv6 L3 drops) — a day-one false positive. TCP/UDP drops are covered by rule 2 instead.
  • East-west / identity-flip rules. Useful, but they need a policy baseline that does not exist yet (3 NetworkPolicies cluster-wide). Adding them now would be noise, and noise mutes the channel.

new-port is LOW and drop-spike carries a floor for the same reason: a rule that can be made quiet only by hiding a real signal gets dropped instead of tuned, per the design note.

Re-deriving a baseline

Each rule's number is a one-liner. Re-run these before changing a threshold:

promq() { kubectl get --raw "/api/v1/namespaces/monitoring/services/http:kube-prometheus-stack-prometheus:9090/proxy/api/v1/query?query=$(python3 -c 'import sys,urllib.parse;print(urllib.parse.quote(sys.argv[1]))' "$1")"; }

promq 'sum by (node) (rate(hubble_lost_events_total[15m]))'                       # rule 1
promq 'sum by (reason,protocol) (rate(hubble_drop_total[5m]))'                    # rule 2
promq 'sum by (flag) (rate(hubble_tcp_flags_total[5m]))'                          # rules 3-4
promq 'count by (port) (hubble_port_distribution_total)'                          # rule 5
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 (archives are gzip+immutable)
ssh -i ~/.ssh/lancelot_priv [email protected] \
  '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:
    f=json.loads(l)["flow"]; ip=f.get("IP") or {}
    w=(f.get("source") or {}).get("namespace"); d=ip.get("destination")
    l4=f.get("l4") or {}; p=next(iter(l4),None)
    if w and d and p: c[(w,d,(l4[p] or {}).get("destination_port"))]+=1
for k,v in c.most_common(20): print(v,k)'

The daily report (reports/YYYY-MM-DD.json) is the same data written down: counts per rule, flows seen that day, egress tuples seen, top 10 new destinations. It is refreshed on every tick (so "today" always exists) and becomes final at the UTC day rollover. No alert is ever raised from it.

Where the inputs come from

  • 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 [email protected] 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-<UTCstamp>-<n>.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.<pid> 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; ~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.<pid> 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).
  • Prometheus: the monitoring Service through the API proxy, read-only, no port-forward, no new credentials.

Flow parsing notes (learned the hard way)

  • Anchor field extraction on the "IP":{…} object: trace lines carry "ethernet":{"source":"98:fa:…"} before IP, so an unanchored "source":" match hands you a MAC.
  • Workload identity is namespace/workload from the peer's workloads[] or k8s:app label — never the pod name, which changes on every rollout and would mint a new fingerprint each deploy.
  • reserved:* peers (host, world, remote-node, ingress) are not workloads. The node's own egress to CDN IPs would otherwise dominate rule 7 with churn.
  • Destinations in pod/mesh/service/LAN/CGNAT/link-local/multicast space are not egress; documentation ranges (203.0.113.0/24 & co) are treated as external so a synthetic fixture behaves like a real destination.

Deployment

Piece Where
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 <HERMES_HOME>/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 local (see below), wrap_response off, catch_up false
delivery deliver: local — this profile has platforms.telegram.enabled: false, so deliver: telegram fails with no delivery target resolved for deliver=telegram (observed on the 00:30 run). The tick's output is therefore captured verbatim in ~/.hermes/profiles/devops/cron/output/<job_id>/<stamp>.md and in executions.db. Pointing it at a real channel is a gateway/config decision (or the wake-path card), not something this sensor can fix; do not set deliver: telegram here without a channel, or every hit reports delivery_outcome: failed instead of landing in the run doc.
state ~/.hermes/cron/netsec-scan-state.json (+ .memo.json for degradation wording)
reports ~/Projects/netsec-agent/reports/YYYY-MM-DD.json

Blast radius: one program, one shim, one cron job. No cluster writes, no credentials, no LLM call, no secret reads.

Verified behaviour (2026-11-27)

  • 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 events/s) and linode (0.13-3.2 events/s); new-port LOW for 3100/9093; the rest quiet.