netsec-agent/docs/gateway-http-rules.md
Sirius DevOps ef7e584d27 http rules: make the LogQL prefilter a superset of classify()
`http-sqli` was unreachable end to end: the prefilter admitted only
`union select`, so boolean (`' OR '1'='1`, `%27%20OR%20…`) and time-based
(`sleep(`, `waitfor delay`) payloads were dropped in Loki before Python saw
them, and the canary passed because it used the one admitted shape.

The prefilter now carries the missing shapes as plain literals (a nested
`(?:...)` group made Loki's filter 10x slower, and re-ordering the alternation
measured 20-60 s, so the old block stays first and the additions append).
Over-match measured on 2026-11-27 06:00-07:00Z over 29 426 lines: 1 202 -> 1 548
lines/h (+29 %), 10-minute query 3.9 s. The extra lines are Forgejo browse URLs
that classify() drops; a calm 10-minute window of 394 admitted lines yields 0
findings.

Durability: tests/fixtures/attack-shapes.json is one table of 105 payload
shapes iterated by both tests - classify() must flag each one and
config.HTTP_LINE_FILTER must match its serialized access line. It fails with 44
dropped shapes on the old filter and passes now, so this class of drift (any
rule kind, not just sqli) cannot come back silently.

Docs also record the data-source limit the bug surfaced: Cloudflare collapses
dot-segments in the path, so `/../../etc/passwd` arrives as `/etc/passwd` and
path traversal is only detectable in a query string (or off-tunnel).
2026-11-27 03:13:16 -05:00

17 KiB
Raw Permalink Blame History

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``
auth rate `sum by (client_ip, peer) (count_over_time(... json ... [1m]))`

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 2026-11-27 06:00–07:00Z over 29 426 lines: 1 202 lines/h before, 1 548 lines/h after the sqli fix (+29 %), all of it filtered out in Python.

The superset property is a test, not a comment. tests/fixtures/attack-shapes.json is one table of payload shapes; TestPrefilterSuperset iterates it twice — every shape must be flagged by classify() and must match config.HTTP_LINE_FILTER on its serialized access line. A shape the classifier knows but the prefilter drops is invisible from Python: Loki never returns the line, so no unit test of classify() can see the gap. http-sqli shipped unreachable for exactly that reason — only union select was admitted and the canary used that shape (t_a3604aab). Add a row when you add a rule or a payload family.

Two measured rules for editing the prefilter:

  • Every alternative is a plain or escaped literal. Wrapping part of the alternation in a (?:…) group made Loki's filter ~10× slower (22 s vs 2 s for a 10-minute window) and LOKI_TIMEOUT is 25 s, i.e. the tick fails.
  • Keep the existing block first and append. The identical set of alternatives in a different order measured 20–60 s. Re-order only with a count_over_time timing behind you; the 10-minute window costs ~3.9 s today.

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).

Data-source limit: Cloudflare normalises the path

More than one reader will assume "path traversal is covered". It is covered in the query string only, and that is a property of the data source, not of the rules:

probe sent        GET /../../../../etc/passwd
arrives at envoy  {"path":"/etc/passwd", …}

Cloudflare collapses dot-segments in the path before the origin ever sees the request, so the traversal string does not exist anywhere in the access log and no rule can match it. What does reach this layer, and is what the traversal rule actually catches:

  • traversal in a query string — GET /?file=../../../etc/passwd (answered 200 by the static landing page, hence MEDIUM not HIGH);
  • requests that bypass Cloudflare — a WireGuard client hitting http://10.10.0.2:8080/ directly sends the path verbatim;
  • percent-encoded traversal the edge does not decode-away — /%2e%2e%2f….

So a traversal test through the public hostname proves only that Cloudflare normalised it. Test path traversal against the Gateway origin, or in a query string, and do not cite this rule as coverage for ../ in paths.

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; boolean ' or/and ', or <n>=<n> in any encoding; time-based sleep(, pg_sleep(, benchmark(, waitfor delay; information_schema, sysobjects, extractvalue(, updatexml(, load_file(, into outfile; stacked ; drop/delete/insert/update
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.

sqli, end to end (2026-11-27 08:10Z, after the prefilter fix)

Four payloads fired at the public hostname (three, percent-encoded) and at the Gateway origin 10.10.0.2:8080 (all four, so the peer path is exercised):

payload wire form result
/?id=1%27%20OR%20%271%27=%271 as sent 200, logged, http-sqli
/?id=1' OR '1'='1 400 from envoy (a raw space is not a valid request target) send /?id=1'%20OR%20'1'='1
/?id=1%27%3BWAITFOR%20DELAY%20%270:0:5%27 as sent 200, logged, http-sqli
/?q=1%27%20AND%20sleep(5)-- as sent 200, logged, http-sqli
$ ./run.sh --http --no-prom --http-window 300          # live tick, 10.10.0.3 + CF client
MEDIUM 7d17b2f6b043 http-sqli sqli siriusdevops.com client=10.10.0.3       GET /?id=1'%20OR%20'1'='1      -> 200 (4x in 5m)
MEDIUM ff5178bdc5ff http-sqli sqli siriusdevops.com client=137.118.156.124 GET /?q=1%27%20AND%20sleep(5)-- -> 200 (3x in 5m)

Before the fix the same requests produced nothing: the four shapes were dropped by the prefilter (the union select canary in the block above was the only sqli shape it admitted). The table in tests/fixtures/attack-shapes.json now pins 105 shapes × (classify, prefilter) and fails with 44 dropped shapes on the pre-fix filter.

Cost, measured on the same hour (06:00–07:00Z, 29 426 lines): 1 202 lines/h → 1 548 lines/h admitted (+346, +29 %), the 10-minute window 474 → 626 lines at 3.9 s per query. The 346 extra lines are Forgejo browse URLs (…/blame/commit/…, …/raw/commit/… containing secret-named files and .gz archives); classify() drops all of them (browse exclusion), and a calm window 07:03:40–07:13:40Z of 394 admitted lines produced 0 findings. Over the last 6 h the ordinary shapes are clean too: 381 info/refs?service=git-*, 83 browse (/src/branch/master/…), 6 /book, 6 /lab, 2 000 runner FetchTask — 0 http-* findings.

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:

"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:

"http": {"ticks": 288, "matched_lines": 4100, "by_rule": {"http-secret-probe": 12, ...},
         "truncated_ticks": 0}

Operating it

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

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.