netsec-agent/netsec_scan/__main__.py

766 lines
33 KiB
Python
Raw Permalink Normal View History

"""Entry point: one tick of the deterministic sensor.
Contract (see README):
* calm tick -> empty stdout, exit 0
* hit -> one line per fingerprint, `SEV <fp> <rule> <detail>` (<= 200 chars)
* degradation-> one memoized line naming the failure class, exit non-zero,
state file untouched
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
import traceback
from datetime import datetime, timezone
from pathlib import Path
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.
2026-11-27 02:17:14 -05:00
from typing import Any, Dict, List, Optional, Tuple
from . import config, report, rules, state as state_mod
from .flows import (
ArchiveTruncated,
BaseStore,
LocalFlowStore,
RemoteFlowStore,
SingleFileStore,
flow_stamp,
fingerprint,
is_archive,
iter_archive,
iter_lines,
parse_flow,
)
from .prom import SensorError
from .rules import SEVERITY_ORDER, Finding
# ------------------------------------------------------------- helpers ----
def log(msg: str, verbose: bool) -> None:
if verbose:
print("netsec-scan: " + msg, file=sys.stderr)
def note(msg: str) -> None:
"""Diagnostic that is always printed: it explains a non-obvious silence.
The seed lines use this. A tick whose stdout is empty must be
distinguishable from a tick whose baseline is still being built, and
`--verbose` is not something a cron job passes.
"""
print("netsec-scan: " + msg, file=sys.stderr)
def memo_path(state_path: Path) -> Path:
"""Degradation memo lives beside the state file, never inside it."""
return state_path.with_name(state_path.stem + ".memo.json")
def load_memo(path: Path) -> Dict[str, str]:
try:
data = json.loads(path.read_text())
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def save_memo(path: Path, memo: Dict[str, str]) -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(memo, indent=2, sort_keys=True) + "\n")
os.replace(tmp, path)
except OSError:
pass
def render(finding: Finding) -> str:
line = "%s %s %s %s" % (finding.severity, finding.fingerprint,
finding.rule, finding.detail)
if len(line) > config.MAX_LINE:
line = line[: config.MAX_LINE - 1] + "\u2026"
return line
def mark_coverage(st: Dict[str, Any], name: str) -> None:
"""Widen `observed_since` to the coverage start of a consumed file.
The filename stamp is the moment the collector opened that file, so it is
the exact start of the coverage (not an estimate), and the minimum over every
file ever consumed is the honest answer to "how far back have I looked".
Monotone: it only ever moves earlier.
"""
stamp = flow_stamp(name)
if stamp is None:
return
prev = st.get("observed_since")
if prev:
try:
if datetime.fromisoformat(prev) <= stamp:
return
except (TypeError, ValueError):
pass
st["observed_since"] = stamp.isoformat(timespec="seconds")
def observe_window(st: Dict[str, Any], now: float) -> Optional[float]:
"""Hours of flow history this sensor has actually consumed.
`observed_since` tracks consumed files, not just the live one, so this is
the number the alert quotes: "no prior in ~Xh of observed flows". Computed
before a tick reads anything, which is exact for every warm tick because new
files are always newer than the oldest thing already consumed.
"""
since = st.get("observed_since")
if not since:
return None
try:
start = datetime.fromisoformat(since)
except (TypeError, ValueError):
return None
hours = max(0.0, (now - start.timestamp()) / 3600.0)
st["window_h"] = round(hours, 2)
return st["window_h"]
def window_text(st: Dict[str, Any], window_h: Optional[float]) -> str:
"""The window the baseline actually covers, in the alert's own spelling."""
if not window_h:
return "no flow history yet"
since = st.get("observed_since")
if not since:
return rules.window_label(window_h)
return "%s from %s" % (rules.window_label(window_h), since)
def consume_flows(store: BaseStore, st: Dict[str, Any], verbose: bool,
on_batch, now: Optional[float] = None) -> Dict[str, Any]:
"""Walk the collector's store once, handing parsed flows to `on_batch`.
* Plain `.jsonl` is being appended to, so it is read from the last consumed
byte (a trailing partial line is carried in state, as before).
* `.jsonl.gz` is immutable once the collector renames it into place, so each
archive is decompressed once, in full, and its name recorded — never
re-read. This is what lets a cold start baseline against the retained
window instead of the live file's minutes.
* Archives are bounded (`config.ARCHIVE_MAX_*`): newest first, stop when the
time/byte/file budget is spent, leave the rest **unread** and report them
as pending so the next tick continues rather than silently narrowing the
baseline. Flows are handed over in batches so a multi-GB seed never exists
as a list of Flow objects.
"""
started = time.monotonic()
now = now if now is not None else started
budget = {"seconds": config.ARCHIVE_MAX_SECONDS,
"bytes": config.ARCHIVE_MAX_BYTES,
"files": config.ARCHIVE_MAX_FILES}
stats: Dict[str, Any] = {
"flows": 0, "malformed": 0, "lines": 0, "plain": 0, "archives": 0,
"archive_bytes": 0, "pending": [], "failed": {}, "files_read": 0,
"budget_hit": False, "seconds": 0.0,
}
batch: List = []
source_of_batch = {"value": "plain"}
def flush() -> None:
nonlocal batch
if batch:
on_batch(batch, source_of_batch["value"])
batch = []
def feed(line: str, source: str) -> None:
line = line.strip()
if not line:
return
try:
obj = json.loads(line)
except ValueError:
stats["malformed"] += 1
return
flow = parse_flow(obj)
if flow is None:
stats["malformed"] += 1
return
stats["flows"] += 1
source_of_batch["value"] = source
batch.append(flow)
if len(batch) >= config.FLOW_BATCH:
flush()
files = store.list_files()
live = {name for name, _size in files}
plain = [(name, size) for name, size in files if not is_archive(name)]
archives = [(name, size) for name, size in files if is_archive(name)]
for name, size in plain:
entry = st["files"].get(name) or {"offset": 0, "size": 0}
offset = int(entry.get("offset", 0) or 0)
if size < offset: # truncated or replaced under us
log("file %s shrank (%d < %d); restarting at 0" % (name, size, offset), verbose)
offset = 0
if size == offset:
st["files"][name] = {"offset": offset, "size": size}
mark_coverage(st, name)
continue
data = store.read_from(name, offset)
lines, partial = iter_lines(data)
consumed = offset + len(data) - len(partial)
for line in lines:
feed(line, "plain")
st["files"][name] = {"offset": consumed, "size": size}
mark_coverage(st, name)
stats["plain"] += 1
stats["files_read"] += 1
stats["lines"] += len(lines)
log("read %s: %d bytes, %d lines" % (name, len(data), len(lines)), verbose)
known = st.setdefault("archives", {})
unread = sorted((name for name, _size in archives if name not in known), reverse=True)
sizes = dict(archives)
for name in unread:
spent = time.monotonic() - started
if stats["archives"] and (spent > budget["seconds"]
or stats["archive_bytes"] > budget["bytes"]
or stats["archives"] >= budget["files"]):
stats["budget_hit"] = True
stats["pending"].append(name)
continue
lines = 0
error = None
try:
for line in iter_archive(store, name):
lines += 1
stats["archive_bytes"] += len(line)
feed(line, "archive")
except ArchiveTruncated as exc:
# Torn/partial archive: keep the readable prefix, note it, move on.
error = str(exc)[:160]
stats["failed"][name] = error
log("archive %s unreadable (%s); read %d line(s), skipped rest"
% (name, error, lines), verbose)
except SensorError:
raise
known[name] = {"size": sizes.get(name, 0),
"read_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"lines": lines}
if error:
known[name]["error"] = error
mark_coverage(st, name)
stats["archives"] += 1
stats["files_read"] += 1
stats["lines"] += lines
log("archive %s: %d line(s), %d bytes decompressed, %.1fs"
% (name, lines, stats["archive_bytes"], time.monotonic() - started), verbose)
flush()
# Forget entries the collector rotated/pruned away; their bytes are consumed
# and a collector filename can never come back.
for name in list(st["files"]):
if name not in live:
st["files"].pop(name, None)
for name in list(known):
if name not in live:
known.pop(name, None)
stats["seconds"] = round(time.monotonic() - started, 2)
return stats
def absorb(st: Dict[str, Any], kind: str, entity: str, rule: str, severity: str) -> bool:
"""Add a novelty fingerprint to the baseline without announcing it.
Used for history the sensor reads *after* the fact: the cold-start seed and
the first pass over pre-existing archives. Announcing those would print
"first-seen … (no prior in ~Xh of observed flows)" for a tuple that is
demonstrably inside that X hours — a false statement, and the alert storm
the state file exists to prevent.
Returns True when the fingerprint was new, so the caller can report how
much history it swallowed instead of leaving the silence unexplained.
"""
now_iso = datetime.now(timezone.utc).isoformat(timespec="seconds")
fp = fingerprint(rule, entity)
if fp in st["seen"]:
return False
st["seen"][fp] = {
"rule": rule, "kind": kind, "entity": entity, "severity": severity,
"first": now_iso, "last_alert": now_iso, "seeded": True,
}
return True
def apply_dedupe(findings: List[Finding], seen: Dict[str, Any], now: float,
dry_run: bool) -> List[Finding]:
"""Emit each fingerprint once; state rules may re-fire after the cooldown.
Batched consumption can surface the same finding from two batches (a beacon
is re-derived per batch), so a fingerprint already emitted in *this* tick is
dropped here as well — one line per finding per tick, always.
"""
emit: List[Finding] = []
this_tick = set()
for finding in findings:
if finding.fingerprint in this_tick:
continue
this_tick.add(finding.fingerprint)
prev = seen.get(finding.fingerprint)
if dry_run:
emit.append(finding)
continue
if prev is None:
seen[finding.fingerprint] = {
"rule": finding.rule,
"kind": finding.kind,
"entity": finding.entity,
"severity": finding.severity,
"first": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"last_alert": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
emit.append(finding)
continue
if finding.kind == "state":
try:
last = datetime.fromisoformat(prev.get("last_alert", "")).timestamp()
except (TypeError, ValueError):
last = 0.0
if now - last >= config.STATE_COOLDOWN:
prev["last_alert"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
emit.append(finding)
return emit
def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding],
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.
2026-11-27 02:17:14 -05:00
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
for finding in emitted:
day["rules"][finding.rule] = int(day["rules"].get(finding.rule, 0)) + 1
if finding.rule == "egress-new-dst":
day["new_dsts"].append(
{"tuple": finding.entity,
"first_seen": datetime.now(timezone.utc).isoformat(timespec="seconds")})
# `egress_tuples_seen` is the day's distinct external tuples, whether or not
# they were novel: it is the baseline rule 7 gets tuned from.
known = day.setdefault("egress", [])
for key in egress_tick:
if key not in known:
known.append(key)
known.sort()
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.
2026-11-27 02:17:14 -05:00
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
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.
2026-11-27 02:17:14 -05:00
# ------------------------------------------------------- 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(
prog="netsec-scan",
description="Deterministic netsec sensor: silent when calm, one line per hit.")
parser.add_argument("--fixture", help="read this JSONL file instead of the live collector")
parser.add_argument("--flows-dir", help="read flows-*.jsonl from this local directory")
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")
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.
2026-11-27 02:17:14 -05:00
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")
return parser.parse_args(argv)
def main(argv: Optional[List[str]] = None) -> int:
args = parse_args(argv)
state_path = Path(args.state or config.STATE_FILE)
reports_dir = Path(args.reports or config.REPORT_DIR)
now = time.time()
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.
2026-11-27 02:17:14 -05:00
# 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
elif args.flows_dir:
store = LocalFlowStore(args.flows_dir)
prom_enabled = not args.no_prom
else:
store = RemoteFlowStore()
prom_enabled = not args.no_prom
try:
st = state_mod.load(state_path)
except SensorError as exc:
print("SENSOR %s netsec-scan: %s" % (exc.cls, exc.detail or exc.cls))
return 2
try:
# Exact for any warm tick: `observed_since` is a monotone minimum over
# consumed files and everything read this tick is newer, so the number
# the findings quote cannot go stale mid-tick.
window_h = observe_window(st, now)
# `seeded` is false until one complete pass over the store has been
# absorbed: a cold start, and every resume tick after a budget hit. On
# all of those the entire retained window is history, so nothing the
# flow store produces may be announced — see on_batch. `seeded` only
# flips at the very end of a pass, which is what makes a resume tick
# silent instead of a second storm.
seeding = not st.get("seeded")
archive_baseline = bool(st.get("archive_baseline"))
tick = int(st["totals"].get("ticks", 0)) + 1
flow_findings: List[Finding] = []
tick_egress = set()
baseline = {"seed": 0, "archive": 0}
def absorb_batch(batch: List, out: List[Finding]) -> int:
"""Fold a slice of history into `seen`; returns new fingerprints."""
added = 0
# Every tuple counts, not just the findings: a web-port tuple needs
# EGRESS_WEB_MIN_TICKS distinct ticks before it is worth a line, so
# without this it would alert later for traffic that was inside the
# window all along.
for key in rules.egress_keys(batch):
if absorb(st, "novelty", key, "egress-new-dst", "MEDIUM"):
added += 1
for finding in out:
if absorb(st, finding.kind, finding.entity, finding.rule,
finding.severity):
added += 1
return added
def on_batch(batch: List, source: str) -> None:
tick_egress.update(rules.egress_keys(batch))
out = rules.rule_egress_first_seen(
batch, st["seen"], st["egress_counts"], _utcnow(), window_h, tick)
out += rules.rule_beacon(batch, st["beacon"], now)
if seeding:
# Cold start / resume: the rules still run (they build the
# egress counts and beacon history the warm ticks need) but
# every result is absorbed into the baseline. This is the guard
# that keeps a fresh state quiet instead of dumping the retained
# window into chat, and it holds for --dry-run as well: a dry
# run against an unseeded state is reading history, not news.
baseline["seed"] += absorb_batch(batch, out)
return
if source == "archive" and not archive_baseline:
# Archives this sensor has never read, while its baseline came
# from the live file only: absorb the whole batch, announce
# nothing.
baseline["archive"] += absorb_batch(batch, out)
return
flow_findings.extend(out)
stats = consume_flows(store, st, args.verbose, on_batch, now)
window_h = observe_window(st, now)
rules.prune_beacon(st["beacon"], now)
if stats["archives"] and not stats["pending"]:
st["archive_baseline"] = True
log("consumed %d flows from %d file(s) (%d archive(s), %d plain), %d malformed, "
"%d pending, %.2fs; window %sh"
% (stats["flows"], stats["files_read"], stats["archives"], stats["plain"],
stats["malformed"], len(stats["pending"]), stats["seconds"], window_h),
args.verbose)
findings: List[Finding] = []
if prom_enabled:
for rule in rules.PROM_RULES:
try:
findings.extend(rule(_prommod()))
except SensorError:
raise
except Exception as exc: # a broken rule must not eat the tick
log("rule %s failed: %s" % (rule.__name__, exc), args.verbose)
raise SensorError("prom-error", "%s: %s" % (rule.__name__, exc))
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.
2026-11-27 02:17:14 -05:00
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)
held = 0
if seeding and findings:
# A current-state tripwire is real, but a seed tick's contract is
# "stdout empty, one summary line" — printing here is what made a
# cold start indistinguishable from an alert storm. Record the
# fingerprints (nothing is forgotten) but leave a state rule *due*:
# no cooldown clock, so the first warm tick reports it instead of a
# 24 h STATE_COOLDOWN eating it. A seed spanning several ticks
# defers them by at most that many intervals.
for finding in findings:
fresh = absorb(st, finding.kind, finding.entity, finding.rule,
finding.severity)
if fresh and finding.kind == "state":
st["seen"][finding.fingerprint]["last_alert"] = ""
held = len(findings)
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
# be seen without --verbose.
note("archive baseline: %d tuple(s) absorbed, 0 reported; window %s"
% (baseline["archive"], window_text(st, window_h)))
if seeding:
# Baseline run: every flow-store result was already absorbed in
# on_batch and every current-state tripwire is held (above), so
# nothing reaches stdout and the tick's delivery outcome is
# `suppressed` by construction.
#
# Belt and braces: absorb *every* egress tuple the window carried,
# not only the ones this pass turned into findings. A web-port tuple
# needs EGRESS_WEB_MIN_TICKS distinct ticks, so it never becomes a
# finding on the tick it first appears and would otherwise alert on
# tick 3 for traffic that was inside the retained window all along.
# On a resume tick this is a no-op (already absorbed).
held_txt = ("%d current-state finding(s) held for the next tick"
% held) if held else ""
for key in list(st["egress_counts"]):
if absorb(st, "novelty", key, "egress-new-dst", "MEDIUM"):
baseline["seed"] += 1
st["seed"] = {
"started_at": st.get("seed", {}).get("started_at")
or datetime.now(timezone.utc).isoformat(timespec="seconds"),
"at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"files": stats["files_read"], "archives": stats["archives"],
"plain": stats["plain"], "flows": stats["flows"],
"tuples": len(st["egress_counts"]),
"fingerprints": len(st["seen"]),
"absorbed": baseline["seed"],
"seconds": stats["seconds"], "bytes": stats["archive_bytes"],
"covered_since": st.get("observed_since"),
"window_h": window_h,
"pending": len(stats["pending"]),
"failed": stats["failed"],
"budget": {"seconds": config.ARCHIVE_MAX_SECONDS,
"bytes": config.ARCHIVE_MAX_BYTES,
"files": config.ARCHIVE_MAX_FILES},
}
if stats["pending"]:
# Not a fault: the budget is the point. Stay unseeded so the
# next tick continues the baseline — and stays silent — instead
# of alerting from a window that is still being filled.
note("seed: %d tuple(s) absorbed, 0 reported; window %s so far, "
"%d archive(s) still pending, next tick continues silently%s"
% (baseline["seed"], window_text(st, window_h),
len(stats["pending"]),
"; " + held_txt if held_txt else ""))
else:
if not args.dry_run:
st["seeded"] = True
st["seeded_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
note("seed: %d tuple(s) absorbed, 0 reported; window %s, "
"%d file(s) (%d archive(s)) in %.2fs%s%s"
% (baseline["seed"], window_text(st, window_h),
stats["files_read"], stats["archives"], stats["seconds"],
"; " + held_txt if held_txt else "",
" (dry run: nothing persisted)" if args.dry_run else ""))
flow_findings = []
emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run)
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.
2026-11-27 02:17:14 -05:00
record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"],
http_stats)
state_mod.prune(st)
if not args.dry_run:
state_mod.save(state_path, st)
report.write(st, reports_dir)
except SensorError as exc:
return degrade(state_path, exc, args.verbose)
except Exception as exc: # never fail silently
traceback.print_exc(file=sys.stderr)
return degrade(state_path, SensorError("internal-error", str(exc)[:160]), args.verbose)
emitted.sort(key=lambda f: (SEVERITY_ORDER.get(f.severity, 9), f.rule, f.entity))
for finding in emitted:
print(render(finding))
return 0
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
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.
2026-11-27 02:17:14 -05:00
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
def degrade(state_path: Path, exc: SensorError, verbose: bool) -> int:
"""One memoized line per failure class; state file is never touched."""
memo_file = memo_path(state_path)
memo = load_memo(memo_file)
now = time.time()
last = memo.get(exc.cls)
announce = True
if last:
try:
announce = (now - datetime.fromisoformat(last).timestamp()) >= config.DEGRADED_MEMO
except (TypeError, ValueError):
announce = True
if announce:
detail = exc.detail or exc.cls
print("SENSOR %s netsec-scan: sensor input unavailable (%s)" % (exc.cls, detail))
memo[exc.cls] = datetime.now(timezone.utc).isoformat(timespec="seconds")
save_memo(memo_file, memo)
if verbose:
print("netsec-scan: degraded class=%s detail=%s" % (exc.cls, exc.detail),
file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())