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
10
netsec_scan/__init__.py
Normal file
10
netsec_scan/__init__.py
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
"""netsec-scan — deterministic network-security sensor for the Sirius homelab.
|
||||
|
||||
The LLM never decides whether something is odd: this program decides, in code,
|
||||
and emits one line per fingerprint. Designed to be run by a 5-minute Hermes
|
||||
cron job whose stdout *is* the alert.
|
||||
|
||||
See README.md for the rule set, thresholds and how to re-derive a baseline.
|
||||
"""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
296
netsec_scan/__main__.py
Normal file
296
netsec_scan/__main__.py
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
"""Entry point: one tick of the deterministic sensor.
|
||||
|
||||
Contract (see README):
|
||||
* calm tick -> empty stdout, exit 0
|
||||
* hit -> one line per fingerprint, `SEV <fp> <rule> <detail>` (<= 200 chars)
|
||||
* degradation-> one memoized line naming the failure class, exit non-zero,
|
||||
state file untouched
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from . import config, report, rules, state as state_mod
|
||||
from .flows import (
|
||||
BaseStore,
|
||||
LocalFlowStore,
|
||||
RemoteFlowStore,
|
||||
SingleFileStore,
|
||||
iter_lines,
|
||||
parse_flow,
|
||||
)
|
||||
from .prom import SensorError
|
||||
from .rules import SEVERITY_ORDER, Finding
|
||||
|
||||
|
||||
# ------------------------------------------------------------- helpers ----
|
||||
def log(msg: str, verbose: bool) -> None:
|
||||
if verbose:
|
||||
print("netsec-scan: " + msg, file=sys.stderr)
|
||||
|
||||
|
||||
def memo_path(state_path: Path) -> Path:
|
||||
"""Degradation memo lives beside the state file, never inside it."""
|
||||
return state_path.with_name(state_path.stem + ".memo.json")
|
||||
|
||||
|
||||
def load_memo(path: Path) -> Dict[str, str]:
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def save_memo(path: Path, memo: Dict[str, str]) -> None:
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_text(json.dumps(memo, indent=2, sort_keys=True) + "\n")
|
||||
os.replace(tmp, path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def render(finding: Finding) -> str:
|
||||
line = "%s %s %s %s" % (finding.severity, finding.fingerprint,
|
||||
finding.rule, finding.detail)
|
||||
if len(line) > config.MAX_LINE:
|
||||
line = line[: config.MAX_LINE - 1] + "\u2026"
|
||||
return line
|
||||
|
||||
|
||||
def collect_flows(store: BaseStore, st: Dict[str, Any], verbose: bool) -> Tuple[List, int, int]:
|
||||
"""Read every un-consumed byte of every collector file; parse complete lines."""
|
||||
files = store.list_files()
|
||||
parsed = []
|
||||
malformed = 0
|
||||
live = set()
|
||||
for name, size in files:
|
||||
live.add(name)
|
||||
entry = st["files"].get(name) or {"offset": 0, "size": 0}
|
||||
offset = int(entry.get("offset", 0) or 0)
|
||||
if size < offset: # truncated or replaced under us
|
||||
log("file %s shrank (%d < %d); restarting at 0" % (name, size, offset), verbose)
|
||||
offset = 0
|
||||
if size == offset:
|
||||
st["files"][name] = {"offset": offset, "size": size}
|
||||
continue
|
||||
data = store.read_from(name, offset)
|
||||
lines, partial = iter_lines(data)
|
||||
consumed = offset + len(data) - len(partial)
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except ValueError:
|
||||
malformed += 1
|
||||
continue
|
||||
flow = parse_flow(obj)
|
||||
if flow is None:
|
||||
malformed += 1
|
||||
continue
|
||||
parsed.append(flow)
|
||||
st["files"][name] = {"offset": consumed, "size": size}
|
||||
log("read %s: %d bytes, %d lines" % (name, len(data), len(lines)), verbose)
|
||||
# Forget files the collector rotated away (their bytes are already consumed).
|
||||
for name in list(st["files"]):
|
||||
if name not in live:
|
||||
st["files"].pop(name, None)
|
||||
return parsed, malformed, len(files)
|
||||
|
||||
|
||||
def apply_dedupe(findings: List[Finding], st: 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:
|
||||
emit.append(finding)
|
||||
continue
|
||||
if prev is None:
|
||||
seen[finding.fingerprint] = {
|
||||
"rule": finding.rule,
|
||||
"kind": finding.kind,
|
||||
"entity": finding.entity,
|
||||
"severity": finding.severity,
|
||||
"first": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"last_alert": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
}
|
||||
emit.append(finding)
|
||||
continue
|
||||
if finding.kind == "state":
|
||||
try:
|
||||
last = datetime.fromisoformat(prev.get("last_alert", "")).timestamp()
|
||||
except (TypeError, ValueError):
|
||||
last = 0.0
|
||||
if now - last >= config.STATE_COOLDOWN:
|
||||
prev["last_alert"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
emit.append(finding)
|
||||
return emit
|
||||
|
||||
|
||||
def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding],
|
||||
new_egress: 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")})
|
||||
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)
|
||||
st["totals"]["malformed"] = int(st["totals"].get("malformed", 0)) + malformed
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- main ----
|
||||
def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="netsec-scan",
|
||||
description="Deterministic netsec sensor: silent when calm, one line per hit.")
|
||||
parser.add_argument("--fixture", help="read this JSONL file instead of the live collector")
|
||||
parser.add_argument("--flows-dir", help="read flows-*.jsonl from this local directory")
|
||||
parser.add_argument("--dry-run", action="store_true",
|
||||
help="print findings without writing state/report and without seen-set dedupe")
|
||||
parser.add_argument("--no-prom", action="store_true", help="skip the PromQL tripwires")
|
||||
parser.add_argument("--state", help="state file path (default ~/.hermes/cron/netsec-scan-state.json)")
|
||||
parser.add_argument("--reports", help="report directory (default ~/Projects/netsec-agent/reports)")
|
||||
parser.add_argument("--verbose", action="store_true", help="debug lines on stderr")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
args = parse_args(argv)
|
||||
state_path = Path(args.state or config.STATE_FILE)
|
||||
reports_dir = Path(args.reports or config.REPORT_DIR)
|
||||
now = time.time()
|
||||
|
||||
if args.fixture:
|
||||
store: BaseStore = SingleFileStore(args.fixture)
|
||||
prom_enabled = False
|
||||
elif args.flows_dir:
|
||||
store = LocalFlowStore(args.flows_dir)
|
||||
prom_enabled = not args.no_prom
|
||||
else:
|
||||
store = RemoteFlowStore()
|
||||
prom_enabled = not args.no_prom
|
||||
|
||||
try:
|
||||
st = state_mod.load(state_path)
|
||||
except SensorError as exc:
|
||||
print("SENSOR %s netsec-scan: %s" % (exc.cls, exc.detail or exc.cls))
|
||||
return 2
|
||||
|
||||
try:
|
||||
flows, malformed, file_count = collect_flows(store, st, args.verbose)
|
||||
log("parsed %d flows from %d file(s), %d malformed"
|
||||
% (len(flows), file_count, malformed), args.verbose)
|
||||
|
||||
findings: List[Finding] = []
|
||||
if prom_enabled:
|
||||
for rule in rules.PROM_RULES:
|
||||
try:
|
||||
findings.extend(rule(_prommod()))
|
||||
except SensorError:
|
||||
raise
|
||||
except Exception as exc: # a broken rule must not eat the tick
|
||||
log("rule %s failed: %s" % (rule.__name__, exc), args.verbose)
|
||||
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())
|
||||
beacon = rules.rule_beacon(flows, st["beacon"], now)
|
||||
rules.prune_beacon(st["beacon"], now)
|
||||
flow_findings = new_egress + beacon
|
||||
|
||||
if seeding and not args.dry_run:
|
||||
# Baseline run: record history silently instead of dumping the
|
||||
# retained window into chat. PromQL findings still speak (they are
|
||||
# current state, not history).
|
||||
for finding in flow_findings:
|
||||
st["seen"].setdefault(finding.fingerprint, {
|
||||
"rule": finding.rule, "kind": finding.kind, "entity": finding.entity,
|
||||
"severity": finding.severity,
|
||||
"first": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"last_alert": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"seeded": True,
|
||||
})
|
||||
st["seeded"] = True
|
||||
st["seeded_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
log("seed run: %d flow findings recorded silently" % len(flow_findings),
|
||||
args.verbose)
|
||||
flow_findings = []
|
||||
|
||||
emitted = apply_dedupe(findings + flow_findings, st, now, args.dry_run)
|
||||
|
||||
record_counters(st, len(flows), emitted, new_egress, malformed)
|
||||
state_mod.prune(st)
|
||||
|
||||
if not args.dry_run:
|
||||
state_mod.save(state_path, st)
|
||||
report.write(st, reports_dir)
|
||||
|
||||
except SensorError as exc:
|
||||
return degrade(state_path, exc, args.verbose)
|
||||
except Exception as exc: # never fail silently
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
return degrade(state_path, SensorError("internal-error", str(exc)[:160]), args.verbose)
|
||||
|
||||
emitted.sort(key=lambda f: (SEVERITY_ORDER.get(f.severity, 9), f.rule, f.entity))
|
||||
for finding in emitted:
|
||||
print(render(finding))
|
||||
return 0
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _prommod():
|
||||
from . import prom
|
||||
return prom
|
||||
|
||||
|
||||
def degrade(state_path: Path, exc: SensorError, verbose: bool) -> int:
|
||||
"""One memoized line per failure class; state file is never touched."""
|
||||
memo_file = memo_path(state_path)
|
||||
memo = load_memo(memo_file)
|
||||
now = time.time()
|
||||
last = memo.get(exc.cls)
|
||||
announce = True
|
||||
if last:
|
||||
try:
|
||||
announce = (now - datetime.fromisoformat(last).timestamp()) >= config.DEGRADED_MEMO
|
||||
except (TypeError, ValueError):
|
||||
announce = True
|
||||
if announce:
|
||||
detail = exc.detail or exc.cls
|
||||
print("SENSOR %s netsec-scan: sensor input unavailable (%s)" % (exc.cls, detail))
|
||||
memo[exc.cls] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
save_memo(memo_file, memo)
|
||||
if verbose:
|
||||
print("netsec-scan: degraded class=%s detail=%s" % (exc.cls, exc.detail),
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
121
netsec_scan/config.py
Normal file
121
netsec_scan/config.py
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
"""Every tunable in one place, with the measurement it came from.
|
||||
|
||||
Thresholds are deliberately conservative in the sense of *few, quiet rules*
|
||||
rather than tight numbers: a rule that fires on ordinary traffic gets the whole
|
||||
channel muted. Each value below was checked against live data on 2026-11-27
|
||||
(see README "Baselines").
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
HOME = Path.home()
|
||||
|
||||
# ---------------------------------------------------------------- paths ----
|
||||
# The state file must NOT live inside a {job_id} dir: the scheduler reclaims
|
||||
# those. ~/.hermes/cron/ is stable.
|
||||
STATE_FILE = Path(
|
||||
os.environ.get("NETSEC_SCAN_STATE", HOME / ".hermes" / "cron" / "netsec-scan-state.json")
|
||||
)
|
||||
REPORT_DIR = Path(
|
||||
os.environ.get("NETSEC_SCAN_REPORTS", HOME / "Projects" / "netsec-agent" / "reports")
|
||||
)
|
||||
|
||||
# ------------------------------------------------- collector (remote) ----
|
||||
# The collector is a DaemonSet on siriussec writing hostPath /var/log/netsec.
|
||||
# The sensor runs on the admin host, so it reads those files over SSH with
|
||||
# `sudo -n` (NOPASSWD is configured for Lancelot). Never poll hubble directly:
|
||||
# the agent ring buffer is ~28 s at 148 flows/s, so a poll is lossy by design.
|
||||
SSH_HOST = os.environ.get("NETSEC_SCAN_SSH_HOST", "[email protected]")
|
||||
SSH_KEY = os.environ.get("NETSEC_SCAN_SSH_KEY", str(HOME / ".ssh" / "lancelot_priv"))
|
||||
SSH_TIMEOUT = int(os.environ.get("NETSEC_SCAN_SSH_TIMEOUT", "60"))
|
||||
FLOW_DIR = os.environ.get("NETSEC_SCAN_FLOW_DIR", "/var/log/netsec")
|
||||
FLOW_PATTERN = os.environ.get("NETSEC_SCAN_FLOW_PATTERN", "flows-*.jsonl")
|
||||
FLOW_GLOB = FLOW_DIR + "/" + FLOW_PATTERN
|
||||
|
||||
# ----------------------------------------------------- prometheus ----
|
||||
PROM_PROXY = (
|
||||
"/api/v1/namespaces/monitoring/services/"
|
||||
"http:kube-prometheus-stack-prometheus:9090/proxy"
|
||||
)
|
||||
PROM_TIMEOUT = int(os.environ.get("NETSEC_SCAN_PROM_TIMEOUT", "25"))
|
||||
|
||||
# ----------------------------------------------------- thresholds ----
|
||||
# Hubble pipeline loss: events/s over 15m. Measured 0.60/s siriussec, 0.13/s
|
||||
# linode, 0.00/s rpi at idle — i.e. the sensor is already blind to ~0.7 % of
|
||||
# traffic. This rule exists so the other rules cannot lie about being calm.
|
||||
LOST_EVENTS_RATE = 0.05
|
||||
|
||||
# TCP/UDP drops (ICMPv6 UNSUPPORTED_L3_PROTOCOL excluded — it is constant
|
||||
# neighbour-discovery noise at ~0.39/s and would mask a real spike).
|
||||
DROP_FLOOR = 0.05 # events/s; below this a "spike" is one packet
|
||||
DROP_RATIO = 3.0 # vs the 1h baseline rate
|
||||
|
||||
# SYN without SYN-ACK (connect sweep). Measured 1.59 at idle; ring-buffer loss
|
||||
# also nudges it up, hence the 3x gate and the absolute floor.
|
||||
SYN_RATIO = 3.0
|
||||
SYN_FLOOR = 1.0 # SYN/s
|
||||
|
||||
# RST storm: 10x the 6h average. Measured 2.5/s at idle (ephemeral-port churn).
|
||||
RST_RATIO = 10.0
|
||||
RST_FLOOR = 2.0 # RST/s
|
||||
|
||||
# L7 error share. Measured 0.15/s errors of 6.9/s requests (2.2 %).
|
||||
HTTP_ERROR_RATIO = 0.5
|
||||
HTTP_MIN_RATE = 0.5 # requests/s, so a single 404 in a quiet minute cannot trip it
|
||||
|
||||
# Ports below the Linux ephemeral range (32768-60999) that appear in
|
||||
# hubble_port_distribution_total for the first time in 24h are treated as new
|
||||
# listeners. Without the cut, every client source port is a "new port".
|
||||
NEW_PORT_CEILING = 32768
|
||||
NEW_PORT_LOOKBACK = "24h"
|
||||
|
||||
# Flow-store novelty.
|
||||
BEACON_MIN_CONNS = 20 # connections (distinct client sockets) from one workload to one dst:port
|
||||
BEACON_MAX_CV = 0.15 # coefficient of variation of inter-arrival times
|
||||
BEACON_WINDOW = 7200 # seconds of connection history kept per tuple (2h)
|
||||
BEACON_MAX_INTERVAL = 900.0 # mean interval ceiling; 30s beacons fit, 1h cron-ish traffic does not
|
||||
|
||||
# Severity for a first-seen egress tuple: standard web ports are common CDN
|
||||
# churn, everything else is a much stronger beacon/exfil signal.
|
||||
WEB_PORTS = frozenset({80, 443, 8080, 8443})
|
||||
|
||||
# Re-alert cooldown for *state* tripwires (current-condition rules). Flow
|
||||
# novelty is permanent: a tuple fires exactly once, ever. A state rule gets to
|
||||
# fire again after this window so "it broke, was fixed, and broke again" is not
|
||||
# silently forgotten.
|
||||
STATE_COOLDOWN = 86400 # 24h
|
||||
|
||||
# Sensor degradation memo: the same class of failure is announced once per
|
||||
# window, not every 5 minutes.
|
||||
DEGRADED_MEMO = 6 * 3600
|
||||
|
||||
# State bounds (a cumulative seen-set cannot grow forever).
|
||||
MAX_SEEN = 20000
|
||||
MAX_EGRESS = 20000
|
||||
MAX_BEACON_TUPLES = 2000
|
||||
MAX_DAY_EGRESS = 500
|
||||
|
||||
# Output contract.
|
||||
MAX_LINE = 200
|
||||
|
||||
# Local network space. Anything not "global" is not egress; these are explicit
|
||||
# so the rule reads correctly even if a future Python changes is_global.
|
||||
NON_EGRESS_NETS = (
|
||||
"0.0.0.0/8",
|
||||
"10.0.0.0/8", # includes pod 10.244/16, mesh 10.10/24, service 10.96/12
|
||||
"100.64.0.0/10", # CGNAT (tailnet)
|
||||
"127.0.0.0/8",
|
||||
"169.254.0.0/16",
|
||||
"172.16.0.0/12",
|
||||
"192.168.0.0/16", # homelab LAN
|
||||
"::1/128",
|
||||
"fc00::/7",
|
||||
"fe80::/10",
|
||||
"ff00::/8",
|
||||
)
|
||||
|
||||
KUBECTL_CANDIDATES = ("kubectl", "/usr/sbin/kubectl", "/usr/bin/kubectl", "/usr/local/bin/kubectl")
|
||||
SSH_CANDIDATES = ("ssh", "/usr/sbin/ssh", "/usr/bin/ssh")
|
||||
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]
|
||||
81
netsec_scan/prom.py
Normal file
81
netsec_scan/prom.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
"""Read-only Prometheus access through the Kubernetes API proxy.
|
||||
|
||||
No port-forward, no extra credentials: `kubectl get --raw` against the
|
||||
monitoring Service proxy works from the admin host as the operator.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import urllib.parse
|
||||
from typing import Iterable, List, Tuple
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
class SensorError(Exception):
|
||||
"""A sensor input is unavailable. `cls` is the memoizable failure class."""
|
||||
|
||||
def __init__(self, cls: str, detail: str = ""):
|
||||
super().__init__(detail or cls)
|
||||
self.cls = cls
|
||||
self.detail = detail
|
||||
|
||||
|
||||
def _which(candidates: Iterable[str]) -> str:
|
||||
for cand in candidates:
|
||||
path = shutil.which(cand) if not cand.startswith("/") else (cand if os.path.exists(cand) else None)
|
||||
if path:
|
||||
return path
|
||||
raise SensorError("no-kubectl", "kubectl not found in PATH")
|
||||
|
||||
|
||||
def _classify(text: str) -> str:
|
||||
low = text.lower()
|
||||
if "503" in low or "serviceunavailable" in low or "service unavailable" in low:
|
||||
return "HTTP 503"
|
||||
if "timeout" in low or "timed out" in low or "deadline" in low:
|
||||
return "timeout"
|
||||
if "connection refused" in low or "no such host" in low:
|
||||
return "api-unreachable"
|
||||
return "prom-error"
|
||||
|
||||
|
||||
def raw(path: str) -> dict:
|
||||
kubectl = _which(config.KUBECTL_CANDIDATES)
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[kubectl, "get", "--raw", path],
|
||||
capture_output=True, text=True, timeout=config.PROM_TIMEOUT,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise SensorError("timeout", "kubectl get --raw exceeded %ss" % config.PROM_TIMEOUT)
|
||||
if proc.returncode != 0:
|
||||
raise SensorError(_classify(proc.stderr or proc.stdout), (proc.stderr or "").strip()[:200])
|
||||
try:
|
||||
return json.loads(proc.stdout)
|
||||
except ValueError:
|
||||
raise SensorError("prom-bad-json", proc.stdout[:120])
|
||||
|
||||
|
||||
def query(expr: str) -> List[Tuple[dict, float]]:
|
||||
"""Instant query. Returns [(metric_labels, value)] or raises SensorError."""
|
||||
path = config.PROM_PROXY + "/api/v1/query?query=" + urllib.parse.quote(expr)
|
||||
payload = raw(path)
|
||||
if payload.get("status") != "success":
|
||||
raise SensorError("prom-error", str(payload.get("error", ""))[:160])
|
||||
out: List[Tuple[dict, float]] = []
|
||||
for series in payload["data"]["result"]:
|
||||
try:
|
||||
out.append((series.get("metric") or {}, float(series["value"][1])))
|
||||
except (KeyError, IndexError, ValueError):
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def scalar(expr: str) -> float:
|
||||
"""Sum of an (expected single-series) query; 0.0 when it matches nothing."""
|
||||
return sum(v for _, v in query(expr))
|
||||
47
netsec_scan/report.py
Normal file
47
netsec_scan/report.py
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
"""Daily baseline report — no alert, just the numbers thresholds get tuned from.
|
||||
|
||||
Written to `reports/YYYY-MM-DD.json` on every tick, so the file for "today"
|
||||
always exists and carries real counts; it becomes final at the UTC day
|
||||
rollover when a new file starts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
def build(state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
day = state.get("day") or {}
|
||||
egress = day.get("egress", [])
|
||||
new_dsts = day.get("new_dsts", [])
|
||||
rules = day.get("rules", {})
|
||||
flows = int(day.get("flows", 0))
|
||||
return {
|
||||
"date": day.get("date"),
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"flows": flows,
|
||||
"findings_emitted": {k: int(v) for k, v in sorted(rules.items())},
|
||||
"findings_total": sum(int(v) for v in rules.values() if str(v).isdigit()),
|
||||
"egress_tuples_seen": len(egress),
|
||||
"egress_tuples": sorted(egress),
|
||||
"top_new_destinations": new_dsts[-10:],
|
||||
"seen_fingerprints_cumulative": len(state.get("seen", {})),
|
||||
"state_totals": state.get("totals", {}),
|
||||
}
|
||||
|
||||
|
||||
def write(state: Dict[str, Any], directory: Path = None) -> Path:
|
||||
directory = Path(directory or config.REPORT_DIR)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
day = (state.get("day") or {}).get("date") or datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
path = directory / f"{day}.json"
|
||||
tmp = path.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(build(state), indent=2, sort_keys=True) + "\n")
|
||||
os.replace(tmp, path)
|
||||
return path
|
||||
242
netsec_scan/rules.py
Normal file
242
netsec_scan/rules.py
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
"""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
|
||||
122
netsec_scan/state.py
Normal file
122
netsec_scan/state.py
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
"""State file: cumulative seen-set, per-file read offsets, report counters.
|
||||
|
||||
Rules of the house:
|
||||
* the seen-set is UNIONED, never replaced — a transiently-empty read must not
|
||||
re-alert history;
|
||||
* a write is atomic (tmp + rename) and 0600;
|
||||
* a corrupt file is a hard failure (exit non-zero, nothing touched), not a
|
||||
silent reset that re-alerts everything.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
from . import config
|
||||
from .prom import SensorError
|
||||
|
||||
VERSION = 1
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def empty() -> Dict[str, Any]:
|
||||
return {
|
||||
"version": VERSION,
|
||||
"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}
|
||||
"files": {}, # name -> {offset, carry, size}
|
||||
"degraded": {}, # failure class -> iso of last announcement
|
||||
"day": {"date": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||
"flows": 0, "rules": {}, "egress": [], "new_dsts": []},
|
||||
"totals": {"ticks": 0, "flows": 0, "findings": 0},
|
||||
}
|
||||
|
||||
|
||||
def load(path: Path) -> Dict[str, Any]:
|
||||
path = Path(path)
|
||||
if not path.exists():
|
||||
return empty()
|
||||
try:
|
||||
data = json.loads(path.read_text())
|
||||
except (OSError, ValueError) as exc:
|
||||
raise SensorError("state-corrupt", "%s: %s" % (path, exc))
|
||||
if not isinstance(data, dict) or data.get("version") != VERSION:
|
||||
raise SensorError("state-corrupt", "unexpected schema in %s" % path)
|
||||
base = empty()
|
||||
for key, value in base.items():
|
||||
data.setdefault(key, value)
|
||||
for key in ("seen", "egress", "beacon", "files", "degraded"):
|
||||
if not isinstance(data.get(key), dict):
|
||||
data[key] = {}
|
||||
return data
|
||||
|
||||
|
||||
def save(path: Path, state: Dict[str, Any]) -> None:
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
payload = json.dumps(state, separators=(",", ":"), sort_keys=True)
|
||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w") as handle:
|
||||
handle.write(payload)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def prune(state: Dict[str, Any]) -> None:
|
||||
"""Bound every cumulative structure so a long-lived sensor stays small."""
|
||||
seen = state["seen"]
|
||||
if len(seen) > config.MAX_SEEN:
|
||||
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)
|
||||
beacon = state["beacon"]
|
||||
if len(beacon) > config.MAX_BEACON_TUPLES:
|
||||
ordered = sorted(beacon.items(),
|
||||
key=lambda kv: max(kv[1].values()) if kv[1] else 0)
|
||||
for key, _ in ordered[: len(ordered) - config.MAX_BEACON_TUPLES + 200]:
|
||||
beacon.pop(key, None)
|
||||
day = state["day"]
|
||||
if len(day.get("egress", [])) > config.MAX_DAY_EGRESS:
|
||||
day["egress"] = day["egress"][-config.MAX_DAY_EGRESS:]
|
||||
if len(day.get("new_dsts", [])) > config.MAX_DAY_EGRESS:
|
||||
day["new_dsts"] = day["new_dsts"][-config.MAX_DAY_EGRESS:]
|
||||
|
||||
|
||||
def roll_day(state: Dict[str, Any]) -> None:
|
||||
"""Carry report counters into a fresh UTC day (old day stays on disk)."""
|
||||
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
day = state.get("day") or {}
|
||||
if day.get("date") != today:
|
||||
state["day"] = {"date": today, "flows": 0, "rules": {}, "egress": [], "new_dsts": []}
|
||||
|
||||
|
||||
def degraded_memo(state: Dict[str, Any], cls: str, now: float) -> bool:
|
||||
"""True when this failure class was already announced inside the window."""
|
||||
last = state.get("degraded", {}).get(cls)
|
||||
if last is None:
|
||||
return False
|
||||
try:
|
||||
stamp = datetime.fromisoformat(last).timestamp()
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return (now - stamp) < config.DEGRADED_MEMO
|
||||
|
||||
|
||||
def note_degraded(state: Dict[str, Any], cls: str) -> None:
|
||||
state.setdefault("degraded", {})[cls] = _now_iso()
|
||||
Loading…
Reference in a new issue