Merge branch 'agent-node'
This commit is contained in:
commit
5990dddf5a
8 files changed
+126
-60
No files matched your search
+47
-44
@@ -3,10 +3,14 @@
|
||||
import subprocess
|
||||
import json
|
||||
import logging
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import requests
|
||||
|
||||
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"
|
||||
|
||||
@@ -29,48 +33,41 @@ class FirewallAuditor:
|
||||
continue
|
||||
|
||||
val = d.get('value')
|
||||
if val:
|
||||
if val and ':' not in val:
|
||||
ips.add(val)
|
||||
|
||||
logging.info(f"LAPI Parser: found {len(ips)} active bans (IPv4+IPv6).")
|
||||
logging.info(f"LAPI Parser (IPv4-Only) found {len(ips)} active bans.")
|
||||
return ips
|
||||
except Exception as e:
|
||||
logging.error(f"LAPI Query Failed: {e}")
|
||||
return None
|
||||
logging.error(f"LAPI Sync Error: {e}")
|
||||
return {}
|
||||
|
||||
def get_kernel_state(self):
|
||||
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
|
||||
all_ips = set()
|
||||
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)
|
||||
"""Scans ALL sets in the crowdsec table to find every blocked IP."""
|
||||
try:
|
||||
cmd = ["/usr/sbin/nft", "-j", "list", "table", "ip", "crowdsec"]
|
||||
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')
|
||||
if val:
|
||||
all_ips.add(val)
|
||||
else:
|
||||
all_ips.add(e)
|
||||
except subprocess.CalledProcessError:
|
||||
# This happens if a node doesn't have IPv6 enabled/initialized
|
||||
logging.debug(f"Table {target['table']} not found, skipping.")
|
||||
except Exception as e:
|
||||
logging.error(f"Kernel Table Scan Failed for {target['table']}: {e}")
|
||||
ips = set()
|
||||
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')
|
||||
if val:
|
||||
ips.add(val)
|
||||
else:
|
||||
ips.add(e)
|
||||
return ips
|
||||
|
||||
return all_ips
|
||||
except Exception as e:
|
||||
logging.error(f"Kernel Table Scan Failed: {e}")
|
||||
return set()
|
||||
|
||||
def heal(self):
|
||||
"""Directly restarts the bouncer service."""
|
||||
@@ -81,17 +78,23 @@ class FirewallAuditor:
|
||||
logging.error(f"Heal Failed: Could not restart bouncer: {e}")
|
||||
|
||||
def reconcile(self):
|
||||
truth = self.get_lapi_state()
|
||||
reality = self.get_kernel_state()
|
||||
truth_map = self.get_remote_lapi_truth()
|
||||
reality_map = self.get_kernel_state()
|
||||
|
||||
if truth is None or reality is None:
|
||||
return False, 0
|
||||
truth_set = set(truth_map.keys())
|
||||
reality_set = set(reality_map.keys())
|
||||
|
||||
missing_from_kernel = truth - reality
|
||||
extra_in_kernel = reality - truth
|
||||
if truth_set != reality_set:
|
||||
logging.warning("Desync: IP Membership mismatch.")
|
||||
return False, len(reality_set)
|
||||
|
||||
if missing_from_kernel or extra_in_kernel:
|
||||
logging.warning(f"Desync Details: Missing from Kernel: {list(missing_from_kernel)[:5]}... Extra in Kernel: {list(extra_in_kernel)[:5]}...")
|
||||
return False, len(reality)
|
||||
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
|
||||
|
||||
return True, len(reality)
|
||||
if siem_seconds > 86400: # If SIEM target is > 24h
|
||||
if kernel_seconds < 18000: # And kernel has < 5h left
|
||||
logging.warning(f"Metadata Drift: {ip} needs {duration_str}, but kernel only has {int(kernel_seconds/3600)}h left.")
|
||||
return False, len(reality_map)
|
||||
|
||||
return True, len(reality_map)
|
||||
Reference in new issue
Block a user