fix: finalize merge with agent-node branch

This commit is contained in:
patrick committed 2026-01-26 03:14:46 +00:00
1 parent 9977a0d8cf
commit 42c25c145e
1 file changed
+28 -37
+28 -37
View File
@@ -14,42 +14,19 @@ class FirewallAuditor:
self.table = "crowdsec" self.table = "crowdsec"
self.set_name = "0.0.0.0/0-cscli" self.set_name = "0.0.0.0/0-cscli"
def get_lapi_state(self):
"""Precision parser: Only harvests IPs from active remediation decisions."""
try:
res = subprocess.run(["/usr/bin/cscli", "decisions", "list", "-a", "-o", "json"],
capture_output=True, text=True, check=True)
data = json.loads(res.stdout) or []
ips = set()
for item in data:
if item.get('remediation') is True:
for d in item.get('decisions', []):
duration = d.get('duration', '')
if d.get('type') != 'ban':
continue
if duration.startswith('-'):
continue
val = d.get('value')
if val and ':' not in val:
ips.add(val)
logging.info(f"LAPI Parser (IPv4-Only) found {len(ips)} active bans.")
return ips
except Exception as e:
logging.error(f"LAPI Sync Error: {e}")
return {}
def get_kernel_state(self): def get_kernel_state(self):
"""Scans ALL sets in the crowdsec table to find every blocked IP.""" """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: try:
cmd = ["/usr/sbin/nft", "-j", "list", "table", "ip", "crowdsec"] cmd = ["/usr/sbin/nft", "-j", "list", "table", target["family"], target["table"]]
res = subprocess.run(cmd, capture_output=True, text=True, check=True) res = subprocess.run(cmd, capture_output=True, text=True, check=True)
data = json.loads(res.stdout) data = json.loads(res.stdout)
ips = set()
for item in data.get('nftables', []): for item in data.get('nftables', []):
nft_set = item.get('set') nft_set = item.get('set')
if nft_set: if nft_set:
@@ -59,15 +36,29 @@ class FirewallAuditor:
inner = e.get('elem', e) inner = e.get('elem', e)
if isinstance(inner, dict): if isinstance(inner, dict):
val = inner.get('val') val = inner.get('val')
# NFT provides 'expires' in milliseconds
expires_ms = inner.get('expires', 0)
if val: if val:
ips.add(val) all_ips[val] = expires_ms
else: else:
ips.add(e) # Fallback if it's just a raw string IP
return ips all_ips[e] = 0
except subprocess.CalledProcessError:
logging.debug(f"Table {target['table']} not found, skipped.")
except Exception as e: except Exception as e:
logging.error(f"Kernel Table Scan Failed: {e}") logging.error(f"Kernel Table scan failed for {target['table']}: {e}")
return set()
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): def heal(self):
"""Directly restarts the bouncer service.""" """Directly restarts the bouncer service."""