feat(ranges): enforce LAPI range decisions in an agent-owned nft table
CI / Unit tests (push) Successful in 9s
CI / Unit tests (pull_request) Successful in 6s

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:
patrickandClaude Opus 5.5 committed 2026-10-23 09:54:26 -04:00
1 parent e76e957282
commit 7156cfd4fe
10 files changed
+668 -5

No files matched your search

+41 -1
View File
@@ -92,6 +92,7 @@ It needs sufficient access to:
- inspect `nftables` tables via `nft -j list table ...` - inspect `nftables` tables via `nft -j list table ...`
- flush managed CrowdSec sets when performing metadata-drift healing - flush managed CrowdSec sets when performing metadata-drift healing
- restart `crowdsec-firewall-bouncer` via `systemctl` - restart `crowdsec-firewall-bouncer` via `systemctl`
- create and update its own range table via `nft -f -` (only with `ranges.enabled`)
### What it changes ### What it changes
@@ -101,6 +102,7 @@ Depending on drift type, the agent may:
- read `nftables` kernel state - read `nftables` kernel state
- flush **managed CrowdSec sets only** - flush **managed CrowdSec sets only**
- restart `crowdsec-firewall-bouncer` - restart `crowdsec-firewall-bouncer`
- maintain the dedicated range table (see [Range decisions](#range-decisions)), when enabled
- write local health state / history files - write local health state / history files
### What it does not change ### What it does not change
@@ -108,7 +110,7 @@ Depending on drift type, the agent may:
By design, the agent does **not**: By design, the agent does **not**:
- manage unrelated firewall policy - manage unrelated firewall policy
- rewrite arbitrary `nftables` rulesets - rewrite `nftables` rulesets other than its own range table
- invent its own ban decisions - invent its own ban decisions
- replace CrowdSec or the firewall bouncer - replace CrowdSec or the firewall bouncer
- act as a general-purpose firewall orchestration framework - act as a general-purpose firewall orchestration framework
@@ -210,6 +212,31 @@ This is especially important for longer-duration bans, where stale metadata can
To reduce noise, short-duration TTL variance is intentionally tolerated. The goal is to catch meaningful desynchronization, not harmless decay. To reduce noise, short-duration TTL variance is intentionally tolerated. The goal is to catch meaningful desynchronization, not harmless decay.
### Range decisions
`crowdsec-firewall-bouncer` (nftables mode) cannot enforce `Range` decisions: it strips the prefix and bans only the network address, so `195.178.110.0/24` blocks just `195.178.110.0`. The agent pairs such a range with that address so it is not counted as membership drift, and handles it as below.
With `ranges.enabled: false` (the default), the range is reported in `unenforceable_ranges` and the node status is `DEGRADED`.
With `ranges.enabled: true`, every audit syncs the range decisions into a table the agent owns, in one atomic `nft -f` transaction:
```text
table inet crowdsec-ranges {
set ranges-v4 { type ipv4_addr; flags interval, timeout; }
set ranges-v6 { type ipv6_addr; flags interval, timeout; }
chain input { type filter hook input priority -10; policy accept; ip saddr @ranges-v4 drop; ip6 saddr @ranges-v6 drop; }
chain forward { type filter hook forward priority -10; policy accept; ip saddr @ranges-v4 drop; ip6 saddr @ranges-v6 drop; }
}
```
- each range is added with its decision's remaining lifetime as the element timeout, so bans expire on their own even if the agent stops
- elements whose decision is gone are removed, and elements whose decision was extended are refreshed
- a range inside another active range is covered by the wider one rather than inserted (interval sets reject overlaps)
- ranges broader than `min_prefix_v4` / `min_prefix_v6` are refused, so a bad decision cannot cut off a node
- after applying, the table is read back; any range not present is reported in `unenforceable_ranges` (status `DEGRADED`)
To remove the table after disabling the feature: `nft delete table inet crowdsec-ranges`.
--- ---
## Project structure ## Project structure
@@ -221,6 +248,7 @@ To reduce noise, short-duration TTL variance is intentionally tolerated. The goa
├── config.py # Runtime settings + logging setup ├── config.py # Runtime settings + logging setup
├── auditor.py # LAPI vs nft reconciliation and drift fingerprinting ├── auditor.py # LAPI vs nft reconciliation and drift fingerprinting
├── healing.py # Heal gating + post-heal verification ├── healing.py # Heal gating + post-heal verification
├── ranges.py # Range decision enforcement in a dedicated nft table
├── doctor.py # Preflight diagnostics ├── doctor.py # Preflight diagnostics
├── reporter.py # Local state + heal history writer ├── reporter.py # Local state + heal history writer
├── config.yaml # Runtime defaults (overridable) ├── config.yaml # Runtime defaults (overridable)
@@ -308,6 +336,18 @@ Supported environment overrides:
If no explicit set allowlist is given, the agent defaults to managing CrowdSec-style `*-cscli` sets where applicable. This keeps healing scope intentionally narrow. If no explicit set allowlist is given, the agent defaults to managing CrowdSec-style `*-cscli` sets where applicable. This keeps healing scope intentionally narrow.
### Range enforcement
```yaml
ranges:
enabled: true # default false
table: "crowdsec-ranges" # inet table the agent owns
min_prefix_v4: 16 # refuse IPv4 ranges broader than /16
min_prefix_v6: 32 # refuse IPv6 ranges broader than /32
```
See [Range decisions](#range-decisions).
--- ---
## Operational notes ## Operational notes
+29 -2
View File
@@ -6,6 +6,8 @@ import logging
import hashlib import hashlib
import datetime import datetime
import ipaddress import ipaddress
from ranges import element_key
try: try:
from dotenv import load_dotenv from dotenv import load_dotenv
except ImportError: except ImportError:
@@ -17,9 +19,12 @@ class LapiUnavailableError(RuntimeError):
class FirewallAuditor: class FirewallAuditor:
def __init__(self, targets=None, managed_sets=None): def __init__(self, targets=None, managed_sets=None, range_enforcer=None):
"""Ensures the NFT kernel state matches the LAPI's desired state.""" """Ensures the NFT kernel state matches the LAPI's desired state."""
load_dotenv() load_dotenv()
# When set, range decisions are enforced in a dedicated table instead of
# being reported as unenforceable.
self.range_enforcer = range_enforcer
self.targets = list(targets or (("ip", "crowdsec"), ("ip6", "crowdsec6"))) self.targets = list(targets or (("ip", "crowdsec"), ("ip6", "crowdsec6")))
self.managed_sets = {str(name) for name in (managed_sets or ()) if str(name)} self.managed_sets = {str(name) for name in (managed_sets or ()) if str(name)}
self._reported_set_miss = set() self._reported_set_miss = set()
@@ -32,8 +37,12 @@ class FirewallAuditor:
if not target_desc: if not target_desc:
target_desc = "none" target_desc = "none"
sets_desc = ", ".join(sorted(self.managed_sets)) if self.managed_sets else "(auto: *-cscli)" sets_desc = ", ".join(sorted(self.managed_sets)) if self.managed_sets else "(auto: *-cscli)"
ranges_desc = (
f"inet:{self.range_enforcer.table}" if self.range_enforcer else "disabled"
)
logging.info( logging.info(
f"Enforcement config: targets=[{target_desc}] managed_sets=[{sets_desc}] " f"Enforcement config: targets=[{target_desc}] managed_sets=[{sets_desc}] "
f"range_table={ranges_desc}"
) )
for family, table in dict.fromkeys(self.targets): for family, table in dict.fromkeys(self.targets):
@@ -208,7 +217,7 @@ class FirewallAuditor:
if isinstance(e, dict): if isinstance(e, dict):
inner = e.get('elem', e) inner = e.get('elem', e)
if isinstance(inner, dict): if isinstance(inner, dict):
val = inner.get('val') val = element_key(inner.get('val'))
expires_raw = inner.get('expires') expires_raw = inner.get('expires')
if val: if val:
try: try:
@@ -395,7 +404,17 @@ class FirewallAuditor:
reality_set, reality_set,
reality_set - truth_set, reality_set - truth_set,
) )
if self.range_enforcer:
unenforceable_ranges = self.range_enforcer.sync(
{value: meta for value, meta in truth_map.items() if self._is_range(value)}
)
if unenforceable_ranges: if unenforceable_ranges:
logging.warning(
"Range decisions not enforced by the range table "
f"(count={len(unenforceable_ranges)}) "
f"ranges={self._preview_values(unenforceable_ranges)}"
)
elif unenforceable_ranges:
logging.warning( logging.warning(
"Range decisions not enforced: the nft set holds only their network " "Range decisions not enforced: the nft set holds only their network "
"address (it lacks the interval flag), so a bouncer restart cannot " "address (it lacks the interval flag), so a bouncer restart cannot "
@@ -500,6 +519,14 @@ class FirewallAuditor:
unenforceable_ranges.append(value) unenforceable_ranges.append(value)
return remaining_missing, sorted(remaining_extra), unenforceable_ranges return remaining_missing, sorted(remaining_extra), unenforceable_ranges
@staticmethod
def _is_range(value):
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError:
return False
return network.prefixlen < network.max_prefixlen
def _preview_values(self, values, limit=10): def _preview_values(self, values, limit=10):
shown = ",".join(str(v) for v in values[:limit]) shown = ",".join(str(v) for v in values[:limit])
if len(values) > limit: if len(values) > limit:
+41
View File
@@ -12,6 +12,9 @@ DEFAULT_MEMBERSHIP_RECHECK_DELAY = 30
DEFAULT_CONFIG_PATH = "config.yaml" DEFAULT_CONFIG_PATH = "config.yaml"
DEFAULT_NODE_NAME = "Unknown Node" DEFAULT_NODE_NAME = "Unknown Node"
DEFAULT_ENFORCEMENT_TARGETS = (("ip", "crowdsec"), ("ip6", "crowdsec6")) DEFAULT_ENFORCEMENT_TARGETS = (("ip", "crowdsec"), ("ip6", "crowdsec6"))
DEFAULT_RANGES_TABLE = "crowdsec-ranges"
DEFAULT_RANGES_MIN_PREFIX_V4 = 16
DEFAULT_RANGES_MIN_PREFIX_V6 = 32
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -27,6 +30,10 @@ class RuntimeSettings:
enforcement_sets: tuple[str, ...] enforcement_sets: tuple[str, ...]
config_path: str config_path: str
membership_recheck_delay: int = DEFAULT_MEMBERSHIP_RECHECK_DELAY membership_recheck_delay: int = DEFAULT_MEMBERSHIP_RECHECK_DELAY
ranges_enabled: bool = False
ranges_table: str = DEFAULT_RANGES_TABLE
ranges_min_prefix_v4: int = DEFAULT_RANGES_MIN_PREFIX_V4
ranges_min_prefix_v6: int = DEFAULT_RANGES_MIN_PREFIX_V6
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -256,6 +263,16 @@ def load_runtime_settings():
) )
enforcement_targets = _resolve_enforcement_targets(config) enforcement_targets = _resolve_enforcement_targets(config)
enforcement_sets = _resolve_enforcement_sets(config) enforcement_sets = _resolve_enforcement_sets(config)
ranges_enabled = cfg_get(config, "ranges", "enabled", default=False) is True
ranges_table = (
str(cfg_get(config, "ranges", "table", default=DEFAULT_RANGES_TABLE)).strip()
)
ranges_min_prefix_v4 = as_int(
cfg_get(config, "ranges", "min_prefix_v4"), DEFAULT_RANGES_MIN_PREFIX_V4
)
ranges_min_prefix_v6 = as_int(
cfg_get(config, "ranges", "min_prefix_v6"), DEFAULT_RANGES_MIN_PREFIX_V6
)
return RuntimeSettings( return RuntimeSettings(
node_name=node_name, node_name=node_name,
@@ -269,6 +286,10 @@ def load_runtime_settings():
enforcement_sets=enforcement_sets, enforcement_sets=enforcement_sets,
config_path=config_path, config_path=config_path,
membership_recheck_delay=membership_recheck_delay, membership_recheck_delay=membership_recheck_delay,
ranges_enabled=ranges_enabled,
ranges_table=ranges_table,
ranges_min_prefix_v4=ranges_min_prefix_v4,
ranges_min_prefix_v6=ranges_min_prefix_v6,
) )
@@ -322,6 +343,26 @@ def validate_runtime_settings(settings):
) )
) )
if settings.ranges_enabled:
if not settings.ranges_table:
issues.append(ValidationIssue("ERROR", "ranges.table must not be empty."))
if not 1 <= settings.ranges_min_prefix_v4 <= 32:
issues.append(
ValidationIssue(
"ERROR",
"ranges.min_prefix_v4 must be within [1, 32] "
f"(got {settings.ranges_min_prefix_v4})",
)
)
if not 1 <= settings.ranges_min_prefix_v6 <= 128:
issues.append(
ValidationIssue(
"ERROR",
"ranges.min_prefix_v6 must be within [1, 128] "
f"(got {settings.ranges_min_prefix_v6})",
)
)
if settings.check_jitter_pct < 0.0 or settings.check_jitter_pct > 0.90: if settings.check_jitter_pct < 0.0 or settings.check_jitter_pct > 0.90:
issues.append( issues.append(
ValidationIssue( ValidationIssue(
+30
View File
@@ -85,6 +85,35 @@ def check_nft_tables(settings):
return CheckResult("nft_tables", "PASS", ", ".join(summaries)) return CheckResult("nft_tables", "PASS", ", ".join(summaries))
def check_range_table(settings):
if not settings.ranges_enabled:
return CheckResult("range_table", "PASS", "Range enforcement disabled.")
try:
res = _run_cmd(["/usr/sbin/nft", "-j", "list", "table", "inet", settings.ranges_table])
data = json.loads(res.stdout or "{}")
set_names = {
item["set"].get("name")
for item in data.get("nftables", [])
if isinstance(item.get("set"), dict)
}
missing = {"ranges-v4", "ranges-v6"} - set_names
if missing:
return CheckResult(
"range_table",
"FAIL",
f"inet {settings.ranges_table} lacks sets: {', '.join(sorted(missing))}",
)
return CheckResult("range_table", "PASS", f"inet {settings.ranges_table} present.")
except subprocess.CalledProcessError:
return CheckResult(
"range_table",
"WARN",
f"inet {settings.ranges_table} not found; the agent creates it on its first audit.",
)
except Exception as e:
return CheckResult("range_table", "FAIL", f"Unexpected error: {e}")
def check_state_paths(settings): def check_state_paths(settings):
state_dir = os.path.dirname(os.path.abspath(settings.state_file)) state_dir = os.path.dirname(os.path.abspath(settings.state_file))
history_file = os.path.splitext(settings.state_file)[0] + ".history" history_file = os.path.splitext(settings.state_file)[0] + ".history"
@@ -150,6 +179,7 @@ def run_doctor(settings, output=print):
check_runtime_settings(settings), check_runtime_settings(settings),
check_cscli_json(), check_cscli_json(),
check_nft_tables(settings), check_nft_tables(settings),
check_range_table(settings),
check_state_paths(settings), check_state_paths(settings),
check_systemctl_restart_capability(), check_systemctl_restart_capability(),
] ]
+20 -2
View File
@@ -12,6 +12,7 @@ except ImportError:
from auditor import FirewallAuditor from auditor import FirewallAuditor
from config import load_runtime_settings, setup_logging, validate_runtime_settings from config import load_runtime_settings, setup_logging, validate_runtime_settings
from healing import execute_heal_and_verify, recheck_membership_mismatch, should_heal from healing import execute_heal_and_verify, recheck_membership_mismatch, should_heal
from ranges import RangeEnforcer
from reporter import LocalStateReporter from reporter import LocalStateReporter
@@ -58,11 +59,22 @@ def main():
f"state_file={settings.state_file} " f"state_file={settings.state_file} "
f"targets=[{targets_desc}] " f"targets=[{targets_desc}] "
f"sets_mode={sets_mode} sets=[{sets_desc}] " f"sets_mode={sets_mode} sets=[{sets_desc}] "
f"ranges_enabled={settings.ranges_enabled} ranges_table={settings.ranges_table} "
f"ranges_min_prefix=v4:/{settings.ranges_min_prefix_v4},"
f"v6:/{settings.ranges_min_prefix_v6}"
) )
range_enforcer = None
if settings.ranges_enabled:
range_enforcer = RangeEnforcer(
table=settings.ranges_table,
min_prefix_v4=settings.ranges_min_prefix_v4,
min_prefix_v6=settings.ranges_min_prefix_v6,
)
auditor = FirewallAuditor( auditor = FirewallAuditor(
targets=settings.enforcement_targets, targets=settings.enforcement_targets,
managed_sets=settings.enforcement_sets, managed_sets=settings.enforcement_sets,
range_enforcer=range_enforcer,
) )
auditor.log_enforcement_startup_state() auditor.log_enforcement_startup_state()
reporter = LocalStateReporter( reporter = LocalStateReporter(
@@ -117,7 +129,13 @@ def main():
unenforceable_range_count=len(drift.get("unenforceable_ranges", [])), unenforceable_range_count=len(drift.get("unenforceable_ranges", [])),
) )
if is_synced: unenforced_ranges = len(drift.get("unenforceable_ranges", []))
if is_synced and unenforced_ranges:
status_msg = (
f"Audit Success (degraded): {count} IPs in sync, "
f"{unenforced_ranges} range decision(s) not enforced."
)
elif is_synced:
status_msg = f"Audit Success: {count} IPs in sync." status_msg = f"Audit Success: {count} IPs in sync."
else: else:
status_msg = ( status_msg = (
@@ -157,7 +175,7 @@ def main():
else: else:
logging.warning("Healing skipped to prevent flapping.") logging.warning("Healing skipped to prevent flapping.")
else: else:
logging.info(f"Audit Success: {count} IPs in sync.") logging.info(status_msg)
sleep_seconds = compute_sleep_interval( sleep_seconds = compute_sleep_interval(
settings.check_interval, settings.check_interval,
+221
View File
@@ -0,0 +1,221 @@
# threat-engine-agent/ranges.py
import datetime
import ipaddress
import json
import logging
import subprocess
NFT = "/usr/sbin/nft"
SET_V4 = "ranges-v4"
SET_V6 = "ranges-v6"
HOOKS = ("input", "forward")
CHAIN_PRIORITY = -10
class RangeEnforcer:
"""
Enforces LAPI range decisions that crowdsec-firewall-bouncer cannot: its nftables
mode strips the prefix and bans only the network address. Owns one dedicated
inet table holding interval sets and the drop rules that reference them.
"""
def __init__(self, table="crowdsec-ranges", min_prefix_v4=16, min_prefix_v6=32):
self.table = table
self.min_prefix = {4: int(min_prefix_v4), 6: int(min_prefix_v6)}
def sync(self, range_truth, now_epoch=None):
"""
Makes the range table match range_truth ({lapi_value: decision_meta}) and
returns the LAPI values that are not enforced afterwards.
"""
if now_epoch is None:
now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
desired, unenforced = self._desired_elements(range_truth, now_epoch)
current = self.read_elements()
script = self._ensure_table_script() + self._element_changes(desired, current)
try:
subprocess.run(
[NFT, "-f", "-"],
input="\n".join(script) + "\n",
capture_output=True,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
logging.error(
f"Range enforcement: nft update of inet {self.table} failed: "
f"{(e.stderr or '').strip() or e}"
)
enforced = self.read_elements()
for network, entry in desired.items():
covering = entry["covered_by"] or network
if covering not in enforced:
unenforced.extend(entry["values"])
return sorted(unenforced)
def read_elements(self):
"""Returns {network_str: expires_raw} for every element in the range sets."""
try:
res = subprocess.run(
[NFT, "-j", "list", "table", "inet", self.table],
capture_output=True,
text=True,
check=True,
)
except subprocess.CalledProcessError:
return {}
data = json.loads(res.stdout or "{}")
elements = {}
for item in data.get("nftables", []):
nft_set = item.get("set")
if not isinstance(nft_set, dict) or nft_set.get("name") not in (SET_V4, SET_V6):
continue
for e in nft_set.get("elem", []):
inner = e.get("elem", e) if isinstance(e, dict) else {"val": e}
key = element_key(inner.get("val"))
if key:
elements[key] = inner.get("expires")
return elements
def _desired_elements(self, range_truth, now_epoch):
"""
Maps each enforceable LAPI range to its normalized network. Overlapping
prefixes conflict in an interval set, so a range inside another desired
range is marked covered_by that supernet instead of being inserted.
"""
unenforced = []
desired = {}
for value, meta in range_truth.items():
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError:
continue
if network.prefixlen < self.min_prefix[network.version]:
logging.warning(
f"Range enforcement: refusing {value}; broader than "
f"/{self.min_prefix[network.version]} (min_prefix_v{network.version})."
)
unenforced.append(value)
continue
remaining = _remaining_seconds(meta, now_epoch)
if remaining == 0:
continue # Decision already expired.
entry = desired.setdefault(
str(network),
{"network": network, "values": [], "timeout": remaining, "covered_by": None},
)
entry["values"].append(value)
if entry["timeout"] is not None:
entry["timeout"] = None if remaining is None else max(entry["timeout"], remaining)
ordered = sorted(desired.values(), key=lambda entry: entry["network"].prefixlen)
for i, entry in enumerate(ordered):
for wider in ordered[:i]:
if (
wider["covered_by"] is None
and wider["network"].version == entry["network"].version
and wider["network"].prefixlen < entry["network"].prefixlen
and entry["network"].subnet_of(wider["network"])
):
entry["covered_by"] = str(wider["network"])
break
return desired, unenforced
def _ensure_table_script(self):
# Every statement is idempotent; flushing and re-adding the rules in the same
# transaction restores them if someone edited the chains, with no gap.
t = f"inet {self.table}"
script = [
f"add table {t}",
f"add set {t} {SET_V4} {{ type ipv4_addr; flags interval, timeout; }}",
f"add set {t} {SET_V6} {{ type ipv6_addr; flags interval, timeout; }}",
]
for hook in HOOKS:
script += [
f"add chain {t} {hook} {{ type filter hook {hook} priority {CHAIN_PRIORITY}; policy accept; }}",
f"flush chain {t} {hook}",
f"add rule {t} {hook} ip saddr @{SET_V4} drop",
f"add rule {t} {hook} ip6 saddr @{SET_V6} drop",
]
return script
def _element_changes(self, desired, current):
t = f"inet {self.table}"
wanted = {
network: entry for network, entry in desired.items() if entry["covered_by"] is None
}
script = []
for network, expires_raw in sorted(current.items()):
entry = wanted.get(network)
if entry is None or _needs_refresh(entry["timeout"], expires_raw):
script.append(f"delete element {t} {_set_for(network)} {{ {network} }}")
for network, entry in sorted(wanted.items()):
if network in current and not _needs_refresh(entry["timeout"], current[network]):
continue
timeout = f" timeout {entry['timeout']}s" if entry["timeout"] else ""
script.append(f"add element {t} {_set_for(network)} {{ {network}{timeout} }}")
return script
def element_key(val):
"""
Normalizes an nft JSON element value to a string: a prefix becomes "addr/len",
an address stays as-is, a range becomes "start-end". Returns None otherwise.
"""
if isinstance(val, str):
return val
if isinstance(val, dict):
prefix = val.get("prefix")
if isinstance(prefix, dict) and "addr" in prefix and "len" in prefix:
return f"{prefix['addr']}/{prefix['len']}"
bounds = val.get("range")
if isinstance(bounds, list) and len(bounds) == 2:
return f"{bounds[0]}-{bounds[1]}"
return None
def _set_for(element):
return SET_V6 if ":" in element else SET_V4
def _remaining_seconds(meta, now_epoch):
"""Seconds left on a decision: None if unknown, 0 if already expired."""
until_epoch = meta.get("until_epoch")
if until_epoch:
return max(0, int(until_epoch - now_epoch))
duration = str(meta.get("duration") or "").strip()
if duration.startswith("-"):
return 0
seconds = _parse_go_duration(duration)
return seconds or None
def _parse_go_duration(duration):
units = {"h": 3600, "m": 60, "s": 1, "d": 86400}
total = 0.0
number = ""
for ch in duration.lower():
if ch.isdigit() or ch == ".":
number += ch
elif ch in units and number:
total += float(number) * units[ch]
number = ""
else:
return 0
return int(total)
def _needs_refresh(desired_timeout, expires_raw):
"""True when the kernel element's remaining lifetime is far from the decision's."""
if desired_timeout is None:
return False
if not isinstance(expires_raw, (int, float)) or expires_raw <= 0:
return True
# nft reports expires in seconds or milliseconds depending on version.
remaining = min((expires_raw, expires_raw / 1000.0), key=lambda v: abs(v - desired_timeout))
return abs(remaining - desired_timeout) > max(300, desired_timeout * 0.05)
+80
View File
@@ -128,6 +128,54 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
self.assertTrue(is_synced) self.assertTrue(is_synced)
self.assertEqual([], drift["unenforceable_ranges"]) 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): def test_reconcile_logs_missing_and_extra_values(self):
auditor = FirewallAuditor() auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: { auditor.get_remote_lapi_truth = lambda: {
@@ -396,6 +444,38 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
self.assertEqual({"1.1.1.1": 600000.0}, kernel_state) 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") @patch("auditor.subprocess.run")
def test_get_kernel_state_falls_back_when_configured_sets_do_not_match(self, run_mock): def test_get_kernel_state_falls_back_when_configured_sets_do_not_match(self, run_mock):
auditor = FirewallAuditor( auditor = FirewallAuditor(
+29
View File
@@ -63,6 +63,35 @@ class RuntimeSettingsEnforcementTests(unittest.TestCase):
self.assertEqual(0.90, settings.check_jitter_pct) 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): def test_validate_runtime_settings_reports_errors(self):
settings = RuntimeSettings( settings = RuntimeSettings(
node_name="n1", node_name="n1",
+27
View File
@@ -1,3 +1,5 @@
import dataclasses
import json
import subprocess import subprocess
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
@@ -6,6 +8,7 @@ from config import RuntimeSettings
from doctor import ( from doctor import (
CheckResult, CheckResult,
check_cscli_json, check_cscli_json,
check_range_table,
check_systemctl_restart_capability, check_systemctl_restart_capability,
run_doctor, run_doctor,
) )
@@ -40,6 +43,30 @@ class DoctorTests(unittest.TestCase):
self.assertEqual("FAIL", result.status) self.assertEqual("FAIL", result.status)
self.assertIn("Invalid JSON", result.detail) 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) @patch("doctor.os.geteuid", return_value=1000)
def test_check_systemctl_restart_capability_warns_when_not_root(self, _geteuid): def test_check_systemctl_restart_capability_warns_when_not_root(self, _geteuid):
result = check_systemctl_restart_capability() result = check_systemctl_restart_capability()
+150
View File
@@ -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()