feat(ranges): enforce LAPI range decisions in an agent-owned nft table
crowdsec-firewall-bouncer's nftables mode strips the prefix from Range decisions and bans only the network address, so a /24 decision blocked a single IP. With ranges.enabled, every audit now syncs range decisions into a dedicated `inet crowdsec-ranges` table (interval+timeout sets with input/forward drop chains) in one atomic `nft -f` transaction, then reads it back to confirm each range is enforced. - element timeouts track each decision's remaining lifetime; stale elements are removed and extended decisions refreshed - ranges nested in another active range are covered, not inserted - ranges broader than min_prefix_v4/v6 (default /16, /32) are refused - ranges still missing after the sync stay in unenforceable_ranges, so the node reports DEGRADED rather than HEALTHY - the bouncer-set scan normalizes nft prefix elements to addr/len instead of failing the table scan on them - doctor checks the range table; the audit log line says when a synced node is degraded Disabled by default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e76e957282
commit
7156cfd4fe
10 files changed
+671
-8
No files matched your search
@@ -128,6 +128,54 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
|
||||
self.assertTrue(is_synced)
|
||||
self.assertEqual([], drift["unenforceable_ranges"])
|
||||
|
||||
def test_reconcile_uses_range_enforcer_for_range_decisions(self):
|
||||
class StubEnforcer:
|
||||
table = "crowdsec-ranges"
|
||||
|
||||
def __init__(self):
|
||||
self.synced = None
|
||||
|
||||
def sync(self, range_truth):
|
||||
self.synced = range_truth
|
||||
return []
|
||||
|
||||
enforcer = StubEnforcer()
|
||||
auditor = FirewallAuditor(range_enforcer=enforcer)
|
||||
auditor.get_remote_lapi_truth = lambda: {
|
||||
"195.178.110.0/24": {"duration": "11h", "until_epoch": None},
|
||||
"1.1.1.1": {"duration": "4h", "until_epoch": None},
|
||||
"1.2.3.4/32": {"duration": "4h", "until_epoch": None},
|
||||
}
|
||||
auditor.get_kernel_state = lambda: {
|
||||
"195.178.110.0": 40000,
|
||||
"1.1.1.1": 14000,
|
||||
"1.2.3.4": 14000,
|
||||
}
|
||||
|
||||
is_synced, _, drift = auditor.reconcile()
|
||||
|
||||
self.assertTrue(is_synced)
|
||||
self.assertEqual(["195.178.110.0/24"], list(enforcer.synced))
|
||||
self.assertEqual([], drift["unenforceable_ranges"])
|
||||
|
||||
def test_reconcile_reports_ranges_the_range_enforcer_could_not_apply(self):
|
||||
class FailingEnforcer:
|
||||
table = "crowdsec-ranges"
|
||||
|
||||
def sync(self, range_truth):
|
||||
return sorted(range_truth)
|
||||
|
||||
auditor = FirewallAuditor(range_enforcer=FailingEnforcer())
|
||||
auditor.get_remote_lapi_truth = lambda: {
|
||||
"195.178.110.0/24": {"duration": "11h", "until_epoch": None}
|
||||
}
|
||||
auditor.get_kernel_state = lambda: {"195.178.110.0": 40000}
|
||||
|
||||
is_synced, _, drift = auditor.reconcile()
|
||||
|
||||
self.assertTrue(is_synced)
|
||||
self.assertEqual(["195.178.110.0/24"], drift["unenforceable_ranges"])
|
||||
|
||||
def test_reconcile_logs_missing_and_extra_values(self):
|
||||
auditor = FirewallAuditor()
|
||||
auditor.get_remote_lapi_truth = lambda: {
|
||||
@@ -396,6 +444,38 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
|
||||
|
||||
self.assertEqual({"1.1.1.1": 600000.0}, kernel_state)
|
||||
|
||||
@patch("auditor.subprocess.run")
|
||||
def test_get_kernel_state_normalizes_prefix_elements(self, run_mock):
|
||||
auditor = FirewallAuditor(targets=[("ip", "crowdsec")])
|
||||
run_mock.return_value = subprocess.CompletedProcess(
|
||||
args=[],
|
||||
returncode=0,
|
||||
stdout=json.dumps(
|
||||
{
|
||||
"nftables": [
|
||||
{
|
||||
"set": {
|
||||
"name": "crowdsec-blacklists-cscli",
|
||||
"elem": [
|
||||
{
|
||||
"elem": {
|
||||
"val": {"prefix": {"addr": "10.0.0.0", "len": 24}},
|
||||
"expires": 1000,
|
||||
}
|
||||
},
|
||||
{"elem": {"val": "1.1.1.1", "expires": 2000}},
|
||||
],
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
kernel_state = auditor.get_kernel_state()
|
||||
|
||||
self.assertEqual({"10.0.0.0/24": 1000.0, "1.1.1.1": 2000.0}, kernel_state)
|
||||
|
||||
@patch("auditor.subprocess.run")
|
||||
def test_get_kernel_state_falls_back_when_configured_sets_do_not_match(self, run_mock):
|
||||
auditor = FirewallAuditor(
|
||||
|
||||
@@ -63,6 +63,35 @@ class RuntimeSettingsEnforcementTests(unittest.TestCase):
|
||||
|
||||
self.assertEqual(0.90, settings.check_jitter_pct)
|
||||
|
||||
@patch("config.load_config")
|
||||
def test_ranges_settings_default_to_disabled(self, load_config_mock):
|
||||
load_config_mock.return_value = {}
|
||||
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
settings = load_runtime_settings()
|
||||
|
||||
self.assertFalse(settings.ranges_enabled)
|
||||
self.assertEqual("crowdsec-ranges", settings.ranges_table)
|
||||
self.assertEqual(16, settings.ranges_min_prefix_v4)
|
||||
self.assertEqual(32, settings.ranges_min_prefix_v6)
|
||||
|
||||
@patch("config.load_config")
|
||||
def test_ranges_settings_loaded_and_validated(self, load_config_mock):
|
||||
load_config_mock.return_value = {
|
||||
"ranges": {"enabled": True, "table": "r", "min_prefix_v4": 0, "min_prefix_v6": 48}
|
||||
}
|
||||
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
settings = load_runtime_settings()
|
||||
issues = validate_runtime_settings(settings)
|
||||
|
||||
self.assertTrue(settings.ranges_enabled)
|
||||
self.assertEqual("r", settings.ranges_table)
|
||||
self.assertEqual(48, settings.ranges_min_prefix_v6)
|
||||
self.assertTrue(
|
||||
any(i.level == "ERROR" and "min_prefix_v4" in i.message for i in issues)
|
||||
)
|
||||
|
||||
def test_validate_runtime_settings_reports_errors(self):
|
||||
settings = RuntimeSettings(
|
||||
node_name="n1",
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import dataclasses
|
||||
import json
|
||||
import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
@@ -6,6 +8,7 @@ from config import RuntimeSettings
|
||||
from doctor import (
|
||||
CheckResult,
|
||||
check_cscli_json,
|
||||
check_range_table,
|
||||
check_systemctl_restart_capability,
|
||||
run_doctor,
|
||||
)
|
||||
@@ -40,6 +43,30 @@ class DoctorTests(unittest.TestCase):
|
||||
self.assertEqual("FAIL", result.status)
|
||||
self.assertIn("Invalid JSON", result.detail)
|
||||
|
||||
@patch("doctor._run_cmd")
|
||||
def test_check_range_table_warns_when_table_not_created_yet(self, run_cmd_mock):
|
||||
run_cmd_mock.side_effect = subprocess.CalledProcessError(1, ["nft"])
|
||||
settings = dataclasses.replace(_settings(), ranges_enabled=True)
|
||||
|
||||
result = check_range_table(settings)
|
||||
|
||||
self.assertEqual("WARN", result.status)
|
||||
self.assertIn("creates it on its first audit", result.detail)
|
||||
|
||||
@patch("doctor._run_cmd")
|
||||
def test_check_range_table_fails_when_a_set_is_missing(self, run_cmd_mock):
|
||||
run_cmd_mock.return_value = subprocess.CompletedProcess(
|
||||
args=[],
|
||||
returncode=0,
|
||||
stdout=json.dumps({"nftables": [{"set": {"name": "ranges-v4"}}]}),
|
||||
)
|
||||
settings = dataclasses.replace(_settings(), ranges_enabled=True)
|
||||
|
||||
result = check_range_table(settings)
|
||||
|
||||
self.assertEqual("FAIL", result.status)
|
||||
self.assertIn("ranges-v6", result.detail)
|
||||
|
||||
@patch("doctor.os.geteuid", return_value=1000)
|
||||
def test_check_systemctl_restart_capability_warns_when_not_root(self, _geteuid):
|
||||
result = check_systemctl_restart_capability()
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import json
|
||||
import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranges import RangeEnforcer, element_key
|
||||
|
||||
|
||||
def _nft_table(v4=(), v6=()):
|
||||
def elems(items):
|
||||
return [
|
||||
{"elem": {"val": {"prefix": {"addr": addr, "len": length}}, "expires": expires}}
|
||||
for addr, length, expires in items
|
||||
]
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"nftables": [
|
||||
{"table": {"family": "inet", "name": "crowdsec-ranges"}},
|
||||
{"set": {"name": "ranges-v4", "elem": elems(v4)}},
|
||||
{"set": {"name": "ranges-v6", "elem": elems(v6)}},
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class FakeNft:
|
||||
"""Serves `nft -j list` from a queue of table payloads and records `nft -f -` scripts."""
|
||||
|
||||
def __init__(self, listings, apply_error=None):
|
||||
self.listings = list(listings)
|
||||
self.apply_error = apply_error
|
||||
self.scripts = []
|
||||
|
||||
def __call__(self, cmd, **kwargs):
|
||||
if cmd[1:3] == ["-f", "-"]:
|
||||
self.scripts.append(kwargs["input"])
|
||||
if self.apply_error:
|
||||
raise subprocess.CalledProcessError(1, cmd, stderr=self.apply_error)
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
|
||||
listing = self.listings.pop(0)
|
||||
if listing is None:
|
||||
raise subprocess.CalledProcessError(1, cmd, stderr="No such file or directory")
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout=listing, stderr="")
|
||||
|
||||
|
||||
class RangeEnforcerTests(unittest.TestCase):
|
||||
def test_element_key_normalizes_prefix_address_and_range(self):
|
||||
self.assertEqual(
|
||||
"10.0.0.0/24", element_key({"prefix": {"addr": "10.0.0.0", "len": 24}})
|
||||
)
|
||||
self.assertEqual("10.0.0.1", element_key("10.0.0.1"))
|
||||
self.assertEqual("10.0.0.1-10.0.0.9", element_key({"range": ["10.0.0.1", "10.0.0.9"]}))
|
||||
self.assertIsNone(element_key({"elem": 1}))
|
||||
|
||||
def test_sync_creates_table_and_adds_missing_range(self):
|
||||
nft = FakeNft([None, _nft_table(v4=[("195.178.110.0", 24, 3600)])])
|
||||
with patch("ranges.subprocess.run", nft):
|
||||
unenforced = RangeEnforcer().sync(
|
||||
{"195.178.110.0/24": {"duration": "1h", "until_epoch": None}}
|
||||
)
|
||||
|
||||
self.assertEqual([], unenforced)
|
||||
script = nft.scripts[0]
|
||||
self.assertIn("add table inet crowdsec-ranges", script)
|
||||
self.assertIn("flags interval, timeout;", script)
|
||||
self.assertIn("add rule inet crowdsec-ranges input ip saddr @ranges-v4 drop", script)
|
||||
self.assertIn("add rule inet crowdsec-ranges forward ip6 saddr @ranges-v6 drop", script)
|
||||
self.assertIn(
|
||||
"add element inet crowdsec-ranges ranges-v4 { 195.178.110.0/24 timeout 3600s }",
|
||||
script,
|
||||
)
|
||||
|
||||
def test_sync_leaves_matching_element_and_removes_stale_one(self):
|
||||
table = _nft_table(v4=[("195.178.110.0", 24, 3500)], v6=[("2001:db8::", 48, 900)])
|
||||
nft = FakeNft([table, _nft_table(v4=[("195.178.110.0", 24, 3500)])])
|
||||
with patch("ranges.subprocess.run", nft):
|
||||
unenforced = RangeEnforcer().sync(
|
||||
{"195.178.110.0/24": {"duration": "1h", "until_epoch": None}}
|
||||
)
|
||||
|
||||
self.assertEqual([], unenforced)
|
||||
self.assertNotIn("195.178.110.0/24", nft.scripts[0])
|
||||
self.assertIn(
|
||||
"delete element inet crowdsec-ranges ranges-v6 { 2001:db8::/48 }", nft.scripts[0]
|
||||
)
|
||||
|
||||
def test_sync_refreshes_element_when_decision_was_extended(self):
|
||||
table = _nft_table(v4=[("195.178.110.0", 24, 600)])
|
||||
nft = FakeNft([table, _nft_table(v4=[("195.178.110.0", 24, 32400)])])
|
||||
with patch("ranges.subprocess.run", nft):
|
||||
RangeEnforcer().sync({"195.178.110.0/24": {"duration": "9h", "until_epoch": None}})
|
||||
|
||||
script = nft.scripts[0]
|
||||
delete = script.index("delete element inet crowdsec-ranges ranges-v4 { 195.178.110.0/24 }")
|
||||
add = script.index(
|
||||
"add element inet crowdsec-ranges ranges-v4 { 195.178.110.0/24 timeout 32400s }"
|
||||
)
|
||||
self.assertLess(delete, add)
|
||||
|
||||
def test_sync_refuses_ranges_broader_than_min_prefix(self):
|
||||
nft = FakeNft([_nft_table(), _nft_table()])
|
||||
with patch("ranges.subprocess.run", nft):
|
||||
unenforced = RangeEnforcer(min_prefix_v4=16).sync(
|
||||
{"10.0.0.0/8": {"duration": "1h", "until_epoch": None}}
|
||||
)
|
||||
|
||||
self.assertEqual(["10.0.0.0/8"], unenforced)
|
||||
self.assertNotIn("10.0.0.0", nft.scripts[0])
|
||||
|
||||
def test_sync_inserts_only_supernet_of_overlapping_ranges(self):
|
||||
nft = FakeNft([_nft_table(), _nft_table(v4=[("192.0.2.0", 24, 7200)])])
|
||||
with patch("ranges.subprocess.run", nft):
|
||||
unenforced = RangeEnforcer().sync(
|
||||
{
|
||||
"192.0.2.0/24": {"duration": "2h", "until_epoch": None},
|
||||
"192.0.2.64/26": {"duration": "1h", "until_epoch": None},
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual([], unenforced)
|
||||
self.assertIn("192.0.2.0/24", nft.scripts[0])
|
||||
self.assertNotIn("192.0.2.64/26", nft.scripts[0])
|
||||
|
||||
def test_sync_skips_expired_decision_and_parses_fractional_duration(self):
|
||||
nft = FakeNft([_nft_table(), _nft_table(v4=[("192.0.2.0", 24, 5400)])])
|
||||
with patch("ranges.subprocess.run", nft):
|
||||
RangeEnforcer().sync(
|
||||
{
|
||||
"192.0.2.0/24": {"duration": "1h30m0.5s", "until_epoch": None},
|
||||
"198.51.100.0/24": {"duration": "-2m", "until_epoch": None},
|
||||
}
|
||||
)
|
||||
|
||||
self.assertIn("{ 192.0.2.0/24 timeout 5400s }", nft.scripts[0])
|
||||
self.assertNotIn("198.51.100.0", nft.scripts[0])
|
||||
|
||||
def test_sync_reports_ranges_missing_after_failed_apply(self):
|
||||
nft = FakeNft([_nft_table(), _nft_table()], apply_error="Error: conflicting intervals")
|
||||
with patch("ranges.subprocess.run", nft), self.assertLogs(level="ERROR") as logs:
|
||||
unenforced = RangeEnforcer().sync(
|
||||
{"192.0.2.0/24": {"duration": "1h", "until_epoch": None}}
|
||||
)
|
||||
|
||||
self.assertEqual(["192.0.2.0/24"], unenforced)
|
||||
self.assertTrue(any("conflicting intervals" in line for line in logs.output))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user