Files
threat-engine-agent/README.md
T
patrickandClaude Opus 5.5 7156cfd4fe
CI / Unit tests (push) Successful in 9s
CI / Unit tests (pull_request) Successful in 6s
feat(ranges): enforce LAPI range decisions in an agent-owned nft table
crowdsec-firewall-bouncer's nftables mode strips the prefix from Range
decisions and bans only the network address, so a /24 decision blocked
a single IP. With ranges.enabled, every audit now syncs range decisions
into a dedicated `inet crowdsec-ranges` table (interval+timeout sets with
input/forward drop chains) in one atomic `nft -f` transaction, then reads
it back to confirm each range is enforced.

- element timeouts track each decision's remaining lifetime; stale
  elements are removed and extended decisions refreshed
- ranges nested in another active range are covered, not inserted
- ranges broader than min_prefix_v4/v6 (default /16, /32) are refused
- ranges still missing after the sync stay in unenforceable_ranges, so
  the node reports DEGRADED rather than HEALTHY
- the bouncer-set scan normalizes nft prefix elements to addr/len
  instead of failing the table scan on them
- doctor checks the range table; the audit log line says when a synced
  node is degraded

Disabled by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:54:26 -04:00

431 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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`
- create and update its own range table via `nft -f -` (only with `ranges.enabled`)
### 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`
- maintain the dedicated range table (see [Range decisions](#range-decisions)), when enabled
- write local health state / history files
### What it does not change
By design, the agent does **not**:
- manage unrelated firewall policy
- rewrite `nftables` rulesets other than its own range table
- 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`
- `heals_suppressed_total`
- rolling 24h counters for drift and healing activity
Every drift event leads to either a heal attempt or a suppressed heal (`heals_suppressed_24h`): the
heal gate skips a drift whose fingerprint matches a heal from the last `heal_min_interval` seconds,
which means that earlier heal did not hold.
### `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.
### Range decisions
`crowdsec-firewall-bouncer` (nftables mode) cannot enforce `Range` decisions: it strips the prefix and bans only the network address, so `195.178.110.0/24` blocks just `195.178.110.0`. The agent pairs such a range with that address so it is not counted as membership drift, and handles it as below.
With `ranges.enabled: false` (the default), the range is reported in `unenforceable_ranges` and the node status is `DEGRADED`.
With `ranges.enabled: true`, every audit syncs the range decisions into a table the agent owns, in one atomic `nft -f` transaction:
```text
table inet crowdsec-ranges {
set ranges-v4 { type ipv4_addr; flags interval, timeout; }
set ranges-v6 { type ipv6_addr; flags interval, timeout; }
chain input { type filter hook input priority -10; policy accept; ip saddr @ranges-v4 drop; ip6 saddr @ranges-v6 drop; }
chain forward { type filter hook forward priority -10; policy accept; ip saddr @ranges-v4 drop; ip6 saddr @ranges-v6 drop; }
}
```
- each range is added with its decision's remaining lifetime as the element timeout, so bans expire on their own even if the agent stops
- elements whose decision is gone are removed, and elements whose decision was extended are refreshed
- a range inside another active range is covered by the wider one rather than inserted (interval sets reject overlaps)
- ranges broader than `min_prefix_v4` / `min_prefix_v6` are refused, so a bad decision cannot cut off a node
- after applying, the table is read back; any range not present is reported in `unenforceable_ranges` (status `DEGRADED`)
To remove the table after disabling the feature: `nft delete table inet crowdsec-ranges`.
---
## 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
├── ranges.py # Range decision enforcement in a dedicated nft table
├── 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.
The job uses the `ghcr.io/catthehacker/ubuntu:act-24.04` container image, which includes Python 3.12 and Node.js for the checkout action. This makes the job environment independent of the image configured for the runner label and avoids downloading Python builds intended for GitHub-hosted runners.
---
## 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.
### Range enforcement
```yaml
ranges:
enabled: true # default false
table: "crowdsec-ranges" # inet table the agent owns
min_prefix_v4: 16 # refuse IPv4 ranges broader than /16
min_prefix_v6: 32 # refuse IPv6 ranges broader than /32
```
See [Range decisions](#range-decisions).
---
## 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