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:
parent
bde343c75f
commit
63bac6e06f
9 changed files with 1216 additions and 16 deletions
|
|
@ -17,7 +17,7 @@ import time
|
|||
import traceback
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from . import config, report, rules, state as state_mod
|
||||
from .flows import (
|
||||
|
|
@ -332,7 +332,8 @@ def apply_dedupe(findings: List[Finding], seen: Dict[str, Any], now: float,
|
|||
|
||||
|
||||
def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding],
|
||||
egress_tick: List[str], malformed: int) -> None:
|
||||
egress_tick: List[str], malformed: int,
|
||||
http_stats: Optional[Dict[str, Any]] = None) -> None:
|
||||
state_mod.roll_day(st)
|
||||
day = st["day"]
|
||||
day["flows"] = int(day.get("flows", 0)) + flows
|
||||
|
|
@ -349,12 +350,136 @@ def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding],
|
|||
if key not in known:
|
||||
known.append(key)
|
||||
known.sort()
|
||||
if http_stats:
|
||||
http = day.setdefault("http", {"ticks": 0, "matched_lines": 0,
|
||||
"by_rule": {}, "truncated_ticks": 0})
|
||||
http["ticks"] = int(http.get("ticks", 0)) + 1
|
||||
for key in ("lines_processed", "bytes_processed"):
|
||||
if http_stats.get(key) is not None:
|
||||
http[key] = int(http.get(key, 0)) + int(http_stats[key])
|
||||
http["matched_lines"] = int(http.get("matched_lines", 0)) + int(http_stats.get("matched_lines", 0))
|
||||
if http_stats.get("truncated"):
|
||||
http["truncated_ticks"] = int(http.get("truncated_ticks", 0)) + 1
|
||||
for rule, n in (http_stats.get("by_rule") or {}).items():
|
||||
http["by_rule"][rule] = int(http["by_rule"].get(rule, 0)) + int(n)
|
||||
st["totals"]["ticks"] = int(st["totals"].get("ticks", 0)) + 1
|
||||
st["totals"]["flows"] = int(st["totals"].get("flows", 0)) + flows
|
||||
st["totals"]["findings"] = int(st["totals"].get("findings", 0)) + len(emitted)
|
||||
st["totals"]["malformed"] = int(st["totals"].get("malformed", 0)) + malformed
|
||||
|
||||
|
||||
# ------------------------------------------------------- gateway rules ----
|
||||
def http_attack_expr() -> str:
|
||||
"""LogQL for candidate access lines: `|~` filter only, no `| json` pass.
|
||||
|
||||
The returned line *is* the parsed JSON object, so extraction happens once, in
|
||||
Python, where a malformed line costs a `continue` instead of a pipeline
|
||||
error. Backtick string: a regex with `\\.` inside a double-quoted LogQL
|
||||
literal is an escape minefield.
|
||||
"""
|
||||
return "%s |~ `%s`" % (config.LOKI_STREAM, config.HTTP_LINE_FILTER)
|
||||
|
||||
|
||||
def http_rate_expr() -> str:
|
||||
"""Per-client 401/403 counts in 1-minute buckets, aggregated by Loki."""
|
||||
return (
|
||||
'sum by (client_ip, peer) (count_over_time(%s'
|
||||
' | json response_code, client_ip, peer'
|
||||
' | response_code != ""'
|
||||
' | response_code >= 401 and response_code <= 403 [1m]))' % config.LOKI_STREAM
|
||||
)
|
||||
|
||||
|
||||
def http_step(st: Dict[str, Any], start_end: Tuple[float, float], args,
|
||||
verbose: bool) -> Tuple[List[Finding], Dict[str, Any]]:
|
||||
"""One tick of the §4d rules: two Loki queries, then classification.
|
||||
|
||||
Loki does the volume reduction (one line-filter scan + one aggregated
|
||||
metric scan). Nothing is written to disk except a handful of counters, and
|
||||
no seen-set beyond the existing cumulative `seen` map is added: the windows
|
||||
are re-queried each tick and dedupe is the fingerprint map.
|
||||
"""
|
||||
from . import http_rules, loki
|
||||
|
||||
start, end = start_end
|
||||
window = max(60, int(end - start))
|
||||
window_label = "%dm" % max(1, int(round(window / 60.0)))
|
||||
|
||||
streams, summary = loki.query_range(
|
||||
http_attack_expr(), start, end, config.HTTP_MAX_LINES)
|
||||
records: List[Dict[str, Any]] = []
|
||||
dedupe = set()
|
||||
for _labels, values in streams:
|
||||
for _ts, line in values:
|
||||
try:
|
||||
rec = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if not isinstance(rec, dict) or "path" not in rec:
|
||||
continue
|
||||
# Loki can surface the same line through two streams after a pod
|
||||
# restart; the count must not double for that.
|
||||
key = (rec.get("start_time"), rec.get("method"), rec.get("path"),
|
||||
rec.get("response_code"), rec.get("client_ip"), rec.get("peer"))
|
||||
if key in dedupe:
|
||||
continue
|
||||
dedupe.add(key)
|
||||
records.append(rec)
|
||||
findings, by_rule = http_rules.rule_attack_paths(records, window_label)
|
||||
|
||||
rate_findings: List[Finding] = []
|
||||
rate_series = 0
|
||||
rate_window = min(config.HTTP_RATE_WINDOW, window)
|
||||
if rate_window >= 60:
|
||||
matrix = loki.query_matrix(
|
||||
http_rate_expr(), end - rate_window, end, 60)
|
||||
rate_findings, rate_series = http_rules.rule_auth_rate(
|
||||
matrix, "%dm" % max(1, int(round(rate_window / 60.0))))
|
||||
|
||||
kept, overflow = http_rules.cap_findings(findings, host="gateway")
|
||||
all_findings = kept + rate_findings
|
||||
if overflow is not None:
|
||||
all_findings.append(overflow)
|
||||
|
||||
stats = {
|
||||
"window": window_label,
|
||||
# Loki omits `stats` on this deployment's query_range responses, so these
|
||||
# are recorded only when present; `matched_lines` is always exact and is
|
||||
# the number that matters (it is what crossed the wire to this process).
|
||||
"lines_processed": (int(float(summary["totalLinesProcessed"]))
|
||||
if summary.get("totalLinesProcessed") is not None else None),
|
||||
"bytes_processed": (int(float(summary["totalBytesProcessed"]))
|
||||
if summary.get("totalBytesProcessed") is not None else None),
|
||||
"matched_lines": len(records),
|
||||
"truncated": len(records) >= config.HTTP_MAX_LINES,
|
||||
"rate_series": rate_series,
|
||||
"by_rule": dict(by_rule),
|
||||
"findings": len(all_findings),
|
||||
}
|
||||
log("http: %s window, %d candidate line(s) received, %d attack finding(s), "
|
||||
"%d client(s) with 401/403, %d finding(s) total"
|
||||
% (window_label, stats["matched_lines"], len(findings), rate_series,
|
||||
len(all_findings)), verbose)
|
||||
|
||||
hstate = st.setdefault("http", {})
|
||||
if not hstate.get("baselined_at") and not args.dry_run:
|
||||
# Same contract as the flow seed: the first HTTP tick records what is
|
||||
# already in the window instead of dumping existing scanner traffic.
|
||||
for finding in all_findings:
|
||||
absorb(st, finding.kind, finding.entity, finding.rule, finding.severity)
|
||||
hstate["baselined_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
hstate["baseline"] = {"window": window_label,
|
||||
"matched_lines": stats["matched_lines"],
|
||||
"findings": len(all_findings),
|
||||
"by_rule": dict(by_rule)}
|
||||
log("http: baseline absorbed %d finding(s) silently" % len(all_findings), verbose)
|
||||
return [], stats
|
||||
hstate["last"] = {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"window": window_label, "matched_lines": stats["matched_lines"],
|
||||
"findings": len(all_findings)}
|
||||
return all_findings, stats
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- main ----
|
||||
def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
|
|
@ -365,6 +490,14 @@ def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
|
|||
parser.add_argument("--dry-run", action="store_true",
|
||||
help="print findings without writing state/report and without seen-set dedupe")
|
||||
parser.add_argument("--no-prom", action="store_true", help="skip the PromQL tripwires")
|
||||
parser.add_argument("--no-http", action="store_true",
|
||||
help="skip the gateway access-log rules (Loki)")
|
||||
parser.add_argument("--http", action="store_true",
|
||||
help="run the gateway rules even in --fixture/--flows-dir mode")
|
||||
parser.add_argument("--http-window", type=int, metavar="SECONDS",
|
||||
help="gateway log look-back window (default %d)" % config.HTTP_WINDOW)
|
||||
parser.add_argument("--http-end", metavar="EPOCH|ISO8601",
|
||||
help="evaluate the gateway rules as of this instant (forensics; default now)")
|
||||
parser.add_argument("--state", help="state file path (default ~/.hermes/cron/netsec-scan-state.json)")
|
||||
parser.add_argument("--reports", help="report directory (default ~/Projects/netsec-agent/reports)")
|
||||
parser.add_argument("--verbose", action="store_true", help="debug lines on stderr")
|
||||
|
|
@ -377,6 +510,10 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||
reports_dir = Path(args.reports or config.REPORT_DIR)
|
||||
now = time.time()
|
||||
|
||||
# The gateway rules are an independent input (Loki, not the flow store), so
|
||||
# they are on whenever this runs as a sensor and off for fixture/local runs
|
||||
# unless asked: a unit test must never reach the network.
|
||||
http_enabled = not args.no_http and (args.http or not (args.fixture or args.flows_dir))
|
||||
if args.fixture:
|
||||
store: BaseStore = SingleFileStore(args.fixture)
|
||||
prom_enabled = False
|
||||
|
|
@ -471,6 +608,14 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||
log("rule %s failed: %s" % (rule.__name__, exc), args.verbose)
|
||||
raise SensorError("prom-error", "%s: %s" % (rule.__name__, exc))
|
||||
|
||||
http_stats: Optional[Dict[str, Any]] = None
|
||||
if http_enabled:
|
||||
http_end = _parse_instant(args.http_end) if args.http_end else now
|
||||
http_window = args.http_window or config.HTTP_WINDOW
|
||||
http_findings, http_stats = http_step(
|
||||
st, (http_end - http_window, http_end), args, args.verbose)
|
||||
findings.extend(http_findings)
|
||||
|
||||
if baseline["archive"]:
|
||||
# Not a fault, and not news either: these tuples are inside the
|
||||
# window the next alert would quote. Say so once, loudly enough to
|
||||
|
|
@ -531,7 +676,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||
|
||||
emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run)
|
||||
|
||||
record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"])
|
||||
record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"],
|
||||
http_stats)
|
||||
state_mod.prune(st)
|
||||
|
||||
if not args.dry_run:
|
||||
|
|
@ -554,6 +700,18 @@ def _utcnow() -> datetime:
|
|||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _parse_instant(value: str) -> float:
|
||||
"""`--http-end`: epoch seconds or ISO-8601 (Z allowed)."""
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
|
||||
except ValueError:
|
||||
raise SensorError("bad-arg", "--http-end is neither epoch nor ISO-8601: %s" % value[:40])
|
||||
|
||||
|
||||
def _prommod():
|
||||
from . import prom
|
||||
return prom
|
||||
|
|
|
|||
|
|
@ -151,3 +151,60 @@ NON_EGRESS_NETS = (
|
|||
|
||||
KUBECTL_CANDIDATES = ("kubectl", "/usr/sbin/kubectl", "/usr/bin/kubectl", "/usr/local/bin/kubectl")
|
||||
SSH_CANDIDATES = ("ssh", "/usr/sbin/ssh", "/usr/bin/ssh")
|
||||
|
||||
# ------------------------------------------------- gateway access log ----
|
||||
# `cilium-envoy` writes one JSON access line per request (t_e662b03a); the
|
||||
# `logging` Alloy DaemonSet ships it to Loki with 192 h retention. The sensor
|
||||
# reads it **only** through LogQL so the filtering runs in Loki, not here.
|
||||
# Measured 2026-11-27: 641 B/line, 9.54 lines/s, 528 MB/day raw, 93.5 % Forgejo.
|
||||
LOKI_PROXY = (
|
||||
"/api/v1/namespaces/logging/services/loki:3100/proxy"
|
||||
)
|
||||
LOKI_TIMEOUT = int(os.environ.get("NETSEC_SCAN_LOKI_TIMEOUT", "25"))
|
||||
# Exact stream selector from the F7 handoff. Narrow on purpose: it is the
|
||||
# difference between reading one pod's stream on one node and the whole cluster.
|
||||
LOKI_STREAM = os.environ.get(
|
||||
"NETSEC_SCAN_LOKI_STREAM",
|
||||
'{namespace="kube-system", container="cilium-envoy", job="kube/pods", node="siriussec"}',
|
||||
)
|
||||
|
||||
# How far back each tick looks. The cron interval is 5 min, so 10 min guarantees
|
||||
# overlap across ticks (a line can never fall between two windows) and the
|
||||
# fingerprint dedupe absorbs the overlap. 10 min ≈ 3.6 MB scanned per query.
|
||||
HTTP_WINDOW = int(os.environ.get("NETSEC_SCAN_HTTP_WINDOW", "600"))
|
||||
HTTP_RATE_WINDOW = int(os.environ.get("NETSEC_SCAN_HTTP_RATE_WINDOW", "300"))
|
||||
HTTP_MAX_LINES = int(os.environ.get("NETSEC_SCAN_HTTP_MAX_LINES", "600"))
|
||||
# A tick may announce at most this many *new* client/path fingerprints; the rest
|
||||
# collapse into one `http-flood` state line. IP-rotating scanners would otherwise
|
||||
# mint one line per source address.
|
||||
HTTP_MAX_NEW_PER_TICK = int(os.environ.get("NETSEC_SCAN_HTTP_MAX_NEW", "12"))
|
||||
|
||||
# Severity control. Cloudflare replaces the socket peer with the tunnel
|
||||
# (10.10.0.1 on the Pi); `client_ip` is the real client there. A request with
|
||||
# neither is unattributable and is never used as a per-client key.
|
||||
HTTP_EDGE_PEERS = frozenset({"10.10.0.1"})
|
||||
# Only these hosts serve Forgejo browse URLs; on any other host the same path
|
||||
# shape (e.g. `/<a>/<b>/raw/.../.env`) is a probe, not a repository view.
|
||||
HTTP_FORGEJO_HOSTS = frozenset({"forgejo.siriusdevops.com"})
|
||||
|
||||
# 401/403 brute force per client. Measured on a calm hour 2026-11-27: 20 auth
|
||||
# failures *total*, all from the CI git client (git/2.56.0 retrying a push),
|
||||
# peak 1/min. Forgejo's legitimate 303 -> /user/login bulk is 3xx and never
|
||||
# counted. So 20 failures in one minute plus 30 over five minutes is a real
|
||||
# attempt, two orders of magnitude above the CI baseline.
|
||||
HTTP_AUTH_PER_MIN = int(os.environ.get("NETSEC_SCAN_HTTP_AUTH_PER_MIN", "20"))
|
||||
HTTP_AUTH_WINDOW_TOTAL = int(os.environ.get("NETSEC_SCAN_HTTP_AUTH_TOTAL", "30"))
|
||||
|
||||
# LogQL prefilter for attack-shaped *lines*. Deliberately a superset: Loki
|
||||
# drops non-matching bytes cheaply, and `http_rules.classify()` makes the precise
|
||||
# decision in Python (semantics the regex cannot express, e.g. Forgejo browse
|
||||
# URLs and smart-HTTP git). Measured over-matching: ~1 090 of 35 445 lines/h.
|
||||
HTTP_LINE_FILTER = os.environ.get(
|
||||
"NETSEC_SCAN_HTTP_LINE_FILTER",
|
||||
"(?i)(\\.\\.|%2e%2e|union|select|%00|%2500|\\.env|\\.git|\\.svn|\\.hg|"
|
||||
"credential|\\.aws|\\.ssh|id_rsa|\\.kube|\\.npmrc|\\.netrc|\\.htpasswd|"
|
||||
"secrets|service-account|\\.bak|\\.old|\\.orig|\\.save|\\.swp|\\.sql|"
|
||||
"\\.dump|\\.zip|\\.tar|\\.tgz|backup|sqlmap|nikto|nuclei|masscan|zgrab|"
|
||||
"nmap|wpscan|gobuster|dirbuster|ffuf|ferox|acunetix|netsparker|nessus|"
|
||||
"openvas|hydra|w3af|zaproxy)",
|
||||
)
|
||||
|
|
|
|||
353
netsec_scan/http_rules.py
Normal file
353
netsec_scan/http_rules.py
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
"""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",
|
||||
]
|
||||
120
netsec_scan/loki.py
Normal file
120
netsec_scan/loki.py
Normal 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
|
||||
|
|
@ -32,6 +32,9 @@ def build(state: Dict[str, Any]) -> Dict[str, Any]:
|
|||
"egress_tuples": sorted(egress),
|
||||
"top_new_destinations": new_dsts[-10:],
|
||||
"seen_fingerprints_cumulative": len(state.get("seen", {})),
|
||||
# Gateway access-log rules (§4d): how much the tick scanned, how many
|
||||
# candidate lines it matched, and what the rules counted today.
|
||||
"http": day.get("http") or {},
|
||||
# The baseline this sensor actually holds: which files it consumed and
|
||||
# the window they cover. "no prior in ~Xh" comes from this, never from a
|
||||
# guess.
|
||||
|
|
|
|||
Loading…
Reference in a new issue