initial commit: Threat Engine Agent
This commit is contained in:
commit
848a29543d
7 files changed
+283
No files matched your search
@@ -0,0 +1,4 @@
|
|||||||
|
logs/*.log
|
||||||
|
__pycache__/
|
||||||
|
.venv/
|
||||||
|
*.json
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# Threat Engine Agent (Triton Edition)
|
||||||
|
|
||||||
|
A self-healing synchronization agent designed to ensure the local `nftables` kernel state perfectly matches the CrowdSec Local API (LAPI) desired state.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 🎯 Purpose
|
||||||
|
The standard `crowdsec-firewall-bouncer` can occasionally experience "ghost" desynchronization where the LAPI removes a ban, but the kernel retains it (or vice-versa). This agent acts as a high-integrity supervisor to:
|
||||||
|
1. **Audit:** Compare LAPI "Truth" vs. Nftables "Reality" every 5 minutes.
|
||||||
|
2. **Heal:** Automatically restart remediation services if a desync is detected.
|
||||||
|
3. **Filter:** Handle protocol mismatches (filtering IPv6 noise) and expired "zombie" decisions.
|
||||||
|
|
||||||
|
## 🛠️ Technical Architecture
|
||||||
|
|
||||||
|
### The Auditor (`auditor.py`)
|
||||||
|
- **Deep-Harvest Parser:** Recursively scans the `cscli` Alert-style JSON. This bypasses schema variations where IPs might be hidden in `source`, `decisions`, or `meta` blocks.
|
||||||
|
- **Protocol Filtering:** Automatically ignores IPv6 addresses (detected by `:`) to prevent insertion errors in IPv4-only `nft` tables.
|
||||||
|
- **Global Table Scan:** Rather than checking a single set, it scans the **entire** `ip crowdsec` table. This ensures that IPs placed in different "drawers" (like Range sets) are still accounted for.
|
||||||
|
- **Temporal Awareness:** Filters out decisions with negative durations (`startswith('-')`) to ignore bans that are technically expired but not yet vacuumed from the database.
|
||||||
|
|
||||||
|
### The Service
|
||||||
|
- **Root-Level Execution:** Necessary for direct interaction with `nftables` and the `cscli` local socket.
|
||||||
|
- **Dependency Management:** Configured to start only after `crowdsec.service` is initialized to prevent false-positive desyncs on boot.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 📂 Project Structure
|
||||||
|
```text
|
||||||
|
threat-engine-agent/
|
||||||
|
├── main.py # Logic loop and orchestration
|
||||||
|
├── auditor.py # The "Brain": Recursive parsing and kernel scanning
|
||||||
|
├── systemd/ # Deployment configurations
|
||||||
|
│ └── threat-agent.service
|
||||||
|
└── logs/ # Local audit history (Git ignored)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚀 Installation & Deployment
|
||||||
|
|
||||||
|
1. Environment Setup:
|
||||||
|
```chmod +x main.py
|
||||||
|
mkdir logs
|
||||||
|
```
|
||||||
|
2. Systemd Integration:
|
||||||
|
```sudo cp systemd/threat-agent.service /etc/systemd/system/
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now threat-agent```
|
||||||
|
|
||||||
|
3. Monitoring:
|
||||||
|
```# Watch the auditor work in real-time
|
||||||
|
tail -f logs/threat-agent.log```
|
||||||
|
|
||||||
|
## 🔍 Troubleshooting
|
||||||
|
|
||||||
|
If you see a "Heal Loop" in the logs:
|
||||||
|
1. **Manual Check**: Run `/usr/bin/cscli decisions list -a -o json` and check if the count matches `nft list table ip crowdsec`.
|
||||||
|
2. **IPv6 Ghosting**: Verify if the "Missing from Kernel" IPs are actually IPv6. The auditor should filter these, but new formats may require a regex update.
|
||||||
|
3. **Set Naming**: Ensure the bouncer hasn't created a new table name outside of the `crowdsec` namespace.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# threat-engine-agent/agent.py
|
||||||
|
|
||||||
|
import time
|
||||||
|
import logging
|
||||||
|
from auditor import FirewallAuditor
|
||||||
|
from reporter import LocalStateReporter
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||||
|
filename='/home/patrick/threat-engine-agent/logs/threat-agent.log'
|
||||||
|
)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""
|
||||||
|
The Orchestrator: Links Audit findings to the State Reporter.
|
||||||
|
"""
|
||||||
|
auditor = FirewallAuditor()
|
||||||
|
reporter = LocalStateReporter()
|
||||||
|
|
||||||
|
CHECK_INTERVAL = 600
|
||||||
|
logging.info("Threat Engine Agent initialized on Triton.")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
is_synced, count = auditor.reconcile()
|
||||||
|
|
||||||
|
reporter.update_status(is_synced, count)
|
||||||
|
|
||||||
|
if not is_synced:
|
||||||
|
logging.warning(f"Desync detected ({count} IPs in kernel). Healing...")
|
||||||
|
auditor.heal()
|
||||||
|
reporter.log_heal_event(count) # Record the event in history
|
||||||
|
else:
|
||||||
|
logging.info(f"Audit Success: {count} IPs in sync.")
|
||||||
|
|
||||||
|
time.sleep(CHECK_INTERVAL)
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
logging.info("Agent shutting down manually.")
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Main loop error: {e}")
|
||||||
|
# Ensure the reporter notes the error state
|
||||||
|
try:
|
||||||
|
reporter.update_status(False, 0, last_error=str(e))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
time.sleep(60)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+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)
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
agent:
|
||||||
|
node_name: "triton"
|
||||||
|
check_interval: 600 # 10 minutes
|
||||||
|
log_path: "/home/patrick/threat-engine-agent/logs/threat-agent.log"
|
||||||
|
|
||||||
|
enforcement:
|
||||||
|
table: "crowdsec"
|
||||||
|
sets:
|
||||||
|
- "0.0.0.0/0-cscli"
|
||||||
|
- "crowdsec-blacklists"
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
# threat_engine_agent/reporter.py
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
class LocalStateReporter:
|
||||||
|
"""
|
||||||
|
Manages the health manifest on Triton.
|
||||||
|
Acts as the 'Black Box' recorder for Argus to query.
|
||||||
|
"""
|
||||||
|
def __init__(self, state_file="/home/patrick/threat-agent-state.json"):
|
||||||
|
self.state_file = state_file
|
||||||
|
# Ensure the directory is writable
|
||||||
|
os.makedirs(os.path.dirname(os.path.abspath(self.state_file)), exist_ok=True)
|
||||||
|
|
||||||
|
def update_status(self, is_synced, ban_count, last_error=None):
|
||||||
|
"""
|
||||||
|
Writes the current health snapshot to a JSON file.
|
||||||
|
"""
|
||||||
|
status_data = {
|
||||||
|
"node": "triton",
|
||||||
|
"last_check": datetime.now().isoformat(),
|
||||||
|
"status": "HEALTHY" if is_synced else "DESYNC_DETECTED",
|
||||||
|
"is_synced": is_synced,
|
||||||
|
"kernel_ban_count": ban_count,
|
||||||
|
"last_error": last_error
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Atomic write: Write to a temp file then rename to avoid corruption
|
||||||
|
temp_file = f"{self.state_file}.tmp"
|
||||||
|
with open(temp_file, 'w') as f:
|
||||||
|
json.dump(status_data, f, indent=4)
|
||||||
|
os.replace(temp_file, self.state_file)
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Reporter: Failed to write state file: {e}")
|
||||||
|
|
||||||
|
def log_heal_event(self, gap_count):
|
||||||
|
"""
|
||||||
|
Records a specific healing event in a persistent history log.
|
||||||
|
"""
|
||||||
|
history_file = self.state_file.replace(".json", ".history")
|
||||||
|
timestamp = datetime.now().isoformat()
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(history_file, 'a') as f:
|
||||||
|
f.write(f"{timestamp} - HEAL: Fixed desync of {gap_count} IPs\n")
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Reporter: Failed to write to history log: {e}")
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Threat Engine Reconciliation Agent
|
||||||
|
After=network.target crowdsec.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=root
|
||||||
|
Group=root
|
||||||
|
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||||
|
Environment="HOME=/home/patrick"
|
||||||
|
WorkingDirectory=/home/patrick/threat-engine-agent
|
||||||
|
ExecStart=/usr/bin/python3 agent.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
StandardOutput=append:/home/patrick/threat-engine-agent/logs/threat-agent.log
|
||||||
|
StandardError=append:/home/patrick/threat-engine-agent/logs/threat-agent.log
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
Reference in new issue
Block a user