netsec-scan: honest observation window, /dropped tuples, report baseline counts

- first-seen egress is gated by the cumulative seen-set only (deleting a
  fingerprint re-arms the rule); the alert states the observed window
  (~20m / 3.2h / 2.1d) instead of implying the collector holds weeks.
- a DROPPED attempt on a new to-world tuple is keyed separately from forwarded
  traffic to the same destination and graded HIGH.
- daily report counts every external tuple seen that day, not just novel ones.
- drop-prune of the dead state['egress'] map; tests cover the single-fire rearm,
  day counters and the egress union.
- README: measured collector volume/tombstones/partial-tail behaviour, scheduler
  shim path.
This commit is contained in:
sirius 2026-11-27 00:24:22 -05:00
commit c31d46a037
6 changed files with 174 additions and 52 deletions

View file

@ -111,11 +111,32 @@ def collect_flows(store: BaseStore, st: Dict[str, Any], verbose: bool) -> Tuple[
return parsed, malformed, len(files)
def apply_dedupe(findings: List[Finding], st: Dict[str, Any], now: float,
def track_window(st: Dict[str, Any], flows: List) -> Optional[float]:
"""Hours of flow history this sensor has actually observed.
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>".
"""
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"]
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: List[Finding] = []
seen = st["seen"]
for finding in findings:
prev = seen.get(finding.fingerprint)
if dry_run:
@ -144,17 +165,23 @@ def apply_dedupe(findings: List[Finding], st: Dict[str, Any], now: float,
def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding],
new_egress: List[str], malformed: int) -> None:
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["egress"].append(finding.entity)
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)
@ -216,7 +243,8 @@ def main(argv: Optional[List[str]] = None) -> int:
raise SensorError("prom-error", "%s: %s" % (rule.__name__, exc))
seeding = not st.get("seeded")
new_egress = rules.rule_egress_first_seen(flows, st["egress"], _utcnow())
window_h = track_window(st, flows)
new_egress = rules.rule_egress_first_seen(flows, st["seen"], _utcnow(), window_h)
beacon = rules.rule_beacon(flows, st["beacon"], now)
rules.prune_beacon(st["beacon"], now)
flow_findings = new_egress + beacon
@ -239,9 +267,9 @@ def main(argv: Optional[List[str]] = None) -> int:
args.verbose)
flow_findings = []
emitted = apply_dedupe(findings + flow_findings, st, now, args.dry_run)
emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run)
record_counters(st, len(flows), emitted, new_egress, malformed)
record_counters(st, len(flows), emitted, rules.egress_keys(flows), malformed)
state_mod.prune(st)
if not args.dry_run: