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
@@ -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