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.
353 lines
15 KiB
Python
353 lines
15 KiB
Python
"""HTTP attack-shape rules over the Cilium Gateway access log (§4d).
|
||
|
||
Input is the `cilium-envoy` access log: one JSON object per request, shipped by
|
||
the `logging` Alloy DaemonSet into Loki. It is **not** the Hubble flow store:
|
||
flows carry no `path`, no `user_agent`, and no per-request response code.
|
||
|
||
Volume discipline (measured 2026-11-27: 641 B/line, 9.54 lines/s, 528 MB/day
|
||
raw): every rule is a LogQL query whose *filtering happens inside Loki*. The
|
||
agent receives only the matching lines — a 10-minute window is ~5 700 lines /
|
||
3.6 MB scanned and (calm) zero lines returned. There is no second collector.
|
||
|
||
False-positive control is the hard part, because 93.5 % of this stream is
|
||
Forgejo and Forgejo legitimately serves:
|
||
|
||
* `/<owner>/<repo>.git/info/refs?service=git-upload-pack|git-receive-pack`
|
||
and the two POST endpoints — smart HTTP git, done by every `git` client;
|
||
* `/<owner>/<repo>/{raw,src,blame,commits,commit,tree,media,avatars}/…` and
|
||
`/-/archive/…` — users browsing repository files. These paths are full of
|
||
`.env`, `.gitignore`, `.gitlab-ci.yml`, `backup-cronjob.yaml` and
|
||
`*-credentials.yaml` **filenames**, which a naive substring rule flags.
|
||
|
||
So classification is semantic, not substring: browse URLs on the Forgejo hosts
|
||
are excluded from path-shape rules, and smart-HTTP git endpoints are excluded
|
||
from the VCS-probe rule. Severity escalates when the origin actually *served*
|
||
the request (2xx) instead of 404-ing it.
|
||
|
||
`client_ip` is the real client only for Cloudflare-tunnelled traffic
|
||
(`CF-Connecting-IP`). Internal/WG requests carry `client_ip: null` and the real
|
||
address in `peer`, so every per-client key uses `coalesce(client_ip, peer)`.
|
||
`x_forwarded_for` is never trusted on its own (the client can send it, and the
|
||
tunnel appends its own hop).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from datetime import datetime, timezone
|
||
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
||
from urllib.parse import unquote
|
||
|
||
from . import config
|
||
from .rules import Finding, SEVERITY_ORDER
|
||
|
||
# ------------------------------------------------------------- parsing ----
|
||
_CTRL = re.compile(r"[\x00-\x1f\x7f]")
|
||
|
||
|
||
def _text(value: Any, limit: int = 120) -> str:
|
||
"""Single-line, bounded rendering of an untrusted field."""
|
||
if value is None:
|
||
return ""
|
||
out = _CTRL.sub(" ", str(value)).replace("\n", " ")
|
||
return out[:limit]
|
||
|
||
|
||
def decode_path(path: str) -> str:
|
||
"""Percent-decode for classification (twice: `%252f` is `%2f` is `/`)."""
|
||
out = path or ""
|
||
for _ in range(2):
|
||
nxt = unquote(out, errors="replace")
|
||
if nxt == out:
|
||
break
|
||
out = nxt
|
||
return out
|
||
|
||
|
||
def client_of(rec: Dict[str, Any]) -> Optional[str]:
|
||
"""`coalesce(client_ip, peer)`, minus the unattributable Cloudflare edge.
|
||
|
||
`peer == 10.10.0.1` with no `client_ip` means the request came from the Pi's
|
||
cloudflared but Cloudflare did not pass the client address, so every such
|
||
request would collapse into one bucket. Treat it as unattributable instead of
|
||
attributing a whole internet's brute force to the tunnel.
|
||
"""
|
||
ip = _text(rec.get("client_ip"), 64).strip()
|
||
if not ip:
|
||
ip = _text(rec.get("peer"), 64).strip()
|
||
if not ip or ip in config.HTTP_EDGE_PEERS:
|
||
return None
|
||
return ip
|
||
|
||
|
||
def outcome(rec: Dict[str, Any]) -> int:
|
||
try:
|
||
return int(rec.get("response_code"))
|
||
except (TypeError, ValueError):
|
||
return 0
|
||
|
||
|
||
def served(rec: Dict[str, Any]) -> bool:
|
||
return 200 <= outcome(rec) < 300
|
||
|
||
|
||
# -------------------------------------------------------- classification ----
|
||
_TRAVERSAL = re.compile(r"(^|[/\\])\.\.([/\\]|$)")
|
||
_TRAVERSAL_ENC = re.compile(r"(?i)(%2e%2e|\.\.%2f|\.\.%5c|%252e%252e)")
|
||
_SQLI = re.compile(
|
||
r"(?i)(union\s+(?:all\s+|distinct\s+)?select"
|
||
r"|\bor\b\s+['\"]?\w+['\"]?\s*=\s*['\"]?\w+"
|
||
r"|'\s*(?:or|and)\s*'"
|
||
r"|\b(?:sleep|pg_sleep|benchmark)\s*\("
|
||
r"|information_schema|sysobjects|waitfor\s+delay"
|
||
r"|extractvalue\s*\(|updatexml\s*\(|load_file\s*\(|into\s+outfile"
|
||
r"|;\s*(?:drop|delete|insert|update)\s)"
|
||
)
|
||
_NUL = re.compile(r"(?i)(%00|%2500|\x00)")
|
||
|
||
_SECRET = re.compile(
|
||
r"(?i)(^|/)("
|
||
r"\.env(rc)?(\.[a-z0-9_-]+)?"
|
||
r"|\.aws/(credentials|config)"
|
||
r"|\.ssh/(id_rsa|id_dsa|id_ecdsa|id_ed25519|authorized_keys)"
|
||
r"|\.docker/config\.json|\.kube/config|\.git-credentials"
|
||
r"|\.npmrc|\.pypirc|\.netrc|\.pgpass|\.htpasswd|\.my\.cnf"
|
||
r"|(credentials|secrets|client_secret|service[-_]?account|"
|
||
r"application_default_credentials|cluster_credentials|smtp_credentials|"
|
||
r"bedrock[-_]?credentials)[a-z0-9_.-]*\.(json|ya?ml|toml|txt|env|gpg)"
|
||
r"|meta-data/(iam/)?security-credentials"
|
||
r")$"
|
||
)
|
||
_VCS = re.compile(r"(?i)(^|/)\.git/(config|HEAD|index|packed-refs|logs/HEAD|credentials)$"
|
||
r"|(^|/)\.(svn|hg|bzr)/")
|
||
_BACKUP = re.compile(
|
||
r"(?i)(^|/)(?:[a-z0-9_.-]*[_-])?(?:backup|dump|database|db|www|site|wwwroot|"
|
||
r"public_html)[a-z0-9_.-]*\.(zip|tar|tgz|tar\.gz|gz|bz2|rar|7z|sql)$"
|
||
r"|(^|/)[^/]+\.(bak|old|orig|save|swp|swo|sql|dump)$"
|
||
)
|
||
|
||
# Smart-HTTP git endpoints: legitimate traffic from every `git` client.
|
||
_GIT_ENDPOINTS = re.compile(r"(?i)(\.git/info/refs|\.git/git-upload-pack|"
|
||
r"\.git/git-receive-pack)$")
|
||
# Forgejo/Gitea browse + archive URLs. Only applied on the Forgejo hosts: on a
|
||
# static site the same shape is a probe, not a repository view.
|
||
_BROWSE = re.compile(
|
||
r"(?i)^(?:/[^/]+/[^/]+/(?:raw|src|blame|commits?|tree|media|avatars|archive|"
|
||
r"compare|diff|patch|pulls?|issues?|wiki|releases?|activity|settings|"
|
||
r"rss|atom|feeds)/"
|
||
r"|/[^/]+/[^/]+/-/"
|
||
r"|/[^/]+/[^/]+/src/branch/)"
|
||
)
|
||
|
||
|
||
def _browse_url(rec: Dict[str, Any], decoded: str) -> bool:
|
||
host = _text(rec.get("authority"), 120).lower()
|
||
if host not in config.HTTP_FORGEJO_HOSTS:
|
||
return False
|
||
return bool(_BROWSE.search(decoded))
|
||
|
||
|
||
SEVERITY_BY_CATEGORY = {
|
||
# A successful traversal/injection is a compromise; an attempt is still
|
||
# worth a line but not at the same level. `served` bumps these to HIGH.
|
||
"traversal": ("HIGH", "MEDIUM"),
|
||
"sqli": ("HIGH", "MEDIUM"),
|
||
"nul-byte": ("HIGH", "MEDIUM"),
|
||
"secret-file": ("HIGH", "MEDIUM"),
|
||
"vcs-probe": ("HIGH", "MEDIUM"),
|
||
"backup-file": ("MEDIUM", "LOW"),
|
||
}
|
||
|
||
RULE_BY_CATEGORY = {
|
||
"traversal": "http-traversal",
|
||
"sqli": "http-sqli",
|
||
"nul-byte": "http-nul-byte",
|
||
"secret-file": "http-secret-probe",
|
||
"vcs-probe": "http-vcs-probe",
|
||
"backup-file": "http-backup-probe",
|
||
}
|
||
|
||
# Active attack tools vs. generic recon. Both are worth a line; only the former
|
||
# claims an attempt is in progress.
|
||
SCANNER_UA = {
|
||
"sqlmap": "HIGH", "nikto": "HIGH", "nuclei": "HIGH", "wpscan": "HIGH",
|
||
"acunetix": "HIGH", "netsparker": "HIGH", "nessus": "HIGH", "openvas": "HIGH",
|
||
"hydra": "HIGH", "w3af": "HIGH", "zaproxy": "HIGH", "commix": "HIGH",
|
||
"jaeles": "HIGH", "ysoserial": "HIGH", "gobuster": "MEDIUM",
|
||
"dirbuster": "MEDIUM", "ffuf": "MEDIUM", "feroxbuster": "MEDIUM",
|
||
"dirb": "MEDIUM", "masscan": "LOW", "zgrab": "LOW", "nmap": "LOW",
|
||
"whatweb": "LOW", "gospider": "LOW",
|
||
}
|
||
|
||
|
||
def scanner_family(ua: str) -> Optional[str]:
|
||
low = (ua or "").lower()
|
||
for family, _sev in SCANNER_UA.items():
|
||
if family in low:
|
||
return family
|
||
return None
|
||
|
||
|
||
def classify(rec: Dict[str, Any]) -> Optional[Tuple[str, str, str]]:
|
||
"""Return `(category, severity, rule)` for one access-log record, or None.
|
||
|
||
Exactly one category per request (priority order below), so a request that is
|
||
both `../../.env` yields one line instead of three.
|
||
|
||
Severity escalates to "served" only when the shape is in the **path
|
||
component** and the origin answered 2xx. A 200 on `/?file=../../.env` is the
|
||
landing page answering, not the traversal succeeding — on this static site
|
||
every query string returns 200, so escalating on the response code alone
|
||
would claim a leak that did not happen.
|
||
"""
|
||
raw = _text(rec.get("path"), 512)
|
||
decoded = decode_path(raw)
|
||
path_part, _sep, _query = decoded.partition("?")
|
||
browse = _browse_url(rec, decoded)
|
||
git_endpoint = bool(_GIT_ENDPOINTS.search(path_part))
|
||
# `+` is a space in a query string; make `union+select` readable to the regex.
|
||
probe = decoded.replace("+", " ")
|
||
|
||
if not browse:
|
||
if (_TRAVERSAL.search(decoded) or _TRAVERSAL_ENC.search(raw)
|
||
or _TRAVERSAL_ENC.search(decoded)):
|
||
return _shape("traversal", rec, bool(_TRAVERSAL.search(path_part)
|
||
or _TRAVERSAL_ENC.search(path_part)))
|
||
if _SQLI.search(probe):
|
||
return _shape("sqli", rec, bool(_SQLI.search(path_part.replace("+", " "))))
|
||
if _NUL.search(raw) or _NUL.search(decoded):
|
||
return _shape("nul-byte", rec, bool(_NUL.search(path_part)))
|
||
if _SECRET.search(path_part):
|
||
return _shape("secret-file", rec, True)
|
||
if _VCS.search(path_part) and not git_endpoint:
|
||
return _shape("vcs-probe", rec, True)
|
||
if _BACKUP.search(path_part):
|
||
return _shape("backup-file", rec, True)
|
||
family = scanner_family(_text(rec.get("user_agent"), 300))
|
||
if family:
|
||
return ("scanner-ua:%s" % family, SCANNER_UA[family], "http-scanner-ua")
|
||
return None
|
||
|
||
|
||
def _shape(category: str, rec: Dict[str, Any], in_path: bool) -> Tuple[str, str, str]:
|
||
high, low = SEVERITY_BY_CATEGORY[category]
|
||
severity = high if (in_path and served(rec)) else low
|
||
return (category, severity, RULE_BY_CATEGORY[category])
|
||
|
||
|
||
# --------------------------------------------------------------- rules ----
|
||
def rule_attack_paths(records: Iterable[Dict[str, Any]], window_label: str) -> Tuple[List[Finding], Dict[str, int]]:
|
||
"""One finding per (category, host, client) over the window.
|
||
|
||
The fingerprint deliberately excludes the literal path: a scanner walking
|
||
200 `.env` variants from one address is one finding (with a count), not 200.
|
||
That is also what keeps the cumulative seen-set bounded under IP rotation
|
||
attacks — the entity space is category × host × client.
|
||
"""
|
||
out: List[Finding] = []
|
||
counts: Dict[str, int] = {}
|
||
seen_keys: Dict[str, Dict[str, Any]] = {}
|
||
for rec in records:
|
||
hit = classify(rec)
|
||
if not hit:
|
||
continue
|
||
category, severity, rule = hit
|
||
client = client_of(rec) or "unknown"
|
||
host = _text(rec.get("authority"), 120) or "?"
|
||
counts[rule] = counts.get(rule, 0) + 1
|
||
entity = "%s|%s|%s" % (category, host, client)
|
||
entry = seen_keys.get(entity)
|
||
if entry is None:
|
||
seen_keys[entity] = {
|
||
"category": category, "severity": severity, "rule": rule,
|
||
"client": client, "host": host, "n": 1,
|
||
"first": rec.get("start_time") or _now_iso(),
|
||
"sample": (rec.get("method") or "?"), "path": _text(rec.get("path"), 90),
|
||
"code": outcome(rec),
|
||
}
|
||
else:
|
||
entry["n"] = int(entry["n"]) + 1
|
||
if SEVERITY_ORDER.get(severity, 9) < SEVERITY_ORDER.get(entry["severity"], 9):
|
||
entry["severity"] = severity
|
||
# Keep the response code of the worst record: `-> 200` next to a
|
||
# HIGH must be the request that was actually served.
|
||
entry["code"] = outcome(rec)
|
||
for entity, e in seen_keys.items():
|
||
detail = "%s %s client=%s %s %s -> %d (%dx in %s)" % (
|
||
e["category"], e["host"], e["client"], e["sample"], e["path"],
|
||
int(e["code"] or 0), int(e["n"]), window_label)
|
||
out.append(Finding(
|
||
rule=e["rule"], kind="novelty", severity=e["severity"],
|
||
entity=entity, detail=detail,
|
||
))
|
||
return out, counts
|
||
|
||
|
||
def rule_auth_rate(series: List[Tuple[Dict[str, Any], List[Tuple[float, float]]]],
|
||
window_label: str) -> Tuple[List[Finding], int]:
|
||
"""High-rate 401/403 per client per minute, from a LogQL 1-minute matrix.
|
||
|
||
Not "4xx" — Forgejo answers 303 to `/user/login` for every crawler and that
|
||
is the bulk of the stream. Not "any 4xx" either: 404 crawler churn is
|
||
constant (measured 4.9/min). The rule needs one client to fail auth at
|
||
≥ `HTTP_AUTH_PER_MIN` in a single minute *and* ≥ `HTTP_AUTH_WINDOW_TOTAL`
|
||
over the whole query window, i.e. a sustained attempt rather than one
|
||
mistyped password or a CI credential retry (measured: the git client's
|
||
retries peak at 1/min).
|
||
"""
|
||
out: List[Finding] = []
|
||
by_client: Dict[str, Dict[str, Any]] = {}
|
||
for labels, points in series:
|
||
client = (labels.get("client_ip") or "").strip()
|
||
if not client:
|
||
client = (labels.get("peer") or "").strip()
|
||
if not client or client in config.HTTP_EDGE_PEERS:
|
||
continue
|
||
bucket = by_client.setdefault(client, {"per_min": [], "total": 0})
|
||
for _ts, value in points:
|
||
v = int(round(value))
|
||
bucket["per_min"].append(v)
|
||
bucket["total"] += v
|
||
for client, b in by_client.items():
|
||
peak = max(b["per_min"]) if b["per_min"] else 0
|
||
if peak < config.HTTP_AUTH_PER_MIN or b["total"] < config.HTTP_AUTH_WINDOW_TOTAL:
|
||
continue
|
||
severity = "HIGH" if b["total"] >= 3 * config.HTTP_AUTH_WINDOW_TOTAL else "MEDIUM"
|
||
out.append(Finding(
|
||
rule="http-auth-brute", kind="state", severity=severity,
|
||
entity="auth-fail|%s" % client,
|
||
detail="%s: %d x 401/403 in %s (peak %d/min) - sustained auth failure"
|
||
% (client, b["total"], window_label, peak),
|
||
))
|
||
return out, len(by_client)
|
||
|
||
|
||
def cap_findings(findings: List[Finding], host: str = "*") -> Tuple[List[Finding], Optional[Finding]]:
|
||
"""Bound one tick's output; overflow becomes a single state line.
|
||
|
||
An attacker rotating source addresses can otherwise mint one fingerprint per
|
||
address. The cap is not silence — the overflow line is a state rule (24 h
|
||
cooldown), so it keeps re-announcing while the flood continues.
|
||
"""
|
||
if len(findings) <= config.HTTP_MAX_NEW_PER_TICK:
|
||
return findings, None
|
||
ordered = sorted(findings, key=lambda f: (SEVERITY_ORDER.get(f.severity, 9), f.entity))
|
||
kept = ordered[: config.HTTP_MAX_NEW_PER_TICK]
|
||
dropped = len(ordered) - len(kept)
|
||
overflow = Finding(
|
||
rule="http-flood", kind="state", severity="MEDIUM",
|
||
entity="overflow|%s" % host,
|
||
detail="%d more new client/path finding(s) suppressed this tick (cap %d)"
|
||
% (dropped, config.HTTP_MAX_NEW_PER_TICK),
|
||
)
|
||
return kept, overflow
|
||
|
||
|
||
def _now_iso() -> str:
|
||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||
|
||
|
||
__all__ = [
|
||
"classify", "client_of", "decode_path", "rule_attack_paths", "rule_auth_rate",
|
||
"cap_findings", "scanner_family", "served",
|
||
]
|