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.
181 lines
8.3 KiB
Python
181 lines
8.3 KiB
Python
"""Rule tests: novelty, dedupe semantics, ratios, thresholds and line shape."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import unittest
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
from helpers import FakeProm, fixture_flows
|
|
|
|
from netsec_scan import config, rules
|
|
from netsec_scan.rules import Finding
|
|
|
|
|
|
def utc(*args):
|
|
return datetime(*args, tzinfo=timezone.utc)
|
|
|
|
|
|
class TestFirstSeenEgress(unittest.TestCase):
|
|
def test_same_tuple_fires_once(self):
|
|
flows = fixture_flows("egress-sample.jsonl")
|
|
seen = {}
|
|
now = utc(2026, 11, 27, 5, 20)
|
|
first = rules.rule_egress_first_seen(flows, seen, now)
|
|
self.assertTrue(first)
|
|
self.assertTrue(all(f.rule == "egress-new-dst" for f in first))
|
|
# second evaluation over the same flows must be silent
|
|
second = rules.rule_egress_first_seen(flows, seen, now)
|
|
self.assertEqual(second, [])
|
|
|
|
def test_union_semantics_keeps_history(self):
|
|
flows = fixture_flows("egress-sample.jsonl")
|
|
seen = {}
|
|
rules.rule_egress_first_seen(flows, seen, utc(2026, 11, 27, 5, 20))
|
|
before = dict(seen)
|
|
# a later, unrelated evaluation must not shrink the seen-set
|
|
rules.rule_egress_first_seen([], seen, utc(2026, 11, 27, 5, 25))
|
|
self.assertEqual(seen, before)
|
|
|
|
def test_fingerprint_is_stable_across_runs(self):
|
|
flows = fixture_flows("egress-sample.jsonl")
|
|
a = rules.rule_egress_first_seen(flows, {}, utc(2026, 11, 27, 5, 20))
|
|
b = rules.rule_egress_first_seen(flows, {}, utc(2027, 1, 2, 9, 0))
|
|
self.assertEqual([f.fingerprint for f in a], [f.fingerprint for f in b])
|
|
|
|
def test_severity_by_port(self):
|
|
flows = fixture_flows("egress-sample.jsonl")
|
|
findings = rules.rule_egress_first_seen(flows, {}, utc(2026, 11, 27, 5, 20))
|
|
for f in findings:
|
|
port = int(f.entity.rsplit(":", 1)[1].split("/")[0])
|
|
want = "MEDIUM" if port in config.WEB_PORTS else "HIGH"
|
|
self.assertEqual(f.severity, want, f.entity)
|
|
|
|
def test_nonexternal_and_reserved_are_ignored(self):
|
|
flows = fixture_flows("egress-sample.jsonl")
|
|
findings = rules.rule_egress_first_seen(flows, {}, utc(2026, 11, 27, 5, 20))
|
|
for f in findings:
|
|
self.assertNotIn("reserved:", f.entity)
|
|
self.assertNotIn("192.168.", f.entity)
|
|
|
|
|
|
class TestBeacon(unittest.TestCase):
|
|
def setUp(self):
|
|
self.now = utc(2026, 11, 27, 5, 0).timestamp()
|
|
|
|
def test_regular_beacon_fires(self):
|
|
flows = fixture_flows("beacon-shaped.jsonl")
|
|
findings = rules.rule_beacon(flows, {}, self.now)
|
|
self.assertEqual(len(findings), 1)
|
|
self.assertEqual(findings[0].rule, "beacon-shape")
|
|
self.assertEqual(findings[0].severity, "HIGH")
|
|
self.assertIn("jitter 0.0", findings[0].detail)
|
|
|
|
def test_irregular_traffic_does_not_fire(self):
|
|
flows = fixture_flows("beacon-shaped.jsonl")
|
|
# stretch the gaps so the inter-arrival spread is not periodic
|
|
for i, flow in enumerate(flows):
|
|
flow.time = flows[0].time + timedelta(seconds=(i * i * 7) + i * 3)
|
|
findings = rules.rule_beacon(flows, {}, self.now)
|
|
self.assertEqual(findings, [])
|
|
|
|
def test_too_few_connections_do_not_fire(self):
|
|
flows = fixture_flows("beacon-shaped.jsonl")[: config.BEACON_MIN_CONNS - 1]
|
|
self.assertEqual(rules.rule_beacon(flows, {}, self.now), [])
|
|
|
|
def test_same_socket_is_one_connection(self):
|
|
"""Many packets on one long-lived connection must not count as many conns."""
|
|
flows = fixture_flows("beacon-shaped.jsonl")
|
|
for flow in flows:
|
|
flow.src_port = 40000
|
|
self.assertEqual(rules.rule_beacon(flows, {}, self.now), [])
|
|
|
|
|
|
class TestPromRules(unittest.TestCase):
|
|
def test_lost_events_per_node(self):
|
|
prom = FakeProm(vectors={ # noqa: E501
|
|
"hubble_lost_events_total":
|
|
[({"node": "siriussec"}, 0.60), ({"node": "rpi"}, 0.0)]})
|
|
findings = rules.rule_lost_events(prom)
|
|
self.assertEqual(len(findings), 1)
|
|
self.assertEqual(findings[0].entity, "node=siriussec")
|
|
self.assertEqual(findings[0].severity, "HIGH")
|
|
|
|
def test_drop_spike_needs_floor_and_ratio(self):
|
|
quiet = FakeProm(scalars={"hubble_drop_total": 0.02})
|
|
self.assertEqual(rules.rule_drop_spike(quiet), [])
|
|
# same absolute rate, 10x baseline: floor still blocks it
|
|
below_floor = FakeProm(scalars={"hubble_drop_total{protocol!=\"ICMPv6\"}[5m]": 0.02,
|
|
"hubble_drop_total{protocol!=\"ICMPv6\"}[1h] offset 5m": 0.0})
|
|
self.assertEqual(rules.rule_drop_spike(below_floor), [])
|
|
fired = FakeProm(scalars={
|
|
"hubble_drop_total{protocol!=\"ICMPv6\"}[1h] offset 5m": 0.01,
|
|
"hubble_drop_total{protocol!=\"ICMPv6\"}[5m]": 0.30,
|
|
"hubble_drop_total{protocol!=\"ICMPv6\"}": 0.30,
|
|
})
|
|
out = rules.rule_drop_spike(fired)
|
|
self.assertTrue(out)
|
|
self.assertIn("vs 1h baseline 0.01/s", out[0].detail)
|
|
# and when the baseline is genuinely zero the detail must say so
|
|
no_base = FakeProm(scalars={
|
|
"hubble_drop_total{protocol!=\"ICMPv6\"}[1h] offset 5m": 0.0,
|
|
"hubble_drop_total{protocol!=\"ICMPv6\"}[5m]": 0.30,
|
|
})
|
|
self.assertIn("no 1h baseline", rules.rule_drop_spike(no_base)[0].detail)
|
|
|
|
def test_syn_sweep_ratio_and_floor(self):
|
|
normal = FakeProm(scalars={'hubble_tcp_flags_total{flag="SYN"}[5m]': 10.6,
|
|
'hubble_tcp_flags_total{flag="SYN-ACK"}[5m]': 6.7})
|
|
self.assertEqual(rules.rule_syn_sweep(normal), [])
|
|
sweep = FakeProm(scalars={'hubble_tcp_flags_total{flag="SYN"}[5m]': 40.0,
|
|
'hubble_tcp_flags_total{flag="SYN-ACK"}[5m]': 2.0})
|
|
self.assertTrue(rules.rule_syn_sweep(sweep))
|
|
|
|
def test_rst_storm_ratio(self):
|
|
calm = FakeProm(scalars={'hubble_tcp_flags_total{flag="RST"}[5m]': 2.5,
|
|
'hubble_tcp_flags_total{flag="RST"}[5m]))[6h:5m]': 2.4})
|
|
self.assertEqual(rules.rule_rst_storm(calm), [])
|
|
storm = FakeProm(scalars={'hubble_tcp_flags_total{flag="RST"}[5m]': 60.0,
|
|
'hubble_tcp_flags_total{flag="RST"}[5m]))[6h:5m]': 2.4})
|
|
self.assertTrue(rules.rule_rst_storm(storm))
|
|
|
|
def test_new_port_ignores_ephemeral_ports(self):
|
|
prom = FakeProm(vectors={"hubble_port_distribution_total": [
|
|
({"port": "3100"}, 3.0), ({"port": "54321"}, 1.0), ({"port": "0"}, 3.0)]})
|
|
findings = rules.rule_new_port(prom)
|
|
self.assertEqual([f.entity for f in findings], ["port=3100"])
|
|
self.assertEqual(findings[0].severity, "LOW")
|
|
|
|
def test_http_error_ratio_needs_traffic_floor(self):
|
|
quiet = FakeProm(scalars={"sum(rate(hubble_http_requests_total[15m]))": 0.2,
|
|
'status=~"4..|5.."': 0.2})
|
|
self.assertEqual(rules.rule_http_errors(quiet), [])
|
|
busy = FakeProm(scalars={"sum(rate(hubble_http_requests_total[15m]))": 4.0,
|
|
'status=~"4..|5.."': 3.0})
|
|
self.assertTrue(rules.rule_http_errors(busy))
|
|
|
|
|
|
class TestOutputShape(unittest.TestCase):
|
|
def test_render_is_bounded_and_starts_with_severity_and_fingerprint(self):
|
|
from netsec_scan.__main__ import render
|
|
|
|
finding = Finding(rule="egress-new-dst", kind="novelty", severity="HIGH",
|
|
entity="osint/osint-app->203.0.113.9:4444/tcp",
|
|
detail="x" * 400)
|
|
line = render(finding)
|
|
self.assertLessEqual(len(line), config.MAX_LINE)
|
|
self.assertTrue(line.startswith("HIGH "))
|
|
self.assertEqual(line.split(" ")[1], finding.fingerprint)
|
|
|
|
def test_fingerprint_ignores_counts_and_time(self):
|
|
a = Finding(rule="drop-spike", kind="state", severity="MEDIUM",
|
|
entity="cluster", detail="3 drops")
|
|
b = Finding(rule="drop-spike", kind="state", severity="MEDIUM",
|
|
entity="cluster", detail="300 drops at 09:00Z")
|
|
self.assertEqual(a.fingerprint, b.fingerprint)
|
|
c = Finding(rule="drop-spike", kind="state", severity="MEDIUM",
|
|
entity="cluster=other", detail="3 drops")
|
|
self.assertNotEqual(a.fingerprint, c.fingerprint)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|