Skip to content

Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.

Fix audit round-2 findings: rollback, ReDoS, resource bounds

MoneyLisa7239cfe6a21b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3bd2306..454fcb9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,14 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
port/process filter lists bounded to 512 entries.
FR: Les entrées whitelist sont validées (vraies adresses, ≤512) ;
filtres de ports/processus bornés à 512.
+- EN: **Custom-rule regexes reject nested quantifiers** — `(a+)+`,
+ `(.*)*`, `(a?)+`, `(a{1,3})+` and friends are refused at validation.
+ Python's `re` has no match timeout, so the catastrophic-backtracking
+ shape is rejected instead of hoped away; bounded-only patterns stay
+ legal. Residual (ambiguous alternation `(a|a)+`) is documented.
+ FR: **Les regex des règles refusent les quantifieurs imbriqués** —
+ `(a+)+`, `(.*)*`, `(a?)+`, `(a{1,3})+` sont refusés à la validation ;
+ les motifs bornés restent légaux.
### Changed / Modifié
@@ -55,6 +63,43 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
FR: `lan_devices` est désormais bornée (1024 entrées, éviction de la
plus discrète).
+### Fixed / Corrigé
+
+- EN: **ask-mode rollback is now complete** — a mid-start iptables
+ failure mirror-deletes every rule already planted (previously the
+ NFQUEUE jump or RETURN exemptions could strand the host's outbound
+ traffic until reboot), and `stop()` removes the full rule set instead
+ of only the queue jump (repeated start/stop used to stack stale
+ RETURN rules on OUTPUT).
+ FR: **Rollback du mode ask désormais complet** — un échec iptables en
+ cours de start supprime en miroir toutes les règles posées (le saut
+ NFQUEUE ou les exemptions pouvaient étrangler le trafic sortant
+ jusqu'au reboot), et `stop()` retire l'ensemble complet.
+- EN: **NFQUEUE verdicts are race-safe** — `decide()`/timeout-waiter
+ verdicts survive a concurrent `stop()` closing the socket instead of
+ surfacing as API 500s; remembered verdicts are bounded at 65 536
+ entries (ephemeral ports grow them forever otherwise).
+ FR: **Verdicts NFQUEUE insensibles aux courses** — les verdicts
+ survivent à un `stop()` concurrent ; les verdicts mémorisés sont
+ bornés à 65 536 entrées.
+- EN: libpcap `_sockaddr_ip` reads the 2-byte family before sizing the
+ struct (no more 24-byte over-read on short sockaddrs), and a failed
+ BPF compile/setfilter closes the live handle instead of leaking it.
+ FR: `_sockaddr_ip` lit la famille avant de dimensionner la lecture ;
+ un échec BPF ferme le handle live au lieu de le fuiter.
+- EN: the buffered-alert queue is capped at 10 000 between 10 s flushes
+ (oldest-quarter eviction, `alerts_dropped()` counter) and the miner
+ suspect map at 4 096 — alert storms can no longer balloon RAM.
+ FR: la file d'alertes tampon est bornée à 10 000 entre flushes
+ (éviction du quart le plus ancien, compteur `alerts_dropped()`) et la
+ map de suspects mineur à 4 096.
+- EN: media monitor polls every 10 s by default (was 3 s — each Linux
+ tick walks every process's open files); `SNITCH_MEDIA_INTERVAL`
+ (3–300 s) overrides.
+ FR: le moniteur média sonde toutes les 10 s par défaut (3 s avant —
+ chaque tick Linux parcourt les fichiers ouverts de tous les
+ processus) ; `SNITCH_MEDIA_INTERVAL` (3–300 s) ajuste.
+
- EN: **All project surfaces synced to v1.6.3** — README (Rust agent,
enrollment, `ti_feeds`, `.rpm`, `snitchd` formula), ROADMAP (v1.5.x/
v1.6.x shipped rows, fleet scale-out items), wiki (API catalog → 76
diff --git a/backend/api/main.py b/backend/api/main.py
index 10768ec..a78b1ce 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -2065,7 +2065,20 @@ async def _startup() -> None:
threading.Thread(target=_flush_loop, daemon=True).start()
threading.Thread(target=_cleanup_loop, daemon=True).start()
- _media_monitor = MediaMonitor(callback=_on_media_change, interval=3)
+ # EN: 10 s default — on Linux each tick walks every process's open
+ # files, which is real work on a busy host; mic-state latency does
+ # not need sub-second freshness. SNITCH_MEDIA_INTERVAL overrides.
+ # FR: 10 s par défaut — sous Linux chaque tick parcourt les fichiers
+ # ouverts de tous les processus, un vrai coût sur hôte chargé ;
+ # la fraîcheur du micro n'exige pas la seconde.
+ # SNITCH_MEDIA_INTERVAL permet d'ajuster.
+ try:
+ _media_iv = max(3, min(300, int(os.environ.get(
+ "SNITCH_MEDIA_INTERVAL", "10"))))
+ except ValueError:
+ _media_iv = 10
+ _media_monitor = MediaMonitor(callback=_on_media_change,
+ interval=_media_iv)
threading.Thread(target=_media_monitor.start, daemon=True).start()
diff --git a/backend/capture/pcap.py b/backend/capture/pcap.py
index 229039e..c748c67 100644
--- a/backend/capture/pcap.py
+++ b/backend/capture/pcap.py
@@ -248,12 +248,17 @@ def _sockaddr_ip(ptr: Optional[int]) -> Optional[str]:
"""
if not ptr:
return None
- raw = ctypes.string_at(ptr, 24)
- family = raw[1] if sys.platform == "darwin" else int.from_bytes(raw[0:2], "little")
+ # EN: Read the 2-byte family FIRST — a short sockaddr (sa_len/
+ # sa_family only, e.g. AF_UNIX) must not be over-read for 24 bytes.
+ # FR: Lire la famille sur 2 octets D'ABORD — un sockaddr court
+ # (sa_len/sa_family seuls, ex. AF_UNIX) ne doit pas être relu
+ # sur 24 octets.
+ head = ctypes.string_at(ptr, 2)
+ family = head[1] if sys.platform == "darwin" else int.from_bytes(head, "little")
if family == socket.AF_INET:
- return socket.inet_ntop(socket.AF_INET, raw[4:8])
+ return socket.inet_ntop(socket.AF_INET, ctypes.string_at(ptr + 4, 4))
if family == socket.AF_INET6:
- return socket.inet_ntop(socket.AF_INET6, raw[8:24])
+ return socket.inet_ntop(socket.AF_INET6, ctypes.string_at(ptr + 8, 16))
return None
@@ -322,6 +327,14 @@ class PcapSession:
raise PcapError(f"pcap_compile({bpf_filter!r}): {self._err()}")
if self._lib.pcap_setfilter(self._handle, ctypes.byref(prog)) != 0:
raise PcapError(f"pcap_setfilter: {self._err()}")
+ except Exception:
+ # EN: A filter failure must not strand the live handle —
+ # nothing else will ever close it after __init__ raises.
+ # FR: Un échec de filtre ne doit pas orpheliner le handle
+ # live — plus rien ne le fermera si __init__ lève.
+ self._lib.pcap_close(self._handle)
+ self._closed = True
+ raise
finally:
self._lib.pcap_freecode(ctypes.byref(prog))
diff --git a/backend/detection/askmode.py b/backend/detection/askmode.py
index 55374ef..fa61cf6 100644
--- a/backend/detection/askmode.py
+++ b/backend/detection/askmode.py
@@ -56,6 +56,13 @@ logger = logging.getLogger(__name__)
_QUEUE_NUM = 7
_MAX_PENDING = 512
+# EN: Cap on remembered verdicts — long-running hosts see endless fresh
+# (ip, port) pairs via ephemeral ports, so keep only the most recent
+# decisions (dict order = insertion order).
+# FR: Borne des verdicts retenus — un hôte longue durée voit défiler des
+# paires (ip, port) sans fin via les ports éphémères ; on ne garde que
+# les décisions récentes (ordre du dict = ordre d'insertion).
+_MAX_DECIDED = 65_536
_DEFAULT_TIMEOUT = 15.0
@@ -96,12 +103,18 @@ class AskMode:
self._decided: dict[tuple, bool] = {}
self._lock = threading.Lock()
self._rule_installed = False
+ # EN: Rules planted by the last successful start() — needed so
+ # stop() can remove the complete set, not just the queue jump.
+ # FR: Règles posées par le dernier start() réussi — nécessaire pour
+ # que stop() retire l'ensemble complet, pas seulement le saut.
+ self._installed: list[list[str]] = []
# EN: IPs exempted from diversion at start (whitelist — "allow
- # always" verdicts). Bounded; tracked for clean removal.
+ # always" verdicts). Bounded; their delete-mirrors ride in
+ # _installed like every other rule.
# FR: IPs exemptées du détournement au start (whitelist — verdicts
- # « autoriser toujours »). Bornées ; suivies pour le retrait.
+ # « autoriser toujours »). Bornées ; leurs suppressions miroir
+ # voyagent dans _installed comme les autres règles.
self._exempt: list[str] = []
- self._exempt_rules: list[list[str]] = []
# ── lifecycle / cycle de vie ──────────────────────────────────────────
@@ -185,16 +198,35 @@ class AskMode:
cmds.insert(len(cmds) - 1,
["iptables", "-w", "-I", "OUTPUT", "-d", ip,
"-j", "RETURN"])
- self._exempt_rules.append(
- ["iptables", "-w", "-D", "OUTPUT", "-d", ip, "-j",
- "RETURN"])
+ # EN: Rules land one at a time — track each inserted rule so a
+ # mid-sequence failure rolls back EVERYTHING it already
+ # planted (a stranded NFQUEUE jump would wedge the host's
+ # outbound traffic until reboot).
+ # FR: Les règles atterrissent une à une — suivre chaque insertion
+ # pour qu'un échec à mi-parcours annule TOUT ce qui a été posé
+ # (un saut NFQUEUE orphelin bloquerait le trafic sortant de
+ # l'hôte jusqu'au reboot).
+ inserted: list[list[str]] = []
for c in cmds:
try:
subprocess.run(c, timeout=10, check=False,
capture_output=True)
+ inserted.append(c)
except OSError as e:
- self.stop()
+ self._rollback_rules(inserted)
+ try:
+ if self._nfq is not None:
+ self._nfq.close()
+ finally:
+ self._nfq = None
return False, f"iptables failed: {e}"
+ # EN: Remember EVERY rule planted — stop() removes the full set,
+ # not just the queue jump + exemptions (repeated start/stop
+ # cycles used to stack stale RETURN rules on OUTPUT).
+ # FR: Retenir CHAQUE règle posée — stop() retire l'ensemble
+ # complet, pas seulement le saut + exemptions (les cycles
+ # start/stop empilaient des règles RETURN périmées sur OUTPUT).
+ self._installed = inserted
self._rule_installed = True
self._running = True
self._thread = threading.Thread(target=self._run, daemon=True,
@@ -218,6 +250,22 @@ class AskMode:
finally:
self._running = False
+ @staticmethod
+ def _rollback_rules(inserted: list[list[str]]) -> None:
+ """EN: Undo partial rule installation — every `-I` insert becomes
+ the mirror `-D` delete, applied in reverse order so dependant
+ entries unwind cleanly. Best-effort, never raises.
+ FR: Annuler une installation partielle — chaque `-I` devient le
+ `-D` miroir, appliqué en ordre inverse. Au mieux, ne lève jamais."""
+ import subprocess
+ for c in reversed(inserted):
+ rm = ["-D" if a == "-I" else a for a in c]
+ try:
+ subprocess.run(rm, timeout=10, check=False,
+ capture_output=True)
+ except OSError:
+ pass
+
def stop(self) -> None:
self._running = False
with self._lock:
@@ -242,14 +290,13 @@ class AskMode:
except Exception: # noqa: BLE001
pass
if self._rule_installed:
- import subprocess
- subprocess.run(["iptables", "-w", "-D", "OUTPUT", "-j",
- "NFQUEUE", "--queue-num", str(_QUEUE_NUM)],
- timeout=10, check=False, capture_output=True)
- for rm in self._exempt_rules:
- subprocess.run(rm, timeout=10, check=False,
- capture_output=True)
- self._exempt_rules.clear()
+ # EN: Mirror-delete every rule start() planted — jump AND all
+ # the RETURN exemptions, in reverse insertion order.
+ # FR: Suppression miroir de toutes les règles posées par
+ # start() — saut ET toutes les exemptions RETURN, en
+ # ordre inverse d'insertion.
+ self._rollback_rules(self._installed)
+ self._installed = []
self._rule_installed = False
# ── verdict path / chemin du verdict ─────────────────────────────────
@@ -327,6 +374,27 @@ class AskMode:
except Exception: # noqa: BLE001
pass
+ def _remember(self, key: tuple, allow: bool) -> None:
+ """EN: Record a verdict under the lock, evicting the oldest
+ quarter once the cache overflows.
+ FR: Mémoriser un verdict sous le verrou, en évinçant le quart le
+ plus ancien une fois le cache plein. Caller holds _lock."""
+ self._decided[key] = allow
+ if len(self._decided) > _MAX_DECIDED:
+ for k in list(self._decided)[:_MAX_DECIDED // 4]:
+ del self._decided[k]
+
+ def _verdict(self, pkt_id: int, allow: bool) -> None:
+ """EN: Emit an NFQUEUE verdict, swallowing the races a concurrent
+ stop() creates by closing the socket mid-verdict.
+ FR: Émettre un verdict NFQUEUE en absorbant les courses créées par
+ un stop() concurrent qui ferme le socket en plein verdict."""
+ try:
+ if self._nfq is not None:
+ self._nfq.verdict(pkt_id, allow)
+ except Exception: # noqa: BLE001 — stop() raced
+ pass
+
def _waiter(self, key: tuple, ev: threading.Event) -> None:
"""EN: Holds one packet until decide() or the timeout; the recv
loop keeps serving other flows meanwhile.
@@ -336,9 +404,9 @@ class AskMode:
return # EN: decide() applied it
with self._lock:
ent = self._pending.pop(key, None)
- self._decided[key] = self._failopen
- if ent is not None and self._nfq is not None:
- self._nfq.verdict(ent[1], self._failopen)
+ self._remember(key, self._failopen)
+ if ent is not None:
+ self._verdict(ent[1], self._failopen)
def decide(self, remote_ip: str, remote_port: int, proto: str,
allow: bool) -> bool:
@@ -348,11 +416,10 @@ class AskMode:
key = (remote_ip, int(remote_port), (proto or "TCP").upper())
with self._lock:
ent = self._pending.pop(key, None)
- self._decided[key] = bool(allow)
+ self._remember(key, bool(allow))
if ent is None:
return False
- if self._nfq is not None:
- self._nfq.verdict(ent[1], bool(allow))
+ self._verdict(ent[1], bool(allow))
ent[0].set()
return True
diff --git a/backend/detection/customrules.py b/backend/detection/customrules.py
index 747420b..2f203c2 100644
--- a/backend/detection/customrules.py
+++ b/backend/detection/customrules.py
@@ -16,9 +16,11 @@ EN: User-defined alert rules — a deliberately SMALL matcher, not a
Supported ops : eq, ne, contains, regex, gt, lt, cidr.
Actions : alert (default) | block (firewall rule on the
matched remote_ip — the per-flow kill-switch).
- Regex is bounded (pattern <= 200 chars, applied with a per-packet
- compiled cache of <= 64 patterns) so a bad rule cannot DoS the
- packet path; an invalid rule fails validation at creation.
+ Regex is bounded (pattern <= 200 chars, nested quantifiers rejected
+ at validation, compiled cache <= 64 patterns) so a bad rule cannot
+ DoS the packet path; an invalid rule fails validation at creation.
+ Residual: ambiguous alternation under a quantifier ((a|a)+) is a
+ known unblocked shape — the matcher stays O(fields) worst-case.
FR: Règles d'alerte définies par l'utilisateur — un filtreur
volontairement PETIT, pas un langage de signatures. Une règle choisit
@@ -55,6 +57,135 @@ _ACTIONS = ("alert", "block")
_MAX_RULES = 256
_MAX_PATTERN = 200
_MAX_COMPILED = 64
+# EN: Nested-quantifier detector — the dominant catastrophic-backtracking
+# shape: a group that CONTAINS a quantifier is itself quantified
+# ((a+)+, (.*)*, ([a-z]+)+). Python's `re` has no match timeout, so
+# the only honest defence is rejecting the shape at validation time.
+# The scan skips escapes and char classes to avoid flagging
+# `[+*]` or `\+` as real quantifiers.
+# FR: Détecteur de quantifieurs imbriqués — la forme dominante du
+# backtracking catastrophique : un groupe CONTENANT un quantifieur
+# est lui-même quantifié ((a+)+, (.*)*, ([a-z]+)+). Le `re` de Python
+# n'a pas de timeout de match ; la seule défense honnête est de
+# rejeter la forme à la validation. Le scan ignore les échappements
+# et les classes de caractères pour ne pas signaler `[+*]` ou `\+`.
+def _brace_quant(pattern: str, i: int) -> int:
+ """EN: Classify pattern[i] == '{' — 0 = not a quantifier (literal),
+ 1 = bounded ({n}, {n,m}, {,m}), 2 = unbounded ({n,}).
+ FR: Classer pattern[i] == '{' — 0 = pas un quantifieur (littéral),
+ 1 = borné ({n}, {n,m}, {,m}), 2 = non borné ({n,})."""
+ j = pattern.find("}", i + 1)
+ if j == -1 or j - i > 8:
+ return 0
+ inner = pattern[i + 1:j]
+ if not inner or not all(ch.isdigit() or ch == "," for ch in inner):
+ return 0
+ if inner.endswith(",") and inner[:-1].isdigit():
+ return 2 # EN: {n,} — open upper bound / FR: borne haute ouverte
+ return 1
+
+
+def _unbounded_quant(pattern: str, i: int) -> bool:
+ """EN: True when pattern[i] opens an UNBOUNDED repetition — '+', '*'
+ or '{n,}'. '?' and '{n,m}' are bounded and cannot produce
+ exponential backtracking as the OUTER loop.
+ FR: Vrai quand pattern[i] ouvre une répétition NON bornée — '+', '*'
+ ou '{n,}'. '?' et '{n,m}' sont bornés et ne peuvent produire un
+ backtracking exponentiel comme boucle EXTERNE."""
+ c = pattern[i]
+ if c in "+*":
+ return True
+ if c == "{":
+ return _brace_quant(pattern, i) == 2
+ return False
+
+
+def _any_quant(pattern: str, i: int) -> bool:
+ """EN: True when pattern[i] is ANY real quantifier — the INNER
+ criterion. Even a bounded inner repetition under an unbounded
+ outer one is catastrophic: (a{1,3})+ partitions the input
+ exponentially many ways.
+ FR: Vrai quand pattern[i] est un vrai quantifieur — le critère
+ INTERNE. Même une répétition interne bornée sous une externe non
+ bornée est catastrophique : (a{1,3})+ partitionne l'entrée de
+ façon exponentielle."""
+ c = pattern[i]
+ if c in "+*?":
+ return True
+ if c == "{":
+ return _brace_quant(pattern, i) != 0
+ return False
+
+
+def _has_nested_quantifier(pattern: str) -> bool:
+ """EN: True when an unboundedly-quantified group itself contains any
+ quantifier — the (a+)+ / (.*)* / (a?)+ catastrophic shapes.
+ FR: Vrai quand un groupe quantifié sans borne contient un quantifieur
+ — les formes catastrophiques (a+)+ / (.*)* / (a?)+."""
+ stack: list[bool] = [] # EN: group → contains a quantifier / FR: groupe → contient un quantifieur
+ i, n = 0, len(pattern)
+ while i < n:
+ c = pattern[i]
+ if c == "\\":
+ i += 2
+ continue
+ if c == "[":
+ # EN: skip the whole char class (handles ]-first and escapes)
+ # FR: sauter toute la classe (gère ]-premier et échappements)
+ i += 1
+ if i < n and pattern[i] == "^":
+ i += 1
+ if i < n and pattern[i] == "]":
+ i += 1
+ while i < n:
+ if pattern[i] == "\\":
+ i += 2
+ continue
+ if pattern[i] == "]":
+ break
+ i += 1
+ i += 1
+ continue
+ if c == "(":
+ stack.append(False)
+ i += 1
+ # EN: (?: ?= ?! ?<= ?<! ?P<name> ?P= ?# (?flags — the '?' is a
+ # group-type marker, not a quantifier; skip the prefix so
+ # it never flags the group as quantified.
+ # FR: (?: ?= ?! ?<= ?<! ?P<name> ?P= ?# (?flags — le '?' est
+ # un marqueur de type de groupe, pas un quantifieur ;
+ # sauter le préfixe pour ne pas marquer le groupe.
+ if i < n and pattern[i] == "?":
+ i += 1
+ while i < n and pattern[i] in ":<>=!P#aiLmsux_":
+ i += 1
+ if i >= 2 and pattern[i - 1] == "<":
+ # EN: (?P<name> — consume the name up to '>'
+ # FR: (?P<name> — consommer le nom jusqu'à '>'
+ while i < n and pattern[i] not in ")>":
+ i += 1
+ if i < n:
+ i += 1
+ continue
+ if c == ")":
+ inner = stack.pop() if stack else False
+ i += 1
+ # EN: unbounded quantifier right after the group close?
+ # FR: quantifieur non borné juste après la fermeture ?
+ if i < n and _unbounded_quant(pattern, i) and inner:
+ return True
+ # EN: the parent "contains a quantifier" whenever the child
+ # carried one — (a+)b inside (...) + is dangerous too.
+ # FR: le parent « contient un quantifieur » dès que l'enfant
+ # en portait un — (a+)b dans (...) + est dangereux aussi.
+ if stack and inner:
+ stack[-1] = True
+ i += 1
+ continue
+ if c in "+*?{" and _any_quant(pattern, i) and stack:
+ stack[-1] = True
+ i += 1
+ return False
class CustomRules:
@@ -123,6 +254,10 @@ class CustomRules:
re.compile(value)
except re.error as exc:
raise ValueError(f"bad regex: {exc}") from exc
+ if _has_nested_quantifier(value):
+ raise ValueError(
+ "nested quantifiers rejected (ReDoS risk) — "
+ "rewrite without (…+/…*)+" )
if c["op"] == "cidr":
ipaddress.ip_network(value, strict=False)
if c["op"] in ("gt", "lt") and \
diff --git a/backend/detection/miner.py b/backend/detection/miner.py
index 8bbfbf1..f08d866 100644
--- a/backend/detection/miner.py
+++ b/backend/detection/miner.py
@@ -63,6 +63,13 @@ _POOL_PORTS = {3333, 4444, 5555, 7777, 8333, 9999, 14433, 14444,
_CPU_THRESHOLD = 70.0 # EN: sustained % to corroborate / FR: % soutenu corroborant
_CPU_WINDOW_S = 30.0 # EN: min observation before accusing / FR: observation min avant accusation
_COOLDOWN = 600.0 # EN: per-process alert cooldown / FR: cooldown par processus
+# EN: Bound on the suspect map — corroboration drains 32 per tick, so a
+# flood of distinct (pid, remote) pairs is capped well above the
+# plausible legitimate rate but far below memory concern.
+# FR: Borne de la map de suspects — la corroboration draine 32 par tick ;
+# un flot de paires (pid, remote) est borné au-dessus du rythme
+# légitime mais loin de tout souci mémoire.
+_MAX_SUSPECTS = 4096
class MinerDetector:
@@ -125,10 +132,24 @@ class MinerDetector:
return out # EN: no need to suspect further
# EN: Signal 2 — pool port: mark for CPU corroboration, never
- # enough alone. / FR: Signal 2 — port de pool : marqué pour
- # corroboration CPU, jamais suffisant seul.
+ # enough alone. The suspect map is bounded — a process
+ # sweeping many remotes (scanner, busy proxy) must not grow
+ # it past the drain rate of 32 corroborations/tick.
+ # FR: Signal 2 — port de pool : marqué pour corroboration CPU,
+ # jamais suffisant seul. La map est bornée — un processus
+ # balayant beaucoup d'hôtes (scanner, proxy chargé) ne doit
+ # pas la faire croître au-delà du rythme de 32/tick.
if pkt.dst_port in _POOL_PORTS and pid:
with self._lock:
+ if len(self._suspects) >= _MAX_SUSPECTS:
+ # EN: evict the oldest quarter — stale suspects are
+ # the least informative anyway.
+ # FR: évincer le quart le plus ancien — les suspects
+ # périmés sont les moins informatifs.
+ stale = sorted(self._suspects.items(),
+ key=lambda kv: kv[1])
+ for k, _ in stale[:_MAX_SUSPECTS // 4]:
+ self._suspects.pop(k, None)
self._suspects.setdefault((pid, remote), time.time())
return out
diff --git a/backend/storage/db.py b/backend/storage/db.py
index 0197825..7b4162c 100644
--- a/backend/storage/db.py
+++ b/backend/storage/db.py
@@ -53,6 +53,14 @@ _pending: dict[tuple, list] = defaultdict(lambda: [0, 0])
_pending_hist: dict[tuple, list] = defaultdict(lambda: [0, 0])
_pending_alerts: list[tuple] = []
_pending_lock = threading.Lock()
+# EN: Cap on buffered alerts between 10 s flushes — an alert storm must
+# not balloon RAM if the disk ever stalls. Overflow drops the oldest
+# and is counted so it stays visible, never silent.
+# FR: Borne des alertes tamponnées entre deux flushes de 10 s — une
+# tempête d'alertes ne doit pas gonfler la RAM si le disque traîne.
+# Le débordement jette les plus anciennes et est compté, jamais muet.
+_MAX_PENDING_ALERTS = 10_000
+_alerts_dropped = 0
def _utcnow_minute() -> str:
@@ -378,10 +386,27 @@ def log_alert(alert: dict) -> None:
alert["severity"], alert["message"],
alert.get("node_id"), json.dumps(alert.get("details", {})),
)
+ global _alerts_dropped
with _pending_lock:
+ if len(_pending_alerts) >= _MAX_PENDING_ALERTS:
+ # EN: drop the oldest quarter at once so a sustained storm
+ # pays the eviction cost rarely, not per-append.
+ # FR: jeter le quart le plus ancien d'un coup pour qu'une
+ # tempête soutenue paie le coût d'éviction rarement.
+ del _pending_alerts[:_MAX_PENDING_ALERTS // 4]
+ _alerts_dropped += _MAX_PENDING_ALERTS // 4
+ logger.warning("alert buffer overflow — %d dropped total",
+ _alerts_dropped)
_pending_alerts.append(row)
+def alerts_dropped() -> int:
+ """EN: Alerts discarded by the buffer cap since startup — 0 in
+ healthy operation. / FR: Alertes perdues par la borne du tampon
+ depuis le démarrage — 0 en fonctionnement sain."""
+ return _alerts_dropped
+
+
# ── Read helpers / Aides de lecture ──────────────────────────────────────────
def get_timeline(minutes: int = 60) -> list[dict]:
diff --git a/backend/tests/test_db.py b/backend/tests/test_db.py
index 1a588d6..a6f16cc 100644
--- a/backend/tests/test_db.py
+++ b/backend/tests/test_db.py
@@ -95,3 +95,20 @@ def test_get_alerts_reads_persisted():
rows = db.get_alerts(100)
hit = [r for r in rows if r["id"] == alert["id"]]
assert hit and hit[0]["type"] == "PORT_SCAN" and hit[0]["details"]["ports"] == 25
+
+
+def test_alert_buffer_cap_counts_drops():
+ """EN: The alert buffer is bounded — past _MAX_PENDING_ALERTS the
+ oldest quarter is evicted and alerts_dropped() counts it. Flush at the
+ end so the suite's buffer state stays clean.
+ FR: Le tampon d'alertes est borné — au-delà de la borne le quart le
+ plus ancien est évincé et alerts_dropped() le compte. Flush final pour
+ garder l'état propre."""
+ before = db.alerts_dropped()
+ for i in range(db._MAX_PENDING_ALERTS + 1):
+ db.log_alert({
+ "id": f"cap-{i}", "timestamp": "2026-01-01T00:00",
+ "type": "T", "severity": "info", "message": "m",
+ })
+ assert db.alerts_dropped() > before
+ db.flush()
diff --git a/backend/tests/test_enterprise.py b/backend/tests/test_enterprise.py
index eec48c1..a2cc7b2 100644
--- a/backend/tests/test_enterprise.py
+++ b/backend/tests/test_enterprise.py
@@ -158,6 +158,82 @@ def test_sigma_conds_reject_bad_field():
{"field": "nope", "op": "eq", "value": "x"}])
+# ── ReDoS guard / garde ReDoS ────────────────────────────────────────────
+
+def test_regex_rejects_nested_quantifiers():
+ """EN: (a+)+-shaped patterns are refused at validation — Python's re
+ has no match timeout so the shape itself is rejected.
+ FR: Les motifs de forme (a+)+ sont refusés à la validation — le re de
+ Python n'a pas de timeout donc la forme est rejetée."""
+ import pytest
+ from detection.customrules import CustomRules
+ for pat in ("(a+)+", "(.*)*", "([a-z]+)+", "(a?)+",
+ "(a{1,3})+", "((a+)b)+", "(?:a+)+", "(x{2,})+"):
+ with pytest.raises(ValueError, match="nested quantifiers"):
+ CustomRules().add("redos", "host", "regex", pat)
+
+
+def test_regex_accepts_safe_patterns():
+ """EN: Bounded and non-nested patterns stay legal — the guard must
+ not overblock. / FR: Les motifs bornés et non imbriqués restent
+ légaux — la garde ne doit pas surbloquer."""
+ from detection.customrules import CustomRules
+ for pat in ("a+b", r"[a-z]+$", "(?:ab)+", "(a|b)+", r"\+x+",
+ "(a+){2}", "x{2,3}y", "(a?b)c", "foo{bar}"):
+ CustomRules().add("ok", "host", "regex", pat)
+
+
+def test_nested_quantifier_scanner():
+ """EN: Direct unit coverage of the shape detector — escapes, char
+ classes and group-type prefixes must not confuse it.
+ FR: Couverture unitaire directe du détecteur — échappements, classes
+ et préfixes de groupe ne doivent pas le perturber."""
+ from detection.customrules import _has_nested_quantifier as f
+ assert f("(a+)+") and f("((a+)b)+") and f("([a-z]+)+")
+ assert not f("(?:ab)+") and not f("(?P<n>a)b") and not f("[+*]+")
+ assert not f(r"a\(x\)+b") # EN: escaped parens / FR: parenthèses échappées
+
+
+# ── ask-mode bounds / bornes du mode ask ─────────────────────────────────
+
+def test_askmode_decided_bounded():
+ """EN: Verdict memory evicts the oldest entries past _MAX_DECIDED.
+ FR: La mémoire des verdicts évinçe les plus anciens au-delà de la borne."""
+ import sys
+ import pytest
+ if sys.platform != "linux":
+ pytest.skip("NFQUEUE backend is Linux-only")
+ from detection.askmode import AskMode, _MAX_DECIDED
+ am = AskMode(on_ask=lambda e: None)
+ with am._lock:
+ for i in range(_MAX_DECIDED + 100):
+ am._remember((f"10.0.0.{i % 250}", i, "TCP"), True)
+ assert len(am._decided) == _MAX_DECIDED - _MAX_DECIDED // 4 + 100 \
+ or len(am._decided) <= _MAX_DECIDED
+
+
+def test_askmode_rollback_mirrors_inserts(monkeypatch):
+ """EN: _rollback_rules turns every -I insert into the -D delete, in
+ reverse order. / FR: _rollback_rules transforme chaque insertion -I
+ en suppression -D, en ordre inverse."""
+ import sys
+ import pytest
+ if sys.platform != "linux":
+ pytest.skip("iptables is Linux-only")
+ from detection.askmode import AskMode
+ calls = []
+ monkeypatch.setattr("subprocess.run",
+ lambda c, **kw: calls.append(c) or None)
+ AskMode._rollback_rules([
+ ["iptables", "-w", "-I", "OUTPUT", "-o", "lo", "-j", "RETURN"],
+ ["iptables", "-w", "-I", "OUTPUT", "-j", "NFQUEUE",
+ "--queue-num", "7"],
+ ])
+ assert calls[0][3] == "-D" and "NFQUEUE" in calls[0] # EN: jump first / FR: saut d'abord
+ assert calls[1][3] == "-D" and "lo" in calls[1]
+ assert all("-I" not in c for c in calls)
+
+
# ── fleet merge / fusion de flotte ───────────────────────────────────────────
def test_fleet_audit_merge(monkeypatch):
diff --git a/backend/tests/test_v15_features.py b/backend/tests/test_v15_features.py
index b7ee682..3ce8d16 100644
--- a/backend/tests/test_v15_features.py
+++ b/backend/tests/test_v15_features.py
@@ -893,3 +893,23 @@ def test_askmode_exempt_bounded():
am = AskMode(lambda ctx: None)
am._exempt = [f"10.0.0.{i}" for i in range(200)][:64]
assert len(am._exempt) == 64
+
+
+def test_miner_suspects_bounded():
+ """EN: A process sweeping many pool-port remotes cannot grow the
+ suspect map past _MAX_SUSPECTS — the oldest quarter is evicted.
+ FR: Un processus balayant beaucoup d'hôtes pool-port ne peut faire
+ croître la map au-delà de la borne — le quart le plus ancien est
+ évincé."""
+ from detection.miner import MinerDetector, _MAX_SUSPECTS
+
+ class P:
+ direction, protocol, dst_port = "out", "TCP", 3333
+ dst_ip, process_name, pid, app_head = "1.2.3.4", "p", 42, b""
+
+ m = MinerDetector()
+ with m._lock:
+ for i in range(_MAX_SUSPECTS + 10):
+ m._suspects[(1, f"10.0.{i // 250}.{i % 250}")] = 0.0
+ m.analyze_packet(P())
+ assert len(m._suspects) <= _MAX_SUSPECTS