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

220
docs/gateway-http-rules.md Normal file
View file

@ -0,0 +1,220 @@
# Gateway HTTP attack-shape rules (§4d)
The detector for the only application-layer signal the netsec design asks for:
`../` traversal, `union select`, `%00`, `.env`/`.git`/backup probes, scanner
user-agents, and high-rate 401/403 per client. Input is the `cilium-envoy`
access log, **not** the Hubble flow store — flows carry no `path`, no
`user_agent` and no per-request response code.
```
cilium-envoy stdout (JSON, one object per request)
→ kubelet /var/log/pods/... (10 MiB × 5, ≈29 min per file)
→ Alloy DaemonSet (ns logging)
→ Loki {namespace="kube-system", container="cilium-envoy", job="kube/pods", node="siriussec"}
→ netsec_scan.http_step() ← this document
```
No second collector, no file re-read, no Envoy config change (no debug logging,
no added fields). The pod log stays a rotation artifact; Loki is the archive.
## Volume discipline
Measured 2026-11-27: **641 B/line, 9.54 lines/s, 528 MB/day raw**, 93.5 % of it
Forgejo. A 10-minute window is ~5 500 requests / ~3.5 MB.
Each tick runs exactly **two LogQL queries** over that window:
| Query | Shape | What crosses the wire |
|---|---|---|
| candidate lines | `{stream} |~ `prefilter`` | only matching lines (calm: ~150–200 of 5 500, ≈100 KB) |
| auth rate | `sum by (client_ip, peer) (count_over_time(... | json ... [1m]))` | one number per client per minute |
The prefilter is a deliberate **superset** (it matches `.gitignore` in a browse
URL, `.git/info/refs`, `backup-cronjob.yaml`, …). Loki drops non-matching bytes
cheaply; the precise decision is made in `http_rules.classify()` where real
semantics are available. Over-matching measured at ~1 100 of 35 445 lines/hour
(3 %), all of it filtered out in Python.
`limit` on the line query is `HTTP_MAX_LINES = 600`; if a flood exceeds it the
tick reports `truncated` in the day counter and still classifies what arrived
(newest first).
## The rules
Every finding is `SEV <fp12> <rule> <detail>`; the fingerprint is
`sha256(rule + entity)[:12]`, never a path, count or timestamp.
| Rule | Category | Severity | Entity | Fires when |
|---|---|---|---|---|
| `http-traversal` | `traversal` | HIGH served / MEDIUM attempt | `traversal\|host\|client` | `../`, `..\`, `%2e%2e`, `..%2f`, `%252e` in path or query |
| `http-sqli` | `sqli` | HIGH served / MEDIUM attempt | `sqli\|host\|client` | `union [all] select`, `' or 1=1`, `sleep(`, `benchmark(`, `information_schema`, `waitfor delay`, `load_file(`, `into outfile` |
| `http-nul-byte` | `nul-byte` | HIGH served / MEDIUM attempt | `nul-byte\|host\|client` | `%00`, `%2500`, literal NUL |
| `http-secret-probe` | `secret-file` | HIGH served / MEDIUM attempt | `secret-file\|host\|client` | `.env*`, `.aws/{credentials,config}`, `.ssh/id_*`, `.docker/config.json`, `.kube/config`, `.npmrc`, `.netrc`, `.pgpass`, `*credentials*.{json,yml,…}`, `/meta-data/iam/security-credentials` |
| `http-vcs-probe` | `vcs-probe` | HIGH served / MEDIUM attempt | `vcs-probe\|host\|client` | `.git/config`, `.git/HEAD`, `.git/index`, `.git-credentials`, `.svn/`, `.hg/`, `.bzr/` (**not** the smart-HTTP endpoints) |
| `http-backup-probe` | `backup-file` | MEDIUM served / LOW attempt | `backup-file\|host\|client` | `*backup*`/`*dump*`/`*db*`/`*site*` + archive or SQL extension, or any `.bak/.old/.orig/.save/.swp/.sql/.dump` |
| `http-scanner-ua` | `scanner-ua:<family>` | HIGH (sqlmap, nikto, nuclei, wpscan, acunetix, …) / MEDIUM (gobuster, ffuf, feroxbuster, dirb) / LOW (masscan, zgrab, nmap, whatweb) | `scanner-ua:<family>\|host\|client` | user-agent fingerprint |
| `http-auth-brute` | — | MEDIUM, HIGH at ≥3× the total | `auth-fail\|client` | one client with ≥ **20** × 401/403 in a single minute **and** ≥ **30** over the 5-minute window |
| `http-flood` | — | MEDIUM (state, 24 h cooldown) | `overflow\|gateway` | more than **12** *new* client/path fingerprints in one tick |
**One category per request** (priority: traversal → sqli → nul → secret → vcs →
backup → scanner-UA), so `../../.env` is one line, not four.
**Severity escalates only when the origin actually served the shape**: the match
must be in the *path component* and the response 2xx. A 200 on
`/?file=../../.env` is the static site's landing page answering, not a
successful traversal — measured live, and the reason `served` is path-scoped.
**Entity excludes the literal path.** A scanner walking 200 `.env` variants from
one address is one finding with a count (`29x in 10m`), not 200 fingerprints.
That is also what bounds the seen-set under IP rotation; `http-flood` is the
last-resort cap, and the cumulative `seen` map is already pruned at
`MAX_SEEN = 20000`.
## False-positive control (the part that decides whether this is usable)
The stream is 93.5 % Forgejo, and Forgejo legitimately serves every shape a
naive substring rule greps for:
| Legit shape (real lines, 2026-11-27) | Matches | Why it is not an alert |
|---|---|---|
| `/sirius/homek8s.git/info/refs?service=git-upload-pack` | `.git` | smart-HTTP git endpoint, used by every `git` client and by CI |
| `/sirius/homek8s.git/git-upload-pack` (POST) | `.git` | same |
| `/sirius/onionwire/raw/commit/<sha>/.gitignore` | `.git` | repository file view (`/raw/`) |
| `/mayx/blog/blame/commit/<sha>/.gitlab-ci.yml` | `.git` | repository file view (`/blame/`) |
| `/sirius/gcloud-lab/raw/commit/<sha>/.../memory-db-credentials.yaml` | `credential` | repository file view |
| `/sirius/gcloud-lab/commit/<sha>/immediate-backup.yaml` | `backup` | repository file view (`/commit/`) |
| `/sirius/osint-dashboard/rss/branch/<branch>/.env.example` | `.env` | RSS route for a branch, not a file read (303 → login) |
| `/<owner>/<repo>/-/archive/main/repo.tar.gz` | `.tar.gz` | Forgejo archive download |
| `303 → /user/login` (17 639 of 35 445 lines in a measured hour) | 3xx | not 4xx at all; the auth rule counts **401/403 only** |
| 404 crawler churn (`/linda958336097`, `/roscoedelarosa`, …) | 404 | 293/hour is normal internet noise; "4xx alone" is explicitly not a rule |
| `git/2.56.0` retrying a push → 3 × 401/403 per minute, 25/hour | 401 | two orders of magnitude below the 20/min floor |
Mechanisms:
* **Browse-URL exclusion is host-scoped.** The `/<owner>/<repo>/{raw,src,blame,
commits,commit,tree,media,avatars,archive,compare,diff,patch,pulls,issues,
wiki,releases,activity,settings,rss,atom,feeds}/…` and `/-/…` shapes are
exempt **only** on `HTTP_FORGEJO_HOSTS` (`forgejo.siriusdevops.com`). On a
static site the same path is a probe, and it is alerted on.
* **Smart-HTTP git endpoints are exempt everywhere** (`.git/info/refs`,
`.git/git-upload-pack`, `.git/git-receive-pack`); a `.git/config` request is
not.
* **Not 4xx.** The auth rule is scoped to 401/403 (auth *failures*), not "error
codes"; Forgejo answers 303 to every crawler login redirect and 404 to
crawler churn.
* **Per client, per minute.** `coalesce(client_ip, peer)` — `client_ip` is
Cloudflare's `CF-Connecting-IP` for tunnelled traffic, `peer` is the real
address for internal/WG requests. `x_forwarded_for` is never used as a key:
the client can send it and the tunnel appends a hop. A request with neither
(`peer = 10.10.0.1`, the Pi's cloudflared) is **unattributable** and can never
be the subject of a per-client rule — otherwise a whole internet's brute force
collapses into one bucket labelled with the tunnel.
## Measured proof (2026-11-27, live stream)
Calm window `07:03:40–07:13:40Z` — 5 474 requests, 154 candidate lines, **0
findings**, empty stdout, exit 0.
Scanner burst `06:48–06:53Z` (four addresses in `91.92.47.0/24`, Chrome UA):
```
MEDIUM 6581ff5be412 http-secret-probe secret-file siriusdevops.com client=91.92.47.94 GET /backup/.env -> 404 (29x in 5m)
MEDIUM 207e1756a306 http-secret-probe secret-file siriusdevops.com client=91.92.47.95 GET /.env.bedrock -> 404 (21x in 5m)
MEDIUM d5be7f0f5ce0 http-secret-probe secret-file siriusdevops.com client=91.92.47.96 GET /client/src/.env -> 404 (18x in 5m)
MEDIUM c3ffebd1bab3 http-secret-probe secret-file siriusdevops.com client=91.92.47.97 GET /client_secrets.json -> 404 (18x in 5m)
MEDIUM b92f5c1a095e http-traversal traversal siriusdevops.com client=91.92.47.95 GET /?file=../../../../var/www/html/.env -> 200 (1x in 5m)
MEDIUM d3005f01f561 http-vcs-probe vcs-probe siriusdevops.com client=91.92.47.94 GET /.git/config -> 404 (1x in 5m)
MEDIUM 9f4585513ff2 http-vcs-probe vcs-probe siriusdevops.com client=91.92.47.95 GET /.git/credentials -> 404 (1x in 5m)
LOW b02ba0f708e7 http-backup-probe backup-file siriusdevops.com client=91.92.47.96 GET /credentials.bak -> 404 (1x in 5m)
```
Crafted requests (public via Cloudflare, and direct to the Gateway on
`10.10.0.2:8080` to exercise the `peer` fallback):
```
HIGH 1359353db11a http-scanner-ua scanner-ua:nikto siriusdevops.com client=10.10.0.3 GET / -> 200
HIGH 431f76220d12 http-scanner-ua scanner-ua:sqlmap siriusdevops.com client=10.10.0.3 GET / -> 200
MEDIUM 5d058c9a884f http-auth-brute 137.118.156.124: 40 x 401/403 in 5m (peak 33/min) - sustained auth failure
MEDIUM cabab413f491 http-nul-byte nul-byte siriusdevops.com client=10.10.0.3 GET /.env%00probe -> 400
MEDIUM eaa5bb802fe6 http-secret-probe secret-file siriusdevops.com client=10.10.0.3 GET /.env.netsec1d-peer -> 404
MEDIUM f6686c354bbc http-secret-probe secret-file siriusdevops.com client=137.118.156.124 GET /.env -> 404
MEDIUM ff5178bdc5ff http-sqli sqli siriusdevops.com client=137.118.156.124 GET /index.php?q=union+select+1,2 -> 404
MEDIUM 58168ee6b092 http-traversal traversal siriusdevops.com client=137.118.156.124 GET /?file=../../../etc/passwd -> 200
MEDIUM 1f9388a85f27 http-vcs-probe vcs-probe siriusdevops.com client=10.10.0.3 GET /.git/config -> 404
MEDIUM 58d1f046a18a http-vcs-probe vcs-probe siriusdevops.com client=137.118.156.124 GET /.git/config -> 404
```
`10.10.0.3` is the Legion laptop arriving over `wg0` with `client_ip: null` and
`peer: 10.10.0.3`; `137.118.156.124` is that laptop's public address as
Cloudflare reported it in `CF-Connecting-IP`. Same code path, both attribution
sources.
Behavioural contract on the same state file: first tick baselines silently
(`http.baselined_at`, 0 lines out), the next tick after the crafted requests
emits 10, the tick after that is silent, deleting one fingerprint re-emits
exactly that one line, and the following tick is silent again.
## State
Only three scalars/dicts are added, all bounded:
```json
"http": {
"baselined_at": "2026-11-27T07:15:58+00:00",
"baseline": {"window": "10m", "matched_lines": 154, "findings": 0, "by_rule": {}},
"last": {"at": "...", "window": "10m", "matched_lines": 198, "findings": 10}
}
```
Dedupe uses the existing cumulative `seen` map (union-only, pruned at
`MAX_SEEN`). There is no per-path or per-request set: the windows are re-queried
each tick and the fingerprint does the remembering. `st["http"]` is created with
`setdefault`, so an old state file loads unchanged.
The daily report gains one block:
```json
"http": {"ticks": 288, "matched_lines": 4100, "by_rule": {"http-secret-probe": 12, ...},
"truncated_ticks": 0}
```
## Operating it
```bash
cd ~/Projects/netsec-agent
./run.sh # normal 5-minute tick (silent = calm)
./run.sh --verbose # include the "http: ..." line on stderr
./run.sh --no-http # flow/PromQL rules only
./run.sh --http-window 600 --http-end 2026-11-27T06:53:00Z --dry-run --http
./run.sh --http --flows-dir /tmp/empty --dry-run # local mode, no SSH, still hits Loki
```
`--http` is implied for the live sensor; it exists so `--fixture`/`--flows-dir`
runs (unit tests, local checks) never touch the network unless asked.
### Re-deriving the thresholds
```bash
kubectl -n logging get svc loki # 3100
# one hour of auth failures per client, 1-minute buckets:
kubectl get --raw "/api/v1/namespaces/logging/services/loki:3100/proxy/loki/api/v1/query_range?query=$(python3 - <<'PY'
import urllib.parse
print(urllib.parse.quote('sum by (client_ip, peer) (count_over_time({namespace="kube-system", container="cilium-envoy", job="kube/pods", node="siriussec"} | json response_code, client_ip, peer | response_code != "" | response_code >= 401 and response_code <= 403 [1m]))'))
PY
)&start=...&end=...&step=60"
```
Calm-hour baseline 2026-11-27: 20 auth failures in the whole hour, all one
client (`git/2.56.0` retrying a push), peak **1/min** → the 20/min floor sits
20× above the noisiest legitimate client. Do not lower it to "catch more":
a rule that fires on CI retries gets the channel muted.
## Deliberately not done
* **No Envoy debug/trace logging, no extra fields.** The 17-field allowlist is
enough; header/body capture would multiply the volume and the blast radius.
* **No "4xx rate" rule.** 303 login redirects and 404 crawler churn are the
stream; the auth rule watches 401/403 only.
* **No per-path fingerprint.** Unbounded under a path-walking scanner.
* **No blocking.** This is a sensor; the bouncer (Cilium/CrowdSec) is a separate
decision.