Add drift-aware heal path in FirewallAuditor to remediate metadata drift by discovering and flushing *-cscli sets in crowdsec/crowdsec6 tables, then restarting the bouncer. Update execute_heal_and_verify to pass drift context to heal_with_drift when supported, keeping backward compatibility via heal(). Add unit tests covering metadata-drift flush+restart behavior, non-metadata restart-only behavior, and drift context propagation.
294 lines
11 KiB
Python
294 lines
11 KiB
Python
# threat-engine-agent/auditor.py
|
|
|
|
import subprocess
|
|
import json
|
|
import logging
|
|
import hashlib
|
|
import datetime
|
|
try:
|
|
from dotenv import load_dotenv
|
|
except ImportError:
|
|
def load_dotenv():
|
|
return None
|
|
|
|
class FirewallAuditor:
|
|
def __init__(self):
|
|
"""Ensures the NFT kernel state matches the LAPI's desired state."""
|
|
load_dotenv()
|
|
self.table = "crowdsec"
|
|
self.set_name = "0.0.0.0/0-cscli"
|
|
|
|
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 = {}
|
|
for decision in self._extract_decisions(data):
|
|
val = decision.get("value")
|
|
if val and decision.get("origin") != "CAPI":
|
|
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:
|
|
logging.error(f"Failed to get LAPI truth: {e}")
|
|
return {}
|
|
|
|
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 = {} # Changed from set() to {}
|
|
targets = [
|
|
{"family": "ip", "table": "crowdsec"},
|
|
{"family": "ip6", "table": "crowdsec6"}
|
|
]
|
|
for target in targets:
|
|
try:
|
|
cmd = ["/usr/sbin/nft", "-j", "list", "table", target["family"], target["table"]]
|
|
res = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
|
data = json.loads(res.stdout)
|
|
|
|
for item in data.get('nftables', []):
|
|
nft_set = item.get('set')
|
|
if nft_set:
|
|
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')
|
|
# NFT provides 'expires' in milliseconds
|
|
expires_ms = inner.get('expires', 0)
|
|
if val:
|
|
all_ips[val] = expires_ms
|
|
else:
|
|
# Fallback if it's just a raw string IP
|
|
all_ips[e] = 0
|
|
except subprocess.CalledProcessError:
|
|
logging.debug(f"Table {target['table']} not found, skipped.")
|
|
except Exception as e:
|
|
logging.error(f"Kernel Table scan failed for {target['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 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 (("ip", "crowdsec"), ("ip6", "crowdsec6")):
|
|
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_names = []
|
|
for item in data.get("nftables", []):
|
|
nft_set = item.get("set")
|
|
if not isinstance(nft_set, dict):
|
|
continue
|
|
set_name = nft_set.get("name")
|
|
if isinstance(set_name, str) and set_name.endswith("-cscli"):
|
|
set_names.append(set_name)
|
|
|
|
for set_name in set_names:
|
|
subprocess.run(
|
|
["/usr/sbin/nft", "flush", "set", family, table, set_name],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
|
|
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 = sorted(truth_set - reality_set)
|
|
extra = sorted(reality_set - truth_set)
|
|
|
|
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, []),
|
|
}
|
|
logging.warning(
|
|
"Desync: IP membership mismatch "
|
|
f"(missing={drift['missing_count']}, extra={drift['extra_count']})."
|
|
)
|
|
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)
|
|
kernel_seconds = reality_map.get(ip, 0) / 1000 # Convert ms to s
|
|
|
|
if self._has_ttl_drift(siem_seconds, kernel_seconds):
|
|
metadata_drift.append(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),
|
|
}
|
|
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": "",
|
|
}
|
|
return True, len(reality_map), drift
|
|
|
|
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]
|