2026-11-27 00:20:46 -05:00
|
|
|
"""Daily baseline report — no alert, just the numbers thresholds get tuned from.
|
|
|
|
|
|
|
|
|
|
Written to `reports/YYYY-MM-DD.json` on every tick, so the file for "today"
|
|
|
|
|
always exists and carries real counts; it becomes final at the UTC day
|
|
|
|
|
rollover when a new file starts.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import json
|
|
|
|
|
import os
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
from typing import Any, Dict
|
|
|
|
|
|
|
|
|
|
from . import config
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def build(state: Dict[str, Any]) -> Dict[str, Any]:
|
|
|
|
|
day = state.get("day") or {}
|
|
|
|
|
egress = day.get("egress", [])
|
|
|
|
|
new_dsts = day.get("new_dsts", [])
|
|
|
|
|
rules = day.get("rules", {})
|
|
|
|
|
flows = int(day.get("flows", 0))
|
|
|
|
|
return {
|
|
|
|
|
"date": day.get("date"),
|
|
|
|
|
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
|
|
|
"flows": flows,
|
|
|
|
|
"findings_emitted": {k: int(v) for k, v in sorted(rules.items())},
|
|
|
|
|
"findings_total": sum(int(v) for v in rules.values() if str(v).isdigit()),
|
|
|
|
|
"egress_tuples_seen": len(egress),
|
|
|
|
|
"egress_tuples": sorted(egress),
|
|
|
|
|
"top_new_destinations": new_dsts[-10:],
|
|
|
|
|
"seen_fingerprints_cumulative": len(state.get("seen", {})),
|
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 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 {},
|
netsec-scan: read flows-*.jsonl.gz so a cold start baselines the retained window, not the live file
The collector gzips on rotation, so FLOW_PATTERN 'flows-*.jsonl' saw 1 of 5
files (measured: 1/72 of the retained window). Archives are immutable, so each
is read once, whole, decrypted lazily and recorded in state['archives'].
- archives are bounded (ARCHIVE_MAX_SECONDS/BYTES/FILES, newest first) and
flows are consumed in batches; a partial pass leaves state seeded=false and
reports the unread files as pending, so the next tick continues instead of
alerting from a window it has not examined
- the alert window comes from the coverage start in the consumed filenames
(monotone), so 'no prior in ~Xh of observed flows' is now verifiable
- the seed absorbs every egress tuple in the window, not just findings (a
web-port tuple never becomes one on its first tick); a warm state meeting
archives for the first time absorbs them the same way
- a torn .gz keeps its readable prefix, is noted in state/seed.failed, and does
not abort the tick; in-flight *.gz.tmp.* markers are never read
- report.json carries window_h/covered_since/seed; 12 new tests
2026-11-27 02:09:51 -05:00
|
|
|
# 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.
|
|
|
|
|
"window_h": state.get("window_h"),
|
|
|
|
|
"covered_since": state.get("observed_since"),
|
|
|
|
|
"seed": state.get("seed") or {},
|
|
|
|
|
"files": {"plain": len(state.get("files") or {}),
|
|
|
|
|
"archives": len(state.get("archives") or {})},
|
2026-11-27 00:20:46 -05:00
|
|
|
"state_totals": state.get("totals", {}),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write(state: Dict[str, Any], directory: Path = None) -> Path:
|
|
|
|
|
directory = Path(directory or config.REPORT_DIR)
|
|
|
|
|
directory.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
day = (state.get("day") or {}).get("date") or datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
|
|
|
path = directory / f"{day}.json"
|
|
|
|
|
tmp = path.with_suffix(".json.tmp")
|
|
|
|
|
tmp.write_text(json.dumps(build(state), indent=2, sort_keys=True) + "\n")
|
|
|
|
|
os.replace(tmp, path)
|
|
|
|
|
return path
|