A decision issued in the seconds between a heal and its verification is missing from the kernel until the bouncer's next poll, so verification reported the heal as failed even though it had fixed the drift it was started for. Seen on a node: a metadata heal fixed a stale TTL, a new ban arrived inside the 5 s window, and the heal was logged as failed; the next audit found the node in sync. reconcile() now records the decision values it saw (last_truth_values) and takes an optional baseline_truth. Post-heal verification passes the values the drift was found against; values whose LAPI membership changed since then are left out of the drift, logged with a count, returned as lapi_changed_values, and checked by the next regular audit. Drift on decisions that existed when the heal started still fails verification. The regular audit and the membership re-check are unchanged. Tests: baseline handling in reconcile, the verification call, and a replay of the logged sequence (failed before, success now). 78 tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 KiB
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
nftablesafter 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:
- Audit the node’s live enforcement state against LAPI truth
- Classify drift as membership mismatch or metadata drift
- Heal using a targeted remediation path
- Verify that post-heal state converged
- 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
nftablesstate 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:
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
nftablestables vianft -j list table ... - flush managed CrowdSec sets when performing metadata-drift healing
- restart
crowdsec-firewall-bouncerviasystemctl - create and update its own range table via
nft -f -(only withranges.enabled)
What it changes
Depending on drift type, the agent may:
- read CrowdSec decision state
- read
nftableskernel state - flush managed CrowdSec sets only
- restart
crowdsec-firewall-bouncer - maintain the dedicated range table (see 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
nftablesrulesets 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
cscliJSON 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
cscliJSON parseability- configured
nftablestable accessibility - writable state paths
systemctlrestart capability forcrowdsec-firewall-bouncer
reporter.py
Persists lightweight node state and heal history for dashboards and operators.
Exposes metrics such as:
uptime_secondschecks_totalheals_totalheal_failures_totaldrift_events_totalheals_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:
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_v6are 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(statusDEGRADED)
To remove the table after disabling the feature: nft delete table inet crowdsec-ranges.
Project structure
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
sudo mkdir -p /root/threat-engine-agent/logs
cd /root/threat-engine-agent
cp .env.example .env
2. Install service
sudo cp systemd/threat-agent.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now threat-agent
3. Watch logs
tail -f /root/threat-engine-agent/logs/threat-agent.log
4. Run preflight checks
python3 agent.py --doctor
Tests
Run the unit tests from the repository root:
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 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:
- environment variables
config.yaml- built-in defaults
Supported environment overrides:
SERVER_NAMECHECK_INTERVALCHECK_JITTER_PCTHEAL_VERIFY_DELAYHEAL_MIN_INTERVALMEMBERSHIP_RECHECK_DELAYLOG_PATHSTATE_FILETHREAT_AGENT_CONFIG
Enforcement scope
config.yaml supports:
enforcement.targets: list of{family, table}mappingsenforcement.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
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.
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.
- Verification is judged against the decisions the heal started from. A decision issued or removed during the verification window (which the bouncer applies on its next poll) is logged as
lapi_changedand left to the next audit, so it is not counted as a failed heal. Drift on decisions that existed when the heal started still fails verification. doctor.pyshould be run before first deployment or after major environment changes.
Troubleshooting
If the agent appears stuck in repeated drift or heal behavior:
-
Inspect CrowdSec decision output:
/usr/bin/cscli decisions list -a -o json
-
Inspect current kernel enforcement state:
nft -j list table ip crowdsec nft -j list table ip6 crowdsec6
-
Review local agent logs and history:
- drift fingerprint
- missing / extra counts
- metadata drift count
- heal result
- post-heal fingerprint
-
Check service status:
systemctl status threat-agent crowdsec-firewall-bouncer
-
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