netsec-agent/netsec_scan/rules.py
sirius 68b2616cc5 netsec-scan: deterministic sensor (6 PromQL tripwires + 2 flow-store novelty rules)
Silent ticks (empty stdout, exit 0), one line per stable fingerprint, cumulative
union-only seen-set at ~/.hermes/cron/netsec-scan-state.json, memoized sensor-
degradation line, daily baseline report. Stdlib only; reads the collector's
JSONL over SSH with per-file byte offsets and Prometheus via the k8s API proxy.
40 unit tests against fixtures recorded from the live collector.
2026-11-27 00:20:46 -05:00

242 lines
9.1 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 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 rule_egress_first_seen(flows: Iterable[Flow], egress_seen: Dict[str, str],
now: datetime) -> 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.
"""
out: List[Finding] = []
for flow in flows:
key = _egress_key(flow)
if not key or key in egress_seen:
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(
rule="egress-new-dst", kind="novelty", severity=severity, entity=key,
detail="%s first-seen %s (no prior in retained window)" % (key, _ts(flow.time)),
))
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