Files
threat-engine-agent/auditor.py
T

359 lines
14 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 = {}
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')
expires_raw = inner.get('expires')
if val:
if isinstance(expires_raw, (int, float)):
all_ips[val] = float(expires_raw)
else:
# Expiry not reported for this element; TTL drift is unverifiable.
all_ips[val] = None
else:
# Fallback if it's just a raw string IP
all_ips[e] = None
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 _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 (("ip", "crowdsec"), ("ip6", "crowdsec6"), ("inet", "crowdsec")):
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 isinstance(set_name, str) and 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 = 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)
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)
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]