Compare commits

...
62 Commits
Author SHA1 Message Date
patrick 05f437e673 Merge pull request 'fix(healing): judge post-heal verification against the pre-heal decisions' (#7) from fix/verify-ignores-new-decisions into main
CI / Unit tests (push) Successful in 6s
Reviewed-on: #7
2026-11-14 04:34:00 +00:00
patrickandClaude Opus 5.5 16338a2507 fix(healing): judge post-heal verification against the pre-heal decisions
CI / Unit tests (push) Successful in 3s
CI / Unit tests (pull_request) Successful in 3s
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>
2026-11-13 23:32:41 -05:00
patrick 6cb7fae06a Merge pull request 'feat(ranges): enforce LAPI range decisions in an agent-owned nft table' (#6) from feat/range-enforcement into main
CI / Unit tests (push) Successful in 2s
Reviewed-on: #6
2026-10-23 13:55:59 +00:00
patrickandClaude Opus 5.5 7156cfd4fe feat(ranges): enforce LAPI range decisions in an agent-owned nft table
CI / Unit tests (push) Successful in 9s
CI / Unit tests (pull_request) Successful in 6s
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
patrick 88d3c57ab0 Merge pull request 'fix(auditor): report range decisions the kernel can't enforce instead of healing' (#5) from fix/unenforceable-range-decisions into main
CI / Unit tests (push) Successful in 6s
Reviewed-on: #5
2026-10-23 13:44:56 +00:00
patrickandClaude Opus 5.5 e76e957282 fix(auditor): report range decisions the kernel can't enforce instead of healing
CI / Unit tests (push) Successful in 3s
CI / Unit tests (pull_request) Successful in 7s
A LAPI range decision (e.g. 195.178.110.0/24) inserted into an nft set
without the interval flag is stored as its bare network address. The
string diff saw that as one missing and one extra entry, and every heal
re-added the same address, so nodes stuck in DESYNC_DETECTED with the
flap guard suppressing repeat heals.

Pair such ranges with their network address, report them as
unenforceable_ranges with a dedicated warning, and keep them out of the
drift counts and fingerprint. The reporter records
unenforceable_range_count and shows DEGRADED for a node that is
otherwise in sync. Desync log lines now name the missing and extra
values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:43:46 -04:00
patrick 57ed6cfc1c Merge pull request 'fix(auditor): don't heal when the LAPI is unreachable' (#4) from fix/lapi-unreachable-no-heal into main
CI / Unit tests (push) Successful in 2s
Reviewed-on: #4
2026-10-21 20:51:26 +00:00
patrickandClaude Opus 5.5 8c8be8ec63 fix(auditor): don't heal when the LAPI is unreachable
CI / Unit tests (push) Successful in 4s
CI / Unit tests (pull_request) Successful in 3s
get_remote_lapi_truth() returned {} when 'cscli decisions list' failed, which is
indistinguishable from "no active bans". reconcile() then saw every kernel ban as extra,
reported membership_mismatch, and the heal restarted crowdsec-firewall-bouncer. A LAPI
outage would do that on every node at once, every heal interval.

Raise LapiUnavailableError instead. reconcile() propagates it, so the main loop records
it as last_error and retries in 60s without healing; post-heal verification records it
as verify_error. A genuinely empty decision list still returns {} as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:47:48 -04:00
patrick cb2a88917c Merge pull request 'feat(reporter): count heals the gate suppresses' (#3) from feat/count-suppressed-heals into main
CI / Unit tests (push) Successful in 3s
Reviewed-on: #3
2026-10-19 22:10:31 +00:00
patrickandClaude Opus 5.5 4e8a4d6717 feat(reporter): count heals the gate suppresses
CI / Unit tests (push) Successful in 4s
CI / Unit tests (pull_request) Successful in 3s
A drift whose fingerprint matches a heal from the last heal_min_interval
seconds was counted as a drift event but never as a heal attempt, so the
24h counters showed a drift with no heal and no failure. Decide on the
heal before recording the check and report heals_suppressed_24h and
heals_suppressed_total, so every drift event is either a heal attempt
or a suppressed heal. The suppression warning now names the earlier
heal that did not hold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:04:24 -04:00
patrick 02ca338eb7 Merge pull request 'Add Gitea Actions CI for all branches' (#2) from ci/gitea-actions into main
CI / Unit tests (push) Successful in 4s
Reviewed-on: #2
2026-10-15 00:53:40 +00:00
patrick 73d5112afe Fix CI Python setup with an explicit Ubuntu job image
CI / Unit tests (push) Successful in 3s
CI / Unit tests (pull_request) Successful in 4s
2026-10-14 20:52:20 -04:00
patrick b236611044 Add Gitea Actions CI for all branches
CI / Unit tests (push) Failing after 14s
2026-10-14 20:49:25 -04:00
patrick 053991669b Merge pull request 'fix: replace shorter CrowdSec bans instead of adding beside them' (#1) from fix/multi-set-ttl-drift into main
Reviewed-on: #1
2026-10-14 20:29:00 +00:00
patrickandClaude Opus 5.5 772892b78d feat(healing): re-check membership mismatches before healing
A decision created moments before an audit shows up as missing=1 until
the bouncer's next poll, which triggered a bouncer restart for nothing.

When the audit finds a membership mismatch, wait membership_recheck_delay
seconds (default 30, 0 disables) and audit again; only drift that is still
present is reported and healed. Metadata drift is not delayed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:38:39 -04:00
patrickandClaude Opus 5.5 79f72512e4 fix(auditor): use longest kernel expiry for IPs in multiple sets
The bouncer keeps one nft set per decision origin, so an IP with both a
crowdsec ban and a later, longer cscli ban sits in two sets. The kernel
scan kept whichever set it read last, so the short TTL could be compared
against the longest LAPI decision and reported as metadata drift.

Keep the longest expiry per IP instead, and log per-IP evidence (expected
vs kernel seconds, source sets, LAPI decisions) whenever drift is flagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:27:59 -04:00
patrick 9d68d1f4b4 docs(readme): rewrite project overview and operating model 2026-04-04 20:30:47 -04:00
patrick f5615faeae fix(healing): normalize history timestamps to UTC in heal flap gate 2026-03-06 22:31:24 -05:00
patrick 1013b05790 fix(reporter): emit UTC-aware timestamps for state and heal history 2026-03-06 19:22:25 -05:00
patrick ecda631049 fix(reporter): refresh last_heal_timestamp on every heal result 2026-03-06 18:43:34 -05:00
patrick 469a30df6a feat(reporter): add rolling 24h drift/heal counters to state snapshot 2026-03-06 17:38:42 -05:00
patrick 8c7b0768b0 feat(reporter): add drift event and heal-attempt counters to state snapshot 2026-03-05 21:28:25 -05:00
patrick a2030a71b7 feat(reporter): track last_heal_timestamp in state snapshot 2026-03-05 21:03:56 -05:00
patrick 3b1e25d5cd feat(reporter): add uptime and fleet counters to state snapshot 2026-03-05 20:57:16 -05:00
patrick 7f323ed78b feat(config): validate runtime settings at boot and fail fast on critical errors 2026-03-05 20:55:00 -05:00
patrick be92bb2493 feat(agent): add --doctor preflight self-test mode with structured checks 2026-03-05 20:49:37 -05:00
patrick d2fdd5be44 feat(main): add bounded randomized check-interval jitter across nodes 2026-03-05 20:39:22 -05:00
patrick b34ac69ac1 feat(reporter): persist drift metrics and last heal result in state snapshot 2026-03-05 20:35:18 -05:00
patrick c698d01c40 feat(auditor): add startup enforcement sanity check and dedupe set-mismatch warnings 2026-03-05 20:32:29 -05:00
patrick 389f310f24 chore(config): align enforcement set names with live CrowdSec nft sets 2026-03-05 20:28:52 -05:00
patrick 172f5d7ced fix(auditor): fail open when configured enforcement sets do not match nft state 2026-03-05 20:23:00 -05:00
patrick bffe28485d feat(config): enforce runtime nft targets and managed sets from config.yaml 2026-03-05 20:19:31 -05:00
patrick 3c6c4e384b fix(main,reporter): handle SIGTERM gracefully and normalize history file path 2026-03-05 20:12:17 -05:00
patrick 9b53a4c491 fix(healing): handle post-heal verify exceptions without crashing loop 2026-03-01 21:14:59 -05:00
patrick 9edce6b31d perf(healing): scan heal history from file tail instead of full read
- add tail-based HEAL line lookup to avoid O(file-size) reads in should_heal()
- keep a safe fallback full scan when no HEAL marker is found in tail window
- add regression test for large history files with recent HEAL marker
2026-03-01 21:12:55 -05:00
patrick 55cc29071e Add nft handle fallback when flushing CrowdSec sets with slash-based names 2026-02-26 14:14:20 -05:00
patrick 716468901c Harden metadata heal across nft table variants and non-fatal flush errors 2026-02-26 13:37:48 -05:00
patrick aae920fb73 fix: metadata drift false positives - corrected by normalizing nft TTL and skipping unverifiable expiry 2026-02-25 15:02:24 -05:00
patrick 0f7f03f005 Fix metadata-drift healing by flushing CrowdSec nft sets before restart
Add drift-aware heal path in FirewallAuditor to remediate metadata drift by discovering and flushing
  *-cscli sets in crowdsec/crowdsec6 tables, then restarting the bouncer.

Update execute_heal_and_verify to pass drift context to heal_with_drift when supported, keeping
  backward compatibility via heal().

Add unit tests covering metadata-drift flush+restart behavior, non-metadata restart-only behavior,
  and drift context propagation.
2026-02-25 14:59:44 -05:00
patrick 28267a0cf4 fix(auditor): heal on decision-duration drift, not just IP membership/count 2026-02-23 22:20:16 -05:00
patrick 480eea8095 refactor(agent): split orchestration into config, healing, and main modules 2026-02-10 22:11:33 -05:00
patrick 5fc5b8c114 test(agent): add coverage for drift gating and post-heal verification; remove bare except 2026-02-10 22:04:57 -05:00
patrick 461512f20a feat(config): wire runtime settings from env/config with sane defaults 2026-02-10 22:01:17 -05:00
patrick 6dac06c117 docs(readme): sync architecture and runtime flow with current agent behavior 2026-02-10 21:57:11 -05:00
patrick 234224a5c6 feat(healing): add post-restart verification and heal outcome telemetry 2026-02-10 21:55:43 -05:00
patrick b2c489602a fix(paths): switch agent log and state defaults 2026-02-10 21:53:41 -05:00
patrick e342d83a70 fix(reconcile): gate heal flapping by drift fingerprint instead of kernel count 2026-02-10 21:48:50 -05:00
patrick 3d7c1b3f2a fix(auditor): support flat and nested cscli decision JSON parsing 2026-02-10 21:45:37 -05:00
patrick 82352110a4 fix: incorrect decision pulling from CrowdSec locally 2026-01-25 22:49:19 -05:00
patrick d91cfc7e1f fix: file dir edit for state_file after merge with other branch 2026-01-26 03:33:01 +00:00
patrick 6e98117126 fix: add cscli decision list check for LAPI threat-agent 2026-01-26 03:30:42 +00:00
patrick 6f180753f2 fix: file dir update 2026-01-26 03:24:07 +00:00
patrick f0a70273d3 fix: quick node name update 2026-01-26 03:22:02 +00:00
patrick 42c25c145e fix: finalize merge with agent-node branch 2026-01-26 03:14:46 +00:00
patrick 9977a0d8cf fix: add *.log* to .gitignore 2026-01-26 03:12:21 +00:00
patrick b5722d2013 update: merge branches to integrate TTL awareness and drift detection 2026-01-26 03:11:05 +00:00
patrick 5990dddf5a Merge branch 'agent-node' 2026-01-26 03:10:21 +00:00
patrick cc7bb36e97 update: inclusion of history to gitignore 2026-01-23 21:24:21 +00:00
patrick 19d983c36f update: remove state history file 2026-01-23 21:23:29 +00:00
patrick b08e4bec29 feat: implement dual-stack IPv4/IPv6 auditing and updated logs 2026-01-23 13:18:55 -05:00
patrick 68b8125279 docs: README cleanup 2026-01-23 04:04:37 +00:00
patrick 63a47d4c95 fix: incorrect state file (wrong dir) 2026-01-22 22:58:09 -05:00
21 changed files with 3979 additions and 234 deletions

No files matched your search

+8
View File
@@ -1,2 +1,10 @@
BOUNCER_KEY=example BOUNCER_KEY=example
SERVER_NAME=Name SERVER_NAME=Name
CHECK_INTERVAL=600
CHECK_JITTER_PCT=0.10
HEAL_VERIFY_DELAY=5
HEAL_MIN_INTERVAL=900
MEMBERSHIP_RECHECK_DELAY=30
LOG_PATH=/root/threat-engine-agent/logs/threat-agent.log
STATE_FILE=/root/threat-engine-agent/threat-agent-state.json
THREAT_AGENT_CONFIG=config.yaml
+31
View File
@@ -0,0 +1,31 @@
name: CI
on:
push:
branches:
- "**"
pull_request:
branches:
- "**"
workflow_dispatch:
jobs:
test:
name: Unit tests
runs-on: ubuntu-latest
timeout-minutes: 10
# Runner labels do not guarantee the job's OS or installed tools in Gitea.
container:
image: ghcr.io/catthehacker/ubuntu:act-24.04
steps:
- name: Check out repository
uses: https://github.com/actions/checkout@v4
with:
persist-credentials: false
- name: Show Python version
run: python3 --version
- name: Run unit tests
run: python3 -m unittest discover -s tests -v
+408 -37
View File
@@ -1,60 +1,431 @@
# Threat Engine Agent (Triton Edition) # threat-engine-agent
A self-healing synchronization agent designed to ensure the local `nftables` kernel state perfectly matches the CrowdSec Local API (LAPI) desired state. 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.”
## 🎯 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 ## Why this exists
### The Auditor (`auditor.py`) In practice, `crowdsec-firewall-bouncer` can occasionally drift from the state CrowdSec intends to enforce.
- **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 Examples include:
- **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.
- 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:
## 📂 Project Structure
```text ```text
threat-engine-agent/ 2026-04-04 20:05:13,383 - root - INFO - LAPI Local Parser: Found 295 active bans.
├── main.py # Logic loop and orchestration 2026-04-04 20:05:13,390 - root - WARNING - Metadata Drift detected (count=3).
├── auditor.py # The "Brain": Recursive parsing and kernel scanning 2026-04-04 20:05:13,390 - root - WARNING - Desync detected (kernel=295, missing=0, extra=0, metadata=3).
├── systemd/ # Deployment configurations 2026-04-04 20:05:13,390 - root - WARNING - Healing approved.
│ └── threat-agent.service 2026-04-04 20:05:13,445 - root - INFO - Heal: Flushed CrowdSec nft sets to clear stale metadata.
└── logs/ # Local audit history (Git ignored) 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.
``` ```
## 🚀 Installation & Deployment In this case:
1. Environment Setup: - LAPI still reported 295 valid bans
```chmod +x main.py - kernel membership matched
mkdir logs - 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; }
}
``` ```
2. Systemd Integration: - 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
```sudo cp systemd/threat-agent.service /etc/systemd/system/ - 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 daemon-reload
sudo systemctl enable --now threat-agent sudo systemctl enable --now threat-agent
``` ```
3. Monitoring: ### 3. Watch logs
```# Watch the auditor work in real-time
tail -f logs/threat-agent.log ```bash
tail -f /root/threat-engine-agent/logs/threat-agent.log
``` ```
## 🔍 Troubleshooting ### 4. Run preflight checks
If you see a "Heal Loop" in the logs: ```bash
1. **Manual Check**: Run `/usr/bin/cscli decisions list -a -o json` and check if the count matches `nft list table ip crowdsec`. python3 agent.py --doctor
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.
---
## 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.
- 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_changed` and 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.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
+22 -103
View File
@@ -1,112 +1,31 @@
# threat-engine-agent/agent.py import argparse
import sys
import time from config import load_runtime_settings
import logging from doctor import run_doctor
from auditor import FirewallAuditor from healing import execute_heal_and_verify, should_heal
from reporter import LocalStateReporter from main import main
from dotenv import load_dotenv
import os
from datetime import datetime, timedelta
logging.basicConfig( __all__ = ["main", "should_heal", "execute_heal_and_verify", "run_doctor"]
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='/root/threat-engine-agent/logs/threat-agent.log'
)
################
#### Helpers ###
################
def should_heal(history_file, current_count, min_interval=900):
"""
Prevents heal flapping by suppressing repeated no-op heals.
"""
try:
if not os.path.exists(history_file):
return True
with open(history_file) as f:
lines = [l.strip() for l in f.readlines() if "HEAL:" in l]
if not lines:
return True
last = lines[-1]
ts_str, msg = last.split(" - ", 1)
last_time = datetime.fromisoformat(ts_str)
last_count = int(msg.split("desync of")[1].split("IPs")[0])
# If healed recently AND nothing changed, suppress
if datetime.now() - last_time < timedelta(seconds=min_interval):
if last_count == current_count:
logging.warning(
f"Heal suppressed (recent identical heal: {last_count} IPs)"
)
return False
return True
except Exception as e:
logging.error(f"Heal gate failed open: {e}")
return True
################ def cli(argv=None):
##### Main ##### parser = argparse.ArgumentParser(description="Threat Engine Agent")
################ parser.add_argument(
"--doctor",
action="store_true",
help="Run startup self-tests and exit.",
)
args = parser.parse_args(argv)
def main(): if args.doctor:
""" settings = load_runtime_settings()
The Orchestrator: Links Audit findings to the State Reporter. ok = run_doctor(settings)
""" return 0 if ok else 1
load_dotenv()
auditor = FirewallAuditor() main()
reporter = LocalStateReporter() return 0
node_name = os.getenv("SERVER_NAME", "Unknown Node")
CHECK_INTERVAL = 600
print(f"[*] Agent started. Check interval: {CHECK_INTERVAL}s")
logging.info(f"Threat Engine Agent initialized on {node_name}.")
while True:
try:
is_synced, count = auditor.reconcile()
reporter.update_status(is_synced, count)
status_msg = f"Audit Success: {count} IPs in sync." if is_synced else f"DESYNC: {count} in kernel. Healing..."
print(f"[+] {status_msg}") # This will show up in your terminal!
if not is_synced:
logging.warning(f"Desync detected ({count} IPs in kernel).")
history_file = reporter.state_file.replace(".json", ".history")
if should_heal(history_file, count):
logging.warning("Healing approved.")
auditor.heal()
reporter.log_heal_event(count)
else:
logging.warning("Healing skipped to prevent flapping.")
else:
logging.info(f"Audit Success: {count} IPs in sync.")
print(f"[*] Sleeping for {CHECK_INTERVAL} seconds...")
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__": if __name__ == "__main__":
main() raise SystemExit(cli(sys.argv[1:]))
+526 -81
View File
@@ -3,127 +3,572 @@
import subprocess import subprocess
import json import json
import logging import logging
from dotenv import load_dotenv import hashlib
import os import datetime
import requests import ipaddress
from ranges import element_key
try:
from dotenv import load_dotenv
except ImportError:
def load_dotenv():
return None
class LapiUnavailableError(RuntimeError):
"""The LAPI could not be queried, so there is no decision truth to compare against."""
class FirewallAuditor: class FirewallAuditor:
def __init__(self): def __init__(self, targets=None, managed_sets=None, range_enforcer=None):
"""Ensures the NFT kernel state matches the LAPI's desired state.""" """Ensures the NFT kernel state matches the LAPI's desired state."""
load_dotenv() load_dotenv()
self.table = "crowdsec" # When set, range decisions are enforced in a dedicated table instead of
self.set_name = "0.0.0.0/0-cscli" # being reported as unenforceable.
self.API_KEY = os.getenv("BOUNCER_KEY") self.range_enforcer = range_enforcer
self.TRITON = "triton.beane.me" self.targets = list(targets or (("ip", "crowdsec"), ("ip6", "crowdsec6")))
self.managed_sets = {str(name) for name in (managed_sets or ()) if str(name)}
self._reported_set_miss = set()
# Per-IP evidence from the latest scan, used only for drift diagnostics.
self._last_decisions = {}
self._last_kernel_sources = {}
# Decision values the latest reconcile saw in the LAPI. A heal records them as
# the baseline its post-heal verification is judged against.
self.last_truth_values = None
def log_enforcement_startup_state(self):
target_desc = ", ".join(f"{family}:{table}" for family, table in self.targets)
if not target_desc:
target_desc = "none"
sets_desc = ", ".join(sorted(self.managed_sets)) if self.managed_sets else "(auto: *-cscli)"
ranges_desc = (
f"inet:{self.range_enforcer.table}" if self.range_enforcer else "disabled"
)
logging.info(
f"Enforcement config: targets=[{target_desc}] managed_sets=[{sets_desc}] "
f"range_table={ranges_desc}"
)
for family, table in dict.fromkeys(self.targets):
try:
res = subprocess.run(
["/usr/sbin/nft", "-j", "list", "table", family, table],
check=True,
capture_output=True,
text=True,
)
data = json.loads(res.stdout or "{}")
discovered_sets = sorted(
nft_set.get("name")
for item in data.get("nftables", [])
for nft_set in [item.get("set")]
if isinstance(nft_set, dict) and isinstance(nft_set.get("name"), str)
)
logging.info(
f"Enforcement discovered {len(discovered_sets)} sets in {family} {table}."
)
if self.managed_sets and discovered_sets:
overlap = set(discovered_sets) & self.managed_sets
if not overlap:
logging.warning(
"Configured enforcement sets not found in "
f"{family} {table} at startup."
)
except subprocess.CalledProcessError:
logging.warning(
f"Enforcement startup check: table not found ({family} {table})."
)
except Exception as e:
logging.warning(
"Enforcement startup check failed for "
f"{family} {table}: {e}"
)
def get_remote_lapi_truth(self): def get_remote_lapi_truth(self):
url = f"https://{self.TRITON}:8081/v1/decisions" """Queries CrowdSec decisions and normalizes across schema variants."""
headers = {"X-Api-Key": self.API_KEY}
try: try:
r = requests.get( cmd = ["/usr/bin/cscli", "decisions", "list", "-a", "-o", "json"]
url, res = subprocess.run(cmd, capture_output=True, text=True, check=True)
headers=headers, data = json.loads(res.stdout) or []
verify=True,
timeout=(3.05, 10), # Connect timeout of 3s, Read timeout of 10s
allow_redirects=False
)
data = r.json() or [] truth_map = {}
self._last_decisions = {}
if not isinstance(data, list): for decision in self._extract_decisions(data):
logging.error(f"Unexpected LAPI response type: {type(data)}") val = decision.get("value")
return set() if val and decision.get("origin") != "CAPI":
self._last_decisions.setdefault(val, []).append(
truth_map = { {
d["value"]: d.get("duration") "origin": decision.get("origin"),
for d in data "scenario": decision.get("scenario"),
if isinstance(d, dict) "duration": decision.get("duration"),
and d.get("value") "until": decision.get("until"),
and d.get("origin") != "CAPI" }
} )
parsed = self._normalize_truth_decision(decision)
existing = truth_map.get(val)
if existing is None:
truth_map[val] = parsed
else:
# Keep the decision with the furthest expected expiry.
if self._decision_rank(parsed) > self._decision_rank(existing):
truth_map[val] = parsed
logging.info(f"LAPI Local Parser: Found {len(truth_map)} active bans.")
return truth_map return truth_map
except requests.exceptions.ConnectTimeout:
logging.error("Connection to Triton timed out. Check if port 8081 is open on Triton's firewall.")
return {}
except Exception as e: except Exception as e:
logging.error(f"LAPI Sync Error: {e}") # Raise rather than return {}: an empty truth map would make every kernel ban
return {} # look like drift and trigger a bouncer restart whenever the LAPI is down.
detail = (getattr(e, "stderr", None) or "").strip() or str(e)
logging.error(f"Failed to get LAPI truth: {detail}")
raise LapiUnavailableError(f"LAPI unreachable: {detail}") from e
def _normalize_truth_decision(self, decision):
return {
"duration": decision.get("duration"),
"until_epoch": self._parse_until_epoch(decision.get("until")),
}
def _decision_rank(self, decision_meta):
if decision_meta.get("until_epoch"):
return decision_meta["until_epoch"]
return self.parse_duration(decision_meta.get("duration"))
def _parse_until_epoch(self, until_str):
if not until_str:
return None
try:
normalized = str(until_str).replace("Z", "+00:00")
dt = datetime.datetime.fromisoformat(normalized)
return dt.timestamp()
except Exception:
return None
def _extract_decisions(self, payload):
"""
Supports both:
- Flat decision objects from `cscli decisions list -o json`
- Nested alert-like objects containing `decisions` arrays
"""
seen = set()
yield from self._extract_decisions_recursive(payload, seen)
def _extract_decisions_recursive(self, node, seen):
if isinstance(node, dict):
decisions = node.get("decisions")
if isinstance(decisions, list):
for item in decisions:
if isinstance(item, dict):
key = (item.get("value"), item.get("duration"), item.get("origin"))
if key not in seen:
seen.add(key)
yield item
if "value" in node and any(
k in node for k in ("duration", "origin", "scope", "type", "id")
):
key = (node.get("value"), node.get("duration"), node.get("origin"))
if key not in seen:
seen.add(key)
yield node
for value in node.values():
if isinstance(value, (dict, list)):
yield from self._extract_decisions_recursive(value, seen)
return
if isinstance(node, list):
for item in node:
if isinstance(item, (dict, list)):
yield from self._extract_decisions_recursive(item, seen)
def get_kernel_state(self): def get_kernel_state(self):
"""Scans BOTH IPv4 and IPv6 sets in the crowdsec tables.""" """Scans BOTH IPv4 and IPv6 sets in the crowdsec tables."""
all_ips = {} # Changed from set() to {} all_ips = {}
targets = [ self._last_kernel_sources = {}
{"family": "ip", "table": "crowdsec"}, for family, table in self.targets:
{"family": "ip6", "table": "crowdsec6"}
]
for target in targets:
try: try:
cmd = ["/usr/sbin/nft", "-j", "list", "table", target["family"], target["table"]] cmd = ["/usr/sbin/nft", "-j", "list", "table", family, table]
res = subprocess.run(cmd, capture_output=True, text=True, check=True) res = subprocess.run(cmd, capture_output=True, text=True, check=True)
data = json.loads(res.stdout) data = json.loads(res.stdout)
for item in data.get('nftables', []): set_entries = []
nft_set = item.get('set') for item in data.get("nftables", []):
if nft_set: nft_set = item.get("set")
elements = nft_set.get('elem', []) if isinstance(nft_set, dict):
for e in elements: set_entries.append(nft_set)
if isinstance(e, dict):
inner = e.get('elem', e) selected_sets = set_entries
if isinstance(inner, dict): if self.managed_sets:
val = inner.get('val') filtered = [
# NFT provides 'expires' in milliseconds nft_set
expires_ms = inner.get('expires', 0) for nft_set in set_entries
if val: if nft_set.get("name") in self.managed_sets
all_ips[val] = expires_ms ]
else: if filtered:
# Fallback if it's just a raw string IP selected_sets = filtered
all_ips[e] = 0 elif set_entries:
key = (family, table)
if key not in self._reported_set_miss:
logging.warning(
"Configured enforcement sets not found for "
f"{family} {table}; falling back to scanning all sets."
)
self._reported_set_miss.add(key)
for nft_set in selected_sets:
elements = nft_set.get('elem', [])
for e in elements:
if isinstance(e, dict):
inner = e.get('elem', e)
if isinstance(inner, dict):
val = element_key(inner.get('val'))
expires_raw = inner.get('expires')
if val:
try:
self._last_kernel_sources.setdefault(val, []).append(
{
"set": f"{family}/{table}/{nft_set.get('name')}",
"expires": expires_raw,
"timeout": inner.get("timeout"),
}
)
except TypeError:
pass
if not isinstance(expires_raw, (int, float)):
# Expiry not reported for this element; TTL drift is unverifiable.
all_ips[val] = None
elif val not in all_ips:
all_ips[val] = float(expires_raw)
elif all_ips[val] is not None:
# Same IP in several sets (one per decision origin):
# the longest-lived element is what keeps it blocked.
all_ips[val] = max(all_ips[val], float(expires_raw))
else:
# Fallback if it's just a raw string IP
all_ips[e] = None
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
logging.debug(f"Table {target['table']} not found, skipped.") logging.debug(f"Table {table} not found, skipped.")
except Exception as e: except Exception as e:
logging.error(f"Kernel Table scan failed for {target['table']}: {e}") logging.error(f"Kernel Table scan failed for {table}: {e}")
return all_ips return all_ips
def parse_duration(self, duration_str): def parse_duration(self, duration_str):
"""Converts CrowdSec strings like '14d', '24h', '4h' to seconds.""" """Converts CrowdSec strings like '14d', '24h', '4h', '1h30m' to seconds."""
try: try:
if not duration_str:
return 0
units = {"d": 86400, "h": 3600, "m": 60, "s": 1} units = {"d": 86400, "h": 3600, "m": 60, "s": 1}
unit = duration_str[-1] total = 0
value = int(duration_str[:-1]) number = ""
return value * units.get(unit, 1) for ch in str(duration_str).strip().lower():
except: if ch.isdigit():
number += ch
continue
if ch in units and number:
total += int(number) * units[ch]
number = ""
else:
return 0
return total
except Exception:
return 0 return 0
def heal(self): def _expected_remaining_seconds(self, decision_meta, now_epoch):
"""Directly restarts the bouncer service.""" until_epoch = decision_meta.get("until_epoch")
if until_epoch:
return max(0, int(until_epoch - now_epoch))
return self.parse_duration(decision_meta.get("duration"))
def _has_ttl_drift(self, expected_seconds, kernel_seconds):
if expected_seconds <= 21600:
return False
allowed_shortfall = max(7200, int(expected_seconds * 0.40))
return kernel_seconds + allowed_shortfall < expected_seconds
def _normalize_kernel_remaining_seconds(self, kernel_raw, expected_seconds):
"""
nft 'expires' can appear in either seconds or milliseconds depending on stack/version.
Pick the representation closest to expected TTL from CrowdSec.
"""
try: try:
if kernel_raw is None:
return None
raw = float(kernel_raw)
if raw <= 0:
return None
candidates = [raw, raw / 1000.0]
if expected_seconds <= 0:
return max(candidates)
return min(candidates, key=lambda value: abs(value - expected_seconds))
except Exception:
return None
def heal(self):
"""Executes heal actions based on drift type, then restarts the bouncer."""
return self.heal_with_drift({})
def heal_with_drift(self, drift):
"""Performs targeted pre-heal remediation for metadata drift."""
try:
if drift.get("reason") == "metadata_drift":
self._flush_crowdsec_sets()
logging.info("Heal: Flushed CrowdSec nft sets to clear stale metadata.")
subprocess.run(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True) subprocess.run(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True)
logging.info("Heal: Bouncer restarted successfully.") logging.info("Heal: Bouncer restarted successfully.")
return True
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
logging.error(f"Heal Failed: Could not restart bouncer: {e}") logging.error(f"Heal Failed: Could not restart bouncer: {e}")
return False
except Exception as e:
logging.error(f"Heal Failed: Unexpected error: {e}")
return False
def reconcile(self): def _flush_crowdsec_sets(self):
for family, table in dict.fromkeys(self.targets):
try:
res = subprocess.run(
["/usr/sbin/nft", "-j", "list", "table", family, table],
check=True,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError:
logging.debug(f"Heal: Table not present, skip flush ({family} {table}).")
continue
data = json.loads(res.stdout or "{}")
set_targets = []
for item in data.get("nftables", []):
nft_set = item.get("set")
if not isinstance(nft_set, dict):
continue
set_name = nft_set.get("name")
set_handle = nft_set.get("handle")
if not isinstance(set_name, str):
continue
if self.managed_sets:
if set_name in self.managed_sets:
set_targets.append((set_name, set_handle))
elif set_name.endswith("-cscli"):
set_targets.append((set_name, set_handle))
for set_name, set_handle in set_targets:
try:
subprocess.run(
["/usr/sbin/nft", "flush", "set", family, table, set_name],
check=True,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as e:
stderr = (e.stderr or "").strip()
syntax_error = "syntax error" in stderr.lower()
if syntax_error and isinstance(set_handle, int):
try:
subprocess.run(
[
"/usr/sbin/nft",
"flush",
"set",
family,
table,
"handle",
str(set_handle),
],
check=True,
capture_output=True,
text=True,
)
continue
except subprocess.CalledProcessError as handle_err:
handle_stderr = (handle_err.stderr or "").strip()
logging.warning(
"Heal: Failed to flush set "
f"({family} {table} {set_name}, handle={set_handle}): "
f"{handle_stderr or handle_err}"
)
continue
logging.warning(
"Heal: Failed to flush set "
f"({family} {table} {set_name}): {stderr or e}"
)
def reconcile(self, baseline_truth=None):
"""
Compares LAPI decisions (the truth) with the kernel's nft sets.
baseline_truth: decision values from an earlier reconcile. Values whose LAPI
membership changed since then (added or removed) are left out of the drift:
the bouncer applies such changes on its next poll, so a post-heal check would
otherwise blame the heal for a decision issued after it started. They are
returned in drift["lapi_changed_values"] and checked again by the next audit.
"""
truth_map = self.get_remote_lapi_truth() truth_map = self.get_remote_lapi_truth()
reality_map = self.get_kernel_state() reality_map = self.get_kernel_state()
truth_set = set(truth_map.keys()) truth_set = set(truth_map.keys())
reality_set = set(reality_map.keys()) reality_set = set(reality_map.keys())
self.last_truth_values = frozenset(truth_set)
changed = set() if baseline_truth is None else truth_set ^ set(baseline_truth)
missing, extra, unenforceable_ranges = self._match_collapsed_ranges(
sorted(truth_set - reality_set),
reality_set,
reality_set - truth_set,
)
if self.range_enforcer:
unenforceable_ranges = self.range_enforcer.sync(
{value: meta for value, meta in truth_map.items() if self._is_range(value)}
)
if unenforceable_ranges:
logging.warning(
"Range decisions not enforced by the range table "
f"(count={len(unenforceable_ranges)}) "
f"ranges={self._preview_values(unenforceable_ranges)}"
)
elif unenforceable_ranges:
logging.warning(
"Range decisions not enforced: the nft set holds only their network "
"address (it lacks the interval flag), so a bouncer restart cannot "
f"fix them (count={len(unenforceable_ranges)}) "
f"ranges={self._preview_values(unenforceable_ranges)}"
)
if truth_set != reality_set: lapi_changed = sorted(value for value in [*missing, *extra] if value in changed)
logging.warning("Desync: IP Membership mismatch.") if lapi_changed:
return False, len(reality_set) missing = [value for value in missing if value not in changed]
extra = [value for value in extra if value not in changed]
logging.info(
"Not counted as drift: LAPI decisions changed since the baseline "
f"(count={len(lapi_changed)}); the bouncer applies them on its next poll "
f"and the next audit checks them. values={self._preview_values(lapi_changed)}"
)
for ip, duration_str in truth_map.items(): if missing or extra:
siem_seconds = self.parse_duration(duration_str) drift = {
kernel_seconds = reality_map.get(ip, 0) / 1000 # Convert ms to s "reason": "membership_mismatch",
"lapi_changed_values": lapi_changed,
"missing_count": len(missing),
"extra_count": len(extra),
"metadata_drift_count": 0,
"fingerprint": self._fingerprint_drift(missing, extra, []),
"unenforceable_ranges": unenforceable_ranges,
}
logging.warning(
"Desync: IP membership mismatch "
f"(missing={drift['missing_count']}, extra={drift['extra_count']}) "
f"missing_values={self._preview_values(missing)} "
f"extra_values={self._preview_values(extra)}"
)
return False, len(reality_set), drift
if siem_seconds > 86400: # If SIEM target is > 24h metadata_drift = []
if kernel_seconds < 18000: # And kernel has < 5h left now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
logging.warning(f"Metadata Drift: {ip} needs {duration_str}, but kernel only has {int(kernel_seconds/3600)}h left.")
return False, len(reality_map)
return True, len(reality_map) for ip, decision_meta in truth_map.items():
if ip in changed:
continue
siem_seconds = self._expected_remaining_seconds(decision_meta, now_epoch)
if siem_seconds <= 0:
continue
kernel_raw = reality_map.get(ip)
kernel_seconds = self._normalize_kernel_remaining_seconds(
kernel_raw,
siem_seconds,
)
if kernel_seconds is None:
continue
if self._has_ttl_drift(siem_seconds, kernel_seconds):
metadata_drift.append(ip)
logging.warning(
"Metadata Drift detail "
f"ip={ip} expected_s={int(siem_seconds)} "
f"kernel_s={int(kernel_seconds)} kernel_raw={kernel_raw} "
f"ratio={kernel_seconds / siem_seconds:.2f} "
f"kernel_sources={json.dumps(self._last_kernel_sources.get(ip, []))} "
f"lapi_decisions={json.dumps(self._last_decisions.get(ip, []))}"
)
if metadata_drift:
drift = {
"reason": "metadata_drift",
"lapi_changed_values": lapi_changed,
"missing_count": 0,
"extra_count": 0,
"metadata_drift_count": len(metadata_drift),
"fingerprint": self._fingerprint_drift([], [], metadata_drift),
"unenforceable_ranges": unenforceable_ranges,
}
logging.warning(
"Metadata Drift detected "
f"(count={drift['metadata_drift_count']})."
)
return False, len(reality_map), drift
drift = {
"reason": "in_sync",
"lapi_changed_values": lapi_changed,
"missing_count": 0,
"extra_count": 0,
"metadata_drift_count": 0,
"fingerprint": "",
"unenforceable_ranges": unenforceable_ranges,
}
return True, len(reality_map), drift
def _match_collapsed_ranges(self, missing, kernel_values, extra):
"""
Pairs LAPI range decisions with the bare network address that a set without
the interval flag stores in their place. A restart re-adds that same address,
so these ranges are reported apart from drift rather than healed.
Returns (missing, extra, unenforceable_ranges) with the paired values removed.
A full-length prefix (/32, /128) stored as its address is fully enforced, so
it is dropped from missing without being reported.
"""
remaining_missing = []
remaining_extra = set(extra)
unenforceable_ranges = []
for value in missing:
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError:
remaining_missing.append(value)
continue
address = str(network.network_address)
if address not in kernel_values:
remaining_missing.append(value)
continue
remaining_extra.discard(address)
if network.prefixlen < network.max_prefixlen:
unenforceable_ranges.append(value)
return remaining_missing, sorted(remaining_extra), unenforceable_ranges
@staticmethod
def _is_range(value):
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError:
return False
return network.prefixlen < network.max_prefixlen
def _preview_values(self, values, limit=10):
shown = ",".join(str(v) for v in values[:limit])
if len(values) > limit:
shown += f",+{len(values) - limit} more"
return f"[{shown}]"
def _fingerprint_drift(self, missing, extra, metadata_drift):
payload = {
"missing": sorted(missing),
"extra": sorted(extra),
"metadata_drift": sorted(metadata_drift),
}
digest = hashlib.sha256(
json.dumps(payload, sort_keys=True).encode("utf-8")
).hexdigest()
return digest[:16]
+381
View File
@@ -0,0 +1,381 @@
import logging
import os
from dataclasses import dataclass
DEFAULT_LOG_PATH = "/root/threat-engine-agent/logs/threat-agent.log"
DEFAULT_STATE_FILE = "/root/threat-engine-agent/threat-agent-state.json"
DEFAULT_CHECK_INTERVAL = 600
DEFAULT_CHECK_JITTER_PCT = 0.10
DEFAULT_HEAL_VERIFY_DELAY = 5
DEFAULT_HEAL_MIN_INTERVAL = 900
DEFAULT_MEMBERSHIP_RECHECK_DELAY = 30
DEFAULT_CONFIG_PATH = "config.yaml"
DEFAULT_NODE_NAME = "Unknown Node"
DEFAULT_ENFORCEMENT_TARGETS = (("ip", "crowdsec"), ("ip6", "crowdsec6"))
DEFAULT_RANGES_TABLE = "crowdsec-ranges"
DEFAULT_RANGES_MIN_PREFIX_V4 = 16
DEFAULT_RANGES_MIN_PREFIX_V6 = 32
@dataclass(frozen=True)
class RuntimeSettings:
node_name: str
log_path: str
state_file: str
check_interval: int
check_jitter_pct: float
heal_verify_delay: int
heal_min_interval: int
enforcement_targets: tuple[tuple[str, str], ...]
enforcement_sets: tuple[str, ...]
config_path: str
membership_recheck_delay: int = DEFAULT_MEMBERSHIP_RECHECK_DELAY
ranges_enabled: bool = False
ranges_table: str = DEFAULT_RANGES_TABLE
ranges_min_prefix_v4: int = DEFAULT_RANGES_MIN_PREFIX_V4
ranges_min_prefix_v6: int = DEFAULT_RANGES_MIN_PREFIX_V6
@dataclass(frozen=True)
class ValidationIssue:
level: str # ERROR | WARN
message: str
def _parse_scalar(value):
value = value.strip()
if value.startswith(("'", '"')) and value.endswith(("'", '"')) and len(value) >= 2:
return value[1:-1]
if value.lower() == "true":
return True
if value.lower() == "false":
return False
try:
return int(value)
except ValueError:
return value
def _load_config_minimal(config_path):
"""
Minimal parser for simple two-level YAML mappings.
Supports the current config.yaml structure without external deps.
"""
config = {}
current_section = None
current_list_key = None
with open(config_path, "r") as f:
for raw_line in f:
line = raw_line.split("#", 1)[0].rstrip()
if not line.strip():
continue
if not line.startswith(" "):
if ":" not in line:
continue
key, value = line.split(":", 1)
key = key.strip()
value = value.strip()
if value == "":
config[key] = {}
current_section = key
current_list_key = None
else:
config[key] = _parse_scalar(value)
current_section = None
current_list_key = None
continue
if current_section is None:
continue
stripped = line.strip()
if stripped.startswith("- "):
if current_list_key:
config[current_section].setdefault(current_list_key, []).append(
_parse_scalar(stripped[2:].strip())
)
continue
if ":" not in stripped:
continue
key, value = stripped.split(":", 1)
key = key.strip()
value = value.strip()
if value == "":
config[current_section][key] = []
current_list_key = key
else:
config[current_section][key] = _parse_scalar(value)
current_list_key = None
return config
def load_config(config_path):
"""
Loads YAML config when available. Falls back to empty config.
"""
try:
import yaml # Local import so runtime still works without PyYAML
except ImportError:
try:
return _load_config_minimal(config_path)
except FileNotFoundError:
return {}
except Exception as e:
logging.warning(f"Failed to read config file '{config_path}': {e}")
return {}
try:
with open(config_path, "r") as f:
return yaml.safe_load(f) or {}
except FileNotFoundError:
return {}
except Exception as e:
logging.warning(f"Failed to read config file '{config_path}': {e}")
return {}
def cfg_get(config, *keys, default=None):
cur = config
for key in keys:
if not isinstance(cur, dict):
return default
cur = cur.get(key)
return default if cur is None else cur
def as_int(value, default):
try:
return int(value)
except (TypeError, ValueError):
return default
def as_float(value, default):
try:
return float(value)
except (TypeError, ValueError):
return default
def _as_string_list(value):
if isinstance(value, list):
return [str(item).strip() for item in value if str(item).strip()]
if isinstance(value, str):
return [item.strip() for item in value.split(",") if item.strip()]
return []
def _resolve_enforcement_targets(config):
targets_cfg = cfg_get(config, "enforcement", "targets")
targets = []
if isinstance(targets_cfg, list):
for item in targets_cfg:
if not isinstance(item, dict):
continue
family = str(item.get("family", "")).strip()
table = str(item.get("table", "")).strip()
if family and table:
targets.append((family, table))
if targets:
return tuple(targets)
table_v4 = str(cfg_get(config, "enforcement", "table", default="crowdsec")).strip() or "crowdsec"
table_v6 = str(cfg_get(config, "enforcement", "table6", default="crowdsec6")).strip() or "crowdsec6"
families = _as_string_list(cfg_get(config, "enforcement", "families"))
if not families:
return (("ip", table_v4), ("ip6", table_v6))
resolved = []
for family in families:
if family == "ip":
resolved.append((family, table_v4))
elif family == "ip6":
resolved.append((family, table_v6))
elif family == "inet":
resolved.append((family, table_v4))
return tuple(resolved) if resolved else DEFAULT_ENFORCEMENT_TARGETS
def _resolve_enforcement_sets(config):
return tuple(_as_string_list(cfg_get(config, "enforcement", "sets")))
def setup_logging(log_path):
os.makedirs(os.path.dirname(os.path.abspath(log_path)), exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename=log_path,
force=True,
)
def load_runtime_settings():
config_path = os.getenv("THREAT_AGENT_CONFIG", DEFAULT_CONFIG_PATH)
config = load_config(config_path)
node_name = os.getenv(
"SERVER_NAME",
cfg_get(config, "agent", "node_name", default=DEFAULT_NODE_NAME),
)
log_path = os.getenv(
"LOG_PATH",
cfg_get(config, "agent", "log_path", default=DEFAULT_LOG_PATH),
)
state_file = os.getenv(
"STATE_FILE",
cfg_get(config, "agent", "state_file", default=DEFAULT_STATE_FILE),
)
check_interval = as_int(
os.getenv("CHECK_INTERVAL", cfg_get(config, "agent", "check_interval")),
DEFAULT_CHECK_INTERVAL,
)
check_jitter_pct = as_float(
os.getenv("CHECK_JITTER_PCT", cfg_get(config, "agent", "check_jitter_pct")),
DEFAULT_CHECK_JITTER_PCT,
)
check_jitter_pct = min(max(check_jitter_pct, 0.0), 0.90)
heal_verify_delay = as_int(
os.getenv(
"HEAL_VERIFY_DELAY",
cfg_get(config, "agent", "heal_verify_delay"),
),
DEFAULT_HEAL_VERIFY_DELAY,
)
heal_min_interval = as_int(
os.getenv(
"HEAL_MIN_INTERVAL",
cfg_get(config, "agent", "heal_min_interval"),
),
DEFAULT_HEAL_MIN_INTERVAL,
)
membership_recheck_delay = as_int(
os.getenv(
"MEMBERSHIP_RECHECK_DELAY",
cfg_get(config, "agent", "membership_recheck_delay"),
),
DEFAULT_MEMBERSHIP_RECHECK_DELAY,
)
enforcement_targets = _resolve_enforcement_targets(config)
enforcement_sets = _resolve_enforcement_sets(config)
ranges_enabled = cfg_get(config, "ranges", "enabled", default=False) is True
ranges_table = (
str(cfg_get(config, "ranges", "table", default=DEFAULT_RANGES_TABLE)).strip()
)
ranges_min_prefix_v4 = as_int(
cfg_get(config, "ranges", "min_prefix_v4"), DEFAULT_RANGES_MIN_PREFIX_V4
)
ranges_min_prefix_v6 = as_int(
cfg_get(config, "ranges", "min_prefix_v6"), DEFAULT_RANGES_MIN_PREFIX_V6
)
return RuntimeSettings(
node_name=node_name,
log_path=log_path,
state_file=state_file,
check_interval=check_interval,
check_jitter_pct=check_jitter_pct,
heal_verify_delay=heal_verify_delay,
heal_min_interval=heal_min_interval,
enforcement_targets=enforcement_targets,
enforcement_sets=enforcement_sets,
config_path=config_path,
membership_recheck_delay=membership_recheck_delay,
ranges_enabled=ranges_enabled,
ranges_table=ranges_table,
ranges_min_prefix_v4=ranges_min_prefix_v4,
ranges_min_prefix_v6=ranges_min_prefix_v6,
)
def validate_runtime_settings(settings):
issues = []
if settings.check_interval < 1:
issues.append(
ValidationIssue(
"ERROR",
f"check_interval must be >= 1 (got {settings.check_interval})",
)
)
if settings.heal_verify_delay < 0:
issues.append(
ValidationIssue(
"ERROR",
f"heal_verify_delay must be >= 0 (got {settings.heal_verify_delay})",
)
)
if settings.heal_min_interval < 0:
issues.append(
ValidationIssue(
"ERROR",
f"heal_min_interval must be >= 0 (got {settings.heal_min_interval})",
)
)
if settings.membership_recheck_delay < 0:
issues.append(
ValidationIssue(
"ERROR",
"membership_recheck_delay must be >= 0 "
f"(got {settings.membership_recheck_delay})",
)
)
if not settings.enforcement_targets:
issues.append(
ValidationIssue("ERROR", "At least one enforcement target is required.")
)
for target in settings.enforcement_targets:
if (
not isinstance(target, tuple)
or len(target) != 2
or not all(isinstance(part, str) and part.strip() for part in target)
):
issues.append(
ValidationIssue(
"ERROR",
f"Malformed enforcement target: {target!r}",
)
)
if settings.ranges_enabled:
if not settings.ranges_table:
issues.append(ValidationIssue("ERROR", "ranges.table must not be empty."))
if not 1 <= settings.ranges_min_prefix_v4 <= 32:
issues.append(
ValidationIssue(
"ERROR",
"ranges.min_prefix_v4 must be within [1, 32] "
f"(got {settings.ranges_min_prefix_v4})",
)
)
if not 1 <= settings.ranges_min_prefix_v6 <= 128:
issues.append(
ValidationIssue(
"ERROR",
"ranges.min_prefix_v6 must be within [1, 128] "
f"(got {settings.ranges_min_prefix_v6})",
)
)
if settings.check_jitter_pct < 0.0 or settings.check_jitter_pct > 0.90:
issues.append(
ValidationIssue(
"WARN",
f"check_jitter_pct should be between 0.0 and 0.90 (got {settings.check_jitter_pct})",
)
)
if not os.path.isabs(settings.state_file):
issues.append(
ValidationIssue(
"WARN",
f"state_file is not absolute: {settings.state_file}",
)
)
return issues
+9 -2
View File
@@ -1,10 +1,17 @@
agent: agent:
node_name: "zephyrus" node_name: "zephyrus"
check_interval: 600 # 10 minutes check_interval: 600 # 10 minutes
check_jitter_pct: 0.10
heal_verify_delay: 5
heal_min_interval: 900
membership_recheck_delay: 30 # 0 disables the re-check
log_path: "/root/threat-engine-agent/logs/threat-agent.log" log_path: "/root/threat-engine-agent/logs/threat-agent.log"
state_file: "/root/threat-engine-agent/threat-agent-state.json"
enforcement: enforcement:
table: "crowdsec" table: "crowdsec"
table6: "crowdsec6"
sets: sets:
- "0.0.0.0/0-cscli" - "crowdsec-blacklists-cscli"
- "crowdsec-blacklists" - "crowdsec-blacklists-crowdsec"
- "crowdsec6-blacklists-cscli"
+194
View File
@@ -0,0 +1,194 @@
import json
import os
import tempfile
import subprocess
from dataclasses import dataclass
@dataclass(frozen=True)
class CheckResult:
name: str
status: str # PASS | WARN | FAIL
detail: str
def _run_cmd(cmd, timeout=20):
return subprocess.run(
cmd,
check=True,
capture_output=True,
text=True,
timeout=timeout,
)
def check_runtime_settings(settings):
if settings.check_interval < 1:
return CheckResult(
"runtime_settings",
"FAIL",
f"check_interval must be >= 1 (got {settings.check_interval})",
)
if settings.check_jitter_pct < 0 or settings.check_jitter_pct > 0.90:
return CheckResult(
"runtime_settings",
"FAIL",
f"check_jitter_pct must be within [0.0, 0.90] (got {settings.check_jitter_pct})",
)
if not settings.enforcement_targets:
return CheckResult("runtime_settings", "FAIL", "No enforcement targets configured.")
return CheckResult(
"runtime_settings",
"PASS",
(
f"check_interval={settings.check_interval}s "
f"check_jitter_pct={settings.check_jitter_pct:.2f} "
f"targets={len(settings.enforcement_targets)}"
),
)
def check_cscli_json():
try:
res = _run_cmd(["/usr/bin/cscli", "decisions", "list", "-a", "-o", "json"])
payload = json.loads(res.stdout or "[]")
if isinstance(payload, list):
return CheckResult("cscli_json", "PASS", f"Parsed {len(payload)} top-level entries.")
if isinstance(payload, dict):
return CheckResult("cscli_json", "PASS", "Parsed JSON object payload.")
return CheckResult("cscli_json", "FAIL", "Unexpected JSON type from cscli.")
except subprocess.CalledProcessError as e:
stderr = (e.stderr or "").strip()
return CheckResult("cscli_json", "FAIL", f"Command failed: {stderr or e}")
except json.JSONDecodeError as e:
return CheckResult("cscli_json", "FAIL", f"Invalid JSON output: {e}")
except Exception as e:
return CheckResult("cscli_json", "FAIL", f"Unexpected error: {e}")
def check_nft_tables(settings):
failures = []
summaries = []
for family, table in settings.enforcement_targets:
try:
res = _run_cmd(["/usr/sbin/nft", "-j", "list", "table", family, table])
data = json.loads(res.stdout or "{}")
set_count = sum(
1 for item in data.get("nftables", []) if isinstance(item.get("set"), dict)
)
summaries.append(f"{family} {table} ({set_count} sets)")
except Exception as e:
failures.append(f"{family} {table}: {e}")
if failures:
return CheckResult("nft_tables", "FAIL", "; ".join(failures))
return CheckResult("nft_tables", "PASS", ", ".join(summaries))
def check_range_table(settings):
if not settings.ranges_enabled:
return CheckResult("range_table", "PASS", "Range enforcement disabled.")
try:
res = _run_cmd(["/usr/sbin/nft", "-j", "list", "table", "inet", settings.ranges_table])
data = json.loads(res.stdout or "{}")
set_names = {
item["set"].get("name")
for item in data.get("nftables", [])
if isinstance(item.get("set"), dict)
}
missing = {"ranges-v4", "ranges-v6"} - set_names
if missing:
return CheckResult(
"range_table",
"FAIL",
f"inet {settings.ranges_table} lacks sets: {', '.join(sorted(missing))}",
)
return CheckResult("range_table", "PASS", f"inet {settings.ranges_table} present.")
except subprocess.CalledProcessError:
return CheckResult(
"range_table",
"WARN",
f"inet {settings.ranges_table} not found; the agent creates it on its first audit.",
)
except Exception as e:
return CheckResult("range_table", "FAIL", f"Unexpected error: {e}")
def check_state_paths(settings):
state_dir = os.path.dirname(os.path.abspath(settings.state_file))
history_file = os.path.splitext(settings.state_file)[0] + ".history"
history_dir = os.path.dirname(os.path.abspath(history_file))
try:
os.makedirs(state_dir, exist_ok=True)
os.makedirs(history_dir, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=state_dir, prefix="doctor-", delete=True):
pass
return CheckResult("state_paths", "PASS", f"Writable: {state_dir}")
except Exception as e:
return CheckResult("state_paths", "FAIL", f"Path check failed: {e}")
def check_systemctl_restart_capability():
if os.geteuid() != 0:
return CheckResult(
"systemctl_restart_capability",
"WARN",
"Not running as root; bouncer restart may fail.",
)
try:
res = _run_cmd(
[
"systemctl",
"show",
"crowdsec-firewall-bouncer",
"--property=LoadState",
"--property=CanStart",
"--value",
]
)
lines = [line.strip() for line in (res.stdout or "").splitlines() if line.strip()]
load_state = lines[0] if len(lines) >= 1 else ""
can_start = lines[1] if len(lines) >= 2 else ""
if load_state == "not-found":
return CheckResult(
"systemctl_restart_capability",
"FAIL",
"crowdsec-firewall-bouncer unit not found.",
)
if can_start.lower() == "no":
return CheckResult(
"systemctl_restart_capability",
"FAIL",
"systemd reports CanStart=no for crowdsec-firewall-bouncer.",
)
return CheckResult(
"systemctl_restart_capability",
"PASS",
f"LoadState={load_state or 'unknown'} CanStart={can_start or 'unknown'}",
)
except Exception as e:
return CheckResult(
"systemctl_restart_capability",
"WARN",
f"Could not verify via systemctl: {e}",
)
def run_doctor(settings, output=print):
checks = [
check_runtime_settings(settings),
check_cscli_json(),
check_nft_tables(settings),
check_range_table(settings),
check_state_paths(settings),
check_systemctl_restart_capability(),
]
output("Threat Engine Agent doctor results:")
for item in checks:
output(f"[{item.status}] {item.name}: {item.detail}")
failed = [item for item in checks if item.status == "FAIL"]
warned = [item for item in checks if item.status == "WARN"]
output(f"Summary: {len(failed)} failed, {len(warned)} warnings, {len(checks)} total.")
return len(failed) == 0
+211
View File
@@ -0,0 +1,211 @@
import logging
import os
import time
from datetime import datetime, timedelta, timezone
def _read_last_heal_line(history_file, chunk_size=4096, max_scan_bytes=262144):
"""
Returns the most recent line containing 'HEAL:' by scanning from file tail.
Falls back to a full forward scan if no marker is found in the tail window.
"""
file_size = os.path.getsize(history_file)
if file_size <= 0:
return None
with open(history_file, "rb") as f:
pos = file_size
scanned = 0
buffer = b""
while pos > 0 and scanned < max_scan_bytes:
to_read = min(chunk_size, pos, max_scan_bytes - scanned)
pos -= to_read
f.seek(pos)
chunk = f.read(to_read)
buffer = chunk + buffer
scanned += to_read
lines = buffer.splitlines()
if pos > 0 and lines:
# Drop potential partial line at the chunk boundary.
lines = lines[1:]
for raw_line in reversed(lines):
line = raw_line.decode("utf-8", errors="replace").strip()
if "HEAL:" in line:
return line
# Fallback for unusual files where recent tail has no HEAL marker.
last_heal_line = None
with open(history_file) as f:
for line in f:
if "HEAL:" in line:
last_heal_line = line.strip()
return last_heal_line
def should_heal(history_file, drift_fingerprint, min_interval=900):
"""
Prevents heal flapping by suppressing repeated no-op heals.
"""
try:
if not os.path.exists(history_file):
return True
last = _read_last_heal_line(history_file)
if not last:
return True
ts_str, msg = last.split(" - ", 1)
parsed_last_time = datetime.fromisoformat(ts_str)
if parsed_last_time.tzinfo is None:
# Legacy history lines were written as local naive timestamps.
local_tz = datetime.now().astimezone().tzinfo or timezone.utc
last_time = parsed_last_time.replace(tzinfo=local_tz).astimezone(timezone.utc)
else:
last_time = parsed_last_time.astimezone(timezone.utc)
last_fingerprint = ""
marker = "drift_fingerprint="
if marker in msg:
last_fingerprint = msg.split(marker, 1)[1].split()[0].strip()
if not drift_fingerprint:
return True
# If healed recently AND nothing changed, suppress
if datetime.now(timezone.utc) - last_time < timedelta(seconds=min_interval):
if last_fingerprint and last_fingerprint == drift_fingerprint:
logging.warning(
"Heal suppressed (recent identical drift fingerprint): "
f"the heal at {last_time.isoformat()} did not hold "
f"(fingerprint={drift_fingerprint})."
)
return False
return True
except Exception as e:
logging.error(f"Heal gate failed open: {e}")
return True
def recheck_membership_mismatch(auditor, result, recheck_delay, wait=time.sleep):
"""
Re-audits after a short delay when the finding is a membership mismatch,
so decisions the bouncer has not applied yet are not treated as drift.
"""
is_synced, _count, drift = result
if is_synced or recheck_delay <= 0:
return result
if (drift or {}).get("reason") != "membership_mismatch":
return result
logging.warning(
f"Membership mismatch seen; re-checking in {recheck_delay}s before healing."
)
wait(recheck_delay)
rechecked = auditor.reconcile()
if rechecked[0]:
logging.info("Membership mismatch cleared on re-check; no heal needed.")
else:
logging.warning("Drift persisted on re-check.")
return rechecked
def execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay):
"""
Executes heal + post-heal verification and persists reporter state.
"""
drift = drift or {}
# The decisions the drift was found against. Verification is judged against
# them, so a decision issued after the heal started (which the bouncer only
# applies on its next poll) is not counted as a failed heal.
baseline_truth = getattr(auditor, "last_truth_values", None)
if hasattr(auditor, "heal_with_drift"):
heal_ok = auditor.heal_with_drift(drift)
else:
heal_ok = auditor.heal()
heal_result = "restart_failed"
post_drift = {
"reason": "not_verified",
"missing_count": 0,
"extra_count": 0,
"metadata_drift_count": 0,
"fingerprint": "",
}
if heal_ok:
logging.info(
f"Post-heal verification in {heal_verify_delay}s "
f"(pre_fingerprint={drift.get('fingerprint', '')})."
)
time.sleep(heal_verify_delay)
try:
if baseline_truth is None:
post_is_synced, post_count, post_drift = auditor.reconcile()
else:
post_is_synced, post_count, post_drift = auditor.reconcile(baseline_truth=baseline_truth)
heal_result = "success" if post_is_synced else "failed"
verify_error = None if post_is_synced else "Post-heal verification failed"
reporter.update_status(
post_is_synced,
post_count,
last_error=verify_error,
missing_count=post_drift.get("missing_count", 0),
extra_count=post_drift.get("extra_count", 0),
metadata_drift_count=post_drift.get("metadata_drift_count", 0),
last_drift_fingerprint=post_drift.get("fingerprint", ""),
heal_result=heal_result,
unenforceable_range_count=len(post_drift.get("unenforceable_ranges", [])),
)
logging.warning(
"Post-heal verification result "
f"result={heal_result} pre={drift.get('fingerprint', '')} "
f"post={post_drift.get('fingerprint', '')} "
f"missing={post_drift.get('missing_count', 0)} "
f"extra={post_drift.get('extra_count', 0)} "
f"metadata={post_drift.get('metadata_drift_count', 0)} "
f"lapi_changed={len(post_drift.get('lapi_changed_values', []))}"
)
except Exception as e:
heal_result = "verify_error"
reporter.update_status(
False,
count,
last_error=f"Post-heal verify error: {e}",
missing_count=0,
extra_count=0,
metadata_drift_count=0,
last_drift_fingerprint=drift.get("fingerprint", ""),
heal_result=heal_result,
)
post_drift = {
"reason": "verify_error",
"missing_count": 0,
"extra_count": 0,
"metadata_drift_count": 0,
"fingerprint": "",
}
logging.error(
"Post-heal verification crashed "
f"(pre_fingerprint={drift.get('fingerprint', '')}): {e}"
)
else:
reporter.update_status(
False,
count,
last_error="Bouncer restart failed",
missing_count=drift.get("missing_count", 0),
extra_count=drift.get("extra_count", 0),
metadata_drift_count=drift.get("metadata_drift_count", 0),
last_drift_fingerprint=drift.get("fingerprint", ""),
heal_result=heal_result,
)
logging.error(
f"Heal restart failed; skipping verification "
f"(pre_fingerprint={drift.get('fingerprint', '')})."
)
return heal_result, post_drift
+207
View File
@@ -0,0 +1,207 @@
import logging
import random
import signal
import threading
try:
from dotenv import load_dotenv
except ImportError:
def load_dotenv():
return None
from auditor import FirewallAuditor
from config import load_runtime_settings, setup_logging, validate_runtime_settings
from healing import execute_heal_and_verify, recheck_membership_mismatch, should_heal
from ranges import RangeEnforcer
from reporter import LocalStateReporter
def compute_sleep_interval(base_interval, jitter_pct):
base = max(1.0, float(base_interval))
jitter = min(max(float(jitter_pct), 0.0), 0.90)
if jitter == 0:
return base
factor = 1.0 + random.uniform(-jitter, jitter)
return max(1.0, base * factor)
def main():
"""
The Orchestrator: Links Audit findings to the State Reporter.
"""
load_dotenv()
settings = load_runtime_settings()
setup_logging(settings.log_path)
issues = validate_runtime_settings(settings)
for issue in issues:
if issue.level == "ERROR":
logging.error(f"Config validation: {issue.message}")
else:
logging.warning(f"Config validation: {issue.message}")
if any(issue.level == "ERROR" for issue in issues):
raise RuntimeError("Configuration validation failed; refusing to start.")
targets_desc = ", ".join(
f"{family}:{table}" for family, table in settings.enforcement_targets
)
sets_mode = "explicit" if settings.enforcement_sets else "auto(*-cscli)"
sets_desc = ", ".join(settings.enforcement_sets) if settings.enforcement_sets else "(none)"
logging.info(
"Effective config: "
f"node={settings.node_name} "
f"check_interval={settings.check_interval}s "
f"check_jitter_pct={settings.check_jitter_pct:.2f} "
f"heal_verify_delay={settings.heal_verify_delay}s "
f"heal_min_interval={settings.heal_min_interval}s "
f"membership_recheck_delay={settings.membership_recheck_delay}s "
f"state_file={settings.state_file} "
f"targets=[{targets_desc}] "
f"sets_mode={sets_mode} sets=[{sets_desc}] "
f"ranges_enabled={settings.ranges_enabled} ranges_table={settings.ranges_table} "
f"ranges_min_prefix=v4:/{settings.ranges_min_prefix_v4},"
f"v6:/{settings.ranges_min_prefix_v6}"
)
range_enforcer = None
if settings.ranges_enabled:
range_enforcer = RangeEnforcer(
table=settings.ranges_table,
min_prefix_v4=settings.ranges_min_prefix_v4,
min_prefix_v6=settings.ranges_min_prefix_v6,
)
auditor = FirewallAuditor(
targets=settings.enforcement_targets,
managed_sets=settings.enforcement_sets,
range_enforcer=range_enforcer,
)
auditor.log_enforcement_startup_state()
reporter = LocalStateReporter(
state_file=settings.state_file,
node_name=settings.node_name,
)
stop_event = threading.Event()
def _handle_stop_signal(signum, _frame):
sig_name = signal.Signals(signum).name
logging.info(f"Stop signal received: {sig_name}. Shutting down.")
stop_event.set()
signal.signal(signal.SIGTERM, _handle_stop_signal)
signal.signal(signal.SIGINT, _handle_stop_signal)
print(f"[*] Agent started. Check interval: {settings.check_interval}s")
logging.info(
f"Threat Engine Agent initialized on {settings.node_name}. "
f"config_path={settings.config_path} "
f"log_path={settings.log_path} state_file={settings.state_file} "
f"check_jitter_pct={settings.check_jitter_pct:.2f}"
)
while not stop_event.is_set():
try:
is_synced, count, drift = recheck_membership_mismatch(
auditor,
auditor.reconcile(),
settings.membership_recheck_delay,
wait=stop_event.wait,
)
if stop_event.is_set():
break
# Decide on the heal before recording the check, so a drift the gate
# suppresses is counted as such rather than silently lacking a heal.
heal_approved = is_synced or should_heal(
reporter.get_history_file(),
drift.get("fingerprint", ""),
min_interval=settings.heal_min_interval,
)
reporter.update_status(
is_synced,
count,
missing_count=drift.get("missing_count", 0),
extra_count=drift.get("extra_count", 0),
metadata_drift_count=drift.get("metadata_drift_count", 0),
last_drift_fingerprint=drift.get("fingerprint", ""),
checks_increment=1,
drift_events_increment=0 if is_synced else 1,
heal_suppressed=not heal_approved,
unenforceable_range_count=len(drift.get("unenforceable_ranges", [])),
)
unenforced_ranges = len(drift.get("unenforceable_ranges", []))
if is_synced and unenforced_ranges:
status_msg = (
f"Audit Success (degraded): {count} IPs in sync, "
f"{unenforced_ranges} range decision(s) not enforced."
)
elif is_synced:
status_msg = f"Audit Success: {count} IPs in sync."
else:
status_msg = (
f"DESYNC: kernel={count}, missing={drift['missing_count']}, "
f"extra={drift['extra_count']}, metadata={drift['metadata_drift_count']}. "
"Healing..."
)
print(f"[+] {status_msg}") # This will show up in your terminal!
if not is_synced:
logging.warning(
"Desync detected "
f"(kernel={count}, missing={drift['missing_count']}, "
f"extra={drift['extra_count']}, metadata={drift['metadata_drift_count']})."
)
if heal_approved:
logging.warning("Healing approved.")
heal_result, post_drift = execute_heal_and_verify(
auditor,
reporter,
count,
drift,
settings.heal_verify_delay,
)
reporter.log_heal_event(
count,
drift.get("missing_count", 0),
drift.get("extra_count", 0),
drift.get("metadata_drift_count", 0),
drift.get("fingerprint", ""),
drift.get("reason", "unknown"),
heal_result,
post_drift.get("fingerprint", ""),
)
else:
logging.warning("Healing skipped to prevent flapping.")
else:
logging.info(status_msg)
sleep_seconds = compute_sleep_interval(
settings.check_interval,
settings.check_jitter_pct,
)
print(f"[*] Sleeping for {sleep_seconds:.1f} seconds...")
stop_event.wait(sleep_seconds)
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 Exception as reporter_error:
logging.error(
"Reporter update failed during exception handling: "
f"{reporter_error}"
)
if stop_event.wait(60):
break
logging.info("Agent shutdown complete.")
if __name__ == "__main__":
main()
+221
View File
@@ -0,0 +1,221 @@
# threat-engine-agent/ranges.py
import datetime
import ipaddress
import json
import logging
import subprocess
NFT = "/usr/sbin/nft"
SET_V4 = "ranges-v4"
SET_V6 = "ranges-v6"
HOOKS = ("input", "forward")
CHAIN_PRIORITY = -10
class RangeEnforcer:
"""
Enforces LAPI range decisions that crowdsec-firewall-bouncer cannot: its nftables
mode strips the prefix and bans only the network address. Owns one dedicated
inet table holding interval sets and the drop rules that reference them.
"""
def __init__(self, table="crowdsec-ranges", min_prefix_v4=16, min_prefix_v6=32):
self.table = table
self.min_prefix = {4: int(min_prefix_v4), 6: int(min_prefix_v6)}
def sync(self, range_truth, now_epoch=None):
"""
Makes the range table match range_truth ({lapi_value: decision_meta}) and
returns the LAPI values that are not enforced afterwards.
"""
if now_epoch is None:
now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
desired, unenforced = self._desired_elements(range_truth, now_epoch)
current = self.read_elements()
script = self._ensure_table_script() + self._element_changes(desired, current)
try:
subprocess.run(
[NFT, "-f", "-"],
input="\n".join(script) + "\n",
capture_output=True,
text=True,
check=True,
)
except subprocess.CalledProcessError as e:
logging.error(
f"Range enforcement: nft update of inet {self.table} failed: "
f"{(e.stderr or '').strip() or e}"
)
enforced = self.read_elements()
for network, entry in desired.items():
covering = entry["covered_by"] or network
if covering not in enforced:
unenforced.extend(entry["values"])
return sorted(unenforced)
def read_elements(self):
"""Returns {network_str: expires_raw} for every element in the range sets."""
try:
res = subprocess.run(
[NFT, "-j", "list", "table", "inet", self.table],
capture_output=True,
text=True,
check=True,
)
except subprocess.CalledProcessError:
return {}
data = json.loads(res.stdout or "{}")
elements = {}
for item in data.get("nftables", []):
nft_set = item.get("set")
if not isinstance(nft_set, dict) or nft_set.get("name") not in (SET_V4, SET_V6):
continue
for e in nft_set.get("elem", []):
inner = e.get("elem", e) if isinstance(e, dict) else {"val": e}
key = element_key(inner.get("val"))
if key:
elements[key] = inner.get("expires")
return elements
def _desired_elements(self, range_truth, now_epoch):
"""
Maps each enforceable LAPI range to its normalized network. Overlapping
prefixes conflict in an interval set, so a range inside another desired
range is marked covered_by that supernet instead of being inserted.
"""
unenforced = []
desired = {}
for value, meta in range_truth.items():
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError:
continue
if network.prefixlen < self.min_prefix[network.version]:
logging.warning(
f"Range enforcement: refusing {value}; broader than "
f"/{self.min_prefix[network.version]} (min_prefix_v{network.version})."
)
unenforced.append(value)
continue
remaining = _remaining_seconds(meta, now_epoch)
if remaining == 0:
continue # Decision already expired.
entry = desired.setdefault(
str(network),
{"network": network, "values": [], "timeout": remaining, "covered_by": None},
)
entry["values"].append(value)
if entry["timeout"] is not None:
entry["timeout"] = None if remaining is None else max(entry["timeout"], remaining)
ordered = sorted(desired.values(), key=lambda entry: entry["network"].prefixlen)
for i, entry in enumerate(ordered):
for wider in ordered[:i]:
if (
wider["covered_by"] is None
and wider["network"].version == entry["network"].version
and wider["network"].prefixlen < entry["network"].prefixlen
and entry["network"].subnet_of(wider["network"])
):
entry["covered_by"] = str(wider["network"])
break
return desired, unenforced
def _ensure_table_script(self):
# Every statement is idempotent; flushing and re-adding the rules in the same
# transaction restores them if someone edited the chains, with no gap.
t = f"inet {self.table}"
script = [
f"add table {t}",
f"add set {t} {SET_V4} {{ type ipv4_addr; flags interval, timeout; }}",
f"add set {t} {SET_V6} {{ type ipv6_addr; flags interval, timeout; }}",
]
for hook in HOOKS:
script += [
f"add chain {t} {hook} {{ type filter hook {hook} priority {CHAIN_PRIORITY}; policy accept; }}",
f"flush chain {t} {hook}",
f"add rule {t} {hook} ip saddr @{SET_V4} drop",
f"add rule {t} {hook} ip6 saddr @{SET_V6} drop",
]
return script
def _element_changes(self, desired, current):
t = f"inet {self.table}"
wanted = {
network: entry for network, entry in desired.items() if entry["covered_by"] is None
}
script = []
for network, expires_raw in sorted(current.items()):
entry = wanted.get(network)
if entry is None or _needs_refresh(entry["timeout"], expires_raw):
script.append(f"delete element {t} {_set_for(network)} {{ {network} }}")
for network, entry in sorted(wanted.items()):
if network in current and not _needs_refresh(entry["timeout"], current[network]):
continue
timeout = f" timeout {entry['timeout']}s" if entry["timeout"] else ""
script.append(f"add element {t} {_set_for(network)} {{ {network}{timeout} }}")
return script
def element_key(val):
"""
Normalizes an nft JSON element value to a string: a prefix becomes "addr/len",
an address stays as-is, a range becomes "start-end". Returns None otherwise.
"""
if isinstance(val, str):
return val
if isinstance(val, dict):
prefix = val.get("prefix")
if isinstance(prefix, dict) and "addr" in prefix and "len" in prefix:
return f"{prefix['addr']}/{prefix['len']}"
bounds = val.get("range")
if isinstance(bounds, list) and len(bounds) == 2:
return f"{bounds[0]}-{bounds[1]}"
return None
def _set_for(element):
return SET_V6 if ":" in element else SET_V4
def _remaining_seconds(meta, now_epoch):
"""Seconds left on a decision: None if unknown, 0 if already expired."""
until_epoch = meta.get("until_epoch")
if until_epoch:
return max(0, int(until_epoch - now_epoch))
duration = str(meta.get("duration") or "").strip()
if duration.startswith("-"):
return 0
seconds = _parse_go_duration(duration)
return seconds or None
def _parse_go_duration(duration):
units = {"h": 3600, "m": 60, "s": 1, "d": 86400}
total = 0.0
number = ""
for ch in duration.lower():
if ch.isdigit() or ch == ".":
number += ch
elif ch in units and number:
total += float(number) * units[ch]
number = ""
else:
return 0
return int(total)
def _needs_refresh(desired_timeout, expires_raw):
"""True when the kernel element's remaining lifetime is far from the decision's."""
if desired_timeout is None:
return False
if not isinstance(expires_raw, (int, float)) or expires_raw <= 0:
return True
# nft reports expires in seconds or milliseconds depending on version.
remaining = min((expires_raw, expires_raw / 1000.0), key=lambda v: abs(v - desired_timeout))
return abs(remaining - desired_timeout) > max(300, desired_timeout * 0.05)
+236 -11
View File
@@ -3,29 +3,225 @@
import json import json
import os import os
import logging import logging
from datetime import datetime import time
from datetime import datetime, timezone
class LocalStateReporter: class LocalStateReporter:
""" """
Manages the health manifest on Triton. Manages the health manifest on Triton.
Acts as the 'Black Box' recorder for Argus to query. Acts as the 'Black Box' recorder for Argus to query.
""" """
def __init__(self, state_file="/root/threat-engine-agent/threat-agent-state.json"): def __init__(
self,
state_file="/root/threat-engine-agent/threat-agent-state.json",
node_name="unknown",
):
self.state_file = state_file self.state_file = state_file
self.node_name = node_name
self.started_at_epoch = time.time()
# Ensure the directory is writable # Ensure the directory is writable
os.makedirs(os.path.dirname(os.path.abspath(self.state_file)), exist_ok=True) 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): def _load_previous_state(self):
try:
with open(self.state_file, "r") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def _get_int(self, payload, key, default=0):
try:
return int(payload.get(key, default))
except Exception:
return default
def _normalize_hourly_buckets(self, previous):
raw = previous.get("_rolling_24h_buckets", previous.get("rolling_24h_buckets", {}))
if not isinstance(raw, dict):
return {}
normalized = {}
for hour_key, metrics in raw.items():
try:
hour = int(hour_key)
except Exception:
continue
if not isinstance(metrics, dict):
continue
normalized[str(hour)] = {
"drift_events": max(0, int(metrics.get("drift_events", 0))),
"drift_heal_attempts": max(0, int(metrics.get("drift_heal_attempts", 0))),
"heals": max(0, int(metrics.get("heals", 0))),
"heal_failures": max(0, int(metrics.get("heal_failures", 0))),
"heals_suppressed": max(0, int(metrics.get("heals_suppressed", 0))),
}
return normalized
def _roll_24h_counters(
self,
previous,
now_epoch,
drift_events_increment,
heal_result,
heal_suppressed=False,
):
current_hour = int(now_epoch // 3600)
min_hour = current_hour - 23
buckets = self._normalize_hourly_buckets(previous)
# Prune data outside rolling 24-hour window.
buckets = {
hour_key: metrics
for hour_key, metrics in buckets.items()
if int(hour_key) >= min_hour
}
hour_key = str(current_hour)
bucket = buckets.setdefault(
hour_key,
{
"drift_events": 0,
"drift_heal_attempts": 0,
"heals": 0,
"heal_failures": 0,
"heals_suppressed": 0,
},
)
bucket["drift_events"] += max(0, int(drift_events_increment))
if heal_result is not None:
bucket["drift_heal_attempts"] += 1
bucket["heals"] += 1
if heal_result != "success":
bucket["heal_failures"] += 1
if heal_suppressed:
bucket["heals_suppressed"] += 1
drift_events_24h = sum(v["drift_events"] for v in buckets.values())
drift_heal_attempts_24h = sum(v["drift_heal_attempts"] for v in buckets.values())
heals_24h = sum(v["heals"] for v in buckets.values())
heal_failures_24h = sum(v["heal_failures"] for v in buckets.values())
heals_suppressed_24h = sum(v["heals_suppressed"] for v in buckets.values())
return (
buckets,
drift_events_24h,
drift_heal_attempts_24h,
heals_24h,
heal_failures_24h,
heals_suppressed_24h,
)
def update_status(
self,
is_synced,
ban_count,
last_error=None,
missing_count=0,
extra_count=0,
metadata_drift_count=0,
last_drift_fingerprint="",
last_heal_result=None,
last_heal_timestamp=None,
checks_increment=0,
drift_events_increment=0,
heal_result=None,
heal_suppressed=False,
unenforceable_range_count=0,
):
""" """
Writes the current health snapshot to a JSON file. Writes the current health snapshot to a JSON file.
heal_suppressed marks a drift the heal gate skipped because the same drift was
healed moments ago, so every drift event is either a heal attempt or a suppressed heal.
unenforceable_range_count is the number of LAPI range decisions the kernel holds
only as a single address. They are not drift a heal can fix, so a node that is
otherwise in sync reports DEGRADED rather than HEALTHY.
""" """
previous = self._load_previous_state()
effective_heal_result = (
last_heal_result
if last_heal_result is not None
else previous.get("last_heal_result")
)
effective_last_heal_timestamp = (
last_heal_timestamp
if last_heal_timestamp is not None
else previous.get("last_heal_timestamp")
)
if heal_result is not None:
effective_heal_result = heal_result
effective_last_heal_timestamp = (
last_heal_timestamp
if last_heal_timestamp is not None
else datetime.now(timezone.utc).isoformat()
)
now_epoch = time.time()
checks_total = max(0, self._get_int(previous, "checks_total", 0))
checks_total += max(0, int(checks_increment))
drift_events_total = max(0, self._get_int(previous, "drift_events_total", 0))
drift_events_total += max(0, int(drift_events_increment))
heals_total = max(0, self._get_int(previous, "heals_total", 0))
heal_failures_total = max(0, self._get_int(previous, "heal_failures_total", 0))
drift_heal_attempts_total = max(
0, self._get_int(previous, "drift_heal_attempts_total", 0)
)
if heal_result is not None:
heals_total += 1
drift_heal_attempts_total += 1
if heal_result != "success":
heal_failures_total += 1
heals_suppressed_total = max(0, self._get_int(previous, "heals_suppressed_total", 0))
if heal_suppressed:
heals_suppressed_total += 1
(
rolling_24h_buckets,
drift_events_24h,
drift_heal_attempts_24h,
heals_24h,
heal_failures_24h,
heals_suppressed_24h,
) = self._roll_24h_counters(
previous=previous,
now_epoch=now_epoch,
drift_events_increment=drift_events_increment,
heal_result=heal_result,
heal_suppressed=heal_suppressed,
)
uptime_seconds = max(0, int(now_epoch - self.started_at_epoch))
status_data = { status_data = {
"node": "zephyrus", "node_name": self.node_name,
"last_check": datetime.now().isoformat(), "last_check": datetime.now(timezone.utc).isoformat(),
"status": "HEALTHY" if is_synced else "DESYNC_DETECTED", "status": self._status_label(is_synced, unenforceable_range_count),
"is_synced": is_synced, "is_synced": is_synced,
"kernel_ban_count": ban_count, "kernel_ban_count": ban_count,
"last_error": last_error "last_error": last_error,
"missing_count": missing_count,
"extra_count": extra_count,
"metadata_drift_count": metadata_drift_count,
"unenforceable_range_count": unenforceable_range_count,
"last_drift_fingerprint": last_drift_fingerprint,
"last_heal_result": effective_heal_result,
"last_heal_timestamp": effective_last_heal_timestamp,
"uptime_seconds": uptime_seconds,
"checks_total": checks_total,
"drift_events_total": drift_events_total,
"drift_heal_attempts_total": drift_heal_attempts_total,
"drift_events_24h": drift_events_24h,
"drift_heal_attempts_24h": drift_heal_attempts_24h,
"heals_24h": heals_24h,
"heal_failures_24h": heal_failures_24h,
"heals_total": heals_total,
"heal_failures_total": heal_failures_total,
"heals_suppressed_24h": heals_suppressed_24h,
"heals_suppressed_total": heals_suppressed_total,
"_rolling_24h_buckets": rolling_24h_buckets,
} }
try: try:
@@ -37,15 +233,44 @@ class LocalStateReporter:
except Exception as e: except Exception as e:
logging.error(f"Reporter: Failed to write state file: {e}") logging.error(f"Reporter: Failed to write state file: {e}")
def log_heal_event(self, gap_count): @staticmethod
def _status_label(is_synced, unenforceable_range_count):
if not is_synced:
return "DESYNC_DETECTED"
if unenforceable_range_count:
return "DEGRADED"
return "HEALTHY"
def get_history_file(self):
base, _ = os.path.splitext(self.state_file)
return f"{base}.history"
def log_heal_event(
self,
kernel_count,
missing_count,
extra_count,
metadata_drift_count,
drift_fingerprint,
reason,
heal_result,
post_drift_fingerprint,
):
""" """
Records a specific healing event in a persistent history log. Records a specific healing event in a persistent history log.
""" """
history_file = self.state_file.replace(".json", ".history") history_file = self.get_history_file()
timestamp = datetime.now().isoformat() timestamp = datetime.now(timezone.utc).isoformat()
try: try:
with open(history_file, 'a') as f: with open(history_file, 'a') as f:
f.write(f"{timestamp} - HEAL: Fixed desync of {gap_count} IPs\n") f.write(
f"{timestamp} - HEAL: reason={reason} "
f"kernel={kernel_count} missing={missing_count} "
f"extra={extra_count} metadata={metadata_drift_count} "
f"drift_fingerprint={drift_fingerprint} "
f"heal_result={heal_result} "
f"post_drift_fingerprint={post_drift_fingerprint}\n"
)
except Exception as e: except Exception as e:
logging.error(f"Reporter: Failed to write to history log: {e}") logging.error(f"Reporter: Failed to write to history log: {e}")
+1
View File
@@ -8,6 +8,7 @@ User=root
Group=root Group=root
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Environment="HOME=/root" Environment="HOME=/root"
EnvironmentFile=-/root/threat-engine-agent/.env
WorkingDirectory=/root/threat-engine-agent WorkingDirectory=/root/threat-engine-agent
ExecStart=/usr/bin/python3 agent.py ExecStart=/usr/bin/python3 agent.py
Restart=always Restart=always
+257
View File
@@ -0,0 +1,257 @@
import tempfile
import unittest
from datetime import datetime
from unittest.mock import patch
from healing import should_heal, execute_heal_and_verify, recheck_membership_mismatch
class FakeReporter:
def __init__(self):
self.update_calls = []
def update_status(self, is_synced, ban_count, last_error=None, **kwargs):
self.update_calls.append(
{
"is_synced": is_synced,
"ban_count": ban_count,
"last_error": last_error,
**kwargs,
}
)
class FakeAuditor:
def __init__(self, heal_ok=True, reconcile_result=None, reconcile_exception=None):
self.heal_ok = heal_ok
self.reconcile_result = reconcile_result
self.reconcile_exception = reconcile_exception
self.last_heal_drift = None
def heal(self):
return self.heal_ok
def heal_with_drift(self, drift):
self.last_heal_drift = drift
return self.heal_ok
def reconcile(self, **kwargs):
self.reconcile_kwargs = kwargs
if self.reconcile_exception:
raise self.reconcile_exception
return self.reconcile_result
class HealGateTests(unittest.TestCase):
def test_should_heal_suppresses_identical_recent_fingerprint(self):
now = datetime.now().isoformat()
with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp:
tmp.write(
f"{now} - HEAL: drift_fingerprint=abc123 heal_result=success post_drift_fingerprint=\n"
)
path = tmp.name
self.assertFalse(should_heal(path, "abc123", min_interval=900))
def test_should_heal_allows_different_fingerprint(self):
now = datetime.now().isoformat()
with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp:
tmp.write(
f"{now} - HEAL: drift_fingerprint=abc123 heal_result=success post_drift_fingerprint=\n"
)
path = tmp.name
self.assertTrue(should_heal(path, "xyz999", min_interval=900))
def test_should_heal_reads_recent_heal_from_tail(self):
now = datetime.now().isoformat()
with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp:
for idx in range(4000):
tmp.write(f"noise line {idx}\n")
tmp.write(
f"{now} - HEAL: drift_fingerprint=tail123 heal_result=success post_drift_fingerprint=\n"
)
path = tmp.name
self.assertFalse(should_heal(path, "tail123", min_interval=900))
def test_should_heal_handles_timezone_aware_history_timestamp(self):
now_utc = datetime.now().astimezone().astimezone().isoformat()
with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp:
tmp.write(
f"{now_utc} - HEAL: drift_fingerprint=aware123 heal_result=success post_drift_fingerprint=\n"
)
path = tmp.name
self.assertFalse(should_heal(path, "aware123", min_interval=900))
class PostHealVerificationTests(unittest.TestCase):
@patch("healing.time.sleep", return_value=None)
def test_execute_heal_and_verify_success(self, _sleep):
reporter = FakeReporter()
post_drift = {
"reason": "in_sync",
"missing_count": 0,
"extra_count": 0,
"metadata_drift_count": 0,
"fingerprint": "",
}
auditor = FakeAuditor(heal_ok=True, reconcile_result=(True, 12, post_drift))
heal_result, returned_post_drift = execute_heal_and_verify(
auditor,
reporter,
count=12,
drift={"fingerprint": "pre123"},
heal_verify_delay=0,
)
self.assertEqual("success", heal_result)
self.assertEqual(post_drift, returned_post_drift)
self.assertEqual(1, len(reporter.update_calls))
self.assertTrue(reporter.update_calls[0]["is_synced"])
self.assertEqual(12, reporter.update_calls[0]["ban_count"])
self.assertEqual("success", reporter.update_calls[0]["heal_result"])
self.assertEqual("", reporter.update_calls[0]["last_drift_fingerprint"])
self.assertEqual({"fingerprint": "pre123"}, auditor.last_heal_drift)
@patch("healing.time.sleep", return_value=None)
def test_execute_heal_and_verify_restart_failed(self, _sleep):
reporter = FakeReporter()
auditor = FakeAuditor(heal_ok=False, reconcile_result=(True, 0, {}))
heal_result, returned_post_drift = execute_heal_and_verify(
auditor,
reporter,
count=7,
drift={"fingerprint": "pre123"},
heal_verify_delay=0,
)
self.assertEqual("restart_failed", heal_result)
self.assertEqual("not_verified", returned_post_drift["reason"])
self.assertEqual(1, len(reporter.update_calls))
self.assertFalse(reporter.update_calls[0]["is_synced"])
self.assertEqual(7, reporter.update_calls[0]["ban_count"])
self.assertEqual("Bouncer restart failed", reporter.update_calls[0]["last_error"])
self.assertEqual("restart_failed", reporter.update_calls[0]["heal_result"])
@patch("healing.time.sleep", return_value=None)
def test_execute_heal_and_verify_verify_exception(self, _sleep):
reporter = FakeReporter()
auditor = FakeAuditor(heal_ok=True, reconcile_exception=RuntimeError("boom"))
heal_result, returned_post_drift = execute_heal_and_verify(
auditor,
reporter,
count=7,
drift={"fingerprint": "pre123"},
heal_verify_delay=0,
)
self.assertEqual("verify_error", heal_result)
self.assertEqual("verify_error", returned_post_drift["reason"])
self.assertEqual(1, len(reporter.update_calls))
self.assertFalse(reporter.update_calls[0]["is_synced"])
self.assertEqual(7, reporter.update_calls[0]["ban_count"])
self.assertIn("Post-heal verify error: boom", reporter.update_calls[0]["last_error"])
self.assertEqual("verify_error", reporter.update_calls[0]["heal_result"])
class PostHealBaselineTests(unittest.TestCase):
@patch("healing.time.sleep", return_value=None)
def test_verification_is_judged_against_the_pre_heal_truth(self, _sleep):
auditor = FakeAuditor(heal_ok=True, reconcile_result=(True, 3, {"reason": "in_sync"}))
auditor.last_truth_values = frozenset({"192.0.2.1"})
execute_heal_and_verify(auditor, FakeReporter(), count=3, drift={}, heal_verify_delay=0)
self.assertEqual({"baseline_truth": frozenset({"192.0.2.1"})}, auditor.reconcile_kwargs)
@patch("healing.time.sleep", return_value=None)
def test_auditor_without_baseline_support_is_verified_as_before(self, _sleep):
auditor = FakeAuditor(heal_ok=True, reconcile_result=(True, 3, {"reason": "in_sync"}))
execute_heal_and_verify(auditor, FakeReporter(), count=3, drift={}, heal_verify_delay=0)
self.assertEqual({}, auditor.reconcile_kwargs)
@patch("healing.time.sleep", return_value=None)
def test_decision_issued_during_verification_window_does_not_fail_the_heal(self, _sleep):
# Replays a logged metadata heal: the heal fixed the stale TTL, but a new
# decision arrived in the 5 s before verification, before the bouncer's next
# poll. That used to be recorded as heal_result=failed.
from auditor import FirewallAuditor
long_ban = {"duration": "335h", "until_epoch": None}
truth = {"192.0.2.10": long_ban, "192.0.2.11": long_ban}
kernel = {"192.0.2.10": 13780, "192.0.2.11": 335 * 3600}
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: dict(truth)
auditor.get_kernel_state = lambda: dict(kernel)
def heal(_drift):
kernel["192.0.2.10"] = 335 * 3600 # the restarted bouncer re-adds with the full TTL
truth["203.0.113.70"] = dict(long_ban) # new decision, not yet applied
return True
auditor.heal_with_drift = heal
is_synced, count, drift = auditor.reconcile()
self.assertEqual("metadata_drift", drift["reason"])
reporter = FakeReporter()
heal_result, post_drift = execute_heal_and_verify(auditor, reporter, count, drift, heal_verify_delay=0)
self.assertEqual("success", heal_result)
self.assertEqual(["203.0.113.70"], post_drift["lapi_changed_values"])
self.assertTrue(reporter.update_calls[-1]["is_synced"])
class MembershipRecheckTests(unittest.TestCase):
MISMATCH = (False, 10, {"reason": "membership_mismatch", "missing_count": 1})
IN_SYNC = (True, 11, {"reason": "in_sync"})
def test_recheck_clears_transient_membership_mismatch(self):
auditor = FakeAuditor(reconcile_result=self.IN_SYNC)
waits = []
result = recheck_membership_mismatch(
auditor, self.MISMATCH, 30, wait=waits.append
)
self.assertEqual(self.IN_SYNC, result)
self.assertEqual([30], waits)
def test_recheck_returns_persisting_drift(self):
persisted = (False, 10, {"reason": "membership_mismatch", "missing_count": 2})
auditor = FakeAuditor(reconcile_result=persisted)
result = recheck_membership_mismatch(
auditor, self.MISMATCH, 30, wait=lambda _delay: None
)
self.assertEqual(persisted, result)
def test_recheck_skipped_for_metadata_drift_and_when_disabled(self):
auditor = FakeAuditor(reconcile_exception=AssertionError("must not re-audit"))
metadata = (False, 10, {"reason": "metadata_drift"})
waits = []
self.assertEqual(
metadata,
recheck_membership_mismatch(auditor, metadata, 30, wait=waits.append),
)
self.assertEqual(
self.MISMATCH,
recheck_membership_mismatch(auditor, self.MISMATCH, 0, wait=waits.append),
)
self.assertEqual(
self.IN_SYNC,
recheck_membership_mismatch(auditor, self.IN_SYNC, 30, wait=waits.append),
)
self.assertEqual([], waits)
if __name__ == "__main__":
unittest.main()
+38
View File
@@ -0,0 +1,38 @@
import unittest
from unittest.mock import patch
from config import RuntimeSettings
from agent import cli
def _settings():
return RuntimeSettings(
node_name="n1",
log_path="/tmp/threat-agent.log",
state_file="/tmp/threat-agent-state.json",
check_interval=600,
check_jitter_pct=0.10,
heal_verify_delay=5,
heal_min_interval=900,
enforcement_targets=(("ip", "crowdsec"),),
enforcement_sets=(),
config_path="config.yaml",
)
class AgentCliTests(unittest.TestCase):
@patch("agent.load_runtime_settings", return_value=_settings())
@patch("agent.run_doctor", return_value=True)
def test_cli_doctor_returns_zero_on_success(self, _run_doctor, _settings_mock):
code = cli(["--doctor"])
self.assertEqual(0, code)
@patch("agent.main")
def test_cli_without_doctor_runs_main(self, main_mock):
code = cli([])
self.assertEqual(0, code)
main_mock.assert_called_once()
if __name__ == "__main__":
unittest.main()
+616
View File
@@ -0,0 +1,616 @@
import unittest
import datetime
import json
import subprocess
from unittest.mock import patch, call
from auditor import FirewallAuditor, LapiUnavailableError
class AuditorDecisionExtractionTests(unittest.TestCase):
def test_extract_decisions_handles_flat_and_nested_payloads(self):
auditor = FirewallAuditor()
payload = [
{"value": "1.1.1.1", "duration": "4h", "origin": "lists"},
{
"decisions": [
{"value": "2.2.2.2", "duration": "8h", "origin": "crowdsec"},
{"value": "2.2.2.2", "duration": "8h", "origin": "crowdsec"},
]
},
{
"source": {
"decisions": [
{"value": "3.3.3.3", "duration": "12h", "origin": "manual"}
]
}
},
]
decisions = list(auditor._extract_decisions(payload))
decision_keys = {
(d.get("value"), d.get("duration"), d.get("origin")) for d in decisions
}
self.assertIn(("1.1.1.1", "4h", "lists"), decision_keys)
self.assertIn(("2.2.2.2", "8h", "crowdsec"), decision_keys)
self.assertIn(("3.3.3.3", "12h", "manual"), decision_keys)
self.assertEqual(3, len(decision_keys))
def test_reconcile_detects_metadata_drift_for_extended_duration(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"1.1.1.1": {"duration": "24h", "until_epoch": None}
}
auditor.get_kernel_state = lambda: {"1.1.1.1": 3 * 3600 * 1000}
is_synced, count, drift = auditor.reconcile()
self.assertFalse(is_synced)
self.assertEqual(1, count)
self.assertEqual("metadata_drift", drift["reason"])
self.assertEqual(1, drift["metadata_drift_count"])
def test_reconcile_uses_until_for_expected_remaining(self):
now_epoch = datetime.datetime.now(datetime.timezone.utc).timestamp()
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"2.2.2.2": {
"duration": "4h",
"until_epoch": now_epoch + (24 * 3600),
}
}
auditor.get_kernel_state = lambda: {"2.2.2.2": 2 * 3600 * 1000}
is_synced, _, drift = auditor.reconcile()
self.assertFalse(is_synced)
self.assertEqual("metadata_drift", drift["reason"])
def test_reconcile_reports_range_collapsed_to_network_address_without_drift(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"195.178.110.0/24": {"duration": "11h", "until_epoch": None},
"1.1.1.1": {"duration": "4h", "until_epoch": None},
}
auditor.get_kernel_state = lambda: {"195.178.110.0": 40000, "1.1.1.1": 14000}
is_synced, count, drift = auditor.reconcile()
self.assertTrue(is_synced)
self.assertEqual(2, count)
self.assertEqual("in_sync", drift["reason"])
self.assertEqual(["195.178.110.0/24"], drift["unenforceable_ranges"])
def test_reconcile_keeps_real_drift_alongside_collapsed_range(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"195.178.110.0/24": {"duration": "11h", "until_epoch": None},
"2.2.2.2": {"duration": "4h", "until_epoch": None},
}
auditor.get_kernel_state = lambda: {"195.178.110.0": 40000, "9.9.9.9": 14000}
is_synced, _, drift = auditor.reconcile()
self.assertFalse(is_synced)
self.assertEqual("membership_mismatch", drift["reason"])
self.assertEqual(1, drift["missing_count"])
self.assertEqual(1, drift["extra_count"])
self.assertEqual(
auditor._fingerprint_drift(["2.2.2.2"], ["9.9.9.9"], []),
drift["fingerprint"],
)
self.assertEqual(["195.178.110.0/24"], drift["unenforceable_ranges"])
def test_reconcile_matches_range_whose_network_address_is_also_banned(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"10.0.0.0/24": {"duration": "4h", "until_epoch": None},
"10.0.0.0": {"duration": "4h", "until_epoch": None},
}
auditor.get_kernel_state = lambda: {"10.0.0.0": 14000}
is_synced, _, drift = auditor.reconcile()
self.assertTrue(is_synced)
self.assertEqual(["10.0.0.0/24"], drift["unenforceable_ranges"])
def test_reconcile_treats_full_length_prefix_stored_as_address_as_in_sync(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"1.2.3.4/32": {"duration": "4h", "until_epoch": None},
"2001:db8::1/128": {"duration": "4h", "until_epoch": None},
}
auditor.get_kernel_state = lambda: {"1.2.3.4": 14000, "2001:db8::1": 14000}
is_synced, _, drift = auditor.reconcile()
self.assertTrue(is_synced)
self.assertEqual([], drift["unenforceable_ranges"])
def test_reconcile_uses_range_enforcer_for_range_decisions(self):
class StubEnforcer:
table = "crowdsec-ranges"
def __init__(self):
self.synced = None
def sync(self, range_truth):
self.synced = range_truth
return []
enforcer = StubEnforcer()
auditor = FirewallAuditor(range_enforcer=enforcer)
auditor.get_remote_lapi_truth = lambda: {
"195.178.110.0/24": {"duration": "11h", "until_epoch": None},
"1.1.1.1": {"duration": "4h", "until_epoch": None},
"1.2.3.4/32": {"duration": "4h", "until_epoch": None},
}
auditor.get_kernel_state = lambda: {
"195.178.110.0": 40000,
"1.1.1.1": 14000,
"1.2.3.4": 14000,
}
is_synced, _, drift = auditor.reconcile()
self.assertTrue(is_synced)
self.assertEqual(["195.178.110.0/24"], list(enforcer.synced))
self.assertEqual([], drift["unenforceable_ranges"])
def test_reconcile_reports_ranges_the_range_enforcer_could_not_apply(self):
class FailingEnforcer:
table = "crowdsec-ranges"
def sync(self, range_truth):
return sorted(range_truth)
auditor = FirewallAuditor(range_enforcer=FailingEnforcer())
auditor.get_remote_lapi_truth = lambda: {
"195.178.110.0/24": {"duration": "11h", "until_epoch": None}
}
auditor.get_kernel_state = lambda: {"195.178.110.0": 40000}
is_synced, _, drift = auditor.reconcile()
self.assertTrue(is_synced)
self.assertEqual(["195.178.110.0/24"], drift["unenforceable_ranges"])
def test_reconcile_logs_missing_and_extra_values(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"2.2.2.2": {"duration": "4h", "until_epoch": None}
}
auditor.get_kernel_state = lambda: {"9.9.9.9": 14000}
with self.assertLogs(level="WARNING") as logs:
auditor.reconcile()
self.assertTrue(
any(
"missing_values=[2.2.2.2]" in line and "extra_values=[9.9.9.9]" in line
for line in logs.output
)
)
def test_preview_values_truncates_long_lists(self):
auditor = FirewallAuditor()
values = [f"10.0.0.{i}" for i in range(12)]
self.assertEqual(
"[" + ",".join(values[:10]) + ",+2 more]",
auditor._preview_values(values),
)
def test_parse_duration_supports_compound_values(self):
auditor = FirewallAuditor()
self.assertEqual(5400, auditor.parse_duration("1h30m"))
self.assertEqual(1209600, auditor.parse_duration("14d"))
def test_reconcile_skips_metadata_check_when_kernel_expiry_unavailable(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"4.4.4.4": {"duration": "14d", "until_epoch": None}
}
auditor.get_kernel_state = lambda: {"4.4.4.4": None}
is_synced, count, drift = auditor.reconcile()
self.assertTrue(is_synced)
self.assertEqual(1, count)
self.assertEqual("in_sync", drift["reason"])
def test_reconcile_supports_kernel_ttl_reported_in_seconds(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {
"5.5.5.5": {"duration": "14d", "until_epoch": None}
}
# Some nft stacks report expires directly in seconds.
auditor.get_kernel_state = lambda: {"5.5.5.5": 13 * 24 * 3600}
is_synced, count, drift = auditor.reconcile()
self.assertTrue(is_synced)
self.assertEqual(1, count)
self.assertEqual("in_sync", drift["reason"])
@patch("auditor.subprocess.run")
def test_lapi_query_failure_raises_instead_of_returning_empty_truth(self, run_mock):
auditor = FirewallAuditor()
run_mock.side_effect = subprocess.CalledProcessError(
1, ["/usr/bin/cscli"], stderr="dial tcp 100.64.0.1:8080: connection refused\n"
)
with self.assertRaisesRegex(LapiUnavailableError, "connection refused"):
auditor.get_remote_lapi_truth()
def test_reconcile_does_not_report_drift_when_lapi_unreachable(self):
auditor = FirewallAuditor()
def unreachable():
raise LapiUnavailableError("LAPI unreachable: connection refused")
auditor.get_remote_lapi_truth = unreachable
auditor.get_kernel_state = lambda: {"1.1.1.1": 3600}
with self.assertRaises(LapiUnavailableError):
auditor.reconcile()
@patch("auditor.subprocess.run")
def test_heal_with_metadata_drift_flushes_sets_before_restart(self, run_mock):
auditor = FirewallAuditor()
run_mock.side_effect = [
subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli", "handle": 7}}]}),
),
None, # flush ip set
subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps({"nftables": [{"set": {"name": "::/0-cscli", "handle": 8}}]}),
),
None, # flush ip6 set
None, # systemctl restart
]
ok = auditor.heal_with_drift({"reason": "metadata_drift"})
self.assertTrue(ok)
self.assertEqual(
[
call(
["/usr/sbin/nft", "-j", "list", "table", "ip", "crowdsec"],
check=True,
capture_output=True,
text=True,
),
call(
["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "0.0.0.0/0-cscli"],
check=True,
capture_output=True,
text=True,
),
call(
["/usr/sbin/nft", "-j", "list", "table", "ip6", "crowdsec6"],
check=True,
capture_output=True,
text=True,
),
call(
["/usr/sbin/nft", "flush", "set", "ip6", "crowdsec6", "::/0-cscli"],
check=True,
capture_output=True,
text=True,
),
call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True),
],
run_mock.call_args_list,
)
@patch("auditor.subprocess.run")
def test_heal_without_metadata_drift_only_restarts_bouncer(self, run_mock):
auditor = FirewallAuditor()
run_mock.return_value = None
ok = auditor.heal_with_drift({"reason": "membership_mismatch"})
self.assertTrue(ok)
self.assertEqual(
[call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True)],
run_mock.call_args_list,
)
@patch("auditor.subprocess.run")
def test_heal_metadata_drift_continues_when_one_flush_fails(self, run_mock):
auditor = FirewallAuditor()
run_mock.side_effect = [
subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli", "handle": 9}}]}),
),
subprocess.CalledProcessError(
1,
["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "0.0.0.0/0-cscli"],
stderr="No such file or directory",
),
subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # ip6 crowdsec6 absent
None, # restart still executes
]
ok = auditor.heal_with_drift({"reason": "metadata_drift"})
self.assertTrue(ok)
self.assertEqual(
call(["systemctl", "restart", "crowdsec-firewall-bouncer"], check=True),
run_mock.call_args_list[-1],
)
@patch("auditor.subprocess.run")
def test_heal_metadata_drift_falls_back_to_handle_on_name_syntax_error(self, run_mock):
auditor = FirewallAuditor()
run_mock.side_effect = [
subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps({"nftables": [{"set": {"name": "0.0.0.0/0-cscli", "handle": 21}}]}),
),
subprocess.CalledProcessError(
1,
["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "0.0.0.0/0-cscli"],
stderr="Error: syntax error, unexpected /",
),
None, # fallback flush by handle succeeds
subprocess.CalledProcessError(1, ["/usr/sbin/nft"]), # ip6 crowdsec6 absent
None, # restart
]
ok = auditor.heal_with_drift({"reason": "metadata_drift"})
self.assertTrue(ok)
self.assertIn(
call(
["/usr/sbin/nft", "flush", "set", "ip", "crowdsec", "handle", "21"],
check=True,
capture_output=True,
text=True,
),
run_mock.call_args_list,
)
@patch("auditor.subprocess.run")
def test_get_kernel_state_filters_to_configured_managed_sets(self, run_mock):
auditor = FirewallAuditor(
targets=[("ip", "crowdsec")],
managed_sets=["0.0.0.0/0-cscli"],
)
run_mock.return_value = subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps(
{
"nftables": [
{
"set": {
"name": "0.0.0.0/0-cscli",
"elem": [{"elem": {"val": "1.1.1.1", "expires": 1000}}],
}
},
{
"set": {
"name": "crowdsec-blacklists",
"elem": [{"elem": {"val": "9.9.9.9", "expires": 2000}}],
}
},
]
}
),
)
kernel_state = auditor.get_kernel_state()
self.assertEqual({"1.1.1.1": 1000.0}, kernel_state)
@patch("auditor.subprocess.run")
def test_get_kernel_state_keeps_longest_expiry_for_ip_in_multiple_sets(self, run_mock):
auditor = FirewallAuditor(targets=[("ip", "crowdsec")])
run_mock.return_value = subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps(
{
"nftables": [
{
"set": {
"name": "crowdsec-blacklists-cscli",
"elem": [{"elem": {"val": "1.1.1.1", "expires": 600000}}],
}
},
{
"set": {
"name": "crowdsec-blacklists-crowdsec",
"elem": [{"elem": {"val": "1.1.1.1", "expires": 13000}}],
}
},
]
}
),
)
kernel_state = auditor.get_kernel_state()
self.assertEqual({"1.1.1.1": 600000.0}, kernel_state)
@patch("auditor.subprocess.run")
def test_get_kernel_state_normalizes_prefix_elements(self, run_mock):
auditor = FirewallAuditor(targets=[("ip", "crowdsec")])
run_mock.return_value = subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps(
{
"nftables": [
{
"set": {
"name": "crowdsec-blacklists-cscli",
"elem": [
{
"elem": {
"val": {"prefix": {"addr": "10.0.0.0", "len": 24}},
"expires": 1000,
}
},
{"elem": {"val": "1.1.1.1", "expires": 2000}},
],
}
}
]
}
),
)
kernel_state = auditor.get_kernel_state()
self.assertEqual({"10.0.0.0/24": 1000.0, "1.1.1.1": 2000.0}, kernel_state)
@patch("auditor.subprocess.run")
def test_get_kernel_state_falls_back_when_configured_sets_do_not_match(self, run_mock):
auditor = FirewallAuditor(
targets=[("ip", "crowdsec")],
managed_sets=["missing-set-name"],
)
run_mock.return_value = subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps(
{
"nftables": [
{
"set": {
"name": "0.0.0.0/0-cscli",
"elem": [{"elem": {"val": "1.1.1.1", "expires": 1000}}],
}
}
]
}
),
)
kernel_state = auditor.get_kernel_state()
self.assertEqual({"1.1.1.1": 1000.0}, kernel_state)
@patch("auditor.subprocess.run")
def test_startup_check_warns_when_configured_sets_have_no_overlap(self, run_mock):
auditor = FirewallAuditor(
targets=[("ip", "crowdsec")],
managed_sets=["missing-set-name"],
)
run_mock.return_value = subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps(
{"nftables": [{"set": {"name": "crowdsec-blacklists-cscli"}}]}
),
)
with self.assertLogs(level="WARNING") as logs:
auditor.log_enforcement_startup_state()
self.assertTrue(
any("Configured enforcement sets not found" in msg for msg in logs.output)
)
@patch("auditor.subprocess.run")
@patch("auditor.logging.warning")
def test_startup_check_no_warning_when_overlap_exists(self, warning_mock, run_mock):
auditor = FirewallAuditor(
targets=[("ip", "crowdsec")],
managed_sets=["crowdsec-blacklists-cscli"],
)
run_mock.return_value = subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps(
{"nftables": [{"set": {"name": "crowdsec-blacklists-cscli"}}]}
),
)
auditor.log_enforcement_startup_state()
warning_mock.assert_not_called()
class ReconcileBaselineTests(unittest.TestCase):
"""Post-heal verification is judged against the decisions the heal started from."""
LONG = {"duration": "4h", "until_epoch": None}
def _auditor(self, truth, kernel):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {value: dict(self.LONG) for value in truth}
auditor.get_kernel_state = lambda: {value: 14000 for value in kernel}
return auditor
def test_reconcile_records_the_truth_values_it_saw(self):
auditor = self._auditor(["192.0.2.1", "192.0.2.2"], ["192.0.2.1", "192.0.2.2"])
auditor.reconcile()
self.assertEqual(frozenset({"192.0.2.1", "192.0.2.2"}), auditor.last_truth_values)
def test_without_baseline_a_new_decision_not_yet_applied_is_drift(self):
auditor = self._auditor(["192.0.2.1", "198.51.100.7"], ["192.0.2.1"])
is_synced, _, drift = auditor.reconcile()
self.assertFalse(is_synced)
self.assertEqual("membership_mismatch", drift["reason"])
self.assertEqual(1, drift["missing_count"])
self.assertEqual([], drift["lapi_changed_values"])
def test_decision_added_since_baseline_is_not_drift(self):
auditor = self._auditor(["192.0.2.1", "198.51.100.7"], ["192.0.2.1"])
is_synced, _, drift = auditor.reconcile(baseline_truth={"192.0.2.1"})
self.assertTrue(is_synced)
self.assertEqual("in_sync", drift["reason"])
self.assertEqual(0, drift["missing_count"])
self.assertEqual(["198.51.100.7"], drift["lapi_changed_values"])
def test_decision_removed_since_baseline_is_not_drift(self):
auditor = self._auditor(["192.0.2.1"], ["192.0.2.1", "198.51.100.8"])
is_synced, _, drift = auditor.reconcile(baseline_truth={"192.0.2.1", "198.51.100.8"})
self.assertTrue(is_synced)
self.assertEqual(0, drift["extra_count"])
self.assertEqual(["198.51.100.8"], drift["lapi_changed_values"])
def test_drift_on_decisions_present_at_baseline_still_counts(self):
auditor = self._auditor(["192.0.2.1", "192.0.2.2", "198.51.100.7"], ["192.0.2.1"])
is_synced, _, drift = auditor.reconcile(baseline_truth={"192.0.2.1", "192.0.2.2"})
self.assertFalse(is_synced)
self.assertEqual("membership_mismatch", drift["reason"])
self.assertEqual(1, drift["missing_count"])
self.assertEqual(["198.51.100.7"], drift["lapi_changed_values"])
self.assertEqual(auditor._fingerprint_drift(["192.0.2.2"], [], []), drift["fingerprint"])
def test_metadata_check_skips_decisions_changed_since_baseline(self):
auditor = FirewallAuditor()
auditor.get_remote_lapi_truth = lambda: {"198.51.100.7": {"duration": "24h", "until_epoch": None}}
auditor.get_kernel_state = lambda: {"198.51.100.7": 3 * 3600 * 1000}
is_synced, _, drift = auditor.reconcile(baseline_truth=set())
self.assertTrue(is_synced)
self.assertEqual(0, drift["metadata_drift_count"])
if __name__ == "__main__":
unittest.main()
+135
View File
@@ -0,0 +1,135 @@
import os
import unittest
from unittest.mock import patch
from config import RuntimeSettings, load_runtime_settings, validate_runtime_settings
class RuntimeSettingsEnforcementTests(unittest.TestCase):
@patch("config.load_config")
def test_enforcement_uses_explicit_targets_when_present(self, load_config_mock):
load_config_mock.return_value = {
"agent": {"node_name": "n1"},
"enforcement": {
"targets": [
{"family": "ip", "table": "custom_v4"},
{"family": "inet", "table": "custom_inet"},
],
"sets": ["0.0.0.0/0-cscli", "crowdsec-blacklists"],
},
}
with patch.dict(os.environ, {}, clear=True):
settings = load_runtime_settings()
self.assertEqual(
(("ip", "custom_v4"), ("inet", "custom_inet")),
settings.enforcement_targets,
)
self.assertEqual(
("0.0.0.0/0-cscli", "crowdsec-blacklists"),
settings.enforcement_sets,
)
@patch("config.load_config")
def test_enforcement_falls_back_to_table_fields(self, load_config_mock):
load_config_mock.return_value = {
"enforcement": {
"table": "crowdsec_main",
"table6": "crowdsec6_main",
"families": ["ip", "ip6"],
}
}
with patch.dict(os.environ, {}, clear=True):
settings = load_runtime_settings()
self.assertEqual(
(("ip", "crowdsec_main"), ("ip6", "crowdsec6_main")),
settings.enforcement_targets,
)
self.assertEqual((), settings.enforcement_sets)
@patch("config.load_config")
def test_check_jitter_pct_loaded_and_clamped(self, load_config_mock):
load_config_mock.return_value = {
"agent": {
"check_jitter_pct": 1.5,
}
}
with patch.dict(os.environ, {}, clear=True):
settings = load_runtime_settings()
self.assertEqual(0.90, settings.check_jitter_pct)
@patch("config.load_config")
def test_ranges_settings_default_to_disabled(self, load_config_mock):
load_config_mock.return_value = {}
with patch.dict(os.environ, {}, clear=True):
settings = load_runtime_settings()
self.assertFalse(settings.ranges_enabled)
self.assertEqual("crowdsec-ranges", settings.ranges_table)
self.assertEqual(16, settings.ranges_min_prefix_v4)
self.assertEqual(32, settings.ranges_min_prefix_v6)
@patch("config.load_config")
def test_ranges_settings_loaded_and_validated(self, load_config_mock):
load_config_mock.return_value = {
"ranges": {"enabled": True, "table": "r", "min_prefix_v4": 0, "min_prefix_v6": 48}
}
with patch.dict(os.environ, {}, clear=True):
settings = load_runtime_settings()
issues = validate_runtime_settings(settings)
self.assertTrue(settings.ranges_enabled)
self.assertEqual("r", settings.ranges_table)
self.assertEqual(48, settings.ranges_min_prefix_v6)
self.assertTrue(
any(i.level == "ERROR" and "min_prefix_v4" in i.message for i in issues)
)
def test_validate_runtime_settings_reports_errors(self):
settings = RuntimeSettings(
node_name="n1",
log_path="/tmp/agent.log",
state_file="/tmp/state.json",
check_interval=0,
check_jitter_pct=0.10,
heal_verify_delay=-1,
heal_min_interval=-2,
enforcement_targets=(),
enforcement_sets=(),
config_path="config.yaml",
)
issues = validate_runtime_settings(settings)
errors = [issue for issue in issues if issue.level == "ERROR"]
self.assertGreaterEqual(len(errors), 4)
def test_validate_runtime_settings_reports_warn_for_relative_state_file(self):
settings = RuntimeSettings(
node_name="n1",
log_path="/tmp/agent.log",
state_file="relative-state.json",
check_interval=600,
check_jitter_pct=0.10,
heal_verify_delay=5,
heal_min_interval=900,
enforcement_targets=(("ip", "crowdsec"),),
enforcement_sets=(),
config_path="config.yaml",
)
issues = validate_runtime_settings(settings)
warns = [issue.message for issue in issues if issue.level == "WARN"]
self.assertTrue(any("state_file is not absolute" in msg for msg in warns))
if __name__ == "__main__":
unittest.main()
+104
View File
@@ -0,0 +1,104 @@
import dataclasses
import json
import subprocess
import unittest
from unittest.mock import patch
from config import RuntimeSettings
from doctor import (
CheckResult,
check_cscli_json,
check_range_table,
check_systemctl_restart_capability,
run_doctor,
)
def _settings():
return RuntimeSettings(
node_name="n1",
log_path="/tmp/threat-agent.log",
state_file="/tmp/threat-agent-state.json",
check_interval=600,
check_jitter_pct=0.10,
heal_verify_delay=5,
heal_min_interval=900,
enforcement_targets=(("ip", "crowdsec"),),
enforcement_sets=(),
config_path="config.yaml",
)
class DoctorTests(unittest.TestCase):
@patch("doctor._run_cmd")
def test_check_cscli_json_fail_on_invalid_json(self, run_cmd_mock):
run_cmd_mock.return_value = subprocess.CompletedProcess(
args=[],
returncode=0,
stdout="not-json",
)
result = check_cscli_json()
self.assertEqual("FAIL", result.status)
self.assertIn("Invalid JSON", result.detail)
@patch("doctor._run_cmd")
def test_check_range_table_warns_when_table_not_created_yet(self, run_cmd_mock):
run_cmd_mock.side_effect = subprocess.CalledProcessError(1, ["nft"])
settings = dataclasses.replace(_settings(), ranges_enabled=True)
result = check_range_table(settings)
self.assertEqual("WARN", result.status)
self.assertIn("creates it on its first audit", result.detail)
@patch("doctor._run_cmd")
def test_check_range_table_fails_when_a_set_is_missing(self, run_cmd_mock):
run_cmd_mock.return_value = subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=json.dumps({"nftables": [{"set": {"name": "ranges-v4"}}]}),
)
settings = dataclasses.replace(_settings(), ranges_enabled=True)
result = check_range_table(settings)
self.assertEqual("FAIL", result.status)
self.assertIn("ranges-v6", result.detail)
@patch("doctor.os.geteuid", return_value=1000)
def test_check_systemctl_restart_capability_warns_when_not_root(self, _geteuid):
result = check_systemctl_restart_capability()
self.assertEqual("WARN", result.status)
self.assertIn("Not running as root", result.detail)
@patch("doctor.check_systemctl_restart_capability")
@patch("doctor.check_state_paths")
@patch("doctor.check_nft_tables")
@patch("doctor.check_cscli_json")
@patch("doctor.check_runtime_settings")
def test_run_doctor_returns_false_when_any_fail(
self,
check_runtime_mock,
check_cscli_mock,
check_nft_mock,
check_state_mock,
check_systemctl_mock,
):
check_runtime_mock.return_value = CheckResult("runtime", "PASS", "ok")
check_cscli_mock.return_value = CheckResult("cscli", "FAIL", "bad")
check_nft_mock.return_value = CheckResult("nft", "PASS", "ok")
check_state_mock.return_value = CheckResult("state", "PASS", "ok")
check_systemctl_mock.return_value = CheckResult("systemctl", "WARN", "warn")
lines = []
ok = run_doctor(_settings(), output=lines.append)
self.assertFalse(ok)
self.assertTrue(any("Summary:" in line for line in lines))
if __name__ == "__main__":
unittest.main()
+22
View File
@@ -0,0 +1,22 @@
import unittest
from unittest.mock import patch
from main import compute_sleep_interval
class MainSleepIntervalTests(unittest.TestCase):
@patch("main.random.uniform", return_value=0.0)
def test_compute_sleep_interval_no_jitter(self, _uniform):
self.assertEqual(600.0, compute_sleep_interval(600, 0.0))
@patch("main.random.uniform", return_value=0.10)
def test_compute_sleep_interval_applies_positive_jitter(self, _uniform):
self.assertEqual(660.0, compute_sleep_interval(600, 0.10))
@patch("main.random.uniform", return_value=-0.90)
def test_compute_sleep_interval_enforces_minimum_sleep(self, _uniform):
self.assertEqual(1.0, compute_sleep_interval(1, 0.90))
if __name__ == "__main__":
unittest.main()
+150
View File
@@ -0,0 +1,150 @@
import json
import subprocess
import unittest
from unittest.mock import patch
from ranges import RangeEnforcer, element_key
def _nft_table(v4=(), v6=()):
def elems(items):
return [
{"elem": {"val": {"prefix": {"addr": addr, "len": length}}, "expires": expires}}
for addr, length, expires in items
]
return json.dumps(
{
"nftables": [
{"table": {"family": "inet", "name": "crowdsec-ranges"}},
{"set": {"name": "ranges-v4", "elem": elems(v4)}},
{"set": {"name": "ranges-v6", "elem": elems(v6)}},
]
}
)
class FakeNft:
"""Serves `nft -j list` from a queue of table payloads and records `nft -f -` scripts."""
def __init__(self, listings, apply_error=None):
self.listings = list(listings)
self.apply_error = apply_error
self.scripts = []
def __call__(self, cmd, **kwargs):
if cmd[1:3] == ["-f", "-"]:
self.scripts.append(kwargs["input"])
if self.apply_error:
raise subprocess.CalledProcessError(1, cmd, stderr=self.apply_error)
return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
listing = self.listings.pop(0)
if listing is None:
raise subprocess.CalledProcessError(1, cmd, stderr="No such file or directory")
return subprocess.CompletedProcess(cmd, 0, stdout=listing, stderr="")
class RangeEnforcerTests(unittest.TestCase):
def test_element_key_normalizes_prefix_address_and_range(self):
self.assertEqual(
"10.0.0.0/24", element_key({"prefix": {"addr": "10.0.0.0", "len": 24}})
)
self.assertEqual("10.0.0.1", element_key("10.0.0.1"))
self.assertEqual("10.0.0.1-10.0.0.9", element_key({"range": ["10.0.0.1", "10.0.0.9"]}))
self.assertIsNone(element_key({"elem": 1}))
def test_sync_creates_table_and_adds_missing_range(self):
nft = FakeNft([None, _nft_table(v4=[("195.178.110.0", 24, 3600)])])
with patch("ranges.subprocess.run", nft):
unenforced = RangeEnforcer().sync(
{"195.178.110.0/24": {"duration": "1h", "until_epoch": None}}
)
self.assertEqual([], unenforced)
script = nft.scripts[0]
self.assertIn("add table inet crowdsec-ranges", script)
self.assertIn("flags interval, timeout;", script)
self.assertIn("add rule inet crowdsec-ranges input ip saddr @ranges-v4 drop", script)
self.assertIn("add rule inet crowdsec-ranges forward ip6 saddr @ranges-v6 drop", script)
self.assertIn(
"add element inet crowdsec-ranges ranges-v4 { 195.178.110.0/24 timeout 3600s }",
script,
)
def test_sync_leaves_matching_element_and_removes_stale_one(self):
table = _nft_table(v4=[("195.178.110.0", 24, 3500)], v6=[("2001:db8::", 48, 900)])
nft = FakeNft([table, _nft_table(v4=[("195.178.110.0", 24, 3500)])])
with patch("ranges.subprocess.run", nft):
unenforced = RangeEnforcer().sync(
{"195.178.110.0/24": {"duration": "1h", "until_epoch": None}}
)
self.assertEqual([], unenforced)
self.assertNotIn("195.178.110.0/24", nft.scripts[0])
self.assertIn(
"delete element inet crowdsec-ranges ranges-v6 { 2001:db8::/48 }", nft.scripts[0]
)
def test_sync_refreshes_element_when_decision_was_extended(self):
table = _nft_table(v4=[("195.178.110.0", 24, 600)])
nft = FakeNft([table, _nft_table(v4=[("195.178.110.0", 24, 32400)])])
with patch("ranges.subprocess.run", nft):
RangeEnforcer().sync({"195.178.110.0/24": {"duration": "9h", "until_epoch": None}})
script = nft.scripts[0]
delete = script.index("delete element inet crowdsec-ranges ranges-v4 { 195.178.110.0/24 }")
add = script.index(
"add element inet crowdsec-ranges ranges-v4 { 195.178.110.0/24 timeout 32400s }"
)
self.assertLess(delete, add)
def test_sync_refuses_ranges_broader_than_min_prefix(self):
nft = FakeNft([_nft_table(), _nft_table()])
with patch("ranges.subprocess.run", nft):
unenforced = RangeEnforcer(min_prefix_v4=16).sync(
{"10.0.0.0/8": {"duration": "1h", "until_epoch": None}}
)
self.assertEqual(["10.0.0.0/8"], unenforced)
self.assertNotIn("10.0.0.0", nft.scripts[0])
def test_sync_inserts_only_supernet_of_overlapping_ranges(self):
nft = FakeNft([_nft_table(), _nft_table(v4=[("192.0.2.0", 24, 7200)])])
with patch("ranges.subprocess.run", nft):
unenforced = RangeEnforcer().sync(
{
"192.0.2.0/24": {"duration": "2h", "until_epoch": None},
"192.0.2.64/26": {"duration": "1h", "until_epoch": None},
}
)
self.assertEqual([], unenforced)
self.assertIn("192.0.2.0/24", nft.scripts[0])
self.assertNotIn("192.0.2.64/26", nft.scripts[0])
def test_sync_skips_expired_decision_and_parses_fractional_duration(self):
nft = FakeNft([_nft_table(), _nft_table(v4=[("192.0.2.0", 24, 5400)])])
with patch("ranges.subprocess.run", nft):
RangeEnforcer().sync(
{
"192.0.2.0/24": {"duration": "1h30m0.5s", "until_epoch": None},
"198.51.100.0/24": {"duration": "-2m", "until_epoch": None},
}
)
self.assertIn("{ 192.0.2.0/24 timeout 5400s }", nft.scripts[0])
self.assertNotIn("198.51.100.0", nft.scripts[0])
def test_sync_reports_ranges_missing_after_failed_apply(self):
nft = FakeNft([_nft_table(), _nft_table()], apply_error="Error: conflicting intervals")
with patch("ranges.subprocess.run", nft), self.assertLogs(level="ERROR") as logs:
unenforced = RangeEnforcer().sync(
{"192.0.2.0/24": {"duration": "1h", "until_epoch": None}}
)
self.assertEqual(["192.0.2.0/24"], unenforced)
self.assertTrue(any("conflicting intervals" in line for line in logs.output))
if __name__ == "__main__":
unittest.main()
+202
View File
@@ -0,0 +1,202 @@
import json
import os
import tempfile
import unittest
from datetime import datetime
from unittest.mock import patch
from reporter import LocalStateReporter
class ReporterStateTests(unittest.TestCase):
def test_update_status_writes_drift_and_fingerprint_fields(self):
with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json")
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
reporter.update_status(
False,
10,
last_error="boom",
missing_count=2,
extra_count=3,
metadata_drift_count=1,
last_drift_fingerprint="abc123",
last_heal_result="failed",
)
with open(state_file, "r") as f:
payload = json.load(f)
self.assertEqual("n1", payload["node_name"])
self.assertEqual("DESYNC_DETECTED", payload["status"])
self.assertEqual(10, payload["kernel_ban_count"])
self.assertEqual(2, payload["missing_count"])
self.assertEqual(3, payload["extra_count"])
self.assertEqual(1, payload["metadata_drift_count"])
self.assertEqual("abc123", payload["last_drift_fingerprint"])
self.assertEqual("failed", payload["last_heal_result"])
def test_update_status_reports_degraded_when_synced_with_unenforceable_ranges(self):
with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json")
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
reporter.update_status(True, 10, unenforceable_range_count=1)
with open(state_file, "r") as f:
degraded = json.load(f)
reporter.update_status(True, 10)
with open(state_file, "r") as f:
healthy = json.load(f)
self.assertEqual("DEGRADED", degraded["status"])
self.assertTrue(degraded["is_synced"])
self.assertEqual(1, degraded["unenforceable_range_count"])
self.assertEqual("HEALTHY", healthy["status"])
self.assertEqual(0, healthy["unenforceable_range_count"])
def test_update_status_preserves_last_heal_result_when_omitted(self):
with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json")
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
reporter.update_status(
False,
7,
last_heal_result="success",
last_drift_fingerprint="oldfp",
)
reporter.update_status(
True,
7,
missing_count=0,
extra_count=0,
metadata_drift_count=0,
last_drift_fingerprint="",
)
with open(state_file, "r") as f:
payload = json.load(f)
self.assertEqual("success", payload["last_heal_result"])
self.assertEqual("", payload["last_drift_fingerprint"])
def test_update_status_tracks_checks_and_heal_counters(self):
with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json")
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
reporter.update_status(True, 1, checks_increment=1)
reporter.update_status(True, 1, checks_increment=1)
reporter.update_status(False, 1, drift_events_increment=1)
reporter.update_status(False, 1, heal_result="failed")
reporter.update_status(True, 1, heal_result="success")
with open(state_file, "r") as f:
payload = json.load(f)
self.assertEqual(2, payload["checks_total"])
self.assertEqual(1, payload["drift_events_total"])
self.assertEqual(2, payload["drift_heal_attempts_total"])
self.assertEqual(1, payload["drift_events_24h"])
self.assertEqual(2, payload["drift_heal_attempts_24h"])
self.assertEqual(2, payload["heals_24h"])
self.assertEqual(1, payload["heal_failures_24h"])
self.assertEqual(2, payload["heals_total"])
self.assertEqual(1, payload["heal_failures_total"])
self.assertEqual("success", payload["last_heal_result"])
self.assertIn("last_heal_timestamp", payload)
datetime.fromisoformat(payload["last_heal_timestamp"])
self.assertGreaterEqual(payload["uptime_seconds"], 0)
def test_update_status_can_show_suppressed_heal_gap(self):
with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json")
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
reporter.update_status(False, 5, checks_increment=1, drift_events_increment=1)
reporter.update_status(False, 5, heal_result="success")
reporter.update_status(
False, 5, checks_increment=1, drift_events_increment=1, heal_suppressed=True
)
with open(state_file, "r") as f:
payload = json.load(f)
self.assertEqual(2, payload["drift_events_total"])
self.assertEqual(1, payload["drift_heal_attempts_total"])
self.assertEqual(1, payload["heals_suppressed_total"])
self.assertEqual(2, payload["drift_events_24h"])
self.assertEqual(1, payload["drift_heal_attempts_24h"])
self.assertEqual(1, payload["heals_suppressed_24h"])
# Every drift is accounted for: a heal attempt or a suppressed heal.
self.assertEqual(
payload["drift_events_24h"],
payload["drift_heal_attempts_24h"] + payload["heals_suppressed_24h"],
)
@patch("reporter.time.time")
def test_update_status_rolls_24h_window(self, time_mock):
with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json")
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
reporter.started_at_epoch = 0
# Initial write at hour 1000.
time_mock.return_value = 1000 * 3600
reporter.update_status(
False, 1, drift_events_increment=1, heal_result="failed", heal_suppressed=True
)
# New write 25 hours later; previous hour should be pruned from 24h view.
time_mock.return_value = (1000 + 25) * 3600
reporter.update_status(True, 1, checks_increment=1)
with open(state_file, "r") as f:
payload = json.load(f)
self.assertEqual(0, payload["drift_events_24h"])
self.assertEqual(0, payload["drift_heal_attempts_24h"])
self.assertEqual(0, payload["heals_24h"])
self.assertEqual(0, payload["heal_failures_24h"])
self.assertEqual(0, payload["heals_suppressed_24h"])
def test_update_status_preserves_last_heal_timestamp_when_no_new_heal(self):
with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json")
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
reporter.update_status(False, 1, heal_result="failed")
with open(state_file, "r") as f:
first_payload = json.load(f)
first_ts = first_payload["last_heal_timestamp"]
reporter.update_status(True, 1, checks_increment=1)
with open(state_file, "r") as f:
second_payload = json.load(f)
self.assertEqual(first_ts, second_payload["last_heal_timestamp"])
@patch("reporter.datetime")
def test_update_status_refreshes_last_heal_timestamp_on_each_heal(self, datetime_mock):
with tempfile.TemporaryDirectory() as tmp_dir:
state_file = os.path.join(tmp_dir, "state.json")
reporter = LocalStateReporter(state_file=state_file, node_name="n1")
datetime_mock.now.side_effect = [
datetime.fromisoformat("2026-03-06T10:00:00"),
datetime.fromisoformat("2026-03-06T10:00:00"),
datetime.fromisoformat("2026-03-06T10:05:00"),
datetime.fromisoformat("2026-03-06T10:05:00"),
]
reporter.update_status(False, 1, heal_result="failed")
reporter.update_status(False, 1, heal_result="success")
with open(state_file, "r") as f:
payload = json.load(f)
self.assertEqual("2026-03-06T10:05:00", payload["last_heal_timestamp"])
if __name__ == "__main__":
unittest.main()