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.
This commit is contained in:
commit
68b2616cc5
19 changed files with 1902 additions and 0 deletions
306
netsec_scan/flows.py
Normal file
306
netsec_scan/flows.py
Normal file
|
|
@ -0,0 +1,306 @@
|
|||
"""Flow-store access and parsing.
|
||||
|
||||
Two sources, one parser:
|
||||
|
||||
* `RemoteFlowStore` reads the collector's JSONL on siriussec over SSH with a
|
||||
per-file byte offset, so a 5-minute tick pulls only the new bytes (the whole
|
||||
retained window is <= 1 GiB, but 900 MiB every tick would be absurd).
|
||||
* `LocalFlowStore` reads a directory (tests, fixtures, dev).
|
||||
|
||||
Only complete lines are consumed; a trailing partial line is carried in state
|
||||
and re-parented to the next tick.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, Optional, Tuple
|
||||
|
||||
from . import config
|
||||
from .prom import SensorError
|
||||
|
||||
_LOCAL_NETS = tuple(ipaddress.ip_network(n) for n in config.NON_EGRESS_NETS)
|
||||
# Documentation ranges are not routable, so nothing legitimate ever talks to
|
||||
# them — which makes them a fine destination for fixtures and for a synthetic
|
||||
# single-line demo. Python >= 3.13 classifies them `is_private`, so they are
|
||||
# whitelisted here explicitly rather than left to a version-dependent flag.
|
||||
_DOC_NETS = (
|
||||
ipaddress.ip_network("192.0.2.0/24"),
|
||||
ipaddress.ip_network("198.51.100.0/24"),
|
||||
ipaddress.ip_network("203.0.113.0/24"),
|
||||
ipaddress.ip_network("2001:db8::/32"),
|
||||
)
|
||||
|
||||
# Peers carrying any of these prefixes are not workloads (nodes, world, the
|
||||
# gateway). `reserved:remote-node` / `reserved:host` egress is the node's own
|
||||
# software fetching things — attributing novelty to it produces CDN-IP churn,
|
||||
# not security signal.
|
||||
_RESERVED_PREFIX = "reserved:"
|
||||
|
||||
|
||||
def parse_ts(text: str) -> Optional[datetime]:
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def is_external(ip: Optional[str]) -> bool:
|
||||
"""True only for a globally routable unicast destination outside local space.
|
||||
|
||||
Deliberately not `addr.is_global`: since Python 3.13 that returns False for
|
||||
documentation ranges (203.0.113.0/24 & co), which would make a synthetic
|
||||
beacon fixture invisible. Private/link-local/multicast/loopback/reserved
|
||||
are excluded explicitly, and NON_EGRESS_NETS covers the homelab's real
|
||||
address space (pod CIDR, mesh, LAN, CGNAT/tailnet).
|
||||
"""
|
||||
if not ip:
|
||||
return False
|
||||
try:
|
||||
addr = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
return False
|
||||
if any(addr in net for net in _LOCAL_NETS):
|
||||
return False
|
||||
if any(addr in net for net in _DOC_NETS):
|
||||
return True
|
||||
if (addr.is_private or addr.is_multicast or addr.is_link_local
|
||||
or addr.is_loopback or addr.is_unspecified or addr.is_reserved):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def workload_name(peer: Optional[dict]) -> Optional[str]:
|
||||
"""Stable workload identity (`namespace/name`) for a Cilium peer.
|
||||
|
||||
Pod names change on every rollout, so a fingerprint built from
|
||||
`pod_name` would re-alert on every deploy. Prefer the workload object, then
|
||||
the app labels, and only fall back to a de-hashed pod name.
|
||||
"""
|
||||
if not isinstance(peer, dict):
|
||||
return None
|
||||
labels = peer.get("labels") or []
|
||||
if any(str(lbl).startswith(_RESERVED_PREFIX) for lbl in labels):
|
||||
return None
|
||||
ns = peer.get("namespace") or ""
|
||||
for lbl in labels:
|
||||
if lbl.startswith("k8s:io.kubernetes.pod.namespace="):
|
||||
ns = ns or lbl.split("=", 1)[1]
|
||||
name = None
|
||||
for wl in peer.get("workloads") or []:
|
||||
if isinstance(wl, dict) and wl.get("name"):
|
||||
name = wl["name"]
|
||||
break
|
||||
if not name:
|
||||
for lbl in labels:
|
||||
for key in ("k8s:app=", "k8s:app.kubernetes.io/name="):
|
||||
if lbl.startswith(key):
|
||||
name = lbl[len(key):]
|
||||
break
|
||||
if name:
|
||||
break
|
||||
if not name:
|
||||
pod = peer.get("pod_name")
|
||||
if pod:
|
||||
# strip a Deployment/ReplicaSet suffix: name-hash1-hash2
|
||||
parts = pod.split("-")
|
||||
if len(parts) >= 3 and len(parts[-1]) >= 5 and len(parts[-2]) >= 5:
|
||||
name = "-".join(parts[:-2])
|
||||
else:
|
||||
name = pod
|
||||
if not name:
|
||||
return None
|
||||
return f"{ns}/{name}" if ns else name
|
||||
|
||||
|
||||
@dataclass
|
||||
class Flow:
|
||||
time: Optional[datetime]
|
||||
type: str
|
||||
verdict: str
|
||||
src_ip: Optional[str]
|
||||
dst_ip: Optional[str]
|
||||
proto: Optional[str]
|
||||
src_port: Optional[int]
|
||||
dst_port: Optional[int]
|
||||
src_workload: Optional[str]
|
||||
dst_workload: Optional[str]
|
||||
event_type: Optional[int] = None
|
||||
keys: Tuple[str, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def _peer_ports(l4: dict, proto: str) -> Tuple[Optional[int], Optional[int]]:
|
||||
body = l4.get(proto) if isinstance(l4, dict) else None
|
||||
if not isinstance(body, dict):
|
||||
return None, None
|
||||
sp, dp = body.get("source_port"), body.get("destination_port")
|
||||
return (int(sp) if isinstance(sp, int) else None, int(dp) if isinstance(dp, int) else None)
|
||||
|
||||
|
||||
def parse_flow(obj: dict) -> Optional[Flow]:
|
||||
flow = obj.get("flow") if isinstance(obj, dict) else None
|
||||
if not isinstance(flow, dict):
|
||||
return None
|
||||
ip = flow.get("IP") or {}
|
||||
src_ip, dst_ip = ip.get("source"), ip.get("destination")
|
||||
if not src_ip or not dst_ip:
|
||||
# ARP/non-IP trace events and any malformed line are unusable to every
|
||||
# rule here; counting them as parsed would inflate the flow counters.
|
||||
return None
|
||||
l4 = flow.get("l4") or {}
|
||||
proto = next(iter(l4), None) if isinstance(l4, dict) else None
|
||||
sp, dp = _peer_ports(l4, proto) if proto else (None, None)
|
||||
etype = (flow.get("event_type") or {}).get("type")
|
||||
return Flow(
|
||||
time=parse_ts(flow.get("time") or ""),
|
||||
type=str(flow.get("Type") or ""),
|
||||
verdict=str(flow.get("verdict") or ""),
|
||||
src_ip=src_ip,
|
||||
dst_ip=dst_ip,
|
||||
proto=proto,
|
||||
src_port=sp,
|
||||
dst_port=dp,
|
||||
src_workload=workload_name(flow.get("source")),
|
||||
dst_workload=workload_name(flow.get("destination")),
|
||||
event_type=etype if isinstance(etype, int) else None,
|
||||
)
|
||||
|
||||
|
||||
def iter_lines(data: bytes) -> Tuple[List[str], bytes]:
|
||||
"""Split a byte chunk into complete lines, returning the trailing partial."""
|
||||
if not data:
|
||||
return [], b""
|
||||
idx = data.rfind(b"\n")
|
||||
if idx < 0:
|
||||
return [], data
|
||||
complete = data[:idx].decode("utf-8", "replace")
|
||||
return complete.split("\n"), data[idx + 1:]
|
||||
|
||||
|
||||
# --------------------------------------------------------------- stores ----
|
||||
class BaseStore:
|
||||
def list_files(self) -> List[Tuple[str, int]]:
|
||||
raise NotImplementedError
|
||||
|
||||
def read_from(self, name: str, offset: int) -> bytes:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def _ssh_bin() -> str:
|
||||
for cand in config.SSH_CANDIDATES:
|
||||
if cand.startswith("/"):
|
||||
if os.path.exists(cand):
|
||||
return cand
|
||||
else:
|
||||
found = shutil.which(cand)
|
||||
if found:
|
||||
return found
|
||||
raise SensorError("no-ssh", "ssh client not found")
|
||||
|
||||
|
||||
class RemoteFlowStore(BaseStore):
|
||||
def __init__(self, host: str = None, key: str = None):
|
||||
self.host = host or config.SSH_HOST
|
||||
self.key = key or config.SSH_KEY
|
||||
|
||||
def _run(self, remote_cmd: str) -> "subprocess.CompletedProcess":
|
||||
try:
|
||||
return subprocess.run(
|
||||
[
|
||||
_ssh_bin(), "-i", self.key,
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "ConnectTimeout=10",
|
||||
"-o", "ServerAliveInterval=5",
|
||||
"-o", "ServerAliveCountMax=4",
|
||||
self.host, remote_cmd,
|
||||
],
|
||||
capture_output=True, timeout=config.SSH_TIMEOUT,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise SensorError("ssh-timeout", "ssh to %s exceeded %ss" % (self.host, config.SSH_TIMEOUT))
|
||||
|
||||
def list_files(self) -> List[Tuple[str, int]]:
|
||||
# `find -printf` rather than a shell glob: the glob must not be quoted
|
||||
# (quoted == literal, stat fails) and must not be unquoted (shell
|
||||
# injection surface). find needs neither.
|
||||
cmd = "sudo -n find %s -maxdepth 1 -type f -name %s -printf '%%f %%s\\n'" % (
|
||||
shlex.quote(config.FLOW_DIR), shlex.quote(config.FLOW_PATTERN))
|
||||
proc = self._run(cmd)
|
||||
out = proc.stdout.decode("utf-8", "replace")
|
||||
if proc.returncode != 0:
|
||||
err = proc.stderr.decode("utf-8", "replace").strip()
|
||||
if "No such file" in err or "cannot" in err and "stat" in err:
|
||||
raise SensorError("no-flows-file",
|
||||
"no JSONL under %s on %s" % (config.FLOW_DIR, self.host))
|
||||
if "sudo" in err.lower() or "password" in err.lower():
|
||||
raise SensorError("sudo-denied", err[:160])
|
||||
raise SensorError("ssh-fail", err[:160])
|
||||
files = []
|
||||
for line in out.splitlines():
|
||||
parts = line.rsplit(" ", 1)
|
||||
if len(parts) != 2 or not parts[1].isdigit():
|
||||
continue
|
||||
files.append((os.path.basename(parts[0]), int(parts[1])))
|
||||
if not files:
|
||||
raise SensorError("no-flows-file", "collector directory is empty on %s" % self.host)
|
||||
return files
|
||||
|
||||
def read_from(self, name: str, offset: int) -> bytes:
|
||||
path = os.path.join(config.FLOW_DIR, os.path.basename(name))
|
||||
# tail -c +N is 1-based: +1 is the first byte.
|
||||
cmd = "sudo -n tail -c +%d %s" % (offset + 1, shlex.quote(path))
|
||||
proc = self._run(cmd)
|
||||
if proc.returncode != 0:
|
||||
err = proc.stderr.decode("utf-8", "replace").strip()
|
||||
raise SensorError("ssh-fail", err[:160] or "tail failed")
|
||||
return proc.stdout
|
||||
|
||||
|
||||
class LocalFlowStore(BaseStore):
|
||||
"""For tests, fixtures and local re-runs against a copied collector dir."""
|
||||
|
||||
def __init__(self, directory: str):
|
||||
self.directory = Path(directory)
|
||||
|
||||
def list_files(self) -> List[Tuple[str, int]]:
|
||||
files = []
|
||||
for path in sorted(self.directory.glob("flows-*.jsonl")):
|
||||
files.append((path.name, path.stat().st_size))
|
||||
if not files:
|
||||
raise SensorError("no-flows-file", "no flows-*.jsonl in %s" % self.directory)
|
||||
return files
|
||||
|
||||
def read_from(self, name: str, offset: int) -> bytes:
|
||||
data = (self.directory / name).read_bytes()
|
||||
return data[offset:]
|
||||
|
||||
|
||||
class SingleFileStore(BaseStore):
|
||||
"""One fixture file, read whole; used by --fixture."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.path = Path(path)
|
||||
|
||||
def list_files(self) -> List[Tuple[str, int]]:
|
||||
if not self.path.is_file():
|
||||
raise SensorError("no-flows-file", "fixture not found: %s" % self.path)
|
||||
return [(self.path.name, self.path.stat().st_size)]
|
||||
|
||||
def read_from(self, name: str, offset: int) -> bytes:
|
||||
return self.path.read_bytes()[offset:]
|
||||
|
||||
|
||||
def fingerprint(kind: str, entity: str) -> str:
|
||||
"""Stable id of (rule, entity). Never includes a timestamp or a count."""
|
||||
return hashlib.sha256(f"{kind}|{entity}".encode("utf-8")).hexdigest()[:12]
|
||||
Loading…
Reference in a new issue