Silent ticks (empty stdout, exit 0), one line per stable fingerprint, cumulative union-only seen-set at ~/.hermes/cron/netsec-scan-state.json, memoized sensor- degradation line, daily baseline report. Stdlib only; reads the collector's JSONL over SSH with per-file byte offsets and Prometheus via the k8s API proxy. 40 unit tests against fixtures recorded from the live collector.
11 KiB
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 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)
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
seenis a cumulative, union-only mapfp -> {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
seensilently instead of dumping weeks of history into chat. PromQL findings still speak on the first tick — they are current state.
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) / 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 |
| 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 |
Deliberately not implemented (and why):
- Per-workload PromQL rules. The
podlabel on everyhubble_*metric is the Cilium agent pod (pod="cilium-vs7sb"), not the workload. A ruleby (pod)measures agents and is permanently flat. Workload attribution comes from the flow JSONL instead. Noby (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,.envprobes, scanner UAs).cilium-envoyemits no access log (audit finding F7, cardt_e662b03a), so there is no data source. When that card lands, this is where the parser goes. verdict != FORWARDEDas 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
ssh -i ~/.ssh/lancelot_priv [email protected] 'sudo -n cat /var/log/netsec/flows-*.jsonl' \
| 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-collectorDaemonSet on siriussec writes filtered JSONL to the host's/var/log/netsec(drops, policy verdicts, all L7, andtrace:to-networkwhose peer is outside10.244.0.0/16+10.10.0.0/24). This sensor reads it over SSH as[email protected]withsudo -n, using a per-file byte offset kept in state — a tick pulls only new bytes. It never pollshubble observe: the agent ring buffer is ~28 s at 148 flows/s, so a poll is lossy by design. - 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:…"}beforeIP, so an unanchored"source":"match hands you a MAC. - Workload identity is
namespace/workloadfrom the peer'sworkloads[]ork8s:applabel — 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) |
| 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 |
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)
- 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
seenre-emits exactly one line, and the immediately following run is silent. - Cron delivery proven through
~/.hermes/cron/executions.db(delivery_outcome=delivered) — see the task handoff for the transcript.