netsec-agent/netsec_scan/config.py

243 lines
12 KiB
Python
Raw Normal View History

"""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")
# The collector gzips a file the moment it rotates (t_cfea18ac), so the store is
# `flows-<stamp>-<n>.jsonl` (the live file) plus `flows-<stamp>-<n>.jsonl.gz`
# (closed, immutable). Without the trailing `*` the sensor can only see the live
# file — i.e. minutes of the ~74 h the 960 MiB cap actually retains.
FLOW_PATTERN = os.environ.get("NETSEC_SCAN_FLOW_PATTERN", "flows-*.jsonl*")
FLOW_GLOB = FLOW_DIR + "/" + FLOW_PATTERN
# ------------------------------------------------- archival seed budget ----
# Archives are read once, whole, and only at cold start / right after a
# rotation. Unbounded is not an option: 960 MiB of gzip is ~16 GB of JSON at the
# measured 17.5x ratio, and holding that as Flow objects would exhaust memory
# long before it finished. Measured on the admin host 2026-11-27: json.loads +
# parse_flow + egress-key extraction runs at ~140 MB/s of decompressed JSON, so
# these defaults are sized for a one-time seed of ~12 GB (~55 h of current
# volume) and a warm tick, which reads zero or one archive, finishes in ~1 s.
# Whichever budget binds first wins; the window actually covered is printed and
# persisted, never implied.
ARCHIVE_MAX_SECONDS = float(os.environ.get("NETSEC_SCAN_ARCHIVE_SECONDS", "90"))
ARCHIVE_MAX_BYTES = int(os.environ.get("NETSEC_SCAN_ARCHIVE_BYTES", str(8 * 1024 ** 3)))
ARCHIVE_MAX_FILES = int(os.environ.get("NETSEC_SCAN_ARCHIVE_FILES", "40"))
# Flows are consumed in batches so a seed never holds the whole window in RAM as
# Flow objects (16 GB of JSON is millions of them).
FLOW_BATCH = int(os.environ.get("NETSEC_SCAN_FLOW_BATCH", "20000"))
# ----------------------------------------------------- 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})
# A first-seen *web-port* tuple must also be observed in three distinct ticks
# (~15 min) before it alerts. Measured 2026-11-27: one CI run produced 20
# one-shot AWS/GitHub CDN destinations inside a single 5-minute window, and a
# second-tick gate still let ~2 through per build. CDN rotation is one-shot or
# short-lived; a beacon or an exfil destination persists. Stated cost: a
# smash-and-grab that contacts a brand-new host twice and stops is NOT alerted
# on 80/443/8080/8443 (it is on any other port, and on any DROPPED verdict),
# and periodic C2 is rule 8's job (`beacon-shape`, >= 20 conns in 2 h).
EGRESS_WEB_MIN_TICKS = 3
MAX_EGRESS_COUNTS = 20000
# 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")
netsec-scan: HTTP attack-shape rules over the gateway access log (§4d) F7 (t_e662b03a) gave every Gateway listener a JSON access line and shipped it to Loki; this is the §4d consumer that had none. New `http_rules.py` classifies candidate lines and `loki.py` reads them through the logging/loki Service proxy with two LogQL queries per tick - a `|~` prefilter for attack-shaped lines and a `sum by (client_ip, peer)` 1-minute matrix for 401/403. Loki does the volume reduction: a calm 10-minute window (5 474 requests / 3.5 MB) puts ~150 lines on the wire. Rules (one line per host+client+category, fingerprint excludes the path): http-traversal, -sqli, -nul-byte, -secret-probe, -vcs-probe, -backup-probe, -scanner-ua, http-auth-brute (401/403 only, >=20/min and >=30 in 5m per coalesce(client_ip, peer)), http-flood (cap 12 new fingerprints/tick). FP control is the point: Forgejo is 93.5 % of the stream, so smart-HTTP git endpoints and browse/archive/RSS URLs on the Forgejo hosts are excluded from path rules, and severity escalates only when the shape is in the path component AND the origin answered 2xx (a 200 on `/?file=../../.env` is the landing page). Measured: 17 639 of 35 445 lines/hour are 303 -> /user/login (3xx, never counted); 293 are 404 crawler churn; the noisiest legitimate 401/403 client does 3/min. Verified on the live stream: calm window 07:03:40-07:13:40Z -> 0 findings, empty stdout, exit 0; the 06:48-06:53Z 91.92.47.0/24 burst -> 8 findings; crafted requests fired all nine rule kinds (public via Cloudflare and direct to the overlay for the peer fallback); first tick baselines silently, next emits, next is silent, deleting one fingerprint re-emits exactly one line. 85 unit tests. Docs: docs/gateway-http-rules.md. run.sh now cds to its own directory so a worktree runs its own code.
2026-11-27 02:17:14 -05:00
# ------------------------------------------------- gateway access log ----
# `cilium-envoy` writes one JSON access line per request (t_e662b03a); the
# `logging` Alloy DaemonSet ships it to Loki with 192 h retention. The sensor
# reads it **only** through LogQL so the filtering runs in Loki, not here.
# Measured 2026-11-27: 641 B/line, 9.54 lines/s, 528 MB/day raw, 93.5 % Forgejo.
LOKI_PROXY = (
"/api/v1/namespaces/logging/services/loki:3100/proxy"
)
LOKI_TIMEOUT = int(os.environ.get("NETSEC_SCAN_LOKI_TIMEOUT", "25"))
# Exact stream selector from the F7 handoff. Narrow on purpose: it is the
# difference between reading one pod's stream on one node and the whole cluster.
LOKI_STREAM = os.environ.get(
"NETSEC_SCAN_LOKI_STREAM",
'{namespace="kube-system", container="cilium-envoy", job="kube/pods", node="siriussec"}',
)
# How far back each tick looks. The cron interval is 5 min, so 10 min guarantees
# overlap across ticks (a line can never fall between two windows) and the
# fingerprint dedupe absorbs the overlap. 10 min ≈ 3.6 MB scanned per query.
HTTP_WINDOW = int(os.environ.get("NETSEC_SCAN_HTTP_WINDOW", "600"))
HTTP_RATE_WINDOW = int(os.environ.get("NETSEC_SCAN_HTTP_RATE_WINDOW", "300"))
HTTP_MAX_LINES = int(os.environ.get("NETSEC_SCAN_HTTP_MAX_LINES", "600"))
# A tick may announce at most this many *new* client/path fingerprints; the rest
# collapse into one `http-flood` state line. IP-rotating scanners would otherwise
# mint one line per source address.
HTTP_MAX_NEW_PER_TICK = int(os.environ.get("NETSEC_SCAN_HTTP_MAX_NEW", "12"))
# Severity control. Cloudflare replaces the socket peer with the tunnel
# (10.10.0.1 on the Pi); `client_ip` is the real client there. A request with
# neither is unattributable and is never used as a per-client key.
HTTP_EDGE_PEERS = frozenset({"10.10.0.1"})
# Only these hosts serve Forgejo browse URLs; on any other host the same path
# shape (e.g. `/<a>/<b>/raw/.../.env`) is a probe, not a repository view.
HTTP_FORGEJO_HOSTS = frozenset({"forgejo.siriusdevops.com"})
# 401/403 brute force per client. Measured on a calm hour 2026-11-27: 20 auth
# failures *total*, all from the CI git client (git/2.56.0 retrying a push),
# peak 1/min. Forgejo's legitimate 303 -> /user/login bulk is 3xx and never
# counted. So 20 failures in one minute plus 30 over five minutes is a real
# attempt, two orders of magnitude above the CI baseline.
HTTP_AUTH_PER_MIN = int(os.environ.get("NETSEC_SCAN_HTTP_AUTH_PER_MIN", "20"))
HTTP_AUTH_WINDOW_TOTAL = int(os.environ.get("NETSEC_SCAN_HTTP_AUTH_TOTAL", "30"))
# LogQL prefilter for attack-shaped *lines*. Deliberately a superset of what
# `http_rules.classify()` can flag: Loki drops non-matching bytes cheaply, and
# `classify()` makes the precise decision in Python (semantics the regex cannot
# express, e.g. Forgejo browse URLs and smart-HTTP git). The superset property is
# enforced by tests/fixtures/attack-shapes.json — every shape that table says
# classify() flags must also match this regex. `http-sqli` was unreachable for
# weeks because nobody asserted it: the prefilter admitted only `union select`
# and the canary happened to use that shape (t_a3604aab).
#
# Two rules for edits, both measured on this deployment:
# * every alternative is a plain or escaped literal. Wrapping part of this in a
# `(?:...)` group made Loki's filter ~10x slower (22 s vs 2 s for a 10-minute
# window; `LOKI_TIMEOUT` is 25 s), so payment for "readability" here is a
# timed-out tick.
# * keep the existing block first and append new literals. The same set of
# alternatives in a different order measured 20-60 s, so re-order only with a
# `count_over_time` timing behind you.
#
# Measured over-match, 2026-11-27 06:00-07:00Z on 29 426 lines: 1 202 lines/h
# before, 1 548 lines/h after (+29 %).
netsec-scan: HTTP attack-shape rules over the gateway access log (§4d) F7 (t_e662b03a) gave every Gateway listener a JSON access line and shipped it to Loki; this is the §4d consumer that had none. New `http_rules.py` classifies candidate lines and `loki.py` reads them through the logging/loki Service proxy with two LogQL queries per tick - a `|~` prefilter for attack-shaped lines and a `sum by (client_ip, peer)` 1-minute matrix for 401/403. Loki does the volume reduction: a calm 10-minute window (5 474 requests / 3.5 MB) puts ~150 lines on the wire. Rules (one line per host+client+category, fingerprint excludes the path): http-traversal, -sqli, -nul-byte, -secret-probe, -vcs-probe, -backup-probe, -scanner-ua, http-auth-brute (401/403 only, >=20/min and >=30 in 5m per coalesce(client_ip, peer)), http-flood (cap 12 new fingerprints/tick). FP control is the point: Forgejo is 93.5 % of the stream, so smart-HTTP git endpoints and browse/archive/RSS URLs on the Forgejo hosts are excluded from path rules, and severity escalates only when the shape is in the path component AND the origin answered 2xx (a 200 on `/?file=../../.env` is the landing page). Measured: 17 639 of 35 445 lines/hour are 303 -> /user/login (3xx, never counted); 293 are 404 crawler churn; the noisiest legitimate 401/403 client does 3/min. Verified on the live stream: calm window 07:03:40-07:13:40Z -> 0 findings, empty stdout, exit 0; the 06:48-06:53Z 91.92.47.0/24 burst -> 8 findings; crafted requests fired all nine rule kinds (public via Cloudflare and direct to the overlay for the peer fallback); first tick baselines silently, next emits, next is silent, deleting one fingerprint re-emits exactly one line. 85 unit tests. Docs: docs/gateway-http-rules.md. run.sh now cds to its own directory so a worktree runs its own code.
2026-11-27 02:17:14 -05:00
HTTP_LINE_FILTER = os.environ.get(
"NETSEC_SCAN_HTTP_LINE_FILTER",
"(?i)("
r"\.\.|%2e%2e|union|select|%00|%2500|\.env|\.git|\.svn|\.hg|"
r"credential|\.aws|\.ssh|id_rsa|\.kube|\.npmrc|\.netrc|\.htpasswd|"
r"secrets|service-account|\.bak|\.old|\.orig|\.save|\.swp|\.sql|"
r"\.dump|\.zip|\.tar|\.tgz|backup|sqlmap|nikto|nuclei|masscan|zgrab|"
r"nmap|wpscan|gobuster|dirbuster|ffuf|ferox|acunetix|netsparker|nessus|"
r"openvas|hydra|w3af|zaproxy|"
# Shapes classify() already knew but this filter dropped: double-encoded
# traversal, secret files it did not name, the VCS/backup extensions and
# scanner families it did not list.
r"%252e|\\u0000|\.bzr|secret|id_dsa|id_ecdsa|id_ed25519|authorized_keys|"
r"\.docker|\.pypirc|\.pgpass|\.my\.cnf|\.swo|\.gz|\.bz2|\.rar|\.7z|"
r"dirb|commix|jaeles|ysoserial|whatweb|gospider|"
# SQL injection. Any quote is the cheapest complete superset for the
# boolean/stacked families (`' OR '1'='1`, `%27%20OR%20%271%27=%271`,
# `';WAITFOR DELAY`) whatever the encoding; the time-based and function
# keywords carry no quote at all; the unquoted `or <n>=<n>` shape needs its
# separator spellings because this filter scans raw bytes, before decoding.
r"%27|'|sleep|benchmark|waitfor|pg_sleep|information_schema|sysobjects|"
r"extractvalue|updatexml|load_file|outfile|"
r"%20or|or%20|\+or|or\+|%2Bor|or%2B|\)or|%29or| or |"
r";drop|;delete|;insert|;update|%3bdrop|%3bdelete|%3binsert|%3bupdate"
")",
netsec-scan: HTTP attack-shape rules over the gateway access log (§4d) F7 (t_e662b03a) gave every Gateway listener a JSON access line and shipped it to Loki; this is the §4d consumer that had none. New `http_rules.py` classifies candidate lines and `loki.py` reads them through the logging/loki Service proxy with two LogQL queries per tick - a `|~` prefilter for attack-shaped lines and a `sum by (client_ip, peer)` 1-minute matrix for 401/403. Loki does the volume reduction: a calm 10-minute window (5 474 requests / 3.5 MB) puts ~150 lines on the wire. Rules (one line per host+client+category, fingerprint excludes the path): http-traversal, -sqli, -nul-byte, -secret-probe, -vcs-probe, -backup-probe, -scanner-ua, http-auth-brute (401/403 only, >=20/min and >=30 in 5m per coalesce(client_ip, peer)), http-flood (cap 12 new fingerprints/tick). FP control is the point: Forgejo is 93.5 % of the stream, so smart-HTTP git endpoints and browse/archive/RSS URLs on the Forgejo hosts are excluded from path rules, and severity escalates only when the shape is in the path component AND the origin answered 2xx (a 200 on `/?file=../../.env` is the landing page). Measured: 17 639 of 35 445 lines/hour are 303 -> /user/login (3xx, never counted); 293 are 404 crawler churn; the noisiest legitimate 401/403 client does 3/min. Verified on the live stream: calm window 07:03:40-07:13:40Z -> 0 findings, empty stdout, exit 0; the 06:48-06:53Z 91.92.47.0/24 burst -> 8 findings; crafted requests fired all nine rule kinds (public via Cloudflare and direct to the overlay for the peer fallback); first tick baselines silently, next emits, next is silent, deleting one fingerprint re-emits exactly one line. 85 unit tests. Docs: docs/gateway-http-rules.md. run.sh now cds to its own directory so a worktree runs its own code.
2026-11-27 02:17:14 -05:00
)