netsec-scan: a seed is silent for its whole span, --dry-run included
The seeding guard only ran in on_batch for the archive path, so a cold start still announced the entire retained window whenever the tick was a --dry-run (11-14 egress-new-dst lines: history reported as news, all of it inside the window the line itself quoted). The guard also lived *after* the flow rules had already produced findings, and it was skipped entirely for dry runs. - absorption now happens in on_batch and is keyed on 'seeded' alone, so it covers the cold start, every resume tick of a budget-limited seed, and --dry-run (history is not news in a dry run either); - each seeding tick explains its silence on stderr: 'seed: N tuple(s) absorbed, 0 reported; window Xh from <stamp>, N file(s)', including the still-pending count when the budget stopped the pass; - the warm-state archive pass gets the same one-line summary; - state.seed.absorbed records the count, and absorb() reports whether a fingerprint was new so the number is the baseline's growth, not a loop counter. tests/test_seed.py pins all four: cold start, dry-run cold start, resume tick while unseeded, and single-fire from a seeded state (the guard must not turn into a permanently silent sensor).
This commit is contained in:
parent
ba1bef3814
commit
bde343c75f
4 changed files with 244 additions and 48 deletions
|
|
@ -43,6 +43,16 @@ def log(msg: str, verbose: bool) -> None:
|
|||
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")
|
||||
|
|
@ -115,6 +125,16 @@ def observe_window(st: Dict[str, Any], now: float) -> Optional[float]:
|
|||
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`.
|
||||
|
|
@ -248,7 +268,7 @@ def consume_flows(store: BaseStore, st: Dict[str, Any], verbose: bool,
|
|||
return stats
|
||||
|
||||
|
||||
def absorb(st: Dict[str, Any], kind: str, entity: str, rule: str, severity: str) -> None:
|
||||
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
|
||||
|
|
@ -256,12 +276,19 @@ def absorb(st: Dict[str, Any], kind: str, entity: str, rule: str, severity: str)
|
|||
"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")
|
||||
st["seen"].setdefault(fingerprint(rule, entity), {
|
||||
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,
|
||||
|
|
@ -371,27 +398,54 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||
# 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 source == "archive" and not archive_baseline and not seeding:
|
||||
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. 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)
|
||||
# nothing.
|
||||
baseline["archive"] += absorb_batch(batch, out)
|
||||
return
|
||||
flow_findings.extend(out)
|
||||
|
||||
|
|
@ -417,20 +471,27 @@ 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))
|
||||
|
||||
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:
|
||||
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.
|
||||
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"]):
|
||||
absorb(st, "novelty", key, "egress-new-dst", "MEDIUM")
|
||||
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"),
|
||||
|
|
@ -439,6 +500,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||
"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,
|
||||
|
|
@ -449,21 +511,22 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||
"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)
|
||||
# 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:
|
||||
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)
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -195,6 +195,9 @@ def _window_label(hours: float) -> str:
|
|||
return "%.1fd" % (hours / 24.0)
|
||||
|
||||
|
||||
window_label = _window_label # public name: the seed summary prints it too
|
||||
|
||||
|
||||
def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict],
|
||||
counts: Dict[str, dict], now: datetime,
|
||||
window_h: Optional[float] = None, tick: int = 0) -> List[Finding]:
|
||||
|
|
|
|||
Loading…
Reference in a new issue