- Python 99.8%
- Shell 0.2%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
F7 (t_e662b03a) gave every Gateway listener a JSON access line and shipped it to Loki; this is the §4d consumer that had none. New `http_rules.py` classifies candidate lines and `loki.py` reads them through the logging/loki Service proxy with two LogQL queries per tick - a `|~` prefilter for attack-shaped lines and a `sum by (client_ip, peer)` 1-minute matrix for 401/403. Loki does the volume reduction: a calm 10-minute window (5 474 requests / 3.5 MB) puts ~150 lines on the wire. Rules (one line per host+client+category, fingerprint excludes the path): http-traversal, -sqli, -nul-byte, -secret-probe, -vcs-probe, -backup-probe, -scanner-ua, http-auth-brute (401/403 only, >=20/min and >=30 in 5m per coalesce(client_ip, peer)), http-flood (cap 12 new fingerprints/tick). FP control is the point: Forgejo is 93.5 % of the stream, so smart-HTTP git endpoints and browse/archive/RSS URLs on the Forgejo hosts are excluded from path rules, and severity escalates only when the shape is in the path component AND the origin answered 2xx (a 200 on `/?file=../../.env` is the landing page). Measured: 17 639 of 35 445 lines/hour are 303 -> /user/login (3xx, never counted); 293 are 404 crawler churn; the noisiest legitimate 401/403 client does 3/min. Verified on the live stream: calm window 07:03:40-07:13:40Z -> 0 findings, empty stdout, exit 0; the 06:48-06:53Z 91.92.47.0/24 burst -> 8 findings; crafted requests fired all nine rule kinds (public via Cloudflare and direct to the overlay for the peer fallback); first tick baselines silently, next emits, next is silent, deleting one fingerprint re-emits exactly one line. 85 unit tests. Docs: docs/gateway-http-rules.md. run.sh now cds to its own directory so a worktree runs its own code. |
||
| docs | ||
| netsec_scan | ||
| reports | ||
| tests | ||
| .gitignore | ||
| README.md | ||
| run.sh | ||
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 flow/metric rules (Finding lives here) |
netsec_scan/http_rules.py |
the §4d gateway access-log rules (classification, FP control, caps) |
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/loki.py |
LogQL through the k8s API proxy (gateway access log) |
netsec_scan/state.py |
cumulative seen-set, offsets, report counters |
netsec_scan/report.py |
daily baseline report |
docs/gateway-http-rules.md |
rule catalogue, FP reasoning, measurements for the HTTP rules |
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
./run.sh --http --flows-dir /tmp/empty --dry-run # gateway rules only, no SSH
python3 -m unittest discover -s tests # 89 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: while
seededis false at tick start, the flow-store rules still run (they build the egress counts and beacon history a warm tick needs) but every result is absorbed intoseenand nothing is printed — not just the first pass. That covers--dry-runtoo (history is not news in a dry run either) and it is why the cron's delivery outcome for a seed tick issuppressed. Each seeding tick writes one explanatory line to stderr:seed: N tuple(s) absorbed, 0 reported; window Xh from <stamp>, N file(s). The baseline holds every distinct egress tuple in the 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: truein 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 staysseeded: falseand the unread archives are listed aspendingin state, so the next tick continues the baseline — and stays silent — instead of alerting from a window that is still being filled.seededonly flips at the end of a complete pass, so a seed spanning several ticks never announces anything. 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 rules
Six PromQL tripwires, two flow-store rules (§4a/§4b), and the gateway
access-log rules (§4d: nine rule kinds over the cilium-envoy JSON stream).
See docs/gateway-http-rules.md for the HTTP rule catalogue and its
false-positive reasoning.
| # | 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 |
Gateway access-log rules (§4d) — input is the cilium-envoy JSON line in Loki,
not the flow store. Full catalogue and FP reasoning:
docs/gateway-http-rules.md.
| # | Rule | Severity | What it detects | Threshold / entity |
|---|---|---|---|---|
| 9 | http-traversal |
HIGH served / MEDIUM attempt | ../, ..\, %2e%2e, ..%2f, %252e |
one finding per host+client, not per path |
| 10 | http-sqli |
HIGH served / MEDIUM attempt | union [all] select, ' or 1=1, sleep(, benchmark(, information_schema, into outfile |
idem |
| 11 | http-nul-byte |
HIGH served / MEDIUM attempt | %00, %2500, literal NUL |
idem |
| 12 | http-secret-probe |
HIGH served / MEDIUM attempt | .env*, .aws/*, .ssh/id_*, .kube/config, *credentials*.json, cloud metadata path |
idem |
| 13 | http-vcs-probe |
HIGH served / MEDIUM attempt | .git/config, .git/HEAD, .git-credentials, .svn/, .hg/ (smart-HTTP endpoints exempt) |
idem |
| 14 | http-backup-probe |
MEDIUM served / LOW attempt | *backup*/*dump*/*db* + archive/SQL extension, .bak/.old/.sql/.swp |
idem |
| 15 | http-scanner-ua |
HIGH / MEDIUM / LOW | sqlmap, nikto, nuclei, wpscan, acunetix (HIGH); gobuster, ffuf, feroxbuster, dirb (MEDIUM); masscan, zgrab, nmap, whatweb (LOW) | UA family + host+client |
| 16 | http-auth-brute |
MEDIUM (HIGH at ≥3× total) | one client failing auth repeatedly — 401/403 only, never 4xx in general | ≥ 20/min and ≥ 30 in 5 min, per coalesce(client_ip, peer) |
| 17 | http-flood |
MEDIUM (state) | a scanner rotating source addresses to mint fingerprints | > 12 new client/path findings in one tick → one summary line |
A finding is one line per client × host × category, so a scanner walking 200
.env variants from one address is one line with a count. Severity escalates only
when the shape is in the path component and the origin answered 2xx. Per-client
keys use coalesce(client_ip, peer) — client_ip is Cloudflare's
CF-Connecting-IP, peer the real address for internal/WG requests — and never
x_forwarded_for alone.
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
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 — implemented (rules 9–17). The blocker was
F7 (
t_e662b03a):cilium-envoyemitted no access log, so there was no data source. It now writes one JSON line per request andhttp_rules.pyconsumes it from Loki. Seedocs/gateway-http-rules.md. Still not done: blocking (this is a sensor) and header/body inspection (volume + blast radius). 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 (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
- Gateway access log:
cilium-envoy(kube-system) writes one JSON line per request —gateway, method, path, protocol, response_code, response_flags, duration_ms, bytes_*, authority, client_ip, x_forwarded_for, peer, user_agent, cf_ray, upstream_host— and theloggingAlloy DaemonSet ships it to Loki (192 h retention, ~42 MB/day compressed). The sensor reads it through thelogging/lokiService proxy with two LogQL queries per tick: a|~prefilter for attack-shaped lines and asum by (client_ip, peer)1-minute matrix for 401/403. Loki does the volume reduction; a calm 10-minute window (≈5 500 requests / 3.5 MB) puts ~150 lines on the wire, not 3.5 MB.client_ipis Cloudflare'sCF-Connecting-IP; internal/WG requests have it null and the real address inpeer. - 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. It never pollshubble 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>.jsonlis the single live file and every closed file is….jsonl.gz.FLOW_PATTERNisflows-*.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 instate["archives"]so they are never re-read. Reading only*.jsonlwould 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 asFlowobjects 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 throughjson.loads+parse_flow+ egress-key extraction. - A torn archive costs a note, not the tick. A
.gzthat cannot be decompressed to the end (EOFError: Compressed file ended before the end-of-stream marker was reached) yields the readable prefix, recordsarchives[name].error, is listed inseed.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 (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)
- 89 unit tests pass against recorded fixtures (
tests/test_archives.pycovers the gz path: read-once, torn archive, budget/pending, cold seed, warm-state archive absorption, single-fire;tests/test_http_rules.pycovers the gateway rules: every category, the Forgejo browse/git FP shapes,coalesce(client_ip, peer), the auth-rate floors and the flood cap). - Gateway rules (§4d) on the live stream: calm window
07:03:40–07:13:40Z(5 474 requests, 154 candidate lines) → 0 findings, stdout empty, exit 0. The 06:48–06:53Z91.92.47.0/24burst → 8 findings (secret-file ×4, traversal, vcs-probe ×2, backup). Crafted requests (public through Cloudflare and direct to10.10.0.2:8080to exercise thepeerpath) fired all nine rule kinds — includinghttp-auth-bruteon a 30× 403 burst (40 x 401/403 in 5m, peak 33/min). First tick baselined silently, the next emitted 10 findings, the next was silent; deleting one fingerprint re-emitted exactly that line. - 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_atunchanged). - Single fire, live, over SSH against an isolated copy of the store: a
synthetic
203.0.113.77:5000/tcpline fired exactly one line (HIGH … egress-new-dst … (no prior in ~2.1h of observed flows)) and the next two ticks were empty; deleting thatseenentry re-armed exactly one more line, then silence. - Torn archive: a
.gztruncated 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=1against 3 archives →pending 2,seeded false, window 1.14 h; the next tickpending 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 carrieswindow_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-portLOW for 3100/9093; the rest quiet.