netsec-agent/tests/test_rules.py

255 lines
12 KiB
Python
Raw Normal View History

"""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):
NOW = utc(2026, 11, 27, 5, 20)
def evaluate(self, flows, seen, counts=None, tick=1, now=None):
return rules.rule_egress_first_seen(
flows, seen, counts if counts is not None else {},
now or self.NOW, 0.5, tick)
def warmed(self, flows):
"""Run the ticks *before* the gate fires; emit nothing, fill counts."""
counts = {}
for tick in range(1, config.EGRESS_WEB_MIN_TICKS):
self.assertEqual(self.evaluate(flows, {}, counts, tick=tick), [])
return counts
def test_web_port_tuple_needs_three_ticks(self):
"""One-shot / short-lived CDN destinations must not produce a line."""
flows = fixture_flows("egress-sample.jsonl")
counts = {}
self.assertEqual(self.evaluate(flows, {}, counts, tick=1), [])
self.assertEqual(self.evaluate(flows, {}, counts, tick=2), [])
findings = self.evaluate(flows, {}, counts, tick=3)
self.assertTrue(findings)
self.assertTrue(all(f.rule == "egress-new-dst" for f in findings))
self.assertTrue(all(f.severity == "MEDIUM" for f in findings))
def test_non_web_port_alerts_on_first_sight(self):
flows = fixture_flows("egress-sample.jsonl")
for flow in flows[:1]:
flow.dst_port = 4444
findings = self.evaluate(flows[:1], {}, {}, tick=1)
self.assertEqual(len(findings), 1)
self.assertEqual(findings[0].severity, "HIGH")
self.assertIn(":4444/", findings[0].entity)
def test_dropped_verdict_is_keyed_and_high(self):
flows = fixture_flows("egress-sample.jsonl")
flows = flows[:1]
flows[0].verdict = "DROPPED"
findings = self.evaluate(flows, {}, {}, tick=1)
self.assertEqual(len(findings), 1)
self.assertEqual(findings[0].severity, "HIGH")
self.assertTrue(findings[0].entity.endswith("/dropped"))
def test_seen_fingerprint_suppresses_the_rule(self):
flows = fixture_flows("egress-sample.jsonl")
counts = self.warmed(flows)
first = self.evaluate(flows, {}, counts, tick=config.EGRESS_WEB_MIN_TICKS)
self.assertTrue(first)
seen = {f.fingerprint: {"rule": f.rule} for f in first}
self.assertEqual(self.evaluate(flows, seen, counts,
tick=config.EGRESS_WEB_MIN_TICKS + 1), [])
def test_single_fire_then_rearm_when_one_key_is_deleted(self):
"""The acceptance procedure: delete exactly one fp -> exactly one line."""
from netsec_scan.__main__ import apply_dedupe
fires = config.EGRESS_WEB_MIN_TICKS
flows = fixture_flows("egress-sample.jsonl")
counts = self.warmed(flows)
seen = {}
first = apply_dedupe(self.evaluate(flows, seen, counts, tick=fires),
seen, self.NOW.timestamp(), False)
self.assertTrue(first)
again = apply_dedupe(self.evaluate(flows, seen, counts, tick=fires + 1),
seen, self.NOW.timestamp(), False)
self.assertEqual(again, [])
target = first[0].fingerprint
del seen[target]
rearmed = apply_dedupe(self.evaluate(flows, seen, counts, tick=fires + 2),
seen, self.NOW.timestamp(), False)
self.assertEqual([f.fingerprint for f in rearmed], [target])
def test_seen_set_is_union_only(self):
from netsec_scan.__main__ import apply_dedupe
flows = fixture_flows("egress-sample.jsonl")
seen = {"deadbeef0000": {"rule": "egress-new-dst", "kind": "novelty"}}
apply_dedupe(self.evaluate(flows, seen, self.warmed(flows),
tick=config.EGRESS_WEB_MIN_TICKS),
seen, self.NOW.timestamp(), False)
self.assertIn("deadbeef0000", seen)
self.assertGreater(len(seen), 1)
def test_fingerprint_is_stable_across_runs(self):
flows = fixture_flows("egress-sample.jsonl")
fires = config.EGRESS_WEB_MIN_TICKS
a = self.evaluate(flows, {}, self.warmed(flows), tick=fires,
now=utc(2026, 11, 27, 5, 20))
b = self.evaluate(flows, {}, self.warmed(flows), tick=fires,
now=utc(2027, 1, 2, 9, 0))
self.assertEqual([f.fingerprint for f in a], [f.fingerprint for f in b])
def test_nonexternal_and_reserved_are_ignored(self):
flows = fixture_flows("egress-sample.jsonl")
findings = self.evaluate(flows, {}, self.warmed(flows),
tick=config.EGRESS_WEB_MIN_TICKS)
self.assertTrue(findings)
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 TestDayCounters(unittest.TestCase):
def test_egress_tuples_union_across_ticks(self):
from netsec_scan.__main__ import record_counters
from netsec_scan import state as state_mod
st = state_mod.empty()
record_counters(st, 5, [], ["a->1.2.3.4:443/tcp"], 0)
record_counters(st, 7, [], ["a->1.2.3.4:443/tcp", "b->5.6.7.8:80/tcp"], 1)
self.assertEqual(st["day"]["flows"], 12)
self.assertEqual(st["day"]["egress"], ["a->1.2.3.4:443/tcp", "b->5.6.7.8:80/tcp"])
self.assertEqual(st["totals"]["ticks"], 2)
self.assertEqual(st["totals"]["malformed"], 1)
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()