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

120
netsec_scan/loki.py Normal file
View file

@ -0,0 +1,120 @@
"""Read-only Loki access through the Kubernetes API proxy.
Same access model as `prom.py`: no port-forward, no extra credentials, no
cluster writes — `kubectl get --raw` against the `logging/loki` Service proxy as
the operator. Only the (small) matching line set is returned; the filtering
happens in LogQL so the agent never pulls the whole 528 MB/day ingress stream
into this process (see `http_rules.py`).
Two shapes are used:
* `query_range(...)` for "give me the matching log lines in this window"
(attack-shape rules). Bounded by `limit`, newest first.
* `query(...)` for an instant metric query (per-client 401/403 rate, aggregated
by Loki into one series per client).
"""
from __future__ import annotations
import json
import subprocess
import urllib.parse
from typing import Dict, List, Tuple
from . import config
from .prom import SensorError, _which
def _classify(text: str) -> str:
low = text.lower()
if "503" in low or "service unavailable" in low or "serviceunavailable" in low:
return "loki-503"
if "timeout" in low or "timed out" in low or "deadline" in low:
return "loki-timeout"
if "connection refused" in low or "no such host" in low:
return "loki-unreachable"
return "loki-error"
def _raw(path: str) -> dict:
kubectl = _which(config.KUBECTL_CANDIDATES)
try:
proc = subprocess.run(
[kubectl, "get", "--raw", path],
capture_output=True, text=True, timeout=config.LOKI_TIMEOUT,
)
except subprocess.TimeoutExpired:
raise SensorError("loki-timeout", "kubectl get --raw exceeded %ss" % config.LOKI_TIMEOUT)
if proc.returncode != 0:
raise SensorError(_classify(proc.stderr or proc.stdout), (proc.stderr or "").strip()[:200])
try:
return json.loads(proc.stdout)
except ValueError:
raise SensorError("loki-bad-json", proc.stdout[:120])
def _payload(payload: dict) -> dict:
if payload.get("status") != "success":
raise SensorError("loki-error", str(payload.get("error", ""))[:160])
return payload["data"]
def query_range(expr: str, start: float, end: float, limit: int = 600) -> Tuple[List[Tuple[dict, List[Tuple[str, str]]]], dict]:
"""Log lines matching `expr` in [start, end]; newest first, `limit` bounded.
Returns `(streams, summary)` where summary is Loki's own
`stats.summary` (bytes/lines processed, exec time) so the tick can report how
much it actually read rather than guessing from the window length.
"""
params = {
"query": expr,
"start": "%d000000000" % int(start),
"end": "%d000000000" % int(end),
"limit": str(int(limit)),
"direction": "backward",
}
path = config.LOKI_PROXY + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params)
payload = _raw(path)
data = _payload(payload)
out: List[Tuple[dict, List[Tuple[str, str]]]] = []
for stream in data.get("result") or []:
values = [(str(v[0]), str(v[1])) for v in (stream.get("values") or []) if len(v) >= 2]
out.append((stream.get("stream") or {}, values))
summary = ((payload.get("stats") or {}).get("summary") or {})
return out, summary
def query(expr: str, at: float) -> List[Tuple[dict, float]]:
"""Instant metric query -> [(labels, value)] (0 series on no match)."""
params = {"query": expr, "time": "%d000000000" % int(at)}
path = config.LOKI_PROXY + "/loki/api/v1/query?" + urllib.parse.urlencode(params)
data = _payload(_raw(path))
out: List[Tuple[dict, float]] = []
for series in data.get("result") or []:
try:
out.append((series.get("metric") or {}, float(series["value"][1])))
except (KeyError, IndexError, ValueError):
continue
return out
def query_matrix(expr: str, start: float, end: float, step: int) -> List[Tuple[dict, List[Tuple[float, float]]]]:
"""Range metric query -> [(labels, [(ts, value)])]."""
params = {
"query": expr,
"start": "%d000000000" % int(start),
"end": "%d000000000" % int(end),
"step": str(int(step)),
}
path = config.LOKI_PROXY + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params)
data = _payload(_raw(path))
out: List[Tuple[dict, List[Tuple[float, float]]]] = []
for series in data.get("result") or []:
values: List[Tuple[float, float]] = []
for point in series.get("values") or []:
try:
values.append((float(point[0]), float(point[1])))
except (IndexError, ValueError):
continue
out.append((series.get("metric") or {}, values))
return out