netsec-scan: HTTP attack-shape rules over the gateway access log (§4d)

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.
This commit is contained in:
Hermes 2026-11-27 02:17:14 -05:00
commit 63bac6e06f
9 changed files with 1216 additions and 16 deletions

View file

@ -23,11 +23,14 @@ investigator agent on a hit is a separate, deliberate step — not done here.
|---|---|
| `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/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 |
@ -37,7 +40,8 @@ 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
./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
@ -92,11 +96,12 @@ count: the same finding keeps the same id across ticks, restarts and days.
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
## The 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).
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) |
|---|---|---|---|---|---|
@ -109,6 +114,29 @@ and two flow-store rules (`/var/log/netsec/*.jsonl` on siriussec).
| 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
@ -134,10 +162,11 @@ Rationale and the measured numbers live in `config.EGRESS_WEB_MIN_TICKS`.
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.
* **HTTP attack-shape text rules** — *implemented* (rules 9–17). The blocker was
F7 (`t_e662b03a`): `cilium-envoy` emitted no access log, so there was no data
source. It now writes one JSON line per request and `http_rules.py` consumes
it from Loki. See `docs/gateway-http-rules.md`. Still not done: blocking (this
is a sensor) and header/body inspection (volume + blast radius).
* **`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.
@ -183,6 +212,17 @@ 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 the `logging` Alloy DaemonSet ships it to Loki
(192 h retention, ~42 MB/day compressed). The sensor reads it 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 500 requests / 3.5 MB) puts ~150 lines on the wire, not 3.5 MB.
`client_ip` is Cloudflare's `CF-Connecting-IP`; internal/WG requests have it
null and the real address in `peer`.
* **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`).
@ -259,9 +299,19 @@ credentials, no LLM call, no secret reads.
## Verified behaviour (2026-11-27)
* 56 unit tests pass against recorded fixtures (`tests/test_archives.py` covers
* 89 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).
archive absorption, single-fire; `tests/test_http_rules.py` covers 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:53Z `91.92.47.0/24` burst → 8 findings (secret-file ×4,
traversal, vcs-probe ×2, backup). Crafted requests (public through Cloudflare
and direct to `10.10.0.2:8080` to exercise the `peer` path) fired all nine rule
kinds — including `http-auth-brute` on 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