diff --git a/auditor.py b/auditor.py index 9f3c353..8341b74 100644 --- a/auditor.py +++ b/auditor.py @@ -4,8 +4,6 @@ import subprocess import json import logging from dotenv import load_dotenv -import os -import requests class FirewallAuditor: def __init__(self): @@ -15,21 +13,17 @@ class FirewallAuditor: self.set_name = "0.0.0.0/0-cscli" def get_remote_lapi_truth(self): - """Triton-only: Queries local DB via cscli""" + """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 item in data: - # cscli JSON can be a list of alerts, each containing a list of decisions - decisions = item.get('decisions', []) - for d in decisions: - val = d.get('value') - # Filter: must have a value, must not be CAPI - if val and d.get('origin') != 'CAPI': - truth_map[val] = d.get('duration') + 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 @@ -37,6 +31,44 @@ class FirewallAuditor: 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 {}