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:
parent
68b2616cc5
commit
c31d46a037
6 changed files with 174 additions and 52 deletions
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -165,6 +165,16 @@ def _egress_key(flow: Flow) -> Optional[str]:
|
|||
return "%s->%s:%d/%s" % (flow.src_workload, flow.dst_ip, flow.dst_port, flow.proto.lower())
|
||||
|
||||
|
||||
def egress_keys(flows: Iterable[Flow]) -> List[str]:
|
||||
"""Every external destination tuple in this slice (novel or not)."""
|
||||
keys = []
|
||||
for flow in flows:
|
||||
key = _egress_key(flow)
|
||||
if key and key not in keys:
|
||||
keys.append(key)
|
||||
return keys
|
||||
|
||||
|
||||
def prune_beacon(beacon: Dict[str, Dict[str, float]], now: float) -> None:
|
||||
"""Drop sockets that fell out of the window from every tracked tuple."""
|
||||
cutoff = now - config.BEACON_WINDOW
|
||||
|
|
@ -176,25 +186,54 @@ def prune_beacon(beacon: Dict[str, Dict[str, float]], now: float) -> None:
|
|||
beacon.pop(key, None)
|
||||
|
||||
|
||||
def rule_egress_first_seen(flows: Iterable[Flow], egress_seen: Dict[str, str],
|
||||
now: datetime) -> List[Finding]:
|
||||
def _window_label(hours: float) -> str:
|
||||
"""Observation window in the shortest honest form."""
|
||||
if hours < 1:
|
||||
return "%dm" % max(1, int(round(hours * 60)))
|
||||
if hours < 48:
|
||||
return "%.1fh" % hours
|
||||
return "%.1fd" % (hours / 24.0)
|
||||
|
||||
|
||||
def rule_egress_first_seen(flows: Iterable[Flow], seen: Dict[str, dict],
|
||||
now: datetime, window_h: float = None) -> List[Finding]:
|
||||
"""First-seen egress tuple = candidate beacon/exfil.
|
||||
|
||||
The seen-set is cumulative and seeded silently on the first run, so
|
||||
deploying this sensor cannot dump the whole retained history into chat.
|
||||
Novelty is gated on the **cumulative seen-set only** (fingerprint presence),
|
||||
so there is exactly one place that decides "already reported": deleting a
|
||||
fingerprint from `seen` re-arms the rule, which is what the acceptance
|
||||
procedure exercises.
|
||||
|
||||
The alert says how long this sensor has actually been watching
|
||||
(`window_h`): the collector caps at 1 GiB, which at the measured ~2 MB/min
|
||||
is days, not the month the design note assumed. Never imply a longer
|
||||
baseline than was observed.
|
||||
|
||||
A `DROPPED` verdict on a new to-world tuple is its own signal (the pod tried
|
||||
something that policy refused), so it is keyed and graded separately from
|
||||
the forwarded traffic for the same destination.
|
||||
"""
|
||||
out: List[Finding] = []
|
||||
window = (" (no prior in ~%s of observed flows)" % _window_label(window_h)
|
||||
if window_h else " (no prior in observed flows)")
|
||||
for flow in flows:
|
||||
key = _egress_key(flow)
|
||||
if not key or key in egress_seen:
|
||||
if not key:
|
||||
continue
|
||||
egress_seen[key] = (flow.time or now).astimezone(timezone.utc).isoformat()
|
||||
port = flow.dst_port
|
||||
severity = "MEDIUM" if port in config.WEB_PORTS else "HIGH"
|
||||
out.append(Finding(
|
||||
dropped = flow.verdict == "DROPPED"
|
||||
if dropped:
|
||||
key += "/dropped"
|
||||
if flow.dst_port in config.WEB_PORTS and not dropped:
|
||||
severity = "MEDIUM"
|
||||
else:
|
||||
severity = "HIGH"
|
||||
finding = Finding(
|
||||
rule="egress-new-dst", kind="novelty", severity=severity, entity=key,
|
||||
detail="%s first-seen %s (no prior in retained window)" % (key, _ts(flow.time)),
|
||||
))
|
||||
detail="%s first-seen %s%s" % (key, _ts(flow.time), window),
|
||||
)
|
||||
if finding.fingerprint in seen:
|
||||
continue
|
||||
out.append(finding)
|
||||
return out
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -33,8 +33,8 @@ def empty() -> Dict[str, Any]:
|
|||
"created_at": _now_iso(),
|
||||
"seeded": False, # flow novelty has been baselined once
|
||||
"seen": {}, # fp -> {rule, kind, entity, severity, first, last_alert}
|
||||
"egress": {}, # tuple -> first_seen iso (cumulative)
|
||||
"beacon": {}, # tuple -> {socket: ts}
|
||||
"observed_since": None, # earliest flow timestamp ever observed (ISO)
|
||||
"files": {}, # name -> {offset, carry, size}
|
||||
"degraded": {}, # failure class -> iso of last announcement
|
||||
"day": {"date": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||
|
|
@ -56,7 +56,7 @@ def load(path: Path) -> Dict[str, Any]:
|
|||
base = empty()
|
||||
for key, value in base.items():
|
||||
data.setdefault(key, value)
|
||||
for key in ("seen", "egress", "beacon", "files", "degraded"):
|
||||
for key in ("seen", "beacon", "files", "degraded"):
|
||||
if not isinstance(data.get(key), dict):
|
||||
data[key] = {}
|
||||
return data
|
||||
|
|
@ -80,11 +80,9 @@ def prune(state: Dict[str, Any]) -> None:
|
|||
ordered = sorted(seen.items(), key=lambda kv: kv[1].get("first", ""))
|
||||
for key, _ in ordered[: len(ordered) - config.MAX_SEEN + 2000]:
|
||||
seen.pop(key, None)
|
||||
egress = state["egress"]
|
||||
if len(egress) > config.MAX_EGRESS:
|
||||
ordered = sorted(egress.items(), key=lambda kv: kv[1])
|
||||
for key, _ in ordered[: len(ordered) - config.MAX_EGRESS + 2000]:
|
||||
egress.pop(key, None)
|
||||
egress = state["day"].get("egress", [])
|
||||
if len(egress) > config.MAX_DAY_EGRESS:
|
||||
state["day"]["egress"] = egress[-config.MAX_DAY_EGRESS:]
|
||||
beacon = state["beacon"]
|
||||
if len(beacon) > config.MAX_BEACON_TUPLES:
|
||||
ordered = sorted(beacon.items(),
|
||||
|
|
|
|||
Loading…
Reference in a new issue