netsec-agent/netsec_scan/__main__.py

586 lines
24 KiB
Python
Raw 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
from typing import Any, Dict, List, Optional
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],
egress_tick: List[str], malformed: int) -> 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()
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
# ----------------------------------------------------------------- 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")
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()
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))
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, so nothing from the retained window reaches stdout.
# PromQL findings still speak (they are current state, not history).
#
# 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).
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"
% (baseline["seed"], window_text(st, window_h),
len(stats["pending"])))
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"
% (baseline["seed"], window_text(st, window_h),
stats["files_read"], stats["archives"], stats["seconds"],
" (dry run: nothing persisted)" if args.dry_run else ""))
flow_findings = []
emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run)
record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"])
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)
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())