14 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 ~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
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, 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 second-tick gate:
a first-seen web destination is only worth a line once it appears in two
distinct ticks. Measured 2026-11-27: one CI run produced 20 one-shot AWS/GitHub
CDN destinations inside a single 5-minute window, which is a 20-line message and
exactly how a channel gets muted. CDN rotation is one-shot by nature; a beacon or
an exfil destination is retried, so it still fires — a tick later. Non-web ports
and any DROPPED verdict alert on first sight, and a DROPPED web-port tuple is
HIGH. Rationale and the two-tick evidence live in config.EGRESS_WEB_MIN_TICKS.
Deliberately not implemented (and why):
- 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. - 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
*.jsonlcounts 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 (aJSONDecodeErroron 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:…"}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) |
| 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)
- 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
seenre-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-portLOW for 3100/9093; the rest quiet.