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
This commit is contained in:
parent
f4001d589e
commit
ba1bef3814
8 changed files with 690 additions and 98 deletions
|
|
@ -17,14 +17,19 @@ import time
|
|||
import traceback
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
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,
|
||||
)
|
||||
|
|
@ -69,14 +74,107 @@ def render(finding: Finding) -> str:
|
|||
return line
|
||||
|
||||
|
||||
def collect_flows(store: BaseStore, st: Dict[str, Any], verbose: bool) -> Tuple[List, int, int]:
|
||||
"""Read every un-consumed byte of every collector file; parse complete lines."""
|
||||
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 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()
|
||||
parsed = []
|
||||
malformed = 0
|
||||
live = set()
|
||||
for name, size in files:
|
||||
live.add(name)
|
||||
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
|
||||
|
|
@ -84,60 +182,102 @@ def collect_flows(store: BaseStore, st: Dict[str, Any], verbose: bool) -> Tuple[
|
|||
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:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except ValueError:
|
||||
malformed += 1
|
||||
continue
|
||||
flow = parse_flow(obj)
|
||||
if flow is None:
|
||||
malformed += 1
|
||||
continue
|
||||
parsed.append(flow)
|
||||
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)
|
||||
# Forget files the collector rotated away (their bytes are already consumed).
|
||||
|
||||
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)
|
||||
return parsed, malformed, len(files)
|
||||
for name in list(known):
|
||||
if name not in live:
|
||||
known.pop(name, None)
|
||||
|
||||
stats["seconds"] = round(time.monotonic() - started, 2)
|
||||
return stats
|
||||
|
||||
|
||||
def track_window(st: Dict[str, Any], flows: List) -> Optional[float]:
|
||||
"""Hours of flow history this sensor has actually observed.
|
||||
def absorb(st: Dict[str, Any], kind: str, entity: str, rule: str, severity: str) -> None:
|
||||
"""Add a novelty fingerprint to the baseline without announcing it.
|
||||
|
||||
The collector caps at 1 GiB (days, not weeks), and the state may be younger
|
||||
than that, so a first-seen judgement is only ever "no prior in <window>".
|
||||
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.
|
||||
"""
|
||||
times = [f.time for f in flows if getattr(f, "time", None)]
|
||||
if not times:
|
||||
return st.get("window_h")
|
||||
earliest = min(times)
|
||||
prev = st.get("observed_since")
|
||||
if prev:
|
||||
try:
|
||||
earliest = min(earliest, datetime.fromisoformat(prev))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
st["observed_since"] = earliest.isoformat(timespec="seconds")
|
||||
hours = max(0.0, (datetime.now(timezone.utc) - earliest).total_seconds() / 3600.0)
|
||||
st["window_h"] = round(hours, 2)
|
||||
return st["window_h"]
|
||||
now_iso = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
st["seen"].setdefault(fingerprint(rule, entity), {
|
||||
"rule": rule, "kind": kind, "entity": entity, "severity": severity,
|
||||
"first": now_iso, "last_alert": now_iso, "seeded": 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."""
|
||||
"""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)
|
||||
|
|
@ -227,9 +367,44 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||
return 2
|
||||
|
||||
try:
|
||||
flows, malformed, file_count = collect_flows(store, st, args.verbose)
|
||||
log("parsed %d flows from %d file(s), %d malformed"
|
||||
% (len(flows), file_count, malformed), args.verbose)
|
||||
# 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)
|
||||
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()
|
||||
|
||||
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 source == "archive" and not archive_baseline and not seeding:
|
||||
# Archives this sensor has never read, while its baseline came
|
||||
# from the live file only: absorb the whole batch, announce
|
||||
# nothing. Every tuple counts, not just the findings — a web-port
|
||||
# tuple never becomes a finding on its first tick.
|
||||
for key in rules.egress_keys(batch):
|
||||
absorb(st, "novelty", key, "egress-new-dst", "MEDIUM")
|
||||
for finding in out:
|
||||
absorb(st, finding.kind, finding.entity, finding.rule,
|
||||
finding.severity)
|
||||
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:
|
||||
|
|
@ -242,36 +417,58 @@ 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))
|
||||
|
||||
seeding = not st.get("seeded")
|
||||
window_h = track_window(st, flows)
|
||||
tick = int(st["totals"].get("ticks", 0)) + 1
|
||||
new_egress = rules.rule_egress_first_seen(
|
||||
flows, st["seen"], st["egress_counts"], _utcnow(), window_h, tick)
|
||||
beacon = rules.rule_beacon(flows, st["beacon"], now)
|
||||
rules.prune_beacon(st["beacon"], now)
|
||||
flow_findings = new_egress + beacon
|
||||
|
||||
if seeding and not args.dry_run:
|
||||
# Baseline run: record history silently instead of dumping the
|
||||
# retained window into chat. PromQL findings still speak (they are
|
||||
# current state, not history).
|
||||
for finding in flow_findings:
|
||||
st["seen"].setdefault(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"),
|
||||
"seeded": True,
|
||||
})
|
||||
st["seeded"] = True
|
||||
st["seeded_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
log("seed run: %d flow findings recorded silently" % len(flow_findings),
|
||||
args.verbose)
|
||||
absorb(st, finding.kind, finding.entity, finding.rule, finding.severity)
|
||||
# The baseline must absorb *every* egress tuple in the window, not
|
||||
# only the ones that became findings. A web-port tuple needs
|
||||
# EGRESS_WEB_MIN_TICKS distinct ticks before it is worth a line, so
|
||||
# it never becomes a finding on the one seeding tick — and would then
|
||||
# alert on tick 3 for traffic that was in the retained window all
|
||||
# along. That is the alert storm this file exists to prevent.
|
||||
for key in list(st["egress_counts"]):
|
||||
absorb(st, "novelty", key, "egress-new-dst", "MEDIUM")
|
||||
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"]),
|
||||
"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 instead of alerting from a window
|
||||
# that is still being filled.
|
||||
log("seed: budget hit with %d archive(s) pending (%s); baseline "
|
||||
"covers %sh so far, continuing next tick"
|
||||
% (len(stats["pending"]), ", ".join(sorted(stats["pending"])[:3]),
|
||||
window_h), args.verbose)
|
||||
else:
|
||||
st["seeded"] = True
|
||||
st["seeded_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
log("seed run: %d file(s) (%d archive(s)), window %sh, %d tuple(s), "
|
||||
"%d fingerprint(s) recorded silently in %.2fs"
|
||||
% (stats["files_read"], stats["archives"], window_h,
|
||||
len(st["egress_counts"]), len(st["seen"]), stats["seconds"]),
|
||||
args.verbose)
|
||||
flow_findings = []
|
||||
|
||||
emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run)
|
||||
|
||||
record_counters(st, len(flows), emitted, rules.egress_keys(flows), malformed)
|
||||
record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"])
|
||||
state_mod.prune(st)
|
||||
|
||||
if not args.dry_run:
|
||||
|
|
|
|||
Loading…
Reference in a new issue