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.
Python cybersecurityd3jsebpfedrelectronfastapifirewallfleet-managementlinuxlittle-snitch-alternativemacosnetwork-monitornetwork-securitypacket-captureprivacyreactrustself-hostedsiemwindows
Close remaining gaps: pure-Python NFQUEUE, DGA, proto-mismatch, kill-switch
MoneyLisafc56682c1e0d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53c4a83..8d09f32 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,19 @@ All notable changes to Snitch. / Toutes les modifications notables de Snitch.The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.+## [1.5.2] — 2026-10-22++### Added / Ajouté++- **Pure-Python NFQUEUE client / Client NFQUEUE pur Python** — `detection/nfqueue.py` speaks `nfnetlink_queue` over AF_NETLINK directly: config commands (PF_UNBIND/PF_BIND/BIND/COPY_PACKET) verified by netlink ACKs, packet receive + ACCEPT/DROP verdicts. Ask-on-connect no longer needs `python-netfilterqueue` or `libnetfilter_queue` — Linux + root + iptables only. Each held packet now waits on its own waiter thread so a stalled flow can't starve other verdicts. / `detection/nfqueue.py` parle nfnetlink_queue en AF_NETLINK directement : bind vérifié par ACK, réception + verdicts ACCEPT/DROP. Plus besoin de `python-netfilterqueue` — Linux + root + iptables seulement. Chaque paquet retenu a son thread d'attente dédié.+- **DGA heuristic / Heuristique DGA** — `detection/dga.py` scores resolved DNS names and TLS SNIs on lexical features (Shannon entropy, vowel ratio, consonant runs, digit noise, nesting) → `DGA_SUSPECT` (info), one alert per name per hour. Pure local heuristic — no WHOIS, no domain-age data. / `detection/dga.py` note les noms DNS/SNI sur traits lexicaux → `DGA_SUSPECT` (info), cooldown 1 h par nom. Heuristique locale pure.+- **Protocol/port mismatch / Protocole déguisé** — `detection/protomatch.py` verifies the ≤64 B payload head against the well-known port (HTTP/80, DNS/53 both transports, SSH/22, TLS/443+853, mail ASCII commands) → `PROTO_MISMATCH` (info), cooled down per flow. / `detection/protomatch.py` vérifie la tête du payload contre le port bien connu → `PROTO_MISMATCH` (info).+- **Volume kill-switch (opt-in) / Kill-switch de volume (opt-in)** — setting `kill_switch_enabled` upgrades an `UPLOAD_SPIKE` alert into a real firewall block on the remote IP (deduped per IP, best-effort — needs privileges). Off by default; toggle in Settings. / Le réglage `kill_switch_enabled` transforme `UPLOAD_SPIKE` en vrai blocage pare-feu sur l'IP distante (dédupliqué, privilèges requis). Off par défaut.++### Changed / Modifié++- **Ask-on-connect dependency / Dépendance ask-on-connect** — dropped `NetfilterQueue`/`libnetfilter_queue`; `askmode` uses the bundled pure-Python client. / `NetfilterQueue`/`libnetfilter_queue` abandonnés ; `askmode` utilise le client pur Python embarqué.+## [1.5.1] — 2026-10-22### Added / Ajoutédiff --git a/CITATION.cff b/CITATION.cffindex 8da00ae..a106bdc 100644--- a/CITATION.cff+++ b/CITATION.cff@@ -17,5 +17,5 @@ keywords:- privacy- traffic visualization- cybersecurity-version: "1.5.1"+version: "1.5.2"date-released: "2026-10-01"diff --git a/backend/api/main.py b/backend/api/main.pyindex eed7933..edefd99 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -103,10 +103,12 @@ from detection.llm_local import LocalSlmfrom detection.miner import MinerDetectorfrom detection.mlflow import FlowAnomalyfrom detection import askmode+from detection import dgafrom detection import ebpf_enforcefrom detection import hollow as hollowmodfrom detection.gossip import PeerSyncfrom detection import perfprobe+from detection import protomatchfrom detection.sinkresponder import SinkholeResponderfrom detection.threatintel import ThreatIntelfrom api.notify import notifier@@ -193,6 +195,13 @@ ebpf_enforcer = ebpf_enforce.EbpfEnforcer()_rule_blocks: set[tuple] = set()_entropy_cooldown: dict[str, float] = {}_icmp_window: dict[str, list] = {}+_dga_seen: dict[str, float] = {} # EN: name → last alert ts+_proto_cooldown: dict[tuple, float] = {} # EN: (ip, port) → last ts+# EN: Opt-in volume kill-switch — UPLOAD_SPIKE installs a real firewall+# block on the remote IP instead of only alerting. Off by default.+# FR: Kill-switch de volume opt-in — UPLOAD_SPIKE installe un vrai blocage+# pare-feu sur l'IP distante. Désactivé par défaut.+_kill_switch = False# EN: IOC peer-sync cadence — fixed 5 min; activation is governed by the# `gossip_enabled` setting, not by this constant.# FR: Cadence de sync IOC — 5 min fixe ; l'activation relève du réglage@@ -878,6 +887,31 @@ def _process_batch(packets: list[Packet]) -> None:# d'intégrité une fois par tick (elle déduplique par processus).seen_pids: dict[int, str] = {}+ def _emit(a: Alert, notify: bool = False) -> None:+ """EN: Flag, persist and queue one alert — the standard emit path.+ FR: Marque, persiste et file une alerte — chemin d'émission type."""+ _flag_alert(a, nodes)+ ad = a.to_dict()+ db.log_alert(ad)+ out_alerts.append(ad)+ if notify:+ asyncio.get_running_loop().create_task(_notify(ad))++ def _dga_check(name: str) -> Optional[dict]:+ """EN: DGA lexical score + 1 h per-name cooldown — finding or None.+ FR: Score lexical DGA + cooldown 1 h par nom — finding ou None."""+ hit = dga.score(name)+ if not hit:+ return None+ low = name.rstrip(".").lower()+ now_s = time.monotonic()+ if now_s - _dga_seen.get(low, 0) < 3600:+ return None+ if len(_dga_seen) >= 4096:+ _dga_seen.pop(next(iter(_dga_seen)))+ _dga_seen[low] = now_s+ return hit+for pkt in packets:if pkt.process_name and pkt.process_name in _excluded_processes:_drop_stats["excluded_process"] += 1@@ -918,6 +952,22 @@ def _process_batch(packets: list[Packet]) -> None:dns53.append((name, ip, _ttl))if dns53:learn_dns_answers(dns53)+ # EN: DGA lexical heuristic on resolved names — random-looking+ # domains are a classic C2/exfil signal. Bounded: one+ # alert per name per hour (see _dga_check).+ # FR: Heuristique lexicale DGA sur les noms résolus — les+ # domaines à aspect aléatoire sont un signal C2/exfil.+ for name, _ip, _ttl in dns53:+ hit = _dga_check(name)+ if hit:+ _emit(Alert(+ type="DGA_SUSPECT", severity="info",+ message=f"DGA-looking domain {hit['label']} "+ f"({', '.join(hit['reasons'])}) via "+ f"{name}",+ node_id=remote_ip,+ details={"name": name, "ip": remote_ip,+ **hit}), notify=True)if pkt.dhcp:_learn_dhcp_name(*pkt.dhcp, touched_devices)@@ -930,6 +980,17 @@ def _process_batch(packets: list[Packet]) -> None:if pkt.sni:learn_sni(remote_ip, pkt.sni)+ hit = _dga_check(pkt.sni)+ if hit:+ _emit(Alert(+ type="DGA_SUSPECT", severity="info",+ message=f"DGA-looking SNI {hit['label']} "+ f"({', '.join(hit['reasons'])}) — "+ f"{pkt.process_name or '?'} → {remote_ip}",+ node_id=remote_ip,+ details={"name": pkt.sni, "ip": remote_ip,+ "process": pkt.process_name, "pid": pkt.pid,+ **hit}), notify=True)# ── LAN accounting / Comptabilisation LAN ───────────────────────────if is_private(remote_ip):@@ -1036,6 +1097,21 @@ def _process_batch(packets: list[Packet]) -> None:and not is_private(remote_ip)and ti.begin_check(remote_ip)):asyncio.get_running_loop().create_task(_ti_check(remote_ip))+ # EN: Volume kill-switch (opt-in setting kill_switch_enabled) —+ # an UPLOAD_SPIKE additionally installs a REAL firewall+ # block on the remote IP, deduped, best effort. Off by+ # default: auto-blocking traffic is a deliberate choice.+ # FR: Kill-switch de volume (réglage opt-in) — UPLOAD_SPIKE+ # installe en plus un vrai blocage pare-feu sur l'IP+ # distante, dédupliqué, au mieux. Off par défaut.+ if (alert.type == "UPLOAD_SPIKE" and _kill_switch+ and pkt.direction == "out"+ and not is_private(remote_ip)):+ bk = ("killswitch", remote_ip)+ if bk not in _rule_blocks and len(_rule_blocks) < 4096:+ _rule_blocks.add(bk)+ asyncio.get_running_loop().run_in_executor(+ None, fw.add_rule, "ip", remote_ip, "block", 64)# EN: Firewall visibility — a packet matching an active rule (or the# lockdown) raises BLOCKED_ATTEMPT. This flags policy hits; actual@@ -1174,6 +1250,32 @@ def _process_batch(packets: list[Packet]) -> None:db.log_alert(ad)out_alerts.append(ad)+ # EN: Disguised-protocol check — the payload head must match what+ # the well-known port advertises (HTTP/80, DNS/53, SSH/22,+ # TLS/443, mail ASCII commands; see detection/protomatch.py).+ # One alert per (ip, port) per 10 min. / FR: Contrôle de+ # protocole déguisé — la tête du payload doit correspondre au+ # protocole annoncé par le port. Une alerte / (ip, port) / 10 min.+ if pkt.app_head:+ reason = protomatch.check(pkt.remote_port or 0, pkt.protocol,+ pkt.app_head)+ pk = (remote_ip, pkt.remote_port)+ now_s = time.monotonic()+ if reason and now_s - _proto_cooldown.get(pk, 0) > 600:+ _proto_cooldown[pk] = now_s+ if len(_proto_cooldown) >= 4096:+ _proto_cooldown.pop(next(iter(_proto_cooldown)))+ _emit(Alert(+ type="PROTO_MISMATCH", severity="info",+ message=f"Protocol mismatch: {reason} — "+ f"{pkt.process_name or '?'} → {remote_ip}:"+ f"{pkt.remote_port}",+ node_id=remote_ip,+ details={"ip": remote_ip, "port": pkt.remote_port,+ "reason": reason,+ "process": pkt.process_name, "pid": pkt.pid}),+ notify=True)+# EN: ICMP tunnel heuristic — echo requests/replies SHOULD carry ~0# or timestamp-sized payloads; bulk data or a sustained stream# of fat echoes is the classic ICMP exfil signature (ptunnel,@@ -1739,6 +1841,11 @@ def _load_settings() -> None:detector.set_watchlist(_watchlist)detector.set_upload_threshold_mb(float(db.get_setting("upload_threshold_mb", 50)))+ global _kill_switch+ # EN: Opt-in volume kill-switch — OFF unless the user asked for real+ # auto-blocking on upload spikes. / FR: Kill-switch de volume+ # opt-in — OFF sauf demande explicite de blocage auto.+ _kill_switch = bool(db.get_setting("kill_switch_enabled", False))# EN: Security modules — firewall rules/lockdown, opt-in threat intel,# learned process baselines and the external webhook.# FR: Modules de sécurité — règles/lockdown pare-feu, threat intel opt-in,@@ -1977,6 +2084,13 @@ async def post_settings(body: SettingsBody) -> dict:ask_mode.configure(timeout=db.get_setting("ask_timeout", 15),failopen=bool(db.get_setting("ask_failopen", False)))+ if key == "kill_switch_enabled":+ # EN: Live toggle — UPLOAD_SPIKE stops alerting only and+ # installs a real firewall block on the remote IP.+ # FR: Bascule à chaud — UPLOAD_SPIKE installe un vrai blocage+ # pare-feu au lieu de seulement alerter.+ global _kill_switch+ _kill_switch = bool(value)if key == "integrity_watch":integrity.configure(bool(value))if key == "ebpf_probe":diff --git a/backend/detection/askmode.py b/backend/detection/askmode.pyindex bbcc56d..653bd40 100644--- a/backend/detection/askmode.py+++ b/backend/detection/askmode.py@@ -4,19 +4,23 @@ interactive à la première connexion (NFQUEUE Linux).EN: The honest user-mode slice of "ask before letting a new outbound flowout" — no kernel driver needed on Linux thanks to NFQUEUE: packets- matching an iptables rule are handed to a user-space verdict callback+ matching an iptables rule are handed to a user-space verdict socketthat can ACCEPT or DROP them. We divert the FIRST outbound packet ofeach unseen (remote_ip, remote_port, proto) flow into queue 7, hold itpending the analyst's decision via the API, then apply the verdict.Decisions persist per flow-key for the session, so only the firstpacket of each flow ever waits.- * opt-in only: enable via settings ask_enabled=1 (needs root +- libnetfilter_queue — python package `NetfilterQueue`)+ * opt-in only: enable via settings ask_enabled=1 — needs Linux,+ root (CAP_NET_ADMIN) and iptables; the NFQUEUE client is the+ PURE-PYTHON `nfqueue.py` in this package, so there is nothing+ else to install* iptables rule installed: `OUTPUT -j NFQUEUE --queue-num 7` minusexemptions for loopback/LAN (the API itself must stay reachable)* timeout policy `ask_timeout`: after N seconds with no verdict thepacket is dropped (secure default) or accepted (ask_failopen=1)+ * each held packet waits on its own waiter thread, so a stalled+ flow never blocks the verdict loop for other connections* flows the user already ruled on go straight through — this isask-on-first-connect, not ask-every-packet@@ -27,13 +31,16 @@ EN: The honest user-mode slice of "ask before letting a new outbound flowFR: La tranche user-mode honnête du « demander avant de laisser sortir unnouveau flux » — sans driver noyau sous Linux grâce à NFQUEUE : les- paquets matchés par iptables sont remis à un callback user-space qui- les ACCEPTe ou les DROPpe. On détourne le PREMIER paquet sortant de- chaque flux (ip, port, proto) inconnu vers la file 7, on le gèle en+ paquets matchés par iptables sont remis à un socket de verdict+ user-space qui les ACCEPTe ou les DROPpe. On détourne le PREMIER+ paquet sortant de chaque flux (ip, port, proto) inconnu vers la file 7+ via `nfqueue.py` (pur Python, rien à installer), on le gèle enattendant le verdict de l'analyste via l'API, puis on applique.- Opt-in uniquement (root + libnetfilter_queue requis). Politique de- timeout : drop par défaut (ask_failopen=1 pour accepter). Linux- seulement — Windows/macOS passent par les pistes noyau (contrib/).+ Opt-in uniquement (Linux + root + iptables). Politique de timeout :+ drop par défaut (ask_failopen=1 pour accepter). Chaque paquet retenu+ a son propre thread d'attente — un flux gelé ne bloque pas les autres.+ Linux seulement — Windows/macOS passent par les pistes noyau+ (contrib/)."""from __future__ import annotations@@ -53,19 +60,18 @@ _DEFAULT_TIMEOUT = 15.0def available() -> tuple[bool, str]:- """EN: Linux + root + NetfilterQueue importable + libnetfilter_queue.- FR: Linux + root + NetfilterQueue importable + libnetfilter_queue."""+ """EN: Linux + root + iptables — the NFQUEUE client is pure Python+ (nfqueue.py) so no extra package is needed anymore.+ FR: Linux + root + iptables — le client NFQUEUE est en pur Python+ (nfqueue.py), aucun paquet supplémentaire requis."""if platform.system().lower() != "linux":return False, "NFQUEUE is linux-only (windows/macOS need kernel " \"callouts — see contrib/)"- try:- import netfilterqueue # noqa: F401- except ImportError:- return False, "python package `NetfilterQueue` + libnetfilter_queue " \- "required (pip install NetfilterQueue, apt install " \- "libnetfilter-queue1)"if os.geteuid() != 0:return False, "needs root (CAP_NET_ADMIN) for iptables + NFQUEUE"+ import shutil+ if shutil.which("iptables") is None:+ return False, "iptables binary not found"return True, ""@@ -79,11 +85,13 @@ class AskMode:self._on_ask = on_ask # EN: emit ASK_VERDICT alert / FR: émet l'alerteself._timeout = max(3.0, min(float(timeout), 120.0))self._failopen = failopen- self._nfq = None+ self._nfq = None # EN: NfqSocket / FR: NfqSocketself._thread: Optional[threading.Thread] = Noneself._running = False- # EN: flow-key → (event, pkt, ts) pending verdict; decided → verdict- # FR: clé de flux → (event, pkt, ts) en attente ; décidé → verdict+ # EN: flow-key → [event, packet_id, ts] pending verdict;+ # decided flow-key → allow verdict+ # FR: clé de flux → [event, id du paquet, ts] en attente ;+ # clé décidée → verdictself._pending: dict[tuple, list] = {}self._decided: dict[tuple, bool] = {}self._lock = threading.Lock()@@ -110,15 +118,17 @@ class AskMode:if not ok:return False, whyimport subprocess+ from .nfqueue import NfqSocket # noqa: PLC0415try:- from netfilterqueue import NetfilterQueue- except ImportError as e: # pragma: no cover- return False, str(e)- try:- self._nfq = NetfilterQueue()- self._nfq.bind(_QUEUE_NUM, self._verdict_cb)+ self._nfq = NfqSocket(_QUEUE_NUM)+ self._nfq.open()+ self._nfq.bind_queue()except Exception as e: # noqa: BLE001- self._nfq = None+ try:+ if self._nfq is not None:+ self._nfq.close()+ finally:+ self._nfq = Nonereturn False, f"nfqueue bind failed: {e}"# EN: Divert outbound SYN/non-established flows into queue 7 —# private ranges exempt so the LAN/UI never stalls.@@ -155,7 +165,15 @@ class AskMode:def _run(self) -> None:try:- self._nfq.run()+ while self._running:+ # EN: 0.5 s timeout keeps the loop interruptible; each+ # packet is handled inline (fast) or handed to a+ # per-flow waiter thread for the async verdict.+ # FR: Timeout 0,5 s pour une boucle interruptible ;+ # chaque paquet est traité directement ou remis à un+ # thread d'attente dédié.+ for pid, payload in self._nfq.recv_packets(0.5):+ self._handle(pid, payload)except Exception as e: # noqa: BLE001logger.warning("askmode nfqueue loop ended: %s", e)finally:@@ -163,9 +181,25 @@ class AskMode:def stop(self) -> None:self._running = False+ with self._lock:+ pending = list(self._pending.values())+ self._pending.clear()+ self._decided.clear()+ # EN: Verdict every held packet BEFORE closing — an unverdicted+ # packet dies with the socket; apply the fail-open policy so+ # shutdown semantics stay explicit.+ # FR: Verdicter chaque paquet retenu AVANT de fermer — sans verdict+ # il meurt avec le socket ; on applique la politique fail-open.+ for ent in pending:+ try:+ if self._nfq is not None:+ self._nfq.verdict(ent[1], self._failopen)+ except Exception: # noqa: BLE001+ pass+ ent[0].set()try:if self._nfq is not None:- self._nfq.unbind()+ self._nfq.close()except Exception: # noqa: BLE001passif self._rule_installed:@@ -174,9 +208,6 @@ class AskMode:"NFQUEUE", "--queue-num", str(_QUEUE_NUM)],timeout=10, check=False, capture_output=True)self._rule_installed = False- with self._lock:- self._pending.clear()- self._decided.clear()# ── verdict path / chemin du verdict ─────────────────────────────────@@ -216,42 +247,56 @@ class AskMode:return Nonereturn None- def _verdict_cb(self, pkt) -> None:+ def _handle(self, pid: int, payload: bytes) -> None:+ """EN: One diverted packet: apply the stored verdict, accept when+ not askable, or park it on a per-flow waiter thread.+ FR: Un paquet détourné : applique le verdict stocké, accepte s'il+ n'est pas interrogable, ou le gare sur un thread d'attente."""try:- payload = pkt.get_payload()key = self._flow_key(payload)if key is None:- pkt.accept()+ self._nfq.verdict(pid, True)returnwith self._lock:verdict = self._decided.get(key)+ if verdict is None:+ # EN: Pending table bounded — overflow accepts+ # (fail-open on capacity, documented).+ # FR: Table bornée — débordement accepte.+ if len(self._pending) >= _MAX_PENDING:+ verdict = True+ else:+ ev = threading.Event()+ self._pending[key] = [ev, pid,+ time.monotonic()]if verdict is not None:- (pkt.accept if verdict else pkt.drop)()+ self._nfq.verdict(pid, verdict)return- # EN: Pending table bounded — overflow accepts (fail-open on- # capacity, documented; timeout policy is separate).- # FR: Table bornée — débordement accepte (fail-open capacitaire,- # documenté ; la politique de timeout est à part).- with self._lock:- if len(self._pending) >= _MAX_PENDING:- pkt.accept()- return- ev = threading.Event()- self._pending[key] = [ev, pkt, time.monotonic()]self._on_ask({"type": "ASK_VERDICT", "remote_ip": key[0],"remote_port": key[1], "proto": key[2],"timeout_s": int(self._timeout)})- if not ev.wait(self._timeout):- with self._lock:- self._pending.pop(key, None)- self._decided[key] = self._failopen- (pkt.accept if self._failopen else pkt.drop)()+ threading.Thread(target=self._waiter, args=(key, ev),+ daemon=True,+ name="snitch-ask-waiter").start()except Exception: # noqa: BLE001try:- pkt.accept() # EN: never wedge the host+ self._nfq.verdict(pid, True) # EN: never wedge hostexcept Exception: # noqa: BLE001pass+ 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.+ FR: Retient un paquet jusqu'à decide() ou timeout ; la boucle de+ réception sert les autres flux pendant ce temps."""+ if ev.wait(self._timeout):+ 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)+def decide(self, remote_ip: str, remote_port: int, proto: str,allow: bool) -> bool:"""EN: API entry — verdict for a pending flow; returns False if the@@ -263,12 +308,9 @@ class AskMode:self._decided[key] = bool(allow)if ent is None:return False- ev, pkt, _ = ent- try:- (pkt.accept if allow else pkt.drop)()- except Exception: # noqa: BLE001- pass- ev.set()+ if self._nfq is not None:+ self._nfq.verdict(ent[1], bool(allow))+ ent[0].set()return Truedef status(self) -> dict:diff --git a/backend/detection/dga.py b/backend/detection/dga.pynew file mode 100644index 0000000..dc71cfc--- /dev/null+++ b/backend/detection/dga.py@@ -0,0 +1,140 @@+"""+Snitch — DGA / suspicious-domain heuristics (pure Python, local-only) /+heuristiques anti-DGA (pur Python, local).++EN: Domain-generation-algorithm detection without any external lookup —+ DNS names and TLS SNIs are scored on pure lexical features that+ separate human-chosen domains from algorithmically generated ones:++ * per-label Shannon entropy — dictionary words sit ~2.3–3.1+ bits/char, random strings sit 3.8++ * vowel ratio — pronounceable names keep 25–55 %+ vowels; random consonant soups don't+ * longest consonant run — real words rarely stack 5++ * digit ratio — mixed alnum noise trips it+ * label count + length — DGA C2s favor deep, long names++ A name only flags when entropy AND shape agree, so `duckduckgo`,+ `amazonaws` or `akamaihd` stay quiet while `xj3kq9zw.example` and+ `qwxzjkvbtp` trip. Honest limits: this is a HEURISTIC — no WHOIS, no+ registration-age data, no online reputation. Fresh domains can't be+ dated locally; only the lexical smell is scored.++ Public surface: `score(name)` → {"score", "reasons", "label"} | None+ (None = input not usable — IP literal, single label, idna noise).++FR: Détection de domaines générés algorithmiquement sans aucune requête+ externe — les noms DNS et SNI TLS sont notés sur des caractéristiques+ lexicales pures (entropie, ratio de voyelles, suites de consonnes,+ chiffres, profondeur). Un nom ne déclenche que si l'entropie ET la+ forme concordent — les vrais services restent silencieux. Limites+ honnêtes : HEURISTIQUE locale, sans WHOIS ni âge d'enregistrement.+"""++from __future__ import annotations++import math+import re+from typing import Optional++_LABEL_RE = re.compile(r"^[a-z0-9-]+$")+_VOWELS = set("aeiou")+# EN: Public-suffix-ish second labels that legitimately carry random+# left-hand labels — skip scoring the LEFT label for these parents.+# FR: Suffixes publics dont les labels à gauche sont légitimement+# aléatoires (CDN/cloud) — on ne note pas le label gauche.+_SKIP_LEFT = {"amazonaws", "azure", "cloudfront", "akamaized", "akamai",+ "akamaihd", "fastly", "cloudflare", "googleusercontent",+ "fbcdn", "edgesuite", "edgekey", "azurewebsites"}+++def _entropy(s: str) -> float:+ """EN: Shannon entropy in bits/char over the label alphabet.+ FR: Entropie de Shannon en bits/caractère sur le label."""+ if not s:+ return 0.0+ freq: dict[str, int] = {}+ for ch in s:+ freq[ch] = freq.get(ch, 0) + 1+ n = len(s)+ return -sum((c / n) * math.log2(c / n) for c in freq.values())+++def _consonant_run(s: str) -> int:+ """EN: Longest run of consonants (digits count as consonants).+ FR: Plus longue suite de consonnes (chiffres comptés)."""+ best = run = 0+ for ch in s:+ if ch not in _VOWELS:+ run += 1+ best = max(best, run)+ else:+ run = 0+ return best+++def score(name: str) -> Optional[dict]:+ """EN: Score one hostname for DGA-ness. Returns a finding dict when+ suspicious enough to flag, None when clean or unscorable.++ Thresholds tuned for near-zero false positives on the top-1M shape:+ needs entropy ≥3.4 PLUS a shape anomaly (unpronounceable, stacked+ consonants, digit noise) or entropy ≥4.0 alone. Labels shorter than+ 10 chars are ignored — short domains can't be judged lexically.++ FR: Note l'aspect DGA d'un nom. Renvoie un finding quand assez+ suspect, None sinon. Il faut entropie ≥3.4 ET une anomalie de forme,+ ou ≥4.0 seule. Labels <10 caractères ignorés."""+ if not name or "." not in name:+ return None+ name = name.rstrip(".").lower()+ if name.replace(".", "").isdigit() or ":" in name:+ return None # EN: IP literal / FR: IP+ labels = [l for l in name.split(".") if l]+ if len(labels) < 2:+ return None++ # EN: Score the deepest "interesting" label — usually the registrable+ # part (labels[-2]); CDN parents get their LEFT label skipped.+ # FR: On note le label « intéressant » — en général le registrable ;+ # les parents CDN sautent le label de gauche.+ idx = len(labels) - 2+ if labels[idx] in _SKIP_LEFT and len(labels) >= 3:+ idx = len(labels) - 3+ cand = labels[idx]+ if len(cand) < 10:+ return None++ ent = _entropy(cand)+ vowels = sum(1 for c in cand if c in _VOWELS) / len(cand)+ digits = sum(1 for c in cand if c.isdigit()) / len(cand)+ run = _consonant_run(cand)++ reasons: list[str] = []+ if vowels < 0.15:+ reasons.append("almost no vowels")+ if run >= 5:+ reasons.append(f"{run}-consonant run")+ if digits > 0.2:+ reasons.append("digit-heavy")+ if len(labels) >= 4:+ reasons.append("deeply nested")++ score = 0.0+ if ent >= 4.0:+ score = 1.0+ reasons.insert(0, f"entropy {ent:.1f} bits/char")+ elif ent >= 3.4 and reasons:+ score = 0.7+ reasons.insert(0, f"entropy {ent:.1f} bits/char")+ else:+ return None++ # EN: Extra weight when the name is also long and nested — classic+ # C2 fingerprint. / FR: Poids supplémentaire si long + imbriqué.+ if len(cand) >= 20:+ score = min(1.0, score + 0.1)+ return {"score": round(score, 2),+ "entropy": round(ent, 2),+ "label": cand,+ "reasons": reasons}diff --git a/backend/detection/explain.py b/backend/detection/explain.pyindex 47519f0..3d34ea3 100644--- a/backend/detection/explain.py+++ b/backend/detection/explain.py@@ -659,6 +659,53 @@ EXPLANATIONS: dict[str, dict] = {["Autoriser ou refuser depuis le prompt","Créer une règle pare-feu pour les décisions permanentes","Linux/NFQUEUE seulement — voir /security/ask pour le statut"]),++"DGA_SUSPECT": _e(+ "Domain looks algorithmically generated",+ "Domaine à aspect généré algorithmiquement",+ "The resolved name or TLS SNI fails lexical checks typical of domain-"+ "generation algorithms: high entropy, almost no vowels, stacked "+ "consonants, digit noise — how malware C2 hostnames usually look.",+ "Le nom résolu ou le SNI TLS échoue aux contrôles lexicaux typiques "+ "des algorithmes de génération de domaines : entropie élevée, quasi "+ "aucune voyelle, consonnes empilées, chiffres — le look classique "+ "des C2 de malware.",+ "Pure local heuristic — no WHOIS, no domain-age data. Legit-but-"+ "weird names (hashes, build artifacts) can trip it occasionally; the "+ "finding is info-level and cooled down per name.",+ "Heuristique purement locale — ni WHOIS ni âge du domaine. Des noms "+ "légitimes bizarres (hachés, artefacts de build) peuvent déclencher "+ "occasionnellement ; niveau info, cooldown par nom.",+ ["Check which process resolved it",+ "Look for follow-up connections to the resolved IP",+ "Ignore once for known dev/build tools"],+ ["Vérifier quel processus l'a résolu",+ "Surveiller les connexions vers l'IP résolue",+ "Ignorer une fois pour les outils de build connus"]),++"PROTO_MISMATCH": _e(+ "Payload does not match the port's protocol",+ "Payload non conforme au protocole du port",+ "The first bytes on this socket do not look like the protocol the "+ "port advertises — non-HTTP on :80, non-TLS on :443, non-DNS on :53, "+ "non-SSH on :22… Attackers hide tunnels on friendly ports to slip "+ "past firewall rules.",+ "Les premiers octets de cette socket ne ressemblent pas au protocole "+ "annoncé par le port — non-HTTP sur :80, non-TLS sur :443, non-DNS "+ "sur :53, non-SSH sur :22… Les attaquants planquent des tunnels sur "+ "des ports amicaux pour passer les pare-feux.",+ "Heuristic on the ≤64-byte head only — exotic legit protocols "+ "(WebSocket upgrades, custom daemons) may trip it once, then the "+ "cooldown keeps it quiet.",+ "Heuristique sur la tête ≤64 o seulement — des protocoles légitimes "+ "exotiques (upgrades WebSocket, démons custom) peuvent déclencher une "+ "fois puis le cooldown les tait.",+ ["Inspect the process — legit apps use their own ports",+ "Correlate with HIGH_ENTROPY/DNS_TUNNEL on the same host",+ "Block the flow if the process can't be explained"],+ ["Inspecter le processus — les apps légitimes utilisent leurs ports",+ "Corréler avec HIGH_ENTROPY/DNS_TUNNEL sur le même hôte",+ "Bloquer le flux si le processus est inexplicable"]),}diff --git a/backend/detection/nfqueue.py b/backend/detection/nfqueue.pynew file mode 100644index 0000000..58d6d17--- /dev/null+++ b/backend/detection/nfqueue.py@@ -0,0 +1,277 @@+"""+Snitch — pure-Python NFQUEUE client (Linux AF_NETLINK) / client NFQUEUE+pur Python (AF_NETLINK Linux).++EN: Zero-dependency implementation of the netfilter-queue userspace+ protocol — the feature that makes ask-on-first-connect REAL on Linux+ without `pip install NetfilterQueue` or libnetfilter_queue.so. An+ AF_NETLINK socket of family NETLINK_NETFILTER speaks nfnetlink_queue+ directly:++ * bind — nfqnl config commands (PF_UNBIND/PF_BIND/BIND ++ COPY_PACKET params), each verified by an nlmsg ACK so a+ failed bind surfaces honestly instead of timing out+ * recv — NFQNL_MSG_PACKET messages carrying the diverted IP+ packet in NFQA_PAYLOAD plus its verdict id+ * verdict — NFQNL_MSG_VERDICT with NF_ACCEPT / NF_DROP++ Protocol reference: linux/netfilter/nfnetlink_queue.h and+ libnetfilter_queue's message layout. Everything here is host byte+ order except fields documented __be16/__be32.++FR: Implémentation zéro-dépendance du protocole netfilter-queue —+ l'ask-on-connect réel sous Linux sans `pip install NetfilterQueue`.+ Socket AF_NETLINK famille NETLINK_NETFILTER parlant nfnetlink_queue+ directement : bind via commandes de config vérifiées par ACK, réception+ NFQNL_MSG_PACKET (payload IP + id de verdict), verdict NF_ACCEPT/NF_DROP.+"""++from __future__ import annotations++import os+import socket+import struct+from typing import Optional++# EN: netlink + nfnetlink_queue constants / FR: constantes netlink+NETLINK_NETFILTER = 12+NLMSG_ERROR = 2+NLM_F_REQUEST = 0x0001+NLM_F_ACK = 0x0004++_SUBSYS_QUEUE = 3 # NFNL_SUBSYS_QUEUE+_MSG_PACKET = 0 # NFQNL_MSG_PACKET+_MSG_VERDICT = 1 # NFQNL_MSG_VERDICT+_MSG_CONFIG = 3 # NFQNL_MSG_CONFIG++_CFG_CMD_BIND = 1 # NFQNL_CFG_CMD_BIND+_CFG_CMD_PF_BIND = 3 # NFQNL_CFG_CMD_PF_BIND+_CFG_CMD_PF_UNBIND = 4 # NFQNL_CFG_CMD_PF_UNBIND+_COPY_PACKET = 2 # NFQNL_COPY_PACKET++_ATTR_CFG_CMD = 1 # NFQA_CFG_CMD+_ATTR_CFG_PARAMS = 2 # NFQA_CFG_PARAMS+_ATTR_PACKET_HDR = 1 # NFQA_PACKET_HDR+_ATTR_VERDICT_HDR = 2 # NFQA_VERDICT_HDR+_ATTR_PAYLOAD = 10 # NFQA_PAYLOAD+_ATTR_TYPE_MASK = 0x3FFF # NLA_TYPE_MASK++NF_ACCEPT = 1+NF_DROP = 0++_AF_UNSPEC = 0+_AF_INET = 2+_AF_INET6 = 10+++def _attr(atype: int, payload: bytes) -> bytes:+ """EN: One nfattr TLV — 2-byte len + 2-byte type, 4-aligned.+ FR: Un TLV nfattr — len + type sur 2 octets, aligné 4."""+ length = 4 + len(payload)+ out = struct.pack("HH", length, atype) + payload+ return out + b"\x00" * ((4 - length % 4) % 4)+++def _msg(mtype: int, res_id: int, payload: bytes, seq: int,+ flags: int = NLM_F_REQUEST) -> bytes:+ """EN: nlmsghdr + nfgenmsg + attribute payload. nlmsg_type is+ (subsys<<8)|msg_type in HOST order; nfgenmsg.res_id carries the queue+ number in network order.+ FR: nlmsghdr + nfgenmsg + attributs. type = (subsys<<8)|msg en ordre+ hôte ; res_id porte le numéro de file en ordre réseau."""+ nfgen = struct.pack("!BBH", _AF_UNSPEC, 0, res_id)+ total = 16 + 4 + len(payload)+ return (struct.pack("IHHII", total, (_SUBSYS_QUEUE << 8) | mtype,+ flags, seq, 0) + nfgen + payload)+++def _parse_attrs(body: bytes) -> dict[int, bytes]:+ """EN: Split an nfattr list into {type: payload}; malformed tails are+ dropped quietly. / FR: Découpe la liste nfattr ; queue malformée+ ignorée silencieusement."""+ out: dict[int, bytes] = {}+ off = 0+ while off + 4 <= len(body):+ length, atype = struct.unpack_from("HH", body, off)+ if length < 4 or off + length > len(body):+ break+ out[atype & _ATTR_TYPE_MASK] = body[off + 4: off + length]+ off += (length + 3) & ~3 # EN: NFA_ALIGN / FR: NFA_ALIGN+ return out+++def parse_packet_message(data: bytes) -> Optional[tuple[int, bytes]]:+ """EN: Extract (packet_id, ip_payload) from one NFQNL_MSG_PACKET+ netlink message. Returns None for non-packet messages (ACKs etc.).+ Exposed for unit tests. / FR: Extrait (id, payload IP) d'un message+ NFQNL_MSG_PACKET ; None pour les autres types."""+ if len(data) < 20:+ return None+ _length, mtype, _flags, _seq, _pid = struct.unpack_from(+ "IHHII", data, 0)+ if mtype != (_SUBSYS_QUEUE << 8) | _MSG_PACKET:+ return None+ attrs = _parse_attrs(data[20:]) # EN: skip nfgenmsg+ hdr = attrs.get(_ATTR_PACKET_HDR)+ payload = attrs.get(_ATTR_PAYLOAD)+ if hdr is None or len(hdr) < 5 or payload is None:+ return None+ pkt_id, _hwproto, _hook = struct.unpack("!IHB", hdr[:7])+ return pkt_id, payload+++def build_verdict(packet_id: int, verdict: int, queue: int,+ seq: int = 0) -> bytes:+ """EN: A complete NFQNL_MSG_VERDICT netlink message accepting or+ dropping the held packet. / FR: Message NFQNL_MSG_VERDICT complet+ acceptant ou droppant le paquet retenu."""+ vh = _attr(_ATTR_VERDICT_HDR, struct.pack("!II", verdict, packet_id))+ return _msg(_MSG_VERDICT, queue, vh, seq)+++def build_config_cmd(command: int, pf: int, queue: int,+ seq: int = 0) -> bytes:+ """EN: NFQNL_MSG_CONFIG carrying one NFQA_CFG_CMD (bind/unbind family+ or queue). / FR: NFQNL_MSG_CONFIG portant une NFQA_CFG_CMD."""+ cmd = _attr(_ATTR_CFG_CMD, struct.pack("!BBH", command, 0, pf))+ return _msg(_MSG_CONFIG, queue, cmd, seq)+++def build_config_params(queue: int, seq: int = 0,+ copy_range: int = 0xFFFF) -> bytes:+ """EN: NFQNL_MSG_CONFIG with NFQA_CFG_PARAMS — whole-packet copy mode.+ FR: NFQNL_MSG_CONFIG avec NFQA_CFG_PARAMS — copie du paquet entier."""+ par = _attr(_ATTR_CFG_PARAMS,+ struct.pack("!IB", copy_range, _COPY_PACKET))+ return _msg(_MSG_CONFIG, queue, par, seq)+++class NfqSocket:+ """EN: One bound NFQUEUE — open(), bind_queue(), recv_packet(),+ verdict(), close(). Verdicts for packets never touched by iptables+ are no-ops, so the class stays safe to construct anywhere.+ FR: Une file NFQUEUE liée. Les verdicts pour des paquets jamais+ détournés sont sans effet — la construction est sûre partout."""++ def __init__(self, queue: int = 7):+ self.queue = queue+ self._fd: Optional[socket.socket] = None+ self._seq = 0++ # ── lifecycle / cycle de vie ────────────────────────────────────────++ def open(self) -> None:+ """EN: Create + bind the netlink socket. Needs CAP_NET_ADMIN.+ FR: Crée et lie le socket netlink. Exige CAP_NET_ADMIN."""+ if self._fd is not None:+ return+ fd = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW,+ NETLINK_NETFILTER)+ try:+ fd.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1 << 20)+ fd.bind((0, 0)) # EN: kernel assigns pid+ except Exception:+ fd.close()+ raise+ self._fd = fd++ def bind_queue(self, timeout: float = 2.0) -> None:+ """EN: PF_UNBIND (cleanup), PF_BIND, BIND and COPY_PACKET for+ AF_INET + AF_INET6 — every step ACK-verified so failures raise a+ real error, not silence. / FR: PF_UNBIND, PF_BIND, BIND et+ COPY_PACKET v4+v6 — chaque étape vérifiée par ACK."""+ if self._fd is None:+ self.open()+ for pf in (_AF_INET, _AF_INET6):+ self._send_checked(build_config_cmd(+ _CFG_CMD_PF_UNBIND, pf, self.queue, self._next()),+ timeout, tolerate=True)+ for pf in (_AF_INET, _AF_INET6):+ self._send_checked(build_config_cmd(+ _CFG_CMD_PF_BIND, pf, self.queue, self._next()), timeout)+ self._send_checked(build_config_cmd(+ _CFG_CMD_BIND, _AF_UNSPEC, self.queue, self._next()), timeout)+ self._send_checked(build_config_params(+ self.queue, self._next()), timeout)++ def close(self) -> None:+ try:+ if self._fd is not None:+ self._fd.close()+ finally:+ self._fd = None++ def _next(self) -> int:+ self._seq = (self._seq + 1) & 0x7FFFFFFF+ return self._seq++ # ── protocol / protocole ────────────────────────────────────────────++ def _send_checked(self, msg: bytes, timeout: float,+ tolerate: bool = False) -> None:+ """EN: Send one message then wait for its NLMSG_ERROR ack —+ error 0 means accepted. `tolerate` swallows failures (the initial+ PF_UNBIND legitimately fails when nothing is bound).+ FR: Envoie puis attend l'ACK NLMSG_ERROR — erreur 0 = accepté.+ `tolerate` avale les échecs (PF_UNBIND échoue normalement)."""+ assert self._fd is not None+ self._fd.send(msg)+ self._fd.settimeout(timeout)+ try:+ while True:+ data = self._fd.recv(65535)+ off = 0+ while off + 16 <= len(data):+ (length, mtype, _f, _s, _p) = struct.unpack_from(+ "IHHII", data, off)+ if mtype == NLMSG_ERROR and length >= 20:+ err = struct.unpack_from("i", data, off + 16)[0]+ if err and not tolerate:+ raise OSError(+ -err, f"nfqueue config refused: "+ f"{os.strerror(-err)}")+ return+ off += (length + 3) & ~3 if length else len(data)+ except socket.timeout:+ # EN: No ACK back within the window — the kernel answered+ # nothing; treat tolerated steps as silent success.+ # FR: Pas d'ACK dans la fenêtre — étape tolérée = succès muet.+ if not tolerate:+ raise OSError("nfqueue config timed out — kernel did "+ "not acknowledge the bind")++ def recv_packets(self, timeout: Optional[float] = None) \+ -> list[tuple[int, bytes]]:+ """EN: All diverted packets in the next datagram as+ [(id, raw IP payload), ...] — a single recv() can carry several+ queued messages. [] on timeout. / FR: Tous les paquets du prochain+ datagramme — un recv() peut porter plusieurs messages."""+ assert self._fd is not None+ self._fd.settimeout(timeout)+ try:+ data = self._fd.recv(65535)+ except socket.timeout:+ return []+ out = []+ off = 0+ while off + 16 <= len(data):+ res = parse_packet_message(data[off:])+ if res is not None:+ out.append(res)+ length = struct.unpack_from("I", data, off)[0]+ if length < 16:+ break+ off += (length + 3) & ~3+ return out++ def verdict(self, packet_id: int, accept: bool) -> None:+ """EN: NF_ACCEPT/NF_DROP verdict for one held packet.+ FR: Verdict NF_ACCEPT/NF_DROP pour un paquet retenu."""+ if self._fd is None:+ return+ try:+ self._fd.send(build_verdict(+ packet_id, NF_ACCEPT if accept else NF_DROP,+ self.queue, self._next()))+ except OSError:+ pass # EN: packet may be gonediff --git a/backend/detection/protomatch.py b/backend/detection/protomatch.pynew file mode 100644index 0000000..dc8413b--- /dev/null+++ b/backend/detection/protomatch.py@@ -0,0 +1,108 @@+"""+Snitch — protocol/port mismatch classifier / classifieur protocole↔port.++EN: "Disguised protocol" detection for the classic well-known ports —+ when the first payload bytes on a socket do NOT look like the protocol+ the port advertises, someone is riding a friendly port to sneak a+ tunnel past firewalls (HTTP/80, DNS/53, SSH/22, TLS/443, mail…).++ Checks are cheap signature tests on the ≤64-byte app head only — no+ payload is stored, matching Snitch's privacy model:++ tcp/80 expects an HTTP method or "HTTP/" status line+ udp+tcp/53 expects a plausible DNS header (id, flags, qdcount>0,+ labels that fit)+ tcp/22 expects the "SSH-" banner+ tcp/443 expects a TLS record (\\x16\\x03) — cleartext on the+ HTTPS port is itself the anomaly+ tcp/853 expects a TLS record (DNS-over-TLS)+ tcp/21,25,110,143,587 expects printable ASCII commands++ Honest limits: HEURISTIC, one alert per (ip, port) per cooldown —+ exotic-but-legit protocols (WebSocket pre-GET, MQTT on 443) may+ false-positive once, then stay quiet. The classifier flags the+ MISMATCH, it does not identify what the traffic really is.++FR: Détection de « protocole déguisé » sur les ports bien connus — quand+ les premiers octets ne ressemblent pas au protocole annoncé par le+ port, quelqu'un fait passer un tunnel sous un port amical (HTTP/80,+ DNS/53, SSH/22, TLS/443, mail…). Tests de signature bon marché sur la+ tête ≤64 o uniquement. HEURISTIQUE — une alerte par (ip, port) par+ fenêtre de cooldown ; les protocoles exotiques légitimes peuvent+ déclencher une fois puis se taire.+"""++from __future__ import annotations++import struct+from typing import Optional++_HTTP_METHODS = (b"GET ", b"POST", b"HEAD", b"PUT ", b"DELE", b"OPTI",+ b"PATC", b"TRAC", b"CONN")+_ASCII_PORTS = {21: "FTP", 25: "SMTP", 110: "POP3", 143: "IMAP",+ 587: "SMTP-submission"}+++def _looks_dns(payload: bytes) -> bool:+ """EN: Plausible DNS message — ≥12B header, qdcount in 1..32, and the+ first QNAME's label walk must terminate inside the packet (a random+ blob almost never walks cleanly).+ FR: Message DNS plausible — en-tête ≥12 o, qdcount 1..32 et la+ marche des labels du premier QNAME doit se terminer dans le paquet."""+ if len(payload) < 14: # 12B hdr + minimal QNAME+ return False+ _id, _flags, qd = struct.unpack_from(">HHH", payload, 0)+ if not (1 <= qd <= 32):+ return False+ # EN: Walk labels — each byte must be a length ≤63 followed by data,+ # ending on 0 or a pointer (0xC0). / FR: Marche des labels.+ off = 12+ for _ in range(64):+ if off >= len(payload):+ return False+ length = payload[off]+ if length == 0:+ return True # EN: clean terminator+ if length & 0xC0 == 0xC0:+ return True # EN: compression ptr+ if length > 63 or off + 1 + length > len(payload):+ return False+ off += 1 + length+ return False+++def check(port: int, proto: str, app_head: bytes) -> Optional[str]:+ """EN: Mismatch reason when app_head doesn't fit `port`'s protocol,+ else None. Caller owns the cooldown/dedup policy.+ FR: Raison du mismatch quand app_head ne colle pas au port, sinon+ None. Cooldown/dédup à la charge de l'appelant."""+ if not app_head or not port:+ return None+ head = app_head[:64]+ proto = (proto or "").upper()++ if proto == "TCP":+ if port == 80:+ if not (head.startswith(_HTTP_METHODS)+ or head.startswith(b"HTTP/")):+ return "non-HTTP payload on tcp/80"+ elif port == 443:+ if not head.startswith(b"\x16\x03"):+ return "non-TLS payload on tcp/443 (HTTPS port)"+ elif port == 853:+ if not head.startswith(b"\x16\x03"):+ return "cleartext on tcp/853 (DNS-over-TLS port)"+ elif port == 22:+ if not head.startswith(b"SSH-"):+ return "non-SSH payload on tcp/22"+ elif port in _ASCII_PORTS:+ if not all(32 <= b < 127 or b in (9, 10, 13) for b in head):+ return (f"non-{_ASCII_PORTS[port]} payload on "+ f"tcp/{port} (expected printable commands)")+ elif port == 53:+ if not _looks_dns(head):+ return "non-DNS payload on tcp/53"+ elif proto == "UDP":+ if port == 53 and not _looks_dns(head):+ return "non-DNS payload on udp/53"+ return Nonediff --git a/backend/tests/test_integration_os.py b/backend/tests/test_integration_os.pyindex 8b53bc9..be5103b 100644--- a/backend/tests/test_integration_os.py+++ b/backend/tests/test_integration_os.py@@ -332,10 +332,10 @@ class TestMacosReal:@pytest.mark.skipif(SYSTEM != "linux", reason="linux only")class TestLinuxV15Real:"""EN: v1.5 primitives on a real kernel — nftables, firejail,- netfilterqueue, bcc/cgroup. All probe availability first and skip+ nfqueue, bcc/cgroup. All probe availability first and skiphonestly; they never fake a pass.FR: Primitives v1.5 sur un vrai noyau — nftables, firejail,- netfilterqueue, bcc/cgroup. Sondes d'abord, skip honnête sinon."""+ nfqueue, bcc/cgroup. Sondes d'abord, skip honnête sinon."""def test_nftables_table_lifecycle(self):"""EN: If `nft` exists, a dedicated `inet snitch` table can be@@ -377,10 +377,11 @@ class TestLinuxV15Real:def test_netfilterqueue_available_probe(self):"""EN: askmode.available() must answer honestly on a real Linux- box — either (True,"") when root+libnetfilter_queue+NetfilterQueue- are all present, or (False, <reason>) that names what's missing.- FR: askmode.available() répond honnêtement — True ou une raison- nommant ce qui manque."""+ box — (True,"") when root+iptables are present (the NFQUEUE+ client is pure Python — no package to miss), or (False, <reason>)+ naming what's missing. / FR: askmode.available() répond+ honnêtement — True si root+iptables (client NFQUEUE pur Python),+ sinon une raison nommant ce qui manque."""from detection import askmodeok, why = askmode.available()if ok:@@ -389,6 +390,22 @@ class TestLinuxV15Real:else:assert why and isinstance(why, str)+ def test_pure_nfqueue_bind_probe(self):+ """EN: The pure-Python NFQUEUE client binds a scratch queue for+ real when root — honest proof the embedded netlink code works.+ FR: Le client NFQUEUE pur Python bind réellement une file quand+ root — preuve honnête que le code netlink embarqué marche."""+ import os as _os+ if _os.geteuid() != 0:+ pytest.skip("needs root for NETLINK_NETFILTER bind")+ from detection.nfqueue import NfqSocket+ s = NfqSocket(9) # EN: scratch queue+ try:+ s.open()+ s.bind_queue(timeout=2.0) # EN: ACK-verified+ finally:+ s.close()+def test_ebpf_enforce_available_probe(self):"""EN: ebpf_enforce.available() reports a concrete reason —never crashes, never lies on a real kernel.diff --git a/backend/tests/test_v15_features.py b/backend/tests/test_v15_features.pyindex 3e584cb..878e6a5 100644--- a/backend/tests/test_v15_features.py+++ b/backend/tests/test_v15_features.py@@ -587,7 +587,7 @@ def test_explain_covers_new_types():FR: Chaque nouveau type d'alerte a un gabarit bilingue."""from detection.explain import explainfor t in ("TLS_CERT", "HIGH_ENTROPY", "ICMP_TUNNEL", "ML_ANOMALY",- "ASK_VERDICT"):+ "ASK_VERDICT", "DGA_SUSPECT", "PROTO_MISMATCH"):rec = explain(t)assert rec is not None, tassert rec["what_en"] and rec["what_fr"]@@ -642,3 +642,176 @@ def test_ebpf_enforce_scoped_attach(monkeypatch):assert ok, whyassert attached["path"] == str(m._CGROUP_DIR)assert e.status()["attached"] is True+++# ── Pure-Python NFQUEUE / NFQUEUE pur Python ──────────────────────────────++def test_nfqueue_packet_message_roundtrip():+ """EN: A crafted NFQNL_MSG_PACKET parses back to (id, payload); an+ ACK-type message returns None. / FR: Un NFQNL_MSG_PACKET fabriqué se+ reparse en (id, payload) ; un message ACK renvoie None."""+ import struct as st+ from detection import nfqueue as n+ ip_pkt = ipv4(b"\x0a\x00\x00\x01", b"\x08\x08\x08\x08", 6,+ tcp(50000, 443, flags=0x02))+ # EN: attrs — PACKET_HDR {be32 id, be16 proto, u8 hook} + PAYLOAD+ # FR: attributs — PACKET_HDR + PAYLOAD+ attrs = n._attr(n._ATTR_PACKET_HDR, st.pack("!IHB", 42, 0x0800, 0)) \+ + n._attr(n._ATTR_PAYLOAD, ip_pkt)+ body = n._msg(n._MSG_PACKET, 7, attrs, 1)+ pid, payload = n.parse_packet_message(body)+ assert pid == 42 and payload == ip_pkt+ # EN: a CONFIG message is not a packet / FR: un CONFIG n'est pas un paquet+ cfg = n.build_config_cmd(n._CFG_CMD_BIND, 0, 7, 1)+ assert n.parse_packet_message(cfg) is None+++def test_nfqueue_verdict_wire_format():+ """EN: Verdict message carries queue res_id + verdict hdr attr with+ the right id/verdict in network order. / FR: Le message de verdict+ porte la file en res_id et l'en-tête verdict en ordre réseau."""+ import struct as st+ from detection import nfqueue as n+ msg = n.build_verdict(99, n.NF_DROP, 7, 5)+ length, mtype, _f, _s, _p = st.unpack_from("IHHII", msg, 0)+ assert length == len(msg)+ assert mtype == (n._SUBSYS_QUEUE << 8) | n._MSG_VERDICT+ _fam, _ver, res = st.unpack_from("!BBH", msg, 16)+ assert res == 7+ attrs = n._parse_attrs(msg[20:])+ v, pid = st.unpack("!II", attrs[n._ATTR_VERDICT_HDR])+ assert v == n.NF_DROP and pid == 99+++def test_nfqueue_config_params_copy_packet():+ """EN: The bind params ask for whole-packet COPY_PACKET mode.+ FR: Les params du bind demandent le mode COPY_PACKET paquet entier."""+ import struct as st+ from detection import nfqueue as n+ msg = n.build_config_params(7, 1)+ attrs = n._parse_attrs(msg[20:])+ rng, mode = st.unpack("!IB", attrs[n._ATTR_CFG_PARAMS])+ assert mode == n._COPY_PACKET and rng == 0xFFFF+++def test_askmode_pending_entry_shape():+ """EN: _handle parks [event, packet_id, ts] and decide() applies the+ verdict via the socket — mocked end-to-end without a kernel.+ FR: _handle gare [event, id, ts] et decide() applique le verdict via+ le socket — simulé de bout en bout sans noyau."""+ from detection.askmode import AskMode++ class FakeNfq:+ def __init__(self):+ self.verdicts = []++ def verdict(self, pid, accept):+ self.verdicts.append((pid, accept))++ asked = []+ am = AskMode(lambda ctx: asked.append(ctx))+ am._nfq = FakeNfq()+ syn = tcp(50000, 443, flags=0x02)+ ip = ipv4(b"\x0a\x00\x00\x01", b"\x08\x08\x08\x08", 6, syn)+ am._handle(7, ip)+ assert asked and asked[0]["remote_ip"] == "8.8.8.8"+ assert am.decide("8.8.8.8", 443, "TCP", False) is True+ assert am._nfq.verdicts == [(7, False)]+ # EN: Next SYN on the same flow rides the stored DENY instantly.+ # FR: Le SYN suivant du même flux suit le DENY stocké immédiatement.+ am._handle(8, ip)+ assert am._nfq.verdicts[-1] == (8, False)+++# ── DGA heuristic / Heuristique DGA ──────────────────────────────────────++def test_dga_flags_random_names():+ """EN: Long consonant-soup + digit-noise names flag; normal domains+ stay silent. / FR: Les noms en soupe de consonnes/chiffres+ déclenchent ; les domaines normaux restent silencieux."""+ from detection.dga import score+ for bad in ("xj3kq9wzvbtpklm.net", "qwxzjkvbtpxyzqwr.com",+ "8f3k2j9xm4q7z5w1v.tk", "bcdfghjklmnpqrstvwxz.info"):+ hit = score(bad)+ assert hit is not None, bad+ assert hit["score"] >= 0.7 and hit["entropy"] >= 3.4+ for good in ("google.com", "github.io", "duckduckgo.com",+ "wikipedia.org", "apple.com", "cdn.discordapp.net",+ "mail.proton.me", "example.com"):+ assert score(good) is None, good+++def test_dga_skips_unscorable():+ """EN: IP literals, single labels, short names → None, never crash.+ FR: IP, labels uniques, noms courts → None, jamais de crash."""+ from detection.dga import score+ for edge in ("", "localhost", "1.2.3.4", "8.8.8.8.",+ "a.b.c", None, "short.io", "::1"):+ assert score(edge) is None+++def test_dga_cdn_left_label_skipped():+ """EN: Random-looking LEFT labels under CDN parents are expected —+ the score jumps to the registrable part instead.+ FR: Les labels gauches aléatoires sous un parent CDN sont attendus —+ le score saute au registrable."""+ from detection.dga import score+ # EN: akamaihd is a public-suffix-ish parent → score 'example', not+ # the hashed left label. / FR: parent type CDN → on note+ # 'example', pas le label haché.+ assert score("a1b2c3d4e5f6.example.akamaihd.net") is None+ # EN: but a DGA registrable STILL flags under a CDN parent.+ # FR: mais un registrable DGA déclenche quand même sous un CDN.+ hit = score("ok.qwxzjkvbtpxyzqwr.akamaihd.net")+ assert hit is not None and hit["label"] == "qwxzjkvbtpxyzqwr"+++# ── Protocol mismatch / Protocole déguisé ─────────────────────────────────++def test_protomatch_http80():+ """EN: GET/POST/HTTP-response on :80 pass; binary garbage flags.+ FR: GET/POST/réponse HTTP sur :80 passent ; le binaire déclenche."""+ from detection.protomatch import check+ assert check(80, "TCP", b"GET / HTTP/1.1\r\nHost: x\r\n") is None+ assert check(80, "TCP", b"HTTP/1.1 200 OK\r\n") is None+ assert check(80, "TCP", b"\x89PNG\r\n\x1a\nbinary-blob!!") is not None+ assert check(80, "TCP", b"\x16\x03\x01\x00\x80tls-like-data") is not None+++def test_protomatch_tls_ports():+ """EN: TLS records pass :443/:853; cleartext flags.+ FR: Les records TLS passent :443/:853 ; le clair déclenche."""+ from detection.protomatch import check+ tls = b"\x16\x03\x01\x00\x2e" + b"\x01" * 46+ assert check(443, "TCP", tls) is None+ assert check(853, "TCP", tls) is None+ assert check(443, "TCP", b"GET /not-tls HTTP/1.1") is not None+ assert check(853, "TCP", b"plain-dns-over-dot-port!") is not None+++def test_protomatch_dns53():+ """EN: A real DNS query passes on :53; a blob flags — both transports.+ FR: Une vraie requête DNS passe sur :53 ; un blob déclenche — TCP et+ UDP."""+ import struct as st+ from detection.protomatch import check+ qname = b"\x07example\x03com\x00"+ dns = st.pack(">HHHHHH", 0x1234, 0x0100, 1, 0, 0, 0) + qname \+ + st.pack(">HH", 1, 1)+ assert check(53, "UDP", dns) is None+ assert check(53, "TCP", dns) is None+ assert check(53, "UDP", b"\xde\xad\xbe\xef" * 16) is not None+ assert check(53, "TCP", b"not-a-dns-message-at-all!!") is not None+++def test_protomatch_ssh_and_ascii():+ """EN: 'SSH-' banner passes :22; binary on mail ports flags; unknown+ ports never match. / FR: bannière SSH- passe :22 ; binaire sur ports+ mail déclenche ; ports inconnus jamais matchés."""+ from detection.protomatch import check+ assert check(22, "TCP", b"SSH-2.0-OpenSSH_9.6") is None+ assert check(22, "TCP", b"\x00\x01\x02binary!") is not None+ assert check(25, "TCP", b"EHLO mail.example.com\r\n") is None+ assert check(25, "TCP", b"\x16\x03\x01tls-on-smtp?") is not None+ assert check(8443, "TCP", b"whatever") is None+ assert check(0, "TCP", b"") is Nonediff --git a/backend/version.py b/backend/version.pyindex 0d2b809..a1ecb1f 100644--- a/backend/version.py+++ b/backend/version.py@@ -5,4 +5,4 @@ FR: Source unique de la version du backend (affichée dans /diagnostics).À garder alignée avec electron/package.json et frontend/package.json."""-__version__ = "1.5.1"+__version__ = "1.5.2"diff --git a/docs/FIREWALL.de.md b/docs/FIREWALL.de.mdindex 3903e82..bcd1ce3 100644--- a/docs/FIREWALL.de.md+++ b/docs/FIREWALL.de.md@@ -123,7 +123,7 @@ Alle sind **standardmäßig aus oder selbstlimitierend**, degradieren ehrlich un- **High-Entropy-Wache** — Payloads ≥48 B auf Nicht-TLS-Kanälen mit ≥4,7 Bit/Byte → `HIGH_ENTROPY`; 10-Min-Cooldown pro Host.- **ICMP-Tunnel-Heuristik** — Echo-Typen mit ≥24 B Payload, ≥3× in 5 Min → `ICMP_TUNNEL`.- **ML-Flow-Anomalie** — Isolation Forest pur Python (64 Bäume, null Deps) über eigene Flow-Summaries; inert <384 Flows, `ML_ANOMALY` ab 0,62. Baseline-Abweichung, **kein** Malware-Klassifikator.-- **Ask-on-Connect (Linux, opt-in)** — `ask_enabled` + root + `python-netfilterqueue`: neue Ausgangsflüsse werden auf NFQUEUE 7 gehalten bis `POST /security/ask/verdict`; Timeout 15 s, fail-closed (`ask_failopen=1` umgekehrt). Windows/macOS brauchen die signierten Callout-/NetworkExtension-Skelette aus `contrib/`.+- **Ask-on-Connect (Linux, opt-in)** — `ask_enabled` + root + iptables: neue Ausgangsflüsse werden auf NFQUEUE 7 gehalten bis `POST /security/ask/verdict` — der NFQUEUE-Client ist **reines Python** (`detection/nfqueue.py`, AF_NETLINK), kein `python-netfilterqueue` nötig; Timeout 15 s, fail-closed (`ask_failopen=1` umgekehrt). Windows/macOS brauchen die signierten Callout-/NetworkExtension-Skelette aus `contrib/`.- **eBPF-Cgroup-Enforcement (Linux, opt-in)** — `POST /security/ebpf/isolate {pid}` + `/security/ebpf/block {ip}`: Programm an den snitch-Cgroup attachiert — Kernel-Drops gelten NUR für isolierte Prozesse.- **Hollowing-Check (Linux)** — `POST /security/hollow {pid}` diff't ausführbare file-backed Seiten aus `/proc/<pid>/mem` gegen Disk.- **IOC-Peer-Sync (opt-in)** — `gossip_peers` ≤32 + `gossip_enabled`: Merkle-Proof-Pakete alle 5 Min per authentifiziertem HTTP(S) — kein Discovery, kein ZK-Protokoll.@@ -132,3 +132,12 @@ Alle sind **standardmäßig aus oder selbstlimitierend**, degradieren ehrlich un- **nftables-Backend** — eigene `inet snitch`-Tabelle statt iptables, wo `nft` existiert.- **Actionable Alerts** — strukturierte `actions` (Block IP, Kill/Suspend, Ask-Verdict) als Ein-Klick-Buttons.- **`asn`/`country` in Custom Rules** — lokale Geo-DB, kombinierbar mit `action=block` als Geo-Fence.+- **DGA-Heuristik** — aufgelöste DNS-Namen und TLS-SNIs werden lexikalisch+ bewertet (Entropie, Vokale, Konsonantenläufe, Ziffern) → `DGA_SUSPECT`.+ Reine lokale Heuristik; kein WHOIS, kein Domain-Alter.+- **Getarntes Protokoll** — der ≤64-Byte-Payload-Head muss zum Port passen+ (HTTP/80, DNS/53, SSH/22, TLS/443+853, Mail-ASCII) → `PROTO_MISMATCH`,+ Cooldown pro Flow.+- **Volumen-Kill-Switch (opt-in)** — `kill_switch_enabled` verwandelt einen+ `UPLOAD_SPIKE` in eine echte Firewall-Blockade der Remote-IP+ (dedupliziert, best-effort). Standardmäßig aus.diff --git a/docs/FIREWALL.es.md b/docs/FIREWALL.es.mdindex 3f65116..0d6dc10 100644--- a/docs/FIREWALL.es.md+++ b/docs/FIREWALL.es.md@@ -124,7 +124,7 @@ Todas están **desactivadas por defecto o se autolimitan**, degradan honestament- **Guardia de alta entropía** — payloads ≥48 B en canales no TLS con ≥4,7 bits/byte → `HIGH_ENTROPY`; cooldown 10 min por host.- **Heurística de túnel ICMP** — tipos echo con ≥24 B de payload, ≥3× en 5 min → `ICMP_TUNNEL`.- **Anomalía ML de flujo** — isolation forest en Python puro (64 árboles, cero deps) sobre tus propios resúmenes; inerte <384 flujos, `ML_ANOMALY` a 0,62. Desviación de baseline, **no** un clasificador.-- **Ask-on-connect (Linux, opt-in)** — `ask_enabled` + root + `python-netfilterqueue`: nuevos flujos salientes retenidos en NFQUEUE 7 hasta `POST /security/ask/verdict`; timeout 15 s, fail-closed (`ask_failopen=1` invierte). Windows/macOS necesitan los esqueletos firmados de `contrib/`.+- **Ask-on-connect (Linux, opt-in)** — `ask_enabled` + root + iptables: nuevos flujos salientes retenidos en NFQUEUE 7 hasta `POST /security/ask/verdict` — el cliente NFQUEUE es **Python puro** (`detection/nfqueue.py`, AF_NETLINK), sin `python-netfilterqueue`; timeout 15 s, fail-closed (`ask_failopen=1` invierte). Windows/macOS necesitan los esqueletos firmados de `contrib/`.- **Enforcement eBPF cgroup (Linux, opt-in)** — `POST /security/ebpf/isolate {pid}` + `/security/ebpf/block {ip}`: programa attach al cgroup snitch — drops en kernel SOLO para procesos aislados.- **Check de hollowing (Linux)** — `POST /security/hollow {pid}` compara páginas ejecutables file-backed de `/proc/<pid>/mem` con el disco.- **Sincronización IOC entre pares (opt-in)** — `gossip_peers` ≤32 + `gossip_enabled`: paquetes Merkle cada 5 min por HTTP(S) autenticado — sin discovery, no es ZK.@@ -133,3 +133,12 @@ Todas están **desactivadas por defecto o se autolimitan**, degradan honestament- **Backend nftables** — tabla `inet snitch` dedicada en lugar de iptables donde existe `nft`.- **Alertas accionables** — `actions` estructuradas (bloquear IP, matar/suspender, veredicto ask) como botones de un clic.- **`asn`/`country` en reglas custom** — base geo local, combinable con `action=block` como geo-fence.+- **Heurística DGA** — los nombres DNS resueltos y SNIs TLS se puntúan por+ rasgos léxicos (entropía, vocales, consonantes apiladas, dígitos) →+ `DGA_SUSPECT`. Heurística local pura; sin WHOIS ni edad de dominio.+- **Protocolo disfrazado** — la cabecera ≤64 B del payload debe coincidir+ con el protocolo del puerto (HTTP/80, DNS/53, SSH/22, TLS/443+853,+ comandos ASCII de correo) → `PROTO_MISMATCH`, con cooldown por flujo.+- **Kill-switch de volumen (opt-in)** — `kill_switch_enabled` convierte un+ `UPLOAD_SPIKE` en un bloqueo de firewall real sobre la IP remota+ (deduplicado, best-effort). Desactivado por defecto.diff --git a/docs/FIREWALL.ja.md b/docs/FIREWALL.ja.mdindex b22a148..1422624 100644--- a/docs/FIREWALL.ja.md+++ b/docs/FIREWALL.ja.md@@ -121,7 +121,7 @@ OS ネイティブファイアウォールへ best-effort で適用されます:- **高エントロピー監視** — 非TLSチャネルで ≥48 B・≥4.7ビット/バイトのペイロード → `HIGH_ENTROPY`;ホスト毎10分クールダウン。- **ICMPトンネル検知** — ≥24 Bペイロードのエコーが5分で3回以上 → `ICMP_TUNNEL`。- **MLフロー異常** — 純Pythonのisolation forest(64本、依存ゼロ)が自フロー要約をスコアリング;384フロー未満では不活性、0.62で `ML_ANOMALY`。ベースライン偏差でありマルウェア分類器では**ありません**。-- **Ask-on-Connect(Linux、オプトイン)** — `ask_enabled` + root + `python-netfilterqueue`:新規送信フローをNFQUEUE 7に `POST /security/ask/verdict` まで保留;タイムアウト15秒、fail-closed(`ask_failopen=1`で反転)。Windows/macOSは `contrib/` の署名済みcallout/NetworkExtensionが必要。+- **Ask-on-Connect(Linux、オプトイン)** — `ask_enabled` + root + iptables:新規送信フローをNFQUEUE 7に `POST /security/ask/verdict` まで保留 — NFQUEUEクライアントは**純粋Python**(`detection/nfqueue.py`、AF_NETLINK)で `python-netfilterqueue` 不要;タイムアウト15秒、fail-closed(`ask_failopen=1`で反転)。Windows/macOSは `contrib/` の署名済みcallout/NetworkExtensionが必要。- **eBPF cgroupエンフォースメント(Linux、オプトイン)** — `POST /security/ebpf/isolate {pid}` + `/security/ebpf/block {ip}`:snitch cgroupへattach — カーネルdropは隔離プロセスのみ。- **ハロウィングチェック(Linux)** — `POST /security/hollow {pid}` が `/proc/<pid>/mem` のfile-backed実行可能ページをディスクと比較。- **IOCピア同期(オプトイン)** — `gossip_peers` ≤32 + `gossip_enabled`:Merkleプルーフパックを5分毎に認証HTTP(S)で — 探索なし、ZKプロトコルではありません。@@ -130,3 +130,12 @@ OS ネイティブファイアウォールへ best-effort で適用されます:- **nftablesバックエンド** — `nft` があれば専用 `inet snitch` テーブル(iptablesの代わり)。- **アクション可能アラート** — 構造化 `actions`(IPブロック、終了/一時停止、ask判定)をワンクリックボタンとして表示。- **カスタムルールの `asn`/`country`** — ローカルgeo DB、`action=block` と組み合わせてgeoフェンスに。+- **DGAヒューリスティック** — 解決されたDNS名とTLS SNIを字彙特徴+ (エントロピー、母音率、子音連鎖、数字)でスコア → `DGA_SUSPECT`。+ 完全ローカル;WHOISやドメイン年齢なし。+- **偽装プロトコル** — ≤64バイトのペイロード先頭がポートの示す+ プロトコル(HTTP/80、DNS/53、SSH/22、TLS/443+853、メールASCII)と+ 一致必須 → `PROTO_MISMATCH`、フロー毎にクールダウン。+- **ボリュームキルスイッチ(オプトイン)** — `kill_switch_enabled` が+ `UPLOAD_SPIKE` をリモートIPへの実ファイアウォールブロックに変換+ (重複排除、ベストエフォート)。デフォルトでオフ。diff --git a/docs/FIREWALL.md b/docs/FIREWALL.mdindex 8c12a47..211c23c 100644--- a/docs/FIREWALL.md+++ b/docs/FIREWALL.md@@ -237,10 +237,12 @@ never ship data off the machine:score ≥0.62 → `ML_ANOMALY`. Baseline deviation, **not** a malwareclassifier.- **Ask-on-connect (Linux, opt-in)** — `ask_enabled=1` + root +- `python-netfilterqueue`: new outbound flows are held on NFQUEUE 7- until you answer `POST /security/ask {flow_id, allow}` in the UI —- the Little Snitch-style prompt, for real. Default timeout 15 s,- fail-closed (`ask_failopen=1` to reverse). Windows/macOS need the+ iptables: new outbound flows are held on NFQUEUE 7 until you answer+ `POST /security/ask/verdict` in the UI — the Little Snitch-style+ prompt, for real. The NFQUEUE client is **pure Python**+ (`detection/nfqueue.py`, AF_NETLINK) — no `python-netfilterqueue`+ or libnetfilter_queue to install. Default timeout 15 s, fail-closed+ (`ask_failopen=1` to reverse). Windows/macOS need thesigned callout/NetworkExtension skeletons in `contrib/` — user-modecannot hold a connection.- **eBPF cgroup enforcement (Linux, opt-in)** — `ebpf_enforce.py`@@ -268,6 +270,19 @@ never ship data off the machine:UI renders them as one-click buttons.- **`asn`/`country` in custom rules** — matched against the localgeo DB, usable with `action=block` for a geo-fence kill-switch.+- **DGA heuristic** — resolved DNS names and TLS SNIs are scored on+ lexical features (entropy, vowel ratio, consonant runs, digits) →+ `DGA_SUSPECT`. Pure local heuristic; no WHOIS or domain-age data.+- **Protocol/port mismatch** — the ≤64-byte payload head must match+ what the port advertises (HTTP/80, DNS/53, SSH/22, TLS/443+853,+ mail ASCII commands) → `PROTO_MISMATCH`, cooled down per flow.+- **Volume kill-switch (opt-in)** — `kill_switch_enabled` turns an+ `UPLOAD_SPIKE` alert into a real firewall block on the remote IP+ (deduped, best-effort). Off by default.+- **Pure-Python NFQUEUE** — ask-on-connect no longer needs+ `python-netfilterqueue`: `detection/nfqueue.py` speaks+ nfnetlink_queue over AF_NETLINK directly. Linux + root + iptables+ only.---@@ -513,10 +528,12 @@ honnêtement et n'envoient jamais de données hors de la machine :tous les 256, score ≥0,62 → `ML_ANOMALY`. Déviation de baseline,**pas** un classifieur de malware.- **Ask-on-connect (Linux, opt-in)** — `ask_enabled=1` + root +- `python-netfilterqueue` : les nouveaux flux sortants sont retenus- sur NFQUEUE 7 jusqu'à votre `POST /security/ask {flow_id, allow}`- dans l'UI — la pop-up façon Little Snitch, pour de vrai. Timeout- 15 s, fail-closed (`ask_failopen=1` inverse). Windows/macOS exigent+ iptables : les nouveaux flux sortants sont retenus sur NFQUEUE 7+ jusqu'à votre `POST /security/ask/verdict` dans l'UI — la pop-up+ façon Little Snitch, pour de vrai. Le client NFQUEUE est en **pur+ Python** (`detection/nfqueue.py`, AF_NETLINK) — plus besoin de+ `python-netfilterqueue` ni de libnetfilter_queue. Timeout 15 s,+ fail-closed (`ask_failopen=1` inverse). Windows/macOS exigentles callout/NetworkExtension signés de `contrib/` — le user-mode nepeut pas suspendre une connexion.- **Enforcement eBPF cgroup (Linux, opt-in)** — `ebpf_enforce.py`@@ -544,3 +561,18 @@ honnêtement et n'envoient jamais de données hors de la machine :mémoire) rendues en boutons un clic dans l'UI.- **`asn`/`country` dans les règles custom** — matchés sur la basegeo locale, combinables avec `action=block` pour un geo-fence.+- **Heuristique DGA** — les noms DNS résolus et SNI TLS sont notés sur+ des traits lexicaux (entropie, voyelles, consonnes empilées,+ chiffres) → `DGA_SUSPECT`. Heuristique locale pure ; ni WHOIS ni+ âge de domaine.+- **Protocole déguisé** — la tête ≤64 o du payload doit correspondre+ au protocole annoncé par le port (HTTP/80, DNS/53, SSH/22,+ TLS/443+853, commandes ASCII mail) → `PROTO_MISMATCH`, cooldown+ par flux.+- **Kill-switch de volume (opt-in)** — `kill_switch_enabled`+ transforme une alerte `UPLOAD_SPIKE` en vrai blocage pare-feu sur+ l'IP distante (dédupliqué, au mieux). Désactivé par défaut.+- **NFQUEUE pur Python** — ask-on-connect n'exige plus+ `python-netfilterqueue` : `detection/nfqueue.py` parle+ nfnetlink_queue en AF_NETLINK directement. Linux + root + iptables+ seulement.diff --git a/docs/FIREWALL.pt-BR.md b/docs/FIREWALL.pt-BR.mdindex 7948e7a..d9563b6 100644--- a/docs/FIREWALL.pt-BR.md+++ b/docs/FIREWALL.pt-BR.md@@ -125,7 +125,7 @@ Todas estão **desativadas por padrão ou autolimitadas**, degradam honestamente- **Guarda de alta entropia** — payloads ≥48 B em canais não TLS com ≥4,7 bits/byte → `HIGH_ENTROPY`; cooldown de 10 min por host.- **Heurística de túnel ICMP** — tipos echo com ≥24 B de payload, ≥3× em 5 min → `ICMP_TUNNEL`.- **Anomalia ML de fluxo** — isolation forest em Python puro (64 árvores, zero deps) sobre seus próprios resumos; inerte <384 fluxos, `ML_ANOMALY` a 0,62. Desvio de baseline, **não** um classificador.-- **Ask-on-connect (Linux, opt-in)** — `ask_enabled` + root + `python-netfilterqueue`: novos fluxos de saída retidos na NFQUEUE 7 até `POST /security/ask/verdict`; timeout 15 s, fail-closed (`ask_failopen=1` inverte). Windows/macOS precisam dos esqueletos assinados em `contrib/`.+- **Ask-on-connect (Linux, opt-in)** — `ask_enabled` + root + iptables: novos fluxos de saída retidos na NFQUEUE 7 até `POST /security/ask/verdict` — o cliente NFQUEUE é **Python puro** (`detection/nfqueue.py`, AF_NETLINK), sem `python-netfilterqueue`; timeout 15 s, fail-closed (`ask_failopen=1` inverte). Windows/macOS precisam dos esqueletos assinados em `contrib/`.- **Enforcement eBPF cgroup (Linux, opt-in)** — `POST /security/ebpf/isolate {pid}` + `/security/ebpf/block {ip}`: programa attach ao cgroup snitch — drops em kernel SÓ para processos isolados.- **Check de hollowing (Linux)** — `POST /security/hollow {pid}` compara páginas executáveis file-backed de `/proc/<pid>/mem` com o disco.- **Sincronização IOC entre pares (opt-in)** — `gossip_peers` ≤32 + `gossip_enabled`: pacotes Merkle a cada 5 min via HTTP(S) autenticado — sem discovery, não é ZK.@@ -134,3 +134,12 @@ Todas estão **desativadas por padrão ou autolimitadas**, degradam honestamente- **Backend nftables** — tabela `inet snitch` dedicada em vez de iptables onde existe `nft`.- **Alertas acionáveis** — `actions` estruturadas (bloquear IP, matar/suspender, veredito ask) como botões de um clique.- **`asn`/`country` em regras custom** — base geo local, combinável com `action=block` como geo-fence.+- **Heurística DGA** — nomes DNS resolvidos e SNIs TLS são pontuados por+ traços lexicais (entropia, vogais, consoantes empilhadas, dígitos) →+ `DGA_SUSPECT`. Heurística local pura; sem WHOIS nem idade de domínio.+- **Protocolo disfarçado** — o cabeçalho ≤64 B do payload deve combinar+ com o protocolo da porta (HTTP/80, DNS/53, SSH/22, TLS/443+853,+ comandos ASCII de e-mail) → `PROTO_MISMATCH`, cooldown por fluxo.+- **Kill-switch de volume (opt-in)** — `kill_switch_enabled` transforma um+ `UPLOAD_SPIKE` em bloqueio de firewall real na IP remota (deduplicado,+ best-effort). Desativado por padrão.diff --git a/docs/FIREWALL.ru.md b/docs/FIREWALL.ru.mdindex 79ac94d..9b5c6c9 100644--- a/docs/FIREWALL.ru.md+++ b/docs/FIREWALL.ru.md@@ -122,7 +122,7 @@ endpoint'ы получают `{alert, source, text}`. Сбои пишутся в- **Сторож высокой энтропии** — payloads ≥48 Б на не-TLS каналах с ≥4,7 бит/байт → `HIGH_ENTROPY`; кулдаун 10 мин на хост.- **Эвристика ICMP-туннеля** — echo с ≥24 Б payload, ≥3× за 5 мин → `ICMP_TUNNEL`.- **ML-аномалия потока** — isolation forest на чистом Python (64 дерева, ноль зависимостей) по вашим же сводкам; неактивно <384 потоков, `ML_ANOMALY` при 0,62. Отклонение от baseline, **не** классификатор.-- **Ask-on-connect (Linux, opt-in)** — `ask_enabled` + root + `python-netfilterqueue`: новые исходящие потоки удерживаются в NFQUEUE 7 до `POST /security/ask/verdict`; таймаут 15 с, fail-closed (`ask_failopen=1` наоборот). Windows/macOS требуют подписанные callout/NetworkExtension из `contrib/`.+- **Ask-on-connect (Linux, opt-in)** — `ask_enabled` + root + iptables: новые исходящие потоки удерживаются в NFQUEUE 7 до `POST /security/ask/verdict` — клиент NFQUEUE на **чистом Python** (`detection/nfqueue.py`, AF_NETLINK), `python-netfilterqueue` не нужен; таймаут 15 с, fail-closed (`ask_failopen=1` наоборот). Windows/macOS требуют подписанные callout/NetworkExtension из `contrib/`.- **eBPF cgroup-эндфорсмент (Linux, opt-in)** — `POST /security/ebpf/isolate {pid}` + `/security/ebpf/block {ip}`: программа attach к cgroup snitch — дропы в ядре ТОЛЬКО для изолированных процессов.- **Проверка hollowing (Linux)** — `POST /security/hollow {pid}` сравнивает file-backed исполняемые страницы `/proc/<pid>/mem` с диском.- **Синхронизация IOC с пирами (opt-in)** — `gossip_peers` ≤32 + `gossip_enabled`: Merkle-пакеты каждые 5 мин по аутентифицированному HTTP(S) — без discovery, не ZK.@@ -131,3 +131,12 @@ endpoint'ы получают `{alert, source, text}`. Сбои пишутся в- **Backend nftables** — отдельная таблица `inet snitch` вместо iptables, где есть `nft`.- **Действующие алерты** — структурные `actions` (блок IP, убить/приостановить, вердикт ask) кнопками в один клик.- **`asn`/`country` в своих правилах** — локальная geo-БД, комбинируется с `action=block` как geo-fence.+- **Эвристика DGA** — разрешённые DNS-имена и TLS SNI оцениваются по+ лексическим признакам (энтропия, гласные, цепочки согласных, цифры) →+ `DGA_SUSPECT`. Чисто локальная эвристика; без WHOIS и возраста домена.+- **Замаскированный протокол** — заголовок payload ≤64 Б должен+ соответствовать протоколу порта (HTTP/80, DNS/53, SSH/22,+ TLS/443+853, ASCII-команды почты) → `PROTO_MISMATCH`, cooldown на поток.+- **Килл-свитч по объёму (opt-in)** — `kill_switch_enabled` превращает+ `UPLOAD_SPIKE` в реальную блокировку файрвола для удалённого IP+ (с дедупликацией, best-effort). По умолчанию выключен.diff --git a/docs/FIREWALL.zh-CN.md b/docs/FIREWALL.zh-CN.mdindex 6b7467c..fcd1e34 100644--- a/docs/FIREWALL.zh-CN.md+++ b/docs/FIREWALL.zh-CN.md@@ -114,7 +114,7 @@ Snitch **不**在用户态过滤数据包。规则会被尽力下发到操作系- **高熵监视** — 非 TLS 通道上 ≥48 B、≥4.7 比特/字节的载荷 → `HIGH_ENTROPY`;每主机 10 分钟冷却。- **ICMP 隧道启发式** — 载荷 ≥24 B 的 echo 类型,5 分钟内 ≥3 次 → `ICMP_TUNNEL`。- **ML 流异常** — 纯 Python isolation forest(64 棵树、零依赖)对您自己的流摘要打分;<384 流时惰性,0.62 触发 `ML_ANOMALY`。基线偏差,**不是**恶意软件分类器。-- **Ask-on-connect(Linux,可选)** — `ask_enabled` + root + `python-netfilterqueue`:新出站流在 NFQUEUE 7 挂起至 `POST /security/ask/verdict`;超时 15 秒,默认拒绝(`ask_failopen=1` 反转)。Windows/macOS 需要 `contrib/` 中的签名 callout/NetworkExtension。+- **Ask-on-connect(Linux,可选)** — `ask_enabled` + root + iptables:新出站流在 NFQUEUE 7 挂起至 `POST /security/ask/verdict` — NFQUEUE 客户端为**纯 Python**(`detection/nfqueue.py`,AF_NETLINK),无需 `python-netfilterqueue`;超时 15 秒,默认拒绝(`ask_failopen=1` 反转)。Windows/macOS 需要 `contrib/` 中的签名 callout/NetworkExtension。- **eBPF cgroup 执行(Linux,可选)** — `POST /security/ebpf/isolate {pid}` + `/security/ebpf/block {ip}`:程序挂载到 snitch cgroup — 内核丢弃仅作用于被隔离进程。- **空心化检查(Linux)** — `POST /security/hollow {pid}` 对比 `/proc/<pid>/mem` 中文件映射的可执行页与磁盘。- **IOC 节点同步(可选)** — `gossip_peers` ≤32 + `gossip_enabled`:每 5 分钟经认证 HTTP(S) 推送 Merkle 证明包 — 无发现机制,非 ZK。@@ -123,3 +123,11 @@ Snitch **不**在用户态过滤数据包。规则会被尽力下发到操作系- **nftables 后端** — 有 `nft` 时使用专用 `inet snitch` 表替代 iptables。- **可操作告警** — 结构化 `actions`(封锁 IP、终止/挂起、ask 判定)以一键按钮呈现。- **自定义规则的 `asn`/`country`** — 本地 geo 数据库,可与 `action=block` 组成地理围栏。+- **DGA 启发式** — 已解析的 DNS 名与 TLS SNI 按词汇特征评分(熵、+ 元音比、辅音连缀、数字)→ `DGA_SUSPECT`。纯本地启发式;无 WHOIS+ 或域名年龄数据。+- **伪装协议** — ≤64 字节负载头部必须与端口声明的协议相符+ (HTTP/80、DNS/53、SSH/22、TLS/443+853、邮件 ASCII 命令)→+ `PROTO_MISMATCH`,按流冷却。+- **流量终止开关(可选)** — `kill_switch_enabled` 将 `UPLOAD_SPIKE`+ 变为对远程 IP 的真实防火墙封锁(去重、尽力而为)。默认关闭。diff --git a/electron/package.json b/electron/package.jsonindex 6cb3161..33f1fe0 100644--- a/electron/package.json+++ b/electron/package.json@@ -1,6 +1,6 @@{"name": "snitch",- "version": "1.5.1",+ "version": "1.5.2","description": "Snitch \u2014 real-time network traffic visualizer / visualiseur de trafic r\u00e9seau en temps r\u00e9el","main": "main.js","license": "AGPL-3.0-or-later",diff --git a/frontend/package.json b/frontend/package.jsonindex 3b7bc71..ab64fe9 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -1,6 +1,6 @@{"name": "snitch-frontend",- "version": "1.5.1",+ "version": "1.5.2","private": true,"license": "AGPL-3.0-or-later","description": "Snitch UI \u2014 React + D3.js / Interface React + D3.js",diff --git a/frontend/src/components/Settings.jsx b/frontend/src/components/Settings.jsxindex c1ef7d1..ab91499 100644--- a/frontend/src/components/Settings.jsx+++ b/frontend/src/components/Settings.jsx@@ -590,6 +590,33 @@ export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchl<div style={{ ...hint, marginTop: 4 }}>{t('gs_privacy')}</div></div>+ {/* Volume kill-switch / Kill-switch de volume */}+ <div style={{ ...row, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div>+ <div style={label}>{t('ks_title')}</div>+ <div style={hint}>{t('ks_hint')}</div>+ </div>+ <button+ onClick={() => {+ const v = !settings?.kill_switch_enabled+ setSettings(s => ({ ...s, kill_switch_enabled: v }))+ save('kill_switch_enabled', v)+ }}+ role="switch" aria-checked={!!settings?.kill_switch_enabled}+ style={{+ width: 36, height: 20, borderRadius: 10, border: 'none',+ background: settings?.kill_switch_enabled ? '#3b82f6' : 'var(--bg)',+ outline: '1px solid var(--border)', cursor: 'pointer',+ position: 'relative', flexShrink: 0,+ }}>+ <div style={{+ width: 14, height: 14, borderRadius: '50%', background: 'var(--text)',+ position: 'absolute', top: 3, left: settings?.kill_switch_enabled ? 19 : 3,+ transition: 'left 0.15s',+ }} />+ </button>+ </div>+{/* Integrity watch / Veille d'intégrité */}<div style={{ ...row, display: 'block' }}><div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex d0cfae2..73fa5c5 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -428,6 +428,8 @@ export default {alertmsg_ICMP_TUNNEL: d => `Möglicher ICMP-Tunnel: wiederholte große Echo-Payloads mit ${d.ip}`,alertmsg_ML_ANOMALY: d => `ML-Flussanomalie: ${d.process || '?'} → ${d.ip} (Score ${d.score})`,alertmsg_ASK_VERDICT: d => `Entscheid nötig: ${d.process || 'ein Prozess'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (Auto-Entscheid in ${d.timeout_s}s)`,+ alertmsg_DGA_SUSPECT: d => `DGA-verdächtige Domain ${d.label || d.name} (${(d.reasons || []).join(', ')})`,+ alertmsg_PROTO_MISMATCH: d => `Getarntes Protokoll: ${d.reason} — ${d.process || '?'} → ${d.ip}:${d.port}`,alert_act_block: 'IP blockieren',alert_act_kill: 'Beenden',alert_act_suspend: 'Anhalten',@@ -450,4 +452,6 @@ export default {gs_hint: 'Gesalzene Merkle-Proof-Pakete alle 5 Min an explizit gepaarte Snitch-Instanzen pushen — nur Hash-Commitments, nie rohe Indikatoren.',gs_peers_ph: 'host:port, kommagetrennt',gs_privacy: 'Opt-in Flotten-Sharing — Pakete gehen nur an die hier gelisteten Peers.',+ ks_title: 'Volumen-Kill-Switch',+ ks_hint: 'Blockiert die Remote-IP (echte Firewall-Regel) bei einem Upload-Spike — standardmäßig aus',}diff --git a/frontend/src/locales/en.js b/frontend/src/locales/en.jsindex 8e96520..f3c95ee 100644--- a/frontend/src/locales/en.js+++ b/frontend/src/locales/en.js@@ -432,6 +432,8 @@ export default { // Navigationalertmsg_ICMP_TUNNEL: d => `Possible ICMP tunnelling: repeated fat echo payloads with ${d.ip}`,alertmsg_ML_ANOMALY: d => `ML flow anomaly: ${d.process || '?'} → ${d.ip} (score ${d.score})`,alertmsg_ASK_VERDICT: d => `Verdict needed: ${d.process || 'a process'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (auto-decision in ${d.timeout_s}s)`,+ alertmsg_DGA_SUSPECT: d => `DGA-looking domain ${d.label || d.name} (${(d.reasons || []).join(', ')})`,+ alertmsg_PROTO_MISMATCH: d => `Protocol mismatch: ${d.reason} — ${d.process || '?'} → ${d.ip}:${d.port}`,alert_act_block: 'Block IP',alert_act_kill: 'Kill',alert_act_suspend: 'Suspend',@@ -454,4 +456,6 @@ export default { // Navigationgs_hint: 'Push salted-Merkle proof packs to explicitly paired Snitch instances every 5 min — hash commitments only, never raw indicators.',gs_peers_ph: 'host:port, comma-separated',gs_privacy: 'Opt-in fleet sharing — packs leave only for the peers you list here.',+ ks_title: 'Volume kill-switch',+ ks_hint: 'Auto-block the remote IP (real firewall rule) when an upload spike fires — off by default',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex c8c6b15..3104d50 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -426,6 +426,8 @@ export default { // Navegaciónalertmsg_ICMP_TUNNEL: d => `Posible túnel ICMP: ecos repetidos con payloads grandes hacia ${d.ip}`,alertmsg_ML_ANOMALY: d => `Anomalía ML de flujo: ${d.process || '?'} → ${d.ip} (puntuación ${d.score})`,alertmsg_ASK_VERDICT: d => `Veredicto requerido: ${d.process || 'un proceso'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (decisión auto en ${d.timeout_s}s)`,+ alertmsg_DGA_SUSPECT: d => `Dominio con aspecto de DGA ${d.label || d.name} (${(d.reasons || []).join(', ')})`,+ alertmsg_PROTO_MISMATCH: d => `Protocolo disfrazado: ${d.reason} — ${d.process || '?'} → ${d.ip}:${d.port}`,alert_act_block: 'Bloquear IP',alert_act_kill: 'Matar',alert_act_suspend: 'Suspender',@@ -448,4 +450,6 @@ export default { // Navegacióngs_hint: 'Enviar paquetes Merkle salados a instancias Snitch emparejadas explícitamente cada 5 min — solo compromisos hash, nunca indicadores crudos.',gs_peers_ph: 'host:puerto, separados por comas',gs_privacy: 'Compartición opt-in — los paquetes solo salen hacia los pares listados aquí.',+ ks_title: 'Kill-switch de volumen',+ ks_hint: 'Bloquea la IP remota (regla de firewall real) cuando salta un pico de subida — desactivado por defecto',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex a90ffce..317205e 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -428,6 +428,8 @@ export default { // Navigationalertmsg_ICMP_TUNNEL: d => `Tunnel ICMP possible : échos répétés à gros payload avec ${d.ip}`,alertmsg_ML_ANOMALY: d => `Anomalie ML de flux : ${d.process || '?'} → ${d.ip} (score ${d.score})`,alertmsg_ASK_VERDICT: d => `Verdict requis : ${d.process || 'un processus'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (décision auto dans ${d.timeout_s}s)`,+ alertmsg_DGA_SUSPECT: d => `Domaine à aspect DGA ${d.label || d.name} (${(d.reasons || []).join(', ')})`,+ alertmsg_PROTO_MISMATCH: d => `Protocole déguisé : ${d.reason} — ${d.process || '?'} → ${d.ip}:${d.port}`,alert_act_block: "Bloquer l'IP",alert_act_kill: 'Tuer',alert_act_suspend: 'Suspendre',@@ -450,4 +452,6 @@ export default { // Navigationgs_hint: "Pousser les paquets Merkle salés vers des instances Snitch explicitement appairées toutes les 5 min — engagements de hash seulement, jamais d'indicateurs bruts.",gs_peers_ph: 'hôte:port, séparés par des virgules',gs_privacy: 'Partage de flotte opt-in — les paquets ne partent que vers les pairs listés ici.',+ ks_title: 'Kill-switch de volume',+ ks_hint: 'Bloque l\u2019IP distante (vraie règle pare-feu) quand un pic d\u2019envoi se déclenche — désactivé par défaut',}diff --git a/frontend/src/locales/ja.js b/frontend/src/locales/ja.jsindex b4b81a6..96021c4 100644--- a/frontend/src/locales/ja.js+++ b/frontend/src/locales/ja.js@@ -428,6 +428,8 @@ export default {alertmsg_ICMP_TUNNEL: d => `ICMPトンネルの可能性: ${d.ip} との大きなエコーペイロードの繰り返し`,alertmsg_ML_ANOMALY: d => `MLフロー異常: ${d.process || '?'} → ${d.ip} (スコア ${d.score})`,alertmsg_ASK_VERDICT: d => `判定が必要: ${d.process || 'プロセス'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (${d.timeout_s}秒で自動判定)`,+ alertmsg_DGA_SUSPECT: d => `DGAの疑いがあるドメイン ${d.label || d.name} (${(d.reasons || []).join(', ')})`,+ alertmsg_PROTO_MISMATCH: d => `偽装プロトコル: ${d.reason} — ${d.process || '?'} → ${d.ip}:${d.port}`,alert_act_block: 'IPをブロック',alert_act_kill: '強制終了',alert_act_suspend: '一時停止',@@ -450,4 +452,6 @@ export default {gs_hint: '塩付きMerkleプルーフパックを明示的にペアリングしたSnitchインスタンスへ5分毎にプッシュ — ハッシュコミットメントのみ、生インジケーターは送信しません。',gs_peers_ph: 'host:port(カンマ区切り)',gs_privacy: 'オプトインのフリート共有 — パックはここに列挙したピアにのみ送信されます。',+ ks_title: 'ボリュームキルスイッチ',+ ks_hint: 'アップロード急増時にリモートIPをブロック(実際のファイアウォールルール)— デフォルトでオフ',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 0b345e4..fe3ae12 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -428,6 +428,8 @@ export default {alertmsg_ICMP_TUNNEL: d => `Possível túnel ICMP: ecos repetidos com payloads grandes com ${d.ip}`,alertmsg_ML_ANOMALY: d => `Anomalia ML de fluxo: ${d.process || '?'} → ${d.ip} (score ${d.score})`,alertmsg_ASK_VERDICT: d => `Veredito necessário: ${d.process || 'um processo'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (decisão automática em ${d.timeout_s}s)`,+ alertmsg_DGA_SUSPECT: d => `Domínio com cara de DGA ${d.label || d.name} (${(d.reasons || []).join(', ')})`,+ alertmsg_PROTO_MISMATCH: d => `Protocolo disfarçado: ${d.reason} — ${d.process || '?'} → ${d.ip}:${d.port}`,alert_act_block: 'Bloquear IP',alert_act_kill: 'Matar',alert_act_suspend: 'Suspender',@@ -450,4 +452,6 @@ export default {gs_hint: 'Envia pacotes Merkle com sal a instâncias Snitch pareadas explicitamente a cada 5 min — só compromissos hash, nunca indicadores brutos.',gs_peers_ph: 'host:porta, separados por vírgula',gs_privacy: 'Compartilhamento opt-in — os pacotes só saem para os pares listados aqui.',+ ks_title: 'Kill-switch de volume',+ ks_hint: 'Bloqueia o IP remoto (regra de firewall real) quando um pico de upload dispara — desativado por padrão',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex a071ec7..a873004 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -428,6 +428,8 @@ export default {alertmsg_ICMP_TUNNEL: d => `Возможный ICMP-туннель: повторные объёмные эхо-пакеты с ${d.ip}`,alertmsg_ML_ANOMALY: d => `ML-аномалия потока: ${d.process || '?'} → ${d.ip} (оценка ${d.score})`,alertmsg_ASK_VERDICT: d => `Нужен вердикт: ${d.process || 'процесс'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (авторешение через ${d.timeout_s}с)`,+ alertmsg_DGA_SUSPECT: d => `Домен с признаками DGA ${d.label || d.name} (${(d.reasons || []).join(', ')})`,+ alertmsg_PROTO_MISMATCH: d => `Замаскированный протокол: ${d.reason} — ${d.process || '?'} → ${d.ip}:${d.port}`,alert_act_block: 'Блокировать IP',alert_act_kill: 'Убить',alert_act_suspend: 'Приостановить',@@ -450,4 +452,6 @@ export default {gs_hint: 'Отправлять солёные Merkle-пакеты доказательств явно спаренным экземплярам Snitch каждые 5 мин — только хеш-коммитменты, никогда сырые индикаторы.',gs_peers_ph: 'хост:порт, через запятую',gs_privacy: 'Opt-in обмен внутри флота — пакеты уходят только перечисленным здесь пирам.',+ ks_title: 'Килл-свитч по объёму',+ ks_hint: 'Блокирует удалённый IP (реальное правило файрвола) при всплеске исходящего трафика — выключено по умолчанию',}diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.jsindex 2793fb5..9cd74a5 100644--- a/frontend/src/locales/zh-CN.js+++ b/frontend/src/locales/zh-CN.js@@ -428,6 +428,8 @@ export default {alertmsg_ICMP_TUNNEL: d => `疑似ICMP隧道: 与 ${d.ip} 之间反复出现大载荷回显`,alertmsg_ML_ANOMALY: d => `ML流量异常: ${d.process || '?'} → ${d.ip} (得分 ${d.score})`,alertmsg_ASK_VERDICT: d => `需要判定: ${d.process || '某进程'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (${d.timeout_s}秒后自动判定)`,+ alertmsg_DGA_SUSPECT: d => `疑似DGA域名 ${d.label || d.name} (${(d.reasons || []).join(', ')})`,+ alertmsg_PROTO_MISMATCH: d => `伪装协议: ${d.reason} — ${d.process || '?'} → ${d.ip}:${d.port}`,alert_act_block: '封锁IP',alert_act_kill: '终止',alert_act_suspend: '挂起',@@ -450,4 +452,6 @@ export default {gs_hint: '每 5 分钟向显式配对的 Snitch 实例推送加盐 Merkle 证明包 — 仅哈希承诺,绝不发送原始指标。',gs_peers_ph: '主机:端口,逗号分隔',gs_privacy: '可选的集群共享 — 数据包只发送给此处列出的节点。',+ ks_title: '流量终止开关',+ ks_hint: '上传激增时自动封锁远程IP(真实防火墙规则)— 默认关闭',}