netsec-agent/netsec_scan/rules.py
sirius be60d74159 netsec-scan: second-tick gate for web-port egress novelty (kill CDN churn)
One CI run produced 20 one-shot AWS/GitHub CDN destinations in a single 5-minute
tick (21-line message, nothing reached the operator only because delivery was
unresolved). First-seen tuples now carry per-tick observation counts in state:
web ports (80/443/8080/8443) need two distinct ticks before alerting, non-web
ports and any DROPPED verdict still alert on first sight. A beacon/exfil
destination is retried; CDN rotation is not.

Also: cron deliver switched to local because this profile has
platforms.telegram.enabled=false (deliver=telegram errors 'no delivery target
resolved'), and the README now documents that constraint.
2026-11-27 00:32:25 -05:00

290 lines
11 KiB
Python

"""The eight rules. Deterministic: a rule either trips on code or it doesn't.
Six PromQL tripwires + two flow-store novelty rules. Nothing here is allowed to
use the `pod` label on a `hubble_*` metric: it is the Cilium *agent* pod, so a
per-workload PromQL rule would measure agents forever. Workload attribution
comes from the flow JSONL instead.
"""
from __future__ import annotations
import statistics
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Dict, Iterable, List, Optional, Tuple
from . import config
from .flows import Flow, fingerprint, is_external
@dataclass
class Finding:
rule: str
kind: str # "state" (cooldown) | "novelty" (fire once, ever)
severity: str # HIGH | MEDIUM | LOW
entity: str
detail: str
fingerprint: str = field(default="")
def __post_init__(self) -> None:
if not self.fingerprint:
self.fingerprint = fingerprint(self.rule, self.entity)
SEVERITY_ORDER = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
def _ts(t: Optional[datetime]) -> str:
if not t:
return "??:??Z"
return t.astimezone(timezone.utc).strftime("%H:%MZ")
# ------------------------------------------------------- PromQL rules ----
def rule_lost_events(prom) -> List[Finding]:
"""Hubble ring-buffer loss — the rule that says the others are blind."""
out = []
for labels, value in prom.query("sum by (node) (rate(hubble_lost_events_total[15m]))"):
if value > config.LOST_EVENTS_RATE:
node = labels.get("node", "?")
out.append(Finding(
rule="hubble-loss", kind="state", severity="HIGH",
entity="node=%s" % node,
detail="node=%s lost %.2f events/s over 15m (ring buffer) - other rules are blind to that share"
% (node, value),
))
return out
def rule_drop_spike(prom) -> List[Finding]:
"""TCP/UDP drop-rate spike against a 1 h baseline.
ICMPv6 UNSUPPORTED_L3_PROTOCOL is excluded: it is constant neighbour
discovery (~0.39/s), and including it means the baseline can never be
zero, so a real TCP drop spike is diluted.
"""
sel = 'hubble_drop_total{protocol!="ICMPv6"}'
cur = prom.scalar("sum(rate(%s[5m]))" % sel)
base = prom.scalar("sum(rate(%s[1h] offset 5m))" % sel)
if cur > config.DROP_FLOOR and cur > config.DROP_RATIO * max(base, 1e-9):
if base > 0.005:
shape = "%.2f/s vs 1h baseline %.2f/s (%.1fx)" % (cur, base, cur / base)
else:
shape = "%.2f/s with no 1h baseline (%.0f drops over 5m)" % (cur, cur * 300)
return [Finding(
rule="drop-spike", kind="state", severity="MEDIUM", entity="cluster",
detail="tcp/udp drops " + shape,
)]
return []
def rule_syn_sweep(prom) -> List[Finding]:
syn = prom.scalar('sum(rate(hubble_tcp_flags_total{flag="SYN"}[5m]))')
synack = prom.scalar('sum(rate(hubble_tcp_flags_total{flag="SYN-ACK"}[5m]))')
ratio = syn / synack if synack > 0 else (float("inf") if syn > 0 else 0.0)
if syn > config.SYN_FLOOR and ratio > config.SYN_RATIO:
return [Finding(
rule="syn-sweep", kind="state", severity="MEDIUM", entity="cluster",
detail="SYN %.1f/s vs SYN-ACK %.1f/s (ratio %.1f) - connects that never complete"
% (syn, synack, ratio),
)]
return []
def rule_rst_storm(prom) -> List[Finding]:
cur = prom.scalar('sum(rate(hubble_tcp_flags_total{flag="RST"}[5m]))')
base = prom.scalar(
'avg_over_time(sum(rate(hubble_tcp_flags_total{flag="RST"}[5m]))[6h:5m])')
if cur > config.RST_FLOOR and cur > config.RST_RATIO * max(base, 1e-9):
return [Finding(
rule="rst-storm", kind="state", severity="MEDIUM", entity="cluster",
detail="RST %.1f/s vs 6h average %.1f/s (%.1fx) - refused/reset connections"
% (cur, base, cur / max(base, 1e-9)),
)]
return []
def rule_new_port(prom) -> List[Finding]:
"""A server-range port that carried no flows 24 h ago.
Ephemeral client ports (>= 32768) are excluded, otherwise every new outbound
socket is a "new port".
"""
q = (
'count by (port) (hubble_port_distribution_total{port!="0"})'
' unless count by (port) (hubble_port_distribution_total{port!="0"} offset %s)'
% config.NEW_PORT_LOOKBACK
)
out = []
for labels, _value in prom.query(q):
port = labels.get("port", "")
try:
port_i = int(port)
except ValueError:
continue
if port_i <= 0 or port_i >= config.NEW_PORT_CEILING:
continue
out.append(Finding(
rule="new-port", kind="state", severity="LOW", entity="port=%d" % port_i,
detail="port %d carried flows now but none 24h ago - new listener or new peer port" % port_i,
))
return out
def rule_http_errors(prom) -> List[Finding]:
total = prom.scalar("sum(rate(hubble_http_requests_total[15m]))")
err = prom.scalar('sum(rate(hubble_http_requests_total{status=~"4..|5.."}[15m]))')
if total > config.HTTP_MIN_RATE and err > 0:
share = err / total
if share > config.HTTP_ERROR_RATIO:
return [Finding(
rule="http-error-ratio", kind="state", severity="MEDIUM", entity="cluster",
detail="L7 4xx/5xx share %.2f of %.1f req/s (15m)" % (share, total),
)]
return []
PROM_RULES = (
rule_lost_events,
rule_drop_spike,
rule_syn_sweep,
rule_rst_storm,
rule_new_port,
rule_http_errors,
)
# ---------------------------------------------------- flow-store rules ----
def _egress_key(flow: Flow) -> Optional[str]:
"""`workload->ip:port/proto` for an external, workload-originated flow."""
if flow.type != "L3_L4" or flow.proto not in ("TCP", "UDP"):
return None
if not flow.src_workload or not is_external(flow.dst_ip) or flow.dst_port is None:
return None
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
for key in list(beacon):
kept = {s: t for s, t in beacon[key].items() if t >= cutoff}
if kept:
beacon[key] = kept
else:
beacon.pop(key, None)
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],
counts: Dict[str, dict], now: datetime,
window_h: float = None, tick: int = 0) -> List[Finding]:
"""First-seen egress tuple = candidate beacon/exfil.
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.
`counts` (tuple -> {n, first, last_tick}) exists only to separate one-shot
CDN rotation from a repeat destination: a web-port tuple must be seen in
`EGRESS_WEB_MIN_TICKS` distinct ticks before it is worth a line. Non-web
ports alert immediately, and a `DROPPED` verdict is always HIGH.
The alert says how long this sensor has actually been watching
(`window_h`): the collector caps at 1 GiB, which is days, not the month the
design note assumed. Never imply a longer baseline than was observed.
"""
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:
continue
entry = counts.get(key)
if entry is None:
entry = {"n": 1, "first": (flow.time or now).isoformat(timespec="seconds"),
"last_tick": tick}
counts[key] = entry
elif entry.get("last_tick") != tick:
entry["n"] = int(entry.get("n", 1)) + 1
entry["last_tick"] = tick
dropped = flow.verdict == "DROPPED"
if dropped:
key += "/dropped"
web = flow.dst_port in config.WEB_PORTS
if web and not dropped and int(entry.get("n", 1)) < config.EGRESS_WEB_MIN_TICKS:
continue # one-shot CDN destination: not worth a line yet
severity = "MEDIUM" if web and not dropped else "HIGH"
finding = Finding(
rule="egress-new-dst", kind="novelty", severity=severity, entity=key,
detail="%s first-seen %s%s" % (key, _ts(flow.time), window),
)
if finding.fingerprint in seen:
continue
out.append(finding)
return out
def rule_beacon(flows: Iterable[Flow], beacon: Dict[str, Dict[str, float]],
now: float) -> List[Finding]:
"""Periodic connections to one destination: C2 shape, not app traffic.
Counts distinct client sockets (src_ip:src_port) per (workload, dst, port)
rather than packets — a single long-lived connection produces hundreds of
trace events and would look like a high count. Beaconing is judged on the
inter-arrival CV of *new* sockets over the retained window (2 h).
"""
touched = set()
for flow in flows:
key = _egress_key(flow)
if not key:
continue
sock = "%s:%s" % (flow.src_ip, flow.src_port)
stamp = (flow.time.timestamp() if flow.time else now)
bucket = beacon.setdefault(key, {})
bucket.setdefault(sock, stamp)
touched.add(key)
cutoff = now - config.BEACON_WINDOW
out: List[Finding] = []
for key in touched:
bucket = {s: t for s, t in beacon.get(key, {}).items() if t >= cutoff}
beacon[key] = bucket
if len(bucket) < config.BEACON_MIN_CONNS:
continue
times = sorted(bucket.values())
gaps = [b - a for a, b in zip(times, times[1:]) if b > a]
if len(gaps) < config.BEACON_MIN_CONNS - 1:
continue
mean = statistics.fmean(gaps)
if mean <= 0 or mean > config.BEACON_MAX_INTERVAL:
continue
cv = statistics.pstdev(gaps) / mean
if cv < config.BEACON_MAX_CV:
out.append(Finding(
rule="beacon-shape", kind="novelty", severity="HIGH", entity=key,
detail="%s %d conns in %dh, jitter %.2f (mean %.0fs)"
% (key, len(bucket), config.BEACON_WINDOW // 3600, cv, mean),
))
return out