193 lines
7.3 KiB
Python
193 lines
7.3 KiB
Python
# threat-engine-agent/auditor.py
|
|
|
|
import subprocess
|
|
import json
|
|
import logging
|
|
import hashlib
|
|
from dotenv import load_dotenv
|
|
|
|
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":
|
|
truth_map[val] = decision.get("duration")
|
|
|
|
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 _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' to seconds."""
|
|
try:
|
|
units = {"d": 86400, "h": 3600, "m": 60, "s": 1}
|
|
unit = duration_str[-1]
|
|
value = int(duration_str[:-1])
|
|
return value * units.get(unit, 1)
|
|
except:
|
|
return 0
|
|
|
|
def heal(self):
|
|
"""Directly restarts the bouncer service."""
|
|
try:
|
|
subprocess.run(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True)
|
|
logging.info("Heal: Bouncer restarted successfully.")
|
|
except subprocess.CalledProcessError as e:
|
|
logging.error(f"Heal Failed: Could not restart bouncer: {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 = []
|
|
|
|
for ip, duration_str in truth_map.items():
|
|
siem_seconds = self.parse_duration(duration_str)
|
|
kernel_seconds = reality_map.get(ip, 0) / 1000 # Convert ms to s
|
|
|
|
if siem_seconds > 86400: # If SIEM target is > 24h
|
|
if kernel_seconds < 18000: # And kernel has < 5h left
|
|
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]
|