initial commit: Threat Engine Agent
This commit is contained in:
commit
848a29543d
7 files changed
+283
No files matched your search
+90
@@ -0,0 +1,90 @@
|
||||
# threat-engine-agent/auditor.py
|
||||
|
||||
import subprocess
|
||||
import json
|
||||
import logging
|
||||
|
||||
class FirewallAuditor:
|
||||
def __init__(self):
|
||||
"""Ensures the NFT kernel state matches the LAPI's desired state."""
|
||||
self.table = "crowdsec"
|
||||
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 Query Failed: {e}")
|
||||
return None
|
||||
|
||||
def get_kernel_state(self):
|
||||
"""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)
|
||||
|
||||
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
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Kernel Table Scan Failed: {e}")
|
||||
return set()
|
||||
|
||||
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 = self.get_lapi_state()
|
||||
reality = self.get_kernel_state()
|
||||
|
||||
if truth is None or reality is None:
|
||||
return False, 0
|
||||
|
||||
missing_from_kernel = truth - reality
|
||||
extra_in_kernel = reality - truth
|
||||
|
||||
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)
|
||||
|
||||
return True, len(reality)
|
||||
Reference in new issue
Block a user