fix: replace shorter CrowdSec bans instead of adding beside them #1

Merged
patrick merged 2 commits from fix/multi-set-ttl-drift into main 2026-10-14 20:29:00 +00:00
2 changed files with 68 additions and 3 deletions
Showing only changes of commit 79f72512e4 - Show all commits

No files matched your search

+38 -3
View File
@@ -18,6 +18,9 @@ class FirewallAuditor:
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()
# 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): def log_enforcement_startup_state(self):
target_desc = ", ".join(f"{family}:{table}" for family, table in self.targets) target_desc = ", ".join(f"{family}:{table}" for family, table in self.targets)
@@ -71,9 +74,18 @@ class FirewallAuditor:
data = json.loads(res.stdout) or [] data = json.loads(res.stdout) or []
truth_map = {} truth_map = {}
self._last_decisions = {}
for decision in self._extract_decisions(data): for decision in self._extract_decisions(data):
val = decision.get("value") val = decision.get("value")
if val and decision.get("origin") != "CAPI": 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) parsed = self._normalize_truth_decision(decision)
existing = truth_map.get(val) existing = truth_map.get(val)
if existing is None: if existing is None:
@@ -151,6 +163,7 @@ class FirewallAuditor:
def get_kernel_state(self): def get_kernel_state(self):
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables.""" """Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
all_ips = {} all_ips = {}
self._last_kernel_sources = {}
for family, table in self.targets: for family, table in self.targets:
try: try:
cmd = ["/usr/sbin/nft", "-j", "list", "table", family, table] cmd = ["/usr/sbin/nft", "-j", "list", "table", family, table]
@@ -190,11 +203,25 @@ class FirewallAuditor:
val = inner.get('val') val = inner.get('val')
expires_raw = inner.get('expires') expires_raw = inner.get('expires')
if val: if val:
if isinstance(expires_raw, (int, float)): try:
all_ips[val] = float(expires_raw) self._last_kernel_sources.setdefault(val, []).append(
else: {
"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. # Expiry not reported for this element; TTL drift is unverifiable.
all_ips[val] = None 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: else:
# Fallback if it's just a raw string IP # Fallback if it's just a raw string IP
all_ips[e] = None all_ips[e] = None
@@ -390,6 +417,14 @@ class FirewallAuditor:
if self._has_ttl_drift(siem_seconds, kernel_seconds): if self._has_ttl_drift(siem_seconds, kernel_seconds):
metadata_drift.append(ip) 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: if metadata_drift:
drift = { drift = {
+30
View File
@@ -257,6 +257,36 @@ class AuditorDecisionExtractionTests(unittest.TestCase):
self.assertEqual({"1.1.1.1": 1000.0}, kernel_state) self.assertEqual({"1.1.1.1": 1000.0}, kernel_state)
@patch("auditor.subprocess.run")
def test_get_kernel_state_keeps_longest_expiry_for_ip_in_multiple_sets(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": "1.1.1.1", "expires": 600000}}],
}
},
{
"set": {
"name": "crowdsec-blacklists-crowdsec",
"elem": [{"elem": {"val": "1.1.1.1", "expires": 13000}}],
}
},
]
}
),
)
kernel_state = auditor.get_kernel_state()
self.assertEqual({"1.1.1.1": 600000.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(