384 lines
12 KiB
Markdown
384 lines
12 KiB
Markdown
# threat-engine-agent
|
||
|
||
A reconciliation and self-healing agent for CrowdSec + `nftables` environments.
|
||
|
||
`threat-engine-agent` continuously compares CrowdSec Local API (LAPI) decision truth to the actual `nftables` kernel enforcement state on a node. When drift is detected, it can apply a targeted heal, verify convergence, and record structured telemetry for operators.
|
||
|
||
This is intended for operators running CrowdSec with `nftables` who want stronger guarantees than “the bouncer is probably in sync.”
|
||
|
||
---
|
||
|
||
## Why this exists
|
||
|
||
In practice, `crowdsec-firewall-bouncer` can occasionally drift from the state CrowdSec intends to enforce.
|
||
|
||
Examples include:
|
||
|
||
- a decision exists in LAPI but is missing from kernel enforcement
|
||
- an IP remains in `nftables` after the decision has expired upstream
|
||
- long-duration bans remain present, but their kernel metadata appears stale or near expiry
|
||
- the bouncer process is running, but actual enforcement no longer matches CrowdSec’s desired state
|
||
|
||
`threat-engine-agent` acts as a supervisory reconciliation loop:
|
||
|
||
1. **Audit** the node’s live enforcement state against LAPI truth
|
||
2. **Classify** drift as membership mismatch or metadata drift
|
||
3. **Heal** using a targeted remediation path
|
||
4. **Verify** that post-heal state converged
|
||
5. **Record** the result for operators and dashboards
|
||
|
||
This turns firewall enforcement from a best-effort assumption into something measurable and self-correcting.
|
||
|
||
---
|
||
|
||
## What it does
|
||
|
||
At a high level, the agent:
|
||
|
||
- queries CrowdSec decisions via `cscli`
|
||
- normalizes decision data across supported JSON shapes
|
||
- inspects `nftables` state directly from kernel tables
|
||
- compares desired vs observed enforcement across IPv4 and IPv6
|
||
- detects:
|
||
- **membership drift**: missing or extra enforced IPs
|
||
- **metadata drift**: bans present in kernel state, but with suspicious remaining TTL / expiry metadata
|
||
- computes a deterministic drift fingerprint
|
||
- suppresses repeated no-op heals for identical recent drift
|
||
- performs a heal when allowed
|
||
- re-checks state after healing
|
||
- writes structured local state and heal history for external reporting
|
||
|
||
---
|
||
|
||
## Example reconciliation flow
|
||
|
||
A real metadata drift event looks like this:
|
||
|
||
```text
|
||
2026-04-04 20:05:13,383 - root - INFO - LAPI Local Parser: Found 295 active bans.
|
||
2026-04-04 20:05:13,390 - root - WARNING - Metadata Drift detected (count=3).
|
||
2026-04-04 20:05:13,390 - root - WARNING - Desync detected (kernel=295, missing=0, extra=0, metadata=3).
|
||
2026-04-04 20:05:13,390 - root - WARNING - Healing approved.
|
||
2026-04-04 20:05:13,445 - root - INFO - Heal: Flushed CrowdSec nft sets to clear stale metadata.
|
||
2026-04-04 20:05:13,689 - root - INFO - Heal: Bouncer restarted successfully.
|
||
2026-04-04 20:05:13,689 - root - INFO - Post-heal verification in 5s (pre_fingerprint=ecfd0f22f0c86788).
|
||
2026-04-04 20:05:18,797 - root - INFO - LAPI Local Parser: Found 295 active bans.
|
||
2026-04-04 20:05:18,804 - root - WARNING - Post-heal verification result result=success pre=ecfd0f22f0c86788 post= missing=0 extra=0 metadata=0
|
||
2026-04-04 20:14:37,296 - root - INFO - LAPI Local Parser: Found 295 active bans.
|
||
2026-04-04 20:14:37,303 - root - INFO - Audit Success: 295 IPs in sync.
|
||
```
|
||
|
||
In this case:
|
||
|
||
- LAPI still reported 295 valid bans
|
||
- kernel membership matched
|
||
- three bans showed stale metadata / TTL behavior
|
||
- the agent chose the metadata-drift remediation path
|
||
- CrowdSec-managed sets were flushed
|
||
- the bouncer was restarted
|
||
- post-heal verification confirmed full convergence
|
||
|
||
That is the core design goal of this agent: **don’t just restart blindly — detect, classify, remediate, and verify**.
|
||
|
||
---
|
||
|
||
## Privileges / safety
|
||
|
||
This agent is designed for system-level enforcement reconciliation and therefore **requires elevated privileges** in normal operation.
|
||
|
||
It needs sufficient access to:
|
||
|
||
- run `cscli decisions list -a -o json`
|
||
- inspect `nftables` tables via `nft -j list table ...`
|
||
- flush managed CrowdSec sets when performing metadata-drift healing
|
||
- restart `crowdsec-firewall-bouncer` via `systemctl`
|
||
|
||
### What it changes
|
||
|
||
Depending on drift type, the agent may:
|
||
|
||
- read CrowdSec decision state
|
||
- read `nftables` kernel state
|
||
- flush **managed CrowdSec sets only**
|
||
- restart `crowdsec-firewall-bouncer`
|
||
- write local health state / history files
|
||
|
||
### What it does not change
|
||
|
||
By design, the agent does **not**:
|
||
|
||
- manage unrelated firewall policy
|
||
- rewrite arbitrary `nftables` rulesets
|
||
- invent its own ban decisions
|
||
- replace CrowdSec or the firewall bouncer
|
||
- act as a general-purpose firewall orchestration framework
|
||
|
||
It is a narrow reconciliation and healing supervisor for CrowdSec enforcement drift.
|
||
|
||
---
|
||
|
||
## Core components
|
||
|
||
### `auditor.py`
|
||
|
||
Responsible for desired-vs-observed reconciliation.
|
||
|
||
Key behaviors:
|
||
|
||
- schema-tolerant parsing of `cscli` JSON output
|
||
- support for flat decision objects and nested alert-like payloads
|
||
- normalization of CrowdSec decision metadata
|
||
- scanning of both IPv4 and IPv6 enforcement targets
|
||
- membership mismatch detection (`missing` / `extra`)
|
||
- TTL / metadata drift detection for long-duration bans
|
||
- drift fingerprint generation for suppression and history correlation
|
||
|
||
### `healing.py`
|
||
|
||
Responsible for heal gating and post-heal validation.
|
||
|
||
Key behaviors:
|
||
|
||
- prevents repeated heals for the same recent drift fingerprint
|
||
- executes remediation through the auditor
|
||
- waits a configurable delay before re-checking
|
||
- records whether the heal actually converged
|
||
- distinguishes restart failure, verification failure, and success
|
||
|
||
### `doctor.py`
|
||
|
||
Preflight self-test / environment validation.
|
||
|
||
Checks include:
|
||
|
||
- runtime config sanity
|
||
- `cscli` JSON parseability
|
||
- configured `nftables` table accessibility
|
||
- writable state paths
|
||
- `systemctl` restart capability for `crowdsec-firewall-bouncer`
|
||
|
||
### `reporter.py`
|
||
|
||
Persists lightweight node state and heal history for dashboards and operators.
|
||
|
||
Exposes metrics such as:
|
||
|
||
- `uptime_seconds`
|
||
- `checks_total`
|
||
- `heals_total`
|
||
- `heal_failures_total`
|
||
- `drift_events_total`
|
||
- rolling 24h counters for drift and healing activity
|
||
|
||
### `main.py`
|
||
|
||
Orchestrates the full reconcile loop.
|
||
|
||
Features include:
|
||
|
||
- configurable check interval
|
||
- bounded random jitter to avoid synchronized polling
|
||
- fail-fast config validation at startup
|
||
- heal triggering on detected drift
|
||
- post-heal verification
|
||
|
||
---
|
||
|
||
## Drift model
|
||
|
||
The agent currently reasons about two main drift categories:
|
||
|
||
### 1. Membership mismatch
|
||
|
||
The set of IPs CrowdSec wants enforced does not match what kernel state currently holds.
|
||
|
||
Examples:
|
||
|
||
- LAPI decision exists, kernel entry missing
|
||
- kernel entry exists, but CrowdSec no longer considers it active
|
||
|
||
### 2. Metadata drift
|
||
|
||
An IP is present in both places, but expiry / TTL behavior suggests stale or invalid kernel metadata.
|
||
|
||
This is especially important for longer-duration bans, where stale metadata can create “looks present, behaves wrong” enforcement drift.
|
||
|
||
To reduce noise, short-duration TTL variance is intentionally tolerated. The goal is to catch meaningful desynchronization, not harmless decay.
|
||
|
||
---
|
||
|
||
## Project structure
|
||
|
||
```text
|
||
threat-engine-agent/
|
||
├── agent.py # Compatibility entrypoint / CLI wrapper
|
||
├── main.py # Main loop and orchestration
|
||
├── config.py # Runtime settings + logging setup
|
||
├── auditor.py # LAPI vs nft reconciliation and drift fingerprinting
|
||
├── healing.py # Heal gating + post-heal verification
|
||
├── doctor.py # Preflight diagnostics
|
||
├── reporter.py # Local state + heal history writer
|
||
├── config.yaml # Runtime defaults (overridable)
|
||
├── systemd/
|
||
│ └── threat-agent.service
|
||
└── tests/
|
||
```
|
||
|
||
---
|
||
|
||
## Installation
|
||
|
||
### 1. Prepare directories
|
||
|
||
```bash
|
||
sudo mkdir -p /root/threat-engine-agent/logs
|
||
cd /root/threat-engine-agent
|
||
cp .env.example .env
|
||
```
|
||
|
||
### 2. Install service
|
||
|
||
```bash
|
||
sudo cp systemd/threat-agent.service /etc/systemd/system/
|
||
sudo systemctl daemon-reload
|
||
sudo systemctl enable --now threat-agent
|
||
```
|
||
|
||
### 3. Watch logs
|
||
|
||
```bash
|
||
tail -f /root/threat-engine-agent/logs/threat-agent.log
|
||
```
|
||
|
||
### 4. Run preflight checks
|
||
|
||
```bash
|
||
python3 agent.py --doctor
|
||
```
|
||
|
||
---
|
||
|
||
## Tests
|
||
|
||
Run the unit tests from the repository root:
|
||
|
||
```bash
|
||
python3 -m unittest discover -s tests -v
|
||
```
|
||
|
||
The tests use Python's standard library and mock external system commands. They do not require CrowdSec, `nftables`, elevated privileges, or additional Python packages.
|
||
|
||
[Gitea Actions](.gitea/workflows/ci.yaml) runs the same command with Python 3.12 on an `ubuntu-latest` runner for pushes to any branch, pull requests targeting any branch, and manual runs. Repository Actions must be enabled and a runner with that label must be available.
|
||
|
||
---
|
||
|
||
## Configuration
|
||
|
||
Configuration precedence:
|
||
|
||
1. environment variables
|
||
2. `config.yaml`
|
||
3. built-in defaults
|
||
|
||
Supported environment overrides:
|
||
|
||
- `SERVER_NAME`
|
||
- `CHECK_INTERVAL`
|
||
- `CHECK_JITTER_PCT`
|
||
- `HEAL_VERIFY_DELAY`
|
||
- `HEAL_MIN_INTERVAL`
|
||
- `MEMBERSHIP_RECHECK_DELAY`
|
||
- `LOG_PATH`
|
||
- `STATE_FILE`
|
||
- `THREAT_AGENT_CONFIG`
|
||
|
||
### Enforcement scope
|
||
|
||
`config.yaml` supports:
|
||
|
||
- `enforcement.targets`: list of `{family, table}` mappings
|
||
- `enforcement.sets`: optional allowlist of set names to manage
|
||
|
||
If no explicit set allowlist is given, the agent defaults to managing CrowdSec-style `*-cscli` sets where applicable. This keeps healing scope intentionally narrow.
|
||
|
||
---
|
||
|
||
## Operational notes
|
||
|
||
- This agent is best suited for hosts where CrowdSec enforcement correctness matters enough to justify active reconciliation.
|
||
- It is intentionally conservative about repeated heals and uses drift fingerprints to suppress flap loops.
|
||
- Post-heal verification is part of the design, not an optional extra: a restart is not treated as success unless state actually converges.
|
||
- `doctor.py` should be run before first deployment or after major environment changes.
|
||
|
||
---
|
||
|
||
## Troubleshooting
|
||
|
||
If the agent appears stuck in repeated drift or heal behavior:
|
||
|
||
1. Inspect CrowdSec decision output:
|
||
|
||
/usr/bin/cscli decisions list -a -o json
|
||
|
||
2. Inspect current kernel enforcement state:
|
||
|
||
nft -j list table ip crowdsec
|
||
nft -j list table ip6 crowdsec6
|
||
|
||
3. Review local agent logs and history:
|
||
- drift fingerprint
|
||
- missing / extra counts
|
||
- metadata drift count
|
||
- heal result
|
||
- post-heal fingerprint
|
||
|
||
4. Check service status:
|
||
|
||
systemctl status threat-agent crowdsec-firewall-bouncer
|
||
|
||
5. Run diagnostics:
|
||
|
||
python3 agent.py --doctor
|
||
|
||
---
|
||
|
||
## Why not just trust the bouncer?
|
||
|
||
In many environments, trusting the bouncer is fine.
|
||
|
||
This agent exists for operators who want stronger guarantees around enforcement correctness, especially in multi-node or long-running environments where silent drift is costly or hard to notice.
|
||
|
||
It does not replace CrowdSec’s decisioning model. It supervises the last-mile enforcement path and verifies that local kernel state still reflects upstream intent.
|
||
|
||
If the bouncer is healthy and in sync, the agent becomes a lightweight audit loop.
|
||
If drift appears, it provides a structured, verifiable path back to convergence.
|
||
|
||
---
|
||
|
||
## Scope and philosophy
|
||
|
||
`threat-engine-agent` is intentionally narrow.
|
||
|
||
It does not try to become a full security control plane. It solves one problem well:
|
||
|
||
**keeping CrowdSec enforcement aligned with actual kernel reality, and proving when it is.**
|
||
|
||
That means:
|
||
|
||
- deterministic reconciliation over guesswork
|
||
- targeted healing over blind restart loops
|
||
- verification over assumption
|
||
- operational evidence over “it should be fine”
|
||
|
||
---
|
||
|
||
## Status
|
||
|
||
This project is designed for real production use, but the interface and documentation may continue to evolve as the agent is generalized beyond its original environment.
|
||
|
||
---
|
||
|
||
## License
|
||
|
||
MIT License
|