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
|
||||
|
|
|
|||
Loading…
Reference in a new issue