A LAPI range decision (e.g. 195.178.110.0/24) inserted into an nft set without the interval flag is stored as its bare network address. The string diff saw that as one missing and one extra entry, and every heal re-added the same address, so nodes stuck in DESYNC_DETECTED with the flap guard suppressing repeat heals. Pair such ranges with their network address, report them as unenforceable_ranges with a dedicated warning, and keep them out of the drift counts and fingerprint. The reporter records unenforceable_range_count and shows DEGRADED for a node that is otherwise in sync. Desync log lines now name the missing and extra values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
519 lines
22 KiB
Python
519 lines
22 KiB
Python
# threat-engine-agent/auditor.py
|
|
|
|
import subprocess
|
|
import json
|
|
import logging
|
|
import hashlib
|
|
import datetime
|
|
import ipaddress
|
|
try:
|
|
from dotenv import load_dotenv
|
|
except ImportError:
|
|
def load_dotenv():
|
|
return None
|
|
|
|
class LapiUnavailableError(RuntimeError):
|
|
"""The LAPI could not be queried, so there is no decision truth to compare against."""
|
|
|
|
|
|
class FirewallAuditor:
|
|
def __init__(self, targets=None, managed_sets=None):
|
|
"""Ensures the NFT kernel state matches the LAPI's desired state."""
|
|
load_dotenv()
|
|
self.targets = list(targets or (("ip", "crowdsec"), ("ip6", "crowdsec6")))
|
|
self.managed_sets = {str(name) for name in (managed_sets or ()) if str(name)}
|
|
self._reported_set_miss = set()
|
|
# Per-IP evidence from the latest scan, used only for drift diagnostics.
|
|
self._last_decisions = {}
|
|
self._last_kernel_sources = {}
|
|
|
|
def log_enforcement_startup_state(self):
|
|
target_desc = ", ".join(f"{family}:{table}" for family, table in self.targets)
|
|
if not target_desc:
|
|
target_desc = "none"
|
|
sets_desc = ", ".join(sorted(self.managed_sets)) if self.managed_sets else "(auto: *-cscli)"
|
|
logging.info(
|
|
f"Enforcement config: targets=[{target_desc}] managed_sets=[{sets_desc}]"
|
|
)
|
|
|
|
for family, table in dict.fromkeys(self.targets):
|
|
try:
|
|
res = subprocess.run(
|
|
["/usr/sbin/nft", "-j", "list", "table", family, table],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
data = json.loads(res.stdout or "{}")
|
|
discovered_sets = sorted(
|
|
nft_set.get("name")
|
|
for item in data.get("nftables", [])
|
|
for nft_set in [item.get("set")]
|
|
if isinstance(nft_set, dict) and isinstance(nft_set.get("name"), str)
|
|
)
|
|
logging.info(
|
|
f"Enforcement discovered {len(discovered_sets)} sets in {family} {table}."
|
|
)
|
|
if self.managed_sets and discovered_sets:
|
|
overlap = set(discovered_sets) & self.managed_sets
|
|
if not overlap:
|
|
logging.warning(
|
|
"Configured enforcement sets not found in "
|
|
f"{family} {table} at startup."
|
|
)
|
|
except subprocess.CalledProcessError:
|
|
logging.warning(
|
|
f"Enforcement startup check: table not found ({family} {table})."
|
|
)
|
|
except Exception as e:
|
|
logging.warning(
|
|
"Enforcement startup check failed for "
|
|
f"{family} {table}: {e}"
|
|
)
|
|
|
|
def get_remote_lapi_truth(self):
|
|
"""Queries CrowdSec decisions and normalizes across schema variants."""
|
|
try:
|
|
cmd = ["/usr/bin/cscli", "decisions", "list", "-a", "-o", "json"]
|
|
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
|
data = json.loads(res.stdout) or []
|
|
|
|
truth_map = {}
|
|
self._last_decisions = {}
|
|
for decision in self._extract_decisions(data):
|
|
val = decision.get("value")
|
|
if val and decision.get("origin") != "CAPI":
|
|
self._last_decisions.setdefault(val, []).append(
|
|
{
|
|
"origin": decision.get("origin"),
|
|
"scenario": decision.get("scenario"),
|
|
"duration": decision.get("duration"),
|
|
"until": decision.get("until"),
|
|
}
|
|
)
|
|
parsed = self._normalize_truth_decision(decision)
|
|
existing = truth_map.get(val)
|
|
if existing is None:
|
|
truth_map[val] = parsed
|
|
else:
|
|
# Keep the decision with the furthest expected expiry.
|
|
if self._decision_rank(parsed) > self._decision_rank(existing):
|
|
truth_map[val] = parsed
|
|
|
|
logging.info(f"LAPI Local Parser: Found {len(truth_map)} active bans.")
|
|
return truth_map
|
|
except Exception as e:
|
|
# Raise rather than return {}: an empty truth map would make every kernel ban
|
|
# look like drift and trigger a bouncer restart whenever the LAPI is down.
|
|
detail = (getattr(e, "stderr", None) or "").strip() or str(e)
|
|
logging.error(f"Failed to get LAPI truth: {detail}")
|
|
raise LapiUnavailableError(f"LAPI unreachable: {detail}") from e
|
|
|
|
def _normalize_truth_decision(self, decision):
|
|
return {
|
|
"duration": decision.get("duration"),
|
|
"until_epoch": self._parse_until_epoch(decision.get("until")),
|
|
}
|
|
|
|
def _decision_rank(self, decision_meta):
|
|
if decision_meta.get("until_epoch"):
|
|
return decision_meta["until_epoch"]
|
|
return self.parse_duration(decision_meta.get("duration"))
|
|
|
|
def _parse_until_epoch(self, until_str):
|
|
if not until_str:
|
|
return None
|
|
try:
|
|
normalized = str(until_str).replace("Z", "+00:00")
|
|
dt = datetime.datetime.fromisoformat(normalized)
|
|
return dt.timestamp()
|
|
except Exception:
|
|
return None
|
|
|
|
def _extract_decisions(self, payload):
|
|
"""
|
|
Supports both:
|
|
- Flat decision objects from `cscli decisions list -o json`
|
|
- Nested alert-like objects containing `decisions` arrays
|
|
"""
|
|
seen = set()
|
|
yield from self._extract_decisions_recursive(payload, seen)
|
|
|
|
def _extract_decisions_recursive(self, node, seen):
|
|
if isinstance(node, dict):
|
|
decisions = node.get("decisions")
|
|
if isinstance(decisions, list):
|
|
for item in decisions:
|
|
if isinstance(item, dict):
|
|
key = (item.get("value"), item.get("duration"), item.get("origin"))
|
|
if key not in seen:
|
|
seen.add(key)
|
|
yield item
|
|
|
|
if "value" in node and any(
|
|
k in node for k in ("duration", "origin", "scope", "type", "id")
|
|
):
|
|
key = (node.get("value"), node.get("duration"), node.get("origin"))
|
|
if key not in seen:
|
|
seen.add(key)
|
|
yield node
|
|
|
|
for value in node.values():
|
|
if isinstance(value, (dict, list)):
|
|
yield from self._extract_decisions_recursive(value, seen)
|
|
return
|
|
|
|
if isinstance(node, list):
|
|
for item in node:
|
|
if isinstance(item, (dict, list)):
|
|
yield from self._extract_decisions_recursive(item, seen)
|
|
|
|
def get_kernel_state(self):
|
|
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
|
|
all_ips = {}
|
|
self._last_kernel_sources = {}
|
|
for family, table in self.targets:
|
|
try:
|
|
cmd = ["/usr/sbin/nft", "-j", "list", "table", family, table]
|
|
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
|
data = json.loads(res.stdout)
|
|
|
|
set_entries = []
|
|
for item in data.get("nftables", []):
|
|
nft_set = item.get("set")
|
|
if isinstance(nft_set, dict):
|
|
set_entries.append(nft_set)
|
|
|
|
selected_sets = set_entries
|
|
if self.managed_sets:
|
|
filtered = [
|
|
nft_set
|
|
for nft_set in set_entries
|
|
if nft_set.get("name") in self.managed_sets
|
|
]
|
|
if filtered:
|
|
selected_sets = filtered
|
|
elif set_entries:
|
|
key = (family, table)
|
|
if key not in self._reported_set_miss:
|
|
logging.warning(
|
|
"Configured enforcement sets not found for "
|
|
f"{family} {table}; falling back to scanning all sets."
|
|
)
|
|
self._reported_set_miss.add(key)
|
|
|
|
for nft_set in selected_sets:
|
|
elements = nft_set.get('elem', [])
|
|
for e in elements:
|
|
if isinstance(e, dict):
|
|
inner = e.get('elem', e)
|
|
if isinstance(inner, dict):
|
|
val = inner.get('val')
|
|
expires_raw = inner.get('expires')
|
|
if val:
|
|
try:
|
|
self._last_kernel_sources.setdefault(val, []).append(
|
|
{
|
|
"set": f"{family}/{table}/{nft_set.get('name')}",
|
|
"expires": expires_raw,
|
|
"timeout": inner.get("timeout"),
|
|
}
|
|
)
|
|
except TypeError:
|
|
pass
|
|
if not isinstance(expires_raw, (int, float)):
|
|
# Expiry not reported for this element; TTL drift is unverifiable.
|
|
all_ips[val] = None
|
|
elif val not in all_ips:
|
|
all_ips[val] = float(expires_raw)
|
|
elif all_ips[val] is not None:
|
|
# Same IP in several sets (one per decision origin):
|
|
# the longest-lived element is what keeps it blocked.
|
|
all_ips[val] = max(all_ips[val], float(expires_raw))
|
|
else:
|
|
# Fallback if it's just a raw string IP
|
|
all_ips[e] = None
|
|
except subprocess.CalledProcessError:
|
|
logging.debug(f"Table {table} not found, skipped.")
|
|
except Exception as e:
|
|
logging.error(f"Kernel Table scan failed for {table}: {e}")
|
|
|
|
return all_ips
|
|
|
|
def parse_duration(self, duration_str):
|
|
"""Converts CrowdSec strings like '14d', '24h', '4h', '1h30m' to seconds."""
|
|
try:
|
|
if not duration_str:
|
|
return 0
|
|
|
|
units = {"d": 86400, "h": 3600, "m": 60, "s": 1}
|
|
total = 0
|
|
number = ""
|
|
for ch in str(duration_str).strip().lower():
|
|
if ch.isdigit():
|
|
number += ch
|
|
continue
|
|
if ch in units and number:
|
|
total += int(number) * units[ch]
|
|
number = ""
|
|
else:
|
|
return 0
|
|
return total
|
|
except Exception:
|
|
return 0
|
|
|
|
def _expected_remaining_seconds(self, decision_meta, now_epoch):
|
|
until_epoch = decision_meta.get("until_epoch")
|
|
if until_epoch:
|
|
return max(0, int(until_epoch - now_epoch))
|
|
return self.parse_duration(decision_meta.get("duration"))
|
|
|
|
def _has_ttl_drift(self, expected_seconds, kernel_seconds):
|
|
if expected_seconds <= 21600:
|
|
return False
|
|
|
|
allowed_shortfall = max(7200, int(expected_seconds * 0.40))
|
|
return kernel_seconds + allowed_shortfall < expected_seconds
|
|
|
|
def _normalize_kernel_remaining_seconds(self, kernel_raw, expected_seconds):
|
|
"""
|
|
nft 'expires' can appear in either seconds or milliseconds depending on stack/version.
|
|
Pick the representation closest to expected TTL from CrowdSec.
|
|
"""
|
|
try:
|
|
if kernel_raw is None:
|
|
return None
|
|
raw = float(kernel_raw)
|
|
if raw <= 0:
|
|
return None
|
|
|
|
candidates = [raw, raw / 1000.0]
|
|
if expected_seconds <= 0:
|
|
return max(candidates)
|
|
return min(candidates, key=lambda value: abs(value - expected_seconds))
|
|
except Exception:
|
|
return None
|
|
|
|
def heal(self):
|
|
"""Executes heal actions based on drift type, then restarts the bouncer."""
|
|
return self.heal_with_drift({})
|
|
|
|
def heal_with_drift(self, drift):
|
|
"""Performs targeted pre-heal remediation for metadata drift."""
|
|
try:
|
|
if drift.get("reason") == "metadata_drift":
|
|
self._flush_crowdsec_sets()
|
|
logging.info("Heal: Flushed CrowdSec nft sets to clear stale metadata.")
|
|
subprocess.run(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True)
|
|
logging.info("Heal: Bouncer restarted successfully.")
|
|
return True
|
|
except subprocess.CalledProcessError as e:
|
|
logging.error(f"Heal Failed: Could not restart bouncer: {e}")
|
|
return False
|
|
except Exception as e:
|
|
logging.error(f"Heal Failed: Unexpected error: {e}")
|
|
return False
|
|
|
|
def _flush_crowdsec_sets(self):
|
|
for family, table in dict.fromkeys(self.targets):
|
|
try:
|
|
res = subprocess.run(
|
|
["/usr/sbin/nft", "-j", "list", "table", family, table],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
except subprocess.CalledProcessError:
|
|
logging.debug(f"Heal: Table not present, skip flush ({family} {table}).")
|
|
continue
|
|
|
|
data = json.loads(res.stdout or "{}")
|
|
set_targets = []
|
|
for item in data.get("nftables", []):
|
|
nft_set = item.get("set")
|
|
if not isinstance(nft_set, dict):
|
|
continue
|
|
set_name = nft_set.get("name")
|
|
set_handle = nft_set.get("handle")
|
|
if not isinstance(set_name, str):
|
|
continue
|
|
if self.managed_sets:
|
|
if set_name in self.managed_sets:
|
|
set_targets.append((set_name, set_handle))
|
|
elif set_name.endswith("-cscli"):
|
|
set_targets.append((set_name, set_handle))
|
|
|
|
for set_name, set_handle in set_targets:
|
|
try:
|
|
subprocess.run(
|
|
["/usr/sbin/nft", "flush", "set", family, table, set_name],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
except subprocess.CalledProcessError as e:
|
|
stderr = (e.stderr or "").strip()
|
|
syntax_error = "syntax error" in stderr.lower()
|
|
if syntax_error and isinstance(set_handle, int):
|
|
try:
|
|
subprocess.run(
|
|
[
|
|
"/usr/sbin/nft",
|
|
"flush",
|
|
"set",
|
|
family,
|
|
table,
|
|
"handle",
|
|
str(set_handle),
|
|
],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
continue
|
|
except subprocess.CalledProcessError as handle_err:
|
|
handle_stderr = (handle_err.stderr or "").strip()
|
|
logging.warning(
|
|
"Heal: Failed to flush set "
|
|
f"({family} {table} {set_name}, handle={set_handle}): "
|
|
f"{handle_stderr or handle_err}"
|
|
)
|
|
continue
|
|
logging.warning(
|
|
"Heal: Failed to flush set "
|
|
f"({family} {table} {set_name}): {stderr or e}"
|
|
)
|
|
|
|
def reconcile(self):
|
|
truth_map = self.get_remote_lapi_truth()
|
|
reality_map = self.get_kernel_state()
|
|
|
|
truth_set = set(truth_map.keys())
|
|
reality_set = set(reality_map.keys())
|
|
missing, extra, unenforceable_ranges = self._match_collapsed_ranges(
|
|
sorted(truth_set - reality_set),
|
|
reality_set,
|
|
reality_set - truth_set,
|
|
)
|
|
if unenforceable_ranges:
|
|
logging.warning(
|
|
"Range decisions not enforced: the nft set holds only their network "
|
|
"address (it lacks the interval flag), so a bouncer restart cannot "
|
|
f"fix them (count={len(unenforceable_ranges)}) "
|
|
f"ranges={self._preview_values(unenforceable_ranges)}"
|
|
)
|
|
|
|
if missing or extra:
|
|
drift = {
|
|
"reason": "membership_mismatch",
|
|
"missing_count": len(missing),
|
|
"extra_count": len(extra),
|
|
"metadata_drift_count": 0,
|
|
"fingerprint": self._fingerprint_drift(missing, extra, []),
|
|
"unenforceable_ranges": unenforceable_ranges,
|
|
}
|
|
logging.warning(
|
|
"Desync: IP membership mismatch "
|
|
f"(missing={drift['missing_count']}, extra={drift['extra_count']}) "
|
|
f"missing_values={self._preview_values(missing)} "
|
|
f"extra_values={self._preview_values(extra)}"
|
|
)
|
|
return False, len(reality_set), drift
|
|
|
|
metadata_drift = []
|
|
now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
|
|
|
|
for ip, decision_meta in truth_map.items():
|
|
siem_seconds = self._expected_remaining_seconds(decision_meta, now_epoch)
|
|
if siem_seconds <= 0:
|
|
continue
|
|
|
|
kernel_raw = reality_map.get(ip)
|
|
kernel_seconds = self._normalize_kernel_remaining_seconds(
|
|
kernel_raw,
|
|
siem_seconds,
|
|
)
|
|
if kernel_seconds is None:
|
|
continue
|
|
|
|
if self._has_ttl_drift(siem_seconds, kernel_seconds):
|
|
metadata_drift.append(ip)
|
|
logging.warning(
|
|
"Metadata Drift detail "
|
|
f"ip={ip} expected_s={int(siem_seconds)} "
|
|
f"kernel_s={int(kernel_seconds)} kernel_raw={kernel_raw} "
|
|
f"ratio={kernel_seconds / siem_seconds:.2f} "
|
|
f"kernel_sources={json.dumps(self._last_kernel_sources.get(ip, []))} "
|
|
f"lapi_decisions={json.dumps(self._last_decisions.get(ip, []))}"
|
|
)
|
|
|
|
if metadata_drift:
|
|
drift = {
|
|
"reason": "metadata_drift",
|
|
"missing_count": 0,
|
|
"extra_count": 0,
|
|
"metadata_drift_count": len(metadata_drift),
|
|
"fingerprint": self._fingerprint_drift([], [], metadata_drift),
|
|
"unenforceable_ranges": unenforceable_ranges,
|
|
}
|
|
logging.warning(
|
|
"Metadata Drift detected "
|
|
f"(count={drift['metadata_drift_count']})."
|
|
)
|
|
return False, len(reality_map), drift
|
|
|
|
drift = {
|
|
"reason": "in_sync",
|
|
"missing_count": 0,
|
|
"extra_count": 0,
|
|
"metadata_drift_count": 0,
|
|
"fingerprint": "",
|
|
"unenforceable_ranges": unenforceable_ranges,
|
|
}
|
|
return True, len(reality_map), drift
|
|
|
|
def _match_collapsed_ranges(self, missing, kernel_values, extra):
|
|
"""
|
|
Pairs LAPI range decisions with the bare network address that a set without
|
|
the interval flag stores in their place. A restart re-adds that same address,
|
|
so these ranges are reported apart from drift rather than healed.
|
|
|
|
Returns (missing, extra, unenforceable_ranges) with the paired values removed.
|
|
A full-length prefix (/32, /128) stored as its address is fully enforced, so
|
|
it is dropped from missing without being reported.
|
|
"""
|
|
remaining_missing = []
|
|
remaining_extra = set(extra)
|
|
unenforceable_ranges = []
|
|
for value in missing:
|
|
try:
|
|
network = ipaddress.ip_network(value, strict=False)
|
|
except ValueError:
|
|
remaining_missing.append(value)
|
|
continue
|
|
address = str(network.network_address)
|
|
if address not in kernel_values:
|
|
remaining_missing.append(value)
|
|
continue
|
|
remaining_extra.discard(address)
|
|
if network.prefixlen < network.max_prefixlen:
|
|
unenforceable_ranges.append(value)
|
|
return remaining_missing, sorted(remaining_extra), unenforceable_ranges
|
|
|
|
def _preview_values(self, values, limit=10):
|
|
shown = ",".join(str(v) for v in values[:limit])
|
|
if len(values) > limit:
|
|
shown += f",+{len(values) - limit} more"
|
|
return f"[{shown}]"
|
|
|
|
def _fingerprint_drift(self, missing, extra, metadata_drift):
|
|
payload = {
|
|
"missing": sorted(missing),
|
|
"extra": sorted(extra),
|
|
"metadata_drift": sorted(metadata_drift),
|
|
}
|
|
digest = hashlib.sha256(
|
|
json.dumps(payload, sort_keys=True).encode("utf-8")
|
|
).hexdigest()
|
|
return digest[:16]
|