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.

Ship v1.4.0: pcap export, sandbox, profiles, custom rules, pairing

MoneyLisa229192e3d026
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8465ef4..395bd03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,23 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
## [Unreleased]
+## [1.4.0] — 2026-10-23
+
+### Added / Ajouté
+
+- **Forensic PCAP export / Export PCAP forensique** — `GET /forensics/pcap` serializes the bounded raw-frame ring buffer (~4 MiB) into a Wireshark-ready `.pcap` written by a pure-Python `capture/pcapwriter.py`; real libpcap timestamps preserved, optional `ip`/`process` filters. / `GET /forensics/pcap` sérialise l'anneau de trames brutes (~4 Mio) en `.pcap` lisible par Wireshark via `capture/pcapwriter.py` pur Python ; timestamps réels, filtres `ip`/`process` optionnels.
+- **Outbound byte observation / Observation des octets sortants** — Frida deep inspection now also hooks `send`/`WSASend`/`sendto`/`sendmsg` where exports exist, returning bounded head bytes + SHA-256 per flow — an honest byte-observation slice, not full taint analysis. / L'inspection Frida hooke aussi `send`/`WSASend`/`sendto`/`sendmsg` quand présents — tête bornée + SHA-256 par flux : tranche d'observation honnête, pas une analyse de taint complète.
+- **Exact-membership IOC proofs / Preuves d'appartenance exactes IOC** — `format=proof` on `GET /security/iocpack` builds `snitch-ioc-proof/1`: salted SHA-256 leaves + a Merkle commitment root; `POST /security/iocpack/import` verifies membership cryptographically (zero false positives) and detects tampering. Not an interactive ZK protocol — documented as such. / `format=proof` produit `snitch-ioc-proof/1` : feuilles SHA-256 salées + racine d'engagement Merkle ; l'import vérifie l'appartenance cryptographiquement (zéro faux positif) et détecte la falsification. Pas un protocole ZK — documenté ainsi.
+- **Network-denial sandbox / Sandbox sans réseau** — `POST /security/sandbox` detonates a user-chosen executable with **zero egress**: Linux unprivileged `unshare --user --net` or macOS `sandbox-exec` deny-network; bounded runtime + output, honest unsupported-error elsewhere. `contrib/snitch-contain` is the manual twin. / `POST /security/sandbox` exécute un binaire choisi avec zéro égress : `unshare --user --net` non privilégié (Linux) ou `sandbox-exec` deny-network (macOS) ; durée + sortie bornées, erreur honnête ailleurs. `contrib/snitch-contain` est le pendant manuel.
+- **Embedded local model / Modèle local embarqué** — `slm_mode=embedded` loads a user-provided `.gguf` via the optional `llama-cpp-python` package — alert explanations fully in-process, **zero network at all**. Snitch never downloads weights. / `slm_mode=embedded` charge un `.gguf` fourni par l'utilisateur via `llama-cpp-python` optionnel — explications entièrement en processus, zéro réseau. Snitch ne télécharge jamais de poids.
+- **Named firewall profiles / Profils pare-feu nommés** — `POST /firewall/profile` applies `permissive` (clean slate), `balanced` (conservative egress baseline: spam-SMTP + common stratum pool ports) or `strict` (baseline + lockdown) through the ordinary rule machinery, with dedup. / `POST /firewall/profile` applique `permissive` (table rase), `balanced` (base sortante prudente) ou `strict` (base + lockdown) via la machinerie de règles ordinaire, avec dédup.
+- **Custom alert rules / Règles d'alerte personnalisées** — user-defined matchers (`remote_ip`, `host`, `process_name`, `remote_port`, `protocol`, `direction`, `size` × `eq`/`ne`/`contains`/`regex`/`gt`/`lt`/`cidr`) raising `CUSTOM_RULE` alerts; persisted, bounded regex cache, validated at creation, alert-only (never blocks). / Filtres définis par l'utilisateur levant des alertes `CUSTOM_RULE` ; persistés, cache regex borné, validés à la création, alerte seule (jamais de blocage).
+- **Blocklist import / Import de blocklist** — `POST /firewall/blocklist` turns a local hosts/domain file (purely local) or an **opt-in** remote URL (bounded HTTPS fetch, `remote_fetch` flagged in the response) into `domain` rules, deduplicated and capped at 500–5000 entries. / `POST /firewall/blocklist` convertit un fichier local ou une URL opt-in (fetch HTTPS borné, `remote_fetch` signalé) en règles `domain` dédupliquées, plafonnées à 500–5000.
+- **Remote pairing / Pairing distant** — opt-in `lan_bind` persisted setting (`POST /remote/pairing`) exposing the API on `0.0.0.0` or a chosen LAN address at next backend start; `GET /remote/pairing` reports effective bind, source and LAN addresses honestly. Token auth always enforced. / Réglage `lan_bind` opt-in exposant l'API sur `0.0.0.0` ou une adresse LAN au prochain démarrage ; `GET /remote/pairing` rapporte honnêtement bind effectif, source et adresses LAN. Jeton toujours exigé.
+- **ASN attribution / Attribution ASN** — `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb` lookups now surface `node.asn` (AS number) alongside the org string when the database is present. / Les lookups ASN exposent `node.asn` (numéro d'AS) en plus de l'org quand la base est présente.
+- **Native-filter skeletons / Squelettes de filtres natifs** — `contrib/wfp-callout/` (C: WFP kernel callout register/classify/unregister skeleton + signing/build README, references Microsoft `network/trans/inspect` and `WFPStarterKit`) and `contrib/macos-filter/` (Swift `NEFilterDataProvider` skeleton + entitlements README). Research scaffolding, not shipped components — documented honestly. / `contrib/wfp-callout/` (squelette callout WFP noyau + README signature/build) et `contrib/macos-filter/` (squelette `NEFilterDataProvider` Swift + README entitlements). Échafaudage de recherche, pas des composants livrés — documenté honnêtement.
+- **UI for the new surface / UI des nouvelles fonctionnalités** — profile buttons, blocklist import form (file/URL with opt-in confirm), custom alert rule CRUD, PCAP export button, remote-pairing toggle with LAN addresses + restart notice, sandbox detonation form, SLM backend selector (Ollama/embedded + GGUF path); 43 new i18n keys × 8 locales (365 total, parity-checked). / Boutons de profils, formulaire d'import blocklist, CRUD de règles d'alerte, bouton export PCAP, bascule pairing distant avec adresses LAN + avis de redémarrage, formulaire de détonation sandbox, sélecteur de backend SLM ; 43 nouvelles clés × 8 locales (365 au total, parité vérifiée).
+
## [1.3.0] — 2026-10-22
### Added / Ajouté
diff --git a/CITATION.cff b/CITATION.cff
index 7b3284d..e0dbba3 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -17,5 +17,5 @@ keywords:
- privacy
- traffic visualization
- cybersecurity
-version: "1.0.5"
+version: "1.4.0"
date-released: "2026-10-01"
diff --git a/PRIVACY.de.md b/PRIVACY.de.md
index 582d097..942c8e9 100644
--- a/PRIVACY.de.md
+++ b/PRIVACY.de.md
@@ -76,3 +76,11 @@ an Dritte schickte.
Datenverzeichnis: `data/` in Dev/Docker, `%LOCALAPPDATA%\Snitch` unter
Windows, `~/Library/Application Support/Snitch` unter macOS,
`~/.local/share/snitch` unter Linux bei installierter Nutzung.
+
+## Neu in v1.4 (Privatsphäre)
+
+- **Blockliste per URL (opt-in)** — eine *lokale Datei* ist ein rein lokaler Lesevorgang; eine *URL* löst genau einen begrenzten HTTPS-Abruf aus (≤4 MiB, ≤10 s), in der UI bestätigt und als `remote_fetch` markiert.
+- **Fernkopplung (opt-in, aus)** — die API lauscht nur auf 127.0.0.1; Aktivieren persistiert `lan_bind` für den nächsten Start — Token bleibt pro Anfrage Pflicht.
+- **Sandbox ohne Netzwerk** — `POST /security/sandbox` führt eine Binärdatei in einem netzlosen Namespace (`unshare -n` Linux) bzw. Seatbelt-Profil (`sandbox-exec` macOS) aus: null Egress, Ausgabe bleibt lokal.
+- **IOC `format=proof`** — gesalzene SHA-256-Blätter + Merkle-Wurzel: exakte Mitgliedschaft ohne Aufzählung unverdächtiger Indikatoren; nichts wird automatisch übertragen.
+- **Eingebettetes Modell** — `slm_mode=embedded` lädt Ihr `.gguf` im Prozess via `llama-cpp-python` — null Netzwerk; Snitch lädt nie Gewichte herunter.
diff --git a/PRIVACY.es.md b/PRIVACY.es.md
index 2571ef0..a333492 100644
--- a/PRIVACY.es.md
+++ b/PRIVACY.es.md
@@ -77,3 +77,11 @@ visitadas a un tercero en claro.
Directorio de datos: `data/` en dev/Docker, `%LOCALAPPDATA%\Snitch` en
Windows, `~/Library/Application Support/Snitch` en macOS,
`~/.local/share/snitch` en Linux cuando está instalado.
+
+## Novedades v1.4 (privacidad)
+
+- **Importar blocklist por URL (opt-in)** — un *archivo local* es una lectura puramente local; una *URL* realiza un único fetch HTTPS acotado (≤4 MiB, ≤10 s), confirmado en la UI y marcado `remote_fetch`.
+- **Emparejamiento remoto (opt-in, desactivado)** — la API solo escucha en 127.0.0.1; activar el pairing persiste `lan_bind` para el próximo arranque — el token sigue obligatorio en cada petición.
+- **Sandbox sin red** — `POST /security/sandbox` ejecuta un binario en un namespace sin red (`unshare -n` Linux) o seatbelt (`sandbox-exec` macOS): egress cero, la salida queda en la máquina.
+- **Pruebas IOC `format=proof`** — hojas SHA-256 saladas + raíz Merkle: pertenencia exacta sin enumerar indicadores no sospechados; nada se transmite automáticamente.
+- **Modelo embebido** — `slm_mode=embedded` carga tu `.gguf` en proceso vía `llama-cpp-python` — cero red; Snitch nunca descarga pesos.
diff --git a/PRIVACY.ja.md b/PRIVACY.ja.md
index 2d9ddbf..a810208 100644
--- a/PRIVACY.ja.md
+++ b/PRIVACY.ja.md
@@ -76,3 +76,11 @@ GeoLite2 の `.mmdb` が `<data_dir>/geo/` にあれば、ルックアップは
データディレクトリ: dev/Docker は `data/`、Windows は
`%LOCALAPPDATA%\Snitch`、macOS は `~/Library/Application Support/Snitch`、
Linux はインストール時 `~/.local/share/snitch`。
+
+## v1.4 の新機能(プライバシー)
+
+- **URL からのブロックリスト(オプトイン)** — *ローカルファイル*は純粋にローカル読み取り;*URL* は 1 回の制限付き HTTPS 取得(≤4 MiB、≤10 秒)で、UI で確認され `remote_fetch` と明記されます。
+- **リモートペアリング(オプトイン、デフォルト無効)** — API は 127.0.0.1 のみリッスン;有効化すると `lan_bind` が次回起動時に適用 — トークンは全リクエストで必須のままです。
+- **ネットワーク遮断サンドボックス** — `POST /security/sandbox` がバイナリをネットワークなしの名前空間(Linux `unshare -n`)または seatbelt(macOS `sandbox-exec`)で実行:送信ゼロ、出力はマシン内に留まります。
+- **IOC `format=proof`** — ソルト付き SHA-256 リーフ+Merkle ルート:疑っていない指標を列挙させずに厳密な所属証明;自動送信は一切なし。
+- **埋め込みモデル** — `slm_mode=embedded` がユーザーの `.gguf` を `llama-cpp-python` でプロセス内に読み込み — ネットワーク完全ゼロ;Snitch が重みをダウンロードすることはありません。
diff --git a/PRIVACY.md b/PRIVACY.md
index 5feb72c..704abd0 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -45,15 +45,35 @@ Nothing is sent while the switch is off.
set, alert *metadata* (type, process, destination) may be sent to an
Ollama-compatible model endpoint — **restricted to loopback addresses
only**: the backend rejects any endpoint that does not resolve to
-127.0.0.1 / ::1, so this can never reach the network. Deterministic
-templates remain the default.
+127.0.0.1 / ::1, so this can never reach the network. With
+`slm_mode=embedded`, a `.gguf` you supply is loaded in-process via
+`llama-cpp-python` — zero network at all; Snitch never downloads
+weights. Deterministic templates remain the default.
**IOC packs are never transmitted by Snitch.** `GET /security/iocpack`
builds a Bloom filter + randomized-response encoding of your local
indicators and gives you the file — you decide whether and where to share
it. The encoding is intentionally lossy (ε≈4.6) so raw IPs/domains can't
-be recovered from a pack. Importing a pack only returns probabilistic
-hints; it never auto-blocks.
+be recovered from a pack. A second `format=proof` pack uses salted
+SHA-256 leaves + a Merkle commitment — membership is exact, but the salt
+still prevents enumerating indicators you don't already suspect.
+Importing either pack never auto-blocks.
+
+**Blocklist URL import (opt-in).** Importing a blocklist from a *local
+file* is a pure local read. Importing from a *URL* performs one bounded
+HTTPS fetch (≤4 MiB, ≤10 s) — one of the few outbound requests Snitch
+can ever emit, explicitly confirmed in the UI and flagged `remote_fetch`
+in the API response.
+
+**Remote pairing (opt-in, off by default).** Snitch's API listens on
+127.0.0.1 only. Enabling remote pairing persists `lan_bind` so the *next*
+backend start listens on your LAN — with the API token still mandatory
+on every request. It widens the listen address, never the trust model.
+
+**The sandbox cannot leak.** `POST /security/sandbox` runs a binary you
+choose inside a network-denying namespace (Linux `unshare -n`) or
+seatbelt profile (macOS `sandbox-exec`): the detonated program gets
+*zero* egress, whatever it tries. Output stays on the machine.
**Inspection probes stay read-only and local.** The eBPF connect probe,
Frida deep-inspection, `perf_event_open` counters, module/Merkle integrity
@@ -130,7 +150,10 @@ l'interrupteur est éteint.
destination) peuvent être envoyées à un modèle compatible Ollama —
**restreint aux adresses loopback uniquement** : le backend rejette tout
endpoint qui ne résout pas vers 127.0.0.1 / ::1, donc cela ne peut jamais
-atteindre le réseau. Les gabarits déterministes restent le défaut.
+atteindre le réseau. Avec `slm_mode=embedded`, un `.gguf` que vous
+fournissez est chargé en processus via `llama-cpp-python` — zéro réseau ;
+Snitch ne télécharge jamais de poids. Les gabarits déterministes restent
+le défaut.
**Les paquets IOC ne sont jamais transmis par Snitch.**
`GET /security/iocpack` construit un encodage filtre de Bloom +
@@ -138,7 +161,28 @@ randomized response de vos indicateurs locaux et vous remet le fichier —
vous décidez si et où le partager. L'encodage est volontairement avec
pertes (ε≈4,6) : les IP/domaines en clair ne peuvent pas être retrouvés
depuis un paquet. L'import ne renvoie que des indices probabilistes ;
-jamais de blocage automatique.
+jamais de blocage automatique. Un second format `format=proof` utilise
+des feuilles SHA-256 salées + un engagement Merkle — l'appartenance est
+exacte, mais le sel empêche toujours d'énumérer les indicateurs que vous
+ne soupçonnez pas déjà.
+
+**Import de blocklist par URL (opt-in).** Importer depuis un *fichier
+local* est une lecture purement locale. Importer depuis une *URL*
+effectue un seul fetch HTTPS borné (≤4 Mio, ≤10 s) — l'une des rares
+requêtes sortantes que Snitch puisse émettre, confirmée explicitement
+dans l'UI et signalée `remote_fetch` dans la réponse API.
+
+**Pairing distant (opt-in, désactivé par défaut).** L'API de Snitch
+n'écoute que sur 127.0.0.1. Activer le pairing distant persiste
+`lan_bind` pour que le *prochain* démarrage écoute sur votre LAN — le
+jeton API restant obligatoire sur chaque requête. Cela élargit l'adresse
+d'écoute, jamais le modèle de confiance.
+
+**La sandbox ne peut pas fuiter.** `POST /security/sandbox` exécute un
+binaire de votre choix dans un namespace sans réseau (`unshare -n`
+Linux) ou un profil seatbelt (`sandbox-exec` macOS) : le programme
+détoné obtient *zéro* égress, quoi qu'il tente. La sortie reste sur la
+machine.
**Les sondes d'inspection restent en lecture seule et locales.** La sonde
eBPF, l'inspection Frida, les compteurs `perf_event_open`, les scans
diff --git a/PRIVACY.pt-BR.md b/PRIVACY.pt-BR.md
index e2e76d6..cf1ddd5 100644
--- a/PRIVACY.pt-BR.md
+++ b/PRIVACY.pt-BR.md
@@ -78,3 +78,11 @@ IPs visitados a terceiros em claro.
Diretório de dados: `data/` em dev/Docker, `%LOCALAPPDATA%\Snitch` no
Windows, `~/Library/Application Support/Snitch` no macOS,
`~/.local/share/snitch` no Linux quando instalado.
+
+## Novidades v1.4 (privacidade)
+
+- **Blocklist por URL (opt-in)** — um *arquivo local* é uma leitura puramente local; uma *URL* faz um único fetch HTTPS limitado (≤4 MiB, ≤10 s), confirmado na UI e marcado `remote_fetch`.
+- **Pareamento remoto (opt-in, desativado)** — a API só escuta em 127.0.0.1; ativar persiste `lan_bind` para a próxima inicialização — o token continua obrigatório em cada requisição.
+- **Sandbox sem rede** — `POST /security/sandbox` executa um binário num namespace sem rede (`unshare -n` Linux) ou seatbelt (`sandbox-exec` macOS): egress zero, a saída fica na máquina.
+- **IOC `format=proof`** — folhas SHA-256 com sal + raiz Merkle: pertinência exata sem enumerar indicadores não suspeitos; nada é transmitido automaticamente.
+- **Modelo embutido** — `slm_mode=embedded` carrega seu `.gguf` em processo via `llama-cpp-python` — zero rede; Snitch nunca baixa pesos.
diff --git a/PRIVACY.ru.md b/PRIVACY.ru.md
index a3ad750..143b894 100644
--- a/PRIVACY.ru.md
+++ b/PRIVACY.ru.md
@@ -77,3 +77,11 @@ ip-api.com был удалён именно потому, что отправл
Каталог данных: `data/` в dev/Docker, `%LOCALAPPDATA%\Snitch` в Windows,
`~/Library/Application Support/Snitch` в macOS, `~/.local/share/snitch` в
Linux при установленном запуске.
+
+## Новое в v1.4 (приватность)
+
+- **Блоклист по URL (opt-in)** — *локальный файл* читается чисто локально; *URL* — один ограниченный HTTPS-запрос (≤4 МиБ, ≤10 с), подтверждаемый в UI и помеченный `remote_fetch`.
+- **Удалённое сопряжение (opt-in, выкл.)** — API слушает только 127.0.0.1; включение сохраняет `lan_bind` до следующего запуска — токен обязателен для каждого запроса.
+- **Песочница без сети** — `POST /security/sandbox` запускает бинарник в namespace без сети (`unshare -n` Linux) или seatbelt (`sandbox-exec` macOS): нулевой egress, вывод остаётся на машине.
+- **IOC `format=proof`** — засоленные листья SHA-256 + корень Merkle: точное членство без перечисления неподозреваемых индикаторов; ничего не передаётся автоматически.
+- **Встроенная модель** — `slm_mode=embedded` загружает ваш `.gguf` в процесс через `llama-cpp-python` — ноль сети; Snitch никогда не скачивает веса.
diff --git a/PRIVACY.zh-CN.md b/PRIVACY.zh-CN.md
index 77681ca..0aa7e00 100644
--- a/PRIVACY.zh-CN.md
+++ b/PRIVACY.zh-CN.md
@@ -65,3 +65,11 @@ IP 只是不显示位置。不存在任何 HTTP 地理定位服务——ip-api.c
数据目录:开发/Docker 为 `data/`;Windows 为 `%LOCALAPPDATA%\Snitch`;
macOS 为 `~/Library/Application Support/Snitch`;Linux 安装后运行时为
`~/.local/share/snitch`。
+
+## v1.4 新增(隐私)
+
+- **URL 导入屏蔽列表(可选)** — *本地文件*是纯本地读取;*URL* 仅执行一次受限 HTTPS 抓取(≤4 MiB,≤10 秒),在 UI 中确认并在响应中标记 `remote_fetch`。
+- **远程配对(可选,默认关闭)** — API 仅监听 127.0.0.1;启用后持久化 `lan_bind`,下次启动生效 — 每个请求仍需令牌认证。
+- **无网络沙箱** — `POST /security/sandbox` 在无网络的命名空间(Linux `unshare -n`)或 seatbelt(macOS `sandbox-exec`)中运行二进制:出站为零,输出留在本机。
+- **IOC `format=proof`** — 加盐 SHA-256 叶子 + Merkle 根:精确成员证明且无法枚举未怀疑的指标;绝不自动传输。
+- **内置模型** — `slm_mode=embedded` 通过 `llama-cpp-python` 在进程内加载您的 `.gguf` — 完全零网络;Snitch 从不下载权重。
diff --git a/ROADMAP.md b/ROADMAP.md
index f331c23..3eb8748 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -43,27 +43,27 @@ Also live / également en place : Docker image on GHCR, Homebrew tap (`brew inst
## 🔬 Research — shipped vs remaining / livré vs restant
-Ideas that would take Snitch toward a desktop EDR/XDR. v1.3 shipped the
-user-mode-accessible parts of most of them — what remains here genuinely
-needs a signed kernel component, an Apple entitlement or a research-grade
-build / Idées qui mèneraient Snitch vers un EDR/XDR de bureau. La v1.3 a
-livré les parties accessibles en user-mode de la plupart d'entre elles —
-ce qui reste ici exige réellement un composant noyau signé, un entitlement
-Apple ou un développement de recherche :
+Ideas that would take Snitch toward a desktop EDR/XDR. v1.3/v1.4 shipped
+the user-mode-accessible parts of nearly all of them — what remains here
+genuinely needs a signed kernel component, an Apple entitlement or a
+research-grade build / Idées qui mèneraient Snitch vers un EDR/XDR de
+bureau. Les v1.3/v1.4 ont livré les parties accessibles en user-mode de
+quasiment toutes — ce qui reste ici exige réellement un composant noyau
+signé, un entitlement Apple ou un développement de recherche :
- **eBPF probes (Linux)** — *shipped, optional*: a BCC `tcpconnect`-style kprobe attributes `connect()` from short-lived processes that `psutil.net_connections` misses (setting `ebpf_probe`, needs python3-bcc + root; ambiguous destinations are never guessed). Full kernel-space packet capture stays here / *livré, optionnel* : kprobe `tcpconnect` BCC pour attribuer les `connect()` des processus éphémères (réglage `ebpf_probe`, exige python3-bcc + root). La capture noyau complète reste ici
-- **WFP (Windows)** — *partially shipped*: `detection/wfp.py` drives `fwpuclnt.dll` directly via ctypes — per-app/IP/port ALE filters, delete-by-key, orphan purge. What stays here is a **kernel callout driver** (signed driver, payload inspection) / *partiellement livré* : `wfp.py` pilote `fwpuclnt.dll` en ctypes — filtres ALE par appli/IP/port. Reste ici : un **callout noyau** (driver signé, inspection de payload)
-- **NetworkExtension (macOS)** — `NEFilterProvider` for per-bundle filtering; needs Apple Developer ID + entitlements. Verified: `socketfilterfw` only polices *incoming* app connections — no user-mode substitute exists for outbound per-app / `NEFilterProvider` pour filtrer par bundle ; exige Developer ID + entitlements. Vérifié : `socketfilterfw` ne contrôle que l'**entrant** — aucun équivalent user-mode pour le sortant par-appli
+- **WFP (Windows)** — *partially shipped*: `detection/wfp.py` drives `fwpuclnt.dll` directly via ctypes — per-app/IP/port ALE filters, delete-by-key, orphan purge. A **kernel callout** skeleton now lives in `contrib/wfp-callout/` (register/classify/unregister + signing README); a production signed driver with payload inspection stays here / *partiellement livré* : `wfp.py` pilote `fwpuclnt.dll` en ctypes — filtres ALE par appli/IP/port. Un squelette de **callout noyau** vit dans `contrib/wfp-callout/` ; le pilote signé de production reste ici
+- **NetworkExtension (macOS)** — *skeleton shipped*: `contrib/macos-filter/` holds a `NEFilterDataProvider` Swift skeleton + entitlements README — the only Apple-supported per-app outbound path (needs a paid Developer account). Verified: `socketfilterfw` only polices *incoming* app connections — no user-mode substitute exists / *squelette livré* : `contrib/macos-filter/` contient un squelette `NEFilterDataProvider` Swift — la seule voie sortante par-app d'Apple (compte Developer payant exigé). Vérifié : `socketfilterfw` ne contrôle que l'**entrant**
- **Memory/flow correlation** — *partially shipped*: RWX scan + name/exe mismatch + exe hash + **Frida deep-inspect** (`/security/deep_inspect`) which reports which loaded module issued each `connect()` — injected code in staging paths → `INJECT_SUSPECT` / *partiellement livré* : scan RWX + mismatch nom/exe + hash + **inspection Frida** qui rapporte quel module a émis chaque `connect()` — code injecté en chemin de staging → `INJECT_SUSPECT`
-- **Dynamic Taint Analysis** — Frida's module-origin attribution (above) is the honest user-mode slice; byte-for-byte exfiltration proof stays research / l'attribution de module via Frida (ci-dessus) est la part user-mode honnête ; la preuve d'exfiltration octet par octet reste en recherche
-- **Local SecOps SLM** — *shipped, opt-in*: `detection/llm_local.py` enriches `/security/explain` through an Ollama-compatible endpoint **restricted to loopback** (`slm_enabled`, remote endpoints rejected); deterministic bilingual templates remain the default. Bundling a model binary stays here / *livré, opt-in* : enrichissement via endpoint Ollama **loopback uniquement** ; les gabarits déterministes restent le défaut. Embarquer un modèle binaire reste ici
-- **ZKP fleet intel** — *honest substitute shipped*: `/security/iocpack` exports a Bloom filter + randomized-response pack (ε≈4.6, plausible deniability) instead of raw IOCs; `/security/iocpack/import` checks observed destinations probabilistically. A real ZK protocol + fleet transport stays research / *substitut honnête livré* : paquets Bloom + randomized response au lieu d'IOC en clair. Un vrai protocole ZK + transport de flotte reste en recherche
+- **Dynamic Taint Analysis** — *byte-observation slice shipped*: Frida hooks now also cover `send`/`WSASend`/`sendto`/`sendmsg`, returning bounded head bytes + SHA-256 per outbound flow alongside module attribution. Full byte-for-byte exfiltration proof (real taint tracking) stays research / *tranche d'observation livrée* : les hooks Frida couvrent aussi `send`/`WSASend`/`sendto`/`sendmsg` — tête bornée + SHA-256 par flux sortant + attribution de module. La preuve d'exfiltration octet par octet complète reste en recherche
+- **Local SecOps SLM** — *shipped, opt-in, two backends*: Ollama-compatible endpoint **restricted to loopback**, or a user-provided `.gguf` loaded in-process via `llama-cpp-python` (`slm_mode=embedded` — zero network at all). Deterministic bilingual templates remain the default; Snitch never downloads weights / *livré, opt-in, deux backends* : endpoint Ollama **loopback uniquement**, ou `.gguf` fourni par l'utilisateur chargé en processus via `llama-cpp-python` (zéro réseau). Les gabarits restent le défaut ; Snitch ne télécharge jamais de poids
+- **ZKP fleet intel** — *honest substitutes shipped*: `/security/iocpack` exports either a Bloom + randomized-response pack (ε≈4.6, deniable) or a `format=proof` salted-Merkle commitment (exact membership, tamper-evident) — never raw IOCs. A real interactive ZK protocol + fleet transport stays research / *substituts honnêtes livrés* : paquets Bloom bruité OU engagement Merkle salé (`format=proof`, appartenance exacte, inviolable) — jamais d'IOC en clair. Un vrai protocole ZK + transport de flotte reste en recherche
- **PMU/hardware counters** — *shipped, Linux*: `detection/perfprobe.py` wraps `perf_event_open` in ctypes for cycles/instructions/cache-misses per pid (`/security/perf`, gated by `perf_event_paranoid`) — corroborates `MINING_SUSPECT` / *livré, Linux* : compteurs `perf_event_open` en ctypes (`/security/perf`) — corrobore `MINING_SUSPECT`
- **Merkle integrity of loaded modules** — *shipped*: a real Merkle root over file-backed executable mappings per process → `MODULE_CHANGED`; staging paths (`/tmp`, memfd, AppData Temp) → `MODULE_SUSPECT`. Kernel-enforced module allowlisting stays here / *livré* : racine Merkle sur les mappings exécutables → `MODULE_CHANGED` ; chemins de staging → `MODULE_SUSPECT`. L'allowlist noyau de modules reste ici
-- **Sinkholing / micro-containment** — *mostly shipped*: redirects + a loopback **responder** on :80/:443 that turns each sinkholed attempt into a `SINKHOLE_HIT` alert with Host/SNI/process attribution. Micro-VM containment stays here / *quasi livré* : redirections + **répondeur** loopback :80/:443 → alertes `SINKHOLE_HIT` avec Host/SNI/processus. Le confinement micro-VM reste ici
+- **Sinkholing / micro-containment** — *shipped*: redirects + a loopback **responder** on :80/:443 (`SINKHOLE_HIT` alerts with Host/SNI/process) **and** a zero-egress detonation sandbox (`POST /security/sandbox` — Linux `unshare -n`, macOS `sandbox-exec`, plus `contrib/snitch-contain`). Micro-VM containment stays here / *livré* : redirections + **répondeur** loopback :80/:443 + sandbox de détonation zéro-égress (`unshare -n` Linux, `sandbox-exec` macOS). Le confinement micro-VM reste ici
- **Cryptomining detection** — *shipped*: stratum signatures in bounded payload heads + known pool ports, corroborated by sustained process CPU → `MINING_STRATUM`/`MINING_SUSPECT` / *livré* : signatures stratum + ports de pools, corroborés par CPU soutenue → `MINING_STRATUM`/`MINING_SUSPECT`
- **Egress throttling** — *shipped (Linux)*: `throttle` rule action polices a destination via `tc` clsact/flower at the rule's kbit rate / *livré (Linux)* : action `throttle` bride une destination via `tc` clsact/flower
-- **PCAP export** stays in scope above / l'export PCAP reste dans le périmètre ci-dessus
+- **PCAP export** — *shipped*: `GET /forensics/pcap` serves the bounded raw-frame ring (~4 MiB) as a Wireshark-ready `.pcap` with real timestamps + optional ip/process filters / *livré* : `GET /forensics/pcap` sert l'anneau de trames brutes (~4 Mio) en `.pcap` Wireshark avec timestamps réels + filtres ip/processus optionnels
## 🚫 Out of scope / hors périmètre
diff --git a/backend/api/main.py b/backend/api/main.py
index a10f5c0..3f7d42d 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -89,10 +89,12 @@ from resolver.dns_geo import (enrich_ip, is_private, learn_dns_answers,
from scanner.arp_scanner import ARPScanner, Device, default_gateway as _default_gateway
from scanner.arp_scanner import READ_STATS as _arp_stats
from detection.anomaly import AnomalyDetector, Alert
+from detection.customrules import CustomRules
from capture.ebpf_probe import EbpfProbe
from detection.deepinspect import DeepInspector, suspicious_module_paths
from detection.firewall import FirewallManager
from detection.integrity import IntegrityWatcher
+from detection import blocklist
from detection import explain as alert_explain
from detection import iocshare
from detection.llm_local import LocalSlm
@@ -140,6 +142,7 @@ deep = DeepInspector() # EN: Frida module-origin attribution / FR: at
sink = SinkholeResponder() # EN: loopback :80/:443 sinkhole listener / FR: écouteur sinkhole
miner = MinerDetector() # EN: stratum/pool/CPU mining signals / FR: signaux de minage
slm = LocalSlm() # EN: optional localhost LLM enrichment / FR: enrichissement LLM local
+custom_rules = CustomRules() # EN: user-defined alert rules / FR: règles d'alerte utilisateur
_loop: asyncio.AbstractEventLoop | None = None
_sniffer: PacketSniffer | None = None
_scanner: ARPScanner | None = None
@@ -255,11 +258,71 @@ class IocImportBody(BaseModel):
pack: dict = Field(default_factory=dict)
+class PairingBody(BaseModel):
+ """EN: /remote/pairing payload — opt-in LAN exposure. `enabled`
+ persists a bind address applied at the NEXT backend start (uvicorn
+ cannot rebind a running socket). `bind` accepts "0.0.0.0" or one of
+ the machine's own LAN addresses. Token auth remains mandatory —
+ pairing never weakens authentication, it only changes the listen
+ address.
+ FR: Charge utile /remote/pairing — exposition LAN opt-in. `enabled`
+ persiste une adresse d'écoute appliquée au PROCHAIN démarrage
+ (uvicorn ne peut pas re-binder un socket actif). `bind` accepte
+ « 0.0.0.0 » ou une adresse LAN de la machine. Le jeton reste
+ obligatoire — le pairing ne change que l'adresse d'écoute."""
+ enabled: bool
+ bind: str = ""
+
+
+class SandboxBody(BaseModel):
+ """EN: /security/sandbox payload — an executable to detonate inside
+ the network-denial sandbox. Path must be absolute; `args` bounded.
+ FR: Charge utile /security/sandbox — un exécutable à détoner dans la
+ sandbox sans réseau. Chemin absolu exigé ; `args` bornés."""
+ path: str
+ args: list[str] = Field(default_factory=list)
+ seconds: int = 10
+
+
class FirewallToggleBody(BaseModel):
"""EN: Enable/disable a single rule. / FR: Activer/désactiver une règle."""
enabled: bool = True
+class BlocklistBody(BaseModel):
+ """EN: /firewall/blocklist payload — exactly ONE source: `path`
+ (local hosts/domain file) or `url` (OPT-IN outbound fetch — one of
+ the few places Snitch can emit network traffic). `action` is the
+ firewall action applied to every imported domain.
+ FR: Charge utile /firewall/blocklist — exactement UNE source : `path`
+ (fichier local) ou `url` (fetch sortant OPT-IN — un des rares
+ endroits où Snitch peut émettre du trafic). `action` = l'action
+ pare-feu appliquée à chaque domaine importé."""
+ path: str = ""
+ url: str = ""
+ action: str = "block"
+ max_entries: int = 500
+
+
+class CustomRuleBody(BaseModel):
+ """EN: /alerts/rules payload — one field, one operator, one value.
+ FR: Charge utile /alerts/rules — un champ, un opérateur, une valeur."""
+ name: str = ""
+ field: str
+ op: str
+ value: str
+ severity: str = "warning"
+
+
+class ProfileBody(BaseModel):
+ """EN: /firewall/profile payload — a named rule bundle:
+ permissive (clean slate), balanced (egress baseline), strict
+ (baseline + lockdown). / FR: Charge utile /firewall/profile — un lot
+ nommé de règles : permissive (table rase), balanced (base sortante),
+ strict (base + lockdown)."""
+ name: str
+
+
class LockdownBody(BaseModel):
"""EN: /firewall/lockdown payload — panic switch on/off.
FR: Charge utile de /firewall/lockdown — bouton panique on/off."""
@@ -647,6 +710,7 @@ def _request_enrichment(ip: str) -> None:
"lat": geo.get("lat"),
"lon": geo.get("lon"),
"org": geo.get("org"),
+ "asn": geo.get("asn"),
})
await broadcast({"type": "node_update", "node": node})
except Exception as exc:
@@ -836,6 +900,7 @@ def _process_batch(packets: list[Packet]) -> None:
"lat": geo.get("lat"),
"lon": geo.get("lon"),
"org": geo.get("org"),
+ "asn": geo.get("asn"),
"category": category.category,
"color": category.color,
"bytes": 0, "packets": 0, "alerted": False,
@@ -932,6 +997,27 @@ def _process_batch(packets: list[Packet]) -> None:
# pool-port marking for later CPU corroboration (drain loop).
# FR: Signaux de minage — stratum en clair dans la tête du payload
# et marquage port-pool pour corroboration CPU (boucle drain).
+ # EN: User-defined alert rules — first match per packet raises
+ # CUSTOM_RULE carrying the rule name (alert-only, never blocks).
+ # FR: Règles d'alerte utilisateur — le premier match lève
+ # CUSTOM_RULE portant le nom de la règle (alerte, jamais de blocage).
+ for m in custom_rules.check(pkt)[:1]:
+ r = m["rule"]
+ a = Alert(
+ type="CUSTOM_RULE", severity=r["severity"],
+ message=f"Custom rule matched: {r['name']} "
+ f"({r['field']} {r['op']} {r['value']}) — hit #{m['count']}"
+ + (" by " + pkt.process_name if pkt.process_name else ""),
+ node_id=remote_ip,
+ details={"rule": r, "process": pkt.process_name,
+ "direction": pkt.direction},
+ )
+ _flag_alert(a, nodes)
+ ad = a.to_dict()
+ db.log_alert(ad)
+ out_alerts.append(ad)
+ asyncio.get_running_loop().create_task(_notify(ad))
+
for f in miner.analyze_packet(pkt):
a = Alert(
type=f["type"], severity=f["severity"],
@@ -1410,6 +1496,7 @@ def _load_settings() -> None:
# baselines de processus apprises et webhook externe.
fw.load(db.get_setting("firewall_rules", []) or [],
bool(db.get_setting("firewall_lockdown", False)))
+ custom_rules.load(db.get_setting("custom_rules", []) or [])
ti.configure(db.get_setting("ti_provider", "none") or "none",
db.get_setting("ti_api_key", "") or "")
detector.load_baselines(db.get_setting("app_baselines", {}) or {})
@@ -1426,7 +1513,9 @@ def _load_settings() -> None:
# FR: Enrichissement SLM local — loopback par construction, opt-in.
slm.configure(bool(db.get_setting("slm_enabled", False)),
db.get_setting("slm_endpoint", "") or "",
- db.get_setting("slm_model", "") or "")
+ db.get_setting("slm_model", "") or "",
+ db.get_setting("slm_mode", "") or "",
+ db.get_setting("slm_model_path", "") or "")
if _port_filter:
logger.info("restored port filter: %s", _port_filter)
@@ -1615,12 +1704,96 @@ async def post_settings(body: SettingsBody) -> dict:
_sniffer.set_attribution_probe(ebpf)
else:
ebpf.stop()
- if key in ("slm_enabled", "slm_endpoint", "slm_model"):
+ if key in ("slm_enabled", "slm_endpoint", "slm_model",
+ "slm_mode", "slm_model_path"):
slm.configure(bool(db.get_setting("slm_enabled", False)),
db.get_setting("slm_endpoint", "") or "",
- db.get_setting("slm_model", "") or "")
+ db.get_setting("slm_model", "") or "",
+ db.get_setting("slm_mode", "") or "",
+ db.get_setting("slm_model_path", "") or "")
return {"ok": True}
+
+def _lan_addresses() -> list[str]:
+ """EN: This machine's non-loopback IPv4 addresses — the addresses a
+ remote device could reach Snitch on. / FR: Adresses IPv4 non-loopback
+ de la machine — celles par lesquelles un appareil distant peut
+ joindre Snitch."""
+ out = []
+ try:
+ import psutil
+ for addrs in psutil.net_if_addrs().values():
+ for a in addrs:
+ if a.family.name == "AF_INET":
+ ip = ipaddress.ip_address(a.address)
+ if not ip.is_loopback and not ip.is_link_local:
+ out.append(a.address)
+ except Exception: # noqa: BLE001
+ pass
+ return sorted(set(out))
+
+
+def _current_bind() -> tuple[str, str]:
+ """EN: Effective bind address + its source (env > argv > setting >
+ default) — mirrors run_backend.py's precedence.
+ FR: Adresse d'écoute effective + sa source (env > argv > réglage >
+ défaut) — reflète la priorité de run_backend.py."""
+ if os.environ.get("SNITCH_BIND"):
+ return os.environ["SNITCH_BIND"], "env"
+ args = sys.argv[1:]
+ for i, a in enumerate(args):
+ if a == "--bind" and i + 1 < len(args):
+ return args[i + 1], "argv"
+ persisted = db.get_setting("lan_bind", "") or ""
+ if persisted:
+ return persisted, "setting"
+ return "127.0.0.1", "default"
+
+
[email protected]("/remote/pairing", dependencies=_AUTH)
+async def remote_pairing_status() -> dict:
+ """EN: Remote-pairing state — where the API listens, which LAN
+ addresses clients could use, and whether a persisted opt-in is
+ pending for next start. Token auth is ALWAYS required; pairing only
+ widens the listen address.
+ FR: État du pairing distant — où l'API écoute, quelles adresses LAN
+ les clients peuvent utiliser, et si un opt-in persisté attend le
+ prochain démarrage. Le jeton reste TOUJOURS exigé ; le pairing
+ n'élargit que l'adresse d'écoute."""
+ bind, source = _current_bind()
+ persisted = db.get_setting("lan_bind", "") or ""
+ port = int(os.environ.get("SNITCH_PORT") or "8000")
+ return {
+ "active": not bind.startswith("127.") and bind not in ("::1", "localhost"),
+ "bind": bind, "bind_source": source, "port": port,
+ "lan_ips": _lan_addresses(),
+ "persisted_bind": persisted,
+ "token_required": True,
+ "restart_required": bool(persisted) and persisted != bind,
+ }
+
+
[email protected]("/remote/pairing", dependencies=_AUTH)
+async def remote_pairing_set(body: PairingBody) -> dict:
+ """EN: Opt-in LAN exposure — persist (or clear) a bind address for
+ the next backend start. Only "0.0.0.0" or an address the machine
+ actually owns is accepted. Returns `restart_required: true`
+ because uvicorn cannot rebind a live socket — the UI must say
+ this honestly.
+ FR: Exposition LAN opt-in — persister (ou effacer) une adresse
+ d'écoute pour le prochain démarrage. Seuls « 0.0.0.0 » ou une
+ adresse réelle de la machine sont acceptés. `restart_required:
+ true` car uvicorn ne peut pas re-binder un socket actif."""
+ if not body.enabled:
+ db.set_setting("lan_bind", "")
+ return {"ok": True, "lan_bind": "", "restart_required": True}
+ bind = (body.bind or "0.0.0.0").strip()
+ if bind != "0.0.0.0" and bind not in _lan_addresses():
+ raise HTTPException(400, "bind must be 0.0.0.0 or a local LAN address")
+ db.set_setting("lan_bind", bind)
+ return {"ok": True, "lan_bind": bind, "restart_required": True}
+
+
@app.get("/capture/status", dependencies=_AUTH)
async def get_capture_status() -> dict:
"""EN: Capture state + all active filters. / FR: État de capture + filtres actifs."""
@@ -2190,6 +2363,138 @@ async def firewall_lockdown(body: LockdownBody) -> dict:
return res
[email protected]("/firewall/profiles", dependencies=_AUTH)
+async def firewall_profiles() -> dict:
+ """EN: Available named profiles (labels resolved by the UI).
+ FR: Profils nommés disponibles (libellés résolus par l'UI)."""
+ return {"profiles": sorted(fw.PROFILES)}
+
+
[email protected]("/firewall/profile", dependencies=_AUTH)
+async def firewall_profile(body: ProfileBody) -> dict:
+ """EN: Apply a named profile — expands into ordinary rules + lockdown
+ state through the normal machinery, persists the result, and
+ broadcasts the new policy to every connected client.
+ FR: Appliquer un profil nommé — déplié en règles ordinaires + état
+ lockdown par la machinerie normale, résultat persisté et politique
+ diffusée à tous les clients connectés."""
+ loop = asyncio.get_running_loop()
+ try:
+ res = await loop.run_in_executor(None, fw.apply_profile, body.name)
+ except ValueError as exc:
+ raise HTTPException(400, str(exc))
+ rules, lockdown = fw.serialized()
+ db.set_setting("firewall_rules", rules)
+ db.set_setting("firewall_lockdown", lockdown)
+ await broadcast({"type": "firewall", "rules": rules, "lockdown": lockdown})
+ return {"ok": True, "rules": rules, "lockdown": lockdown, **res}
+
+
[email protected]("/firewall/blocklist", dependencies=_AUTH)
+async def firewall_blocklist(body: BlocklistBody) -> dict:
+ """EN: Import a blocklist into `domain` rules. `path` reads a local
+ file (purely local); `url` performs an OPT-IN outbound HTTPS
+ fetch — surfaced as `remote_fetch: true` in the response so the
+ UI can show that Snitch emitted traffic. Entries deduplicated
+ against existing rules and capped at `max_entries` (<= 5000).
+ FR: Importer une blocklist en règles `domain`. `path` lit un fichier
+ local ; `url` effectue un fetch HTTPS sortant OPT-IN — signalé
+ par `remote_fetch: true` dans la réponse pour que l'UI montre
+ que Snitch a émis du trafic. Entrées dédupliquées et plafonnées
+ à `max_entries` (<= 5000)."""
+ if bool(body.path) == bool(body.url):
+ raise HTTPException(400, "provide exactly one of path or url")
+ if body.action not in ("block", "sinkhole"):
+ raise HTTPException(400, "action must be block or sinkhole")
+ remote = bool(body.url)
+
+ def _load_text() -> str:
+ if remote:
+ return blocklist.fetch_url(body.url)
+ p = Path(body.path).expanduser()
+ if not p.is_file():
+ raise ValueError("file not found")
+ if p.stat().st_size > 4 * 1024 * 1024:
+ raise ValueError("blocklist too large (>4 MiB)")
+ return p.read_text(errors="replace")
+
+ loop = asyncio.get_running_loop()
+ try:
+ text = await loop.run_in_executor(None, _load_text)
+ except (ValueError, OSError) as exc:
+ raise HTTPException(400, str(exc))
+ domains = blocklist.parse_domains(text)
+ cap = blocklist.clamp_max(body.max_entries)
+ truncated = len(domains) > cap
+ domains = domains[:cap]
+
+ def _apply() -> tuple[int, int]:
+ added = skipped = 0
+ for d in domains:
+ if fw._find_rule("domain", d, body.action):
+ skipped += 1
+ continue
+ fw.add_rule("domain", d, body.action)
+ added += 1
+ return added, skipped
+
+ added, skipped = await loop.run_in_executor(None, _apply)
+ rules, lockdown = fw.serialized()
+ db.set_setting("firewall_rules", rules)
+ await broadcast({"type": "firewall", "rules": rules, "lockdown": lockdown})
+ return {"ok": True, "remote_fetch": remote, "parsed": len(domains),
+ "added": added, "skipped": skipped, "truncated": truncated}
+
+
+# ── Custom alert rules / Règles d'alerte utilisateur ─────────────────────────
+
[email protected]("/alerts/rules", dependencies=_AUTH)
+async def alert_rules() -> dict:
+ """EN: All user-defined alert rules + the matcher vocabulary.
+ FR: Toutes les règles utilisateur + le vocabulaire du moteur."""
+ return {"rules": custom_rules.serialized(),
+ "fields": ["remote_ip", "host", "process_name", "remote_port",
+ "protocol", "direction", "size"],
+ "ops": ["eq", "ne", "contains", "regex", "gt", "lt", "cidr"]}
+
+
[email protected]("/alerts/rules", dependencies=_AUTH)
+async def alert_rules_add(body: CustomRuleBody) -> dict:
+ """EN: Create a user alert rule — validated up front (field/op/severity,
+ regex compiles, cidr parses). Alert-only: matching packets raise
+ CUSTOM_RULE alerts, nothing is blocked.
+ FR: Créer une règle d'alerte — validée d'emblée (champ/op/sévérité,
+ regex compilable, cidr analysable). Alerte seule : les paquets
+ correspondants lèvent CUSTOM_RULE, rien n'est bloqué."""
+ try:
+ rule = custom_rules.add(body.name, body.field, body.op,
+ body.value, body.severity)
+ except ValueError as exc:
+ raise HTTPException(400, str(exc))
+ db.set_setting("custom_rules", custom_rules.serialized())
+ return {"ok": True, "rule": rule}
+
+
[email protected]("/alerts/rules/{rule_id}", dependencies=_AUTH)
+async def alert_rules_delete(rule_id: str) -> dict:
+ """EN: Remove a user alert rule. / FR: Supprimer une règle utilisateur."""
+ if not custom_rules.remove(rule_id):
+ raise HTTPException(404, "rule not found")
+ db.set_setting("custom_rules", custom_rules.serialized())
+ return {"ok": True}
+
+
[email protected]("/alerts/rules/{rule_id}/toggle", dependencies=_AUTH)
+async def alert_rules_toggle(rule_id: str, body: FirewallToggleBody) -> dict:
+ """EN: Enable/disable a rule without deleting it.
+ FR: Activer/désactiver une règle sans la supprimer."""
+ rule = custom_rules.toggle(rule_id, body.enabled)
+ if rule is None:
+ raise HTTPException(404, "rule not found")
+ db.set_setting("custom_rules", custom_rules.serialized())
+ return {"ok": True, "rule": rule}
+
+
@app.post("/processes/kill", dependencies=_AUTH)
async def kill_process(body: PidBody) -> dict:
"""EN: Kill a process by PID — incident-response action. Refuses to kill
@@ -2319,7 +2624,8 @@ async def deep_inspect(body: PidSecondsBody) -> dict:
loop = asyncio.get_running_loop()
res = await loop.run_in_executor(
None, deep.inspect, body.pid, min(body.seconds, 60))
- res["suspicious_paths"] = suspicious_module_paths(res.get("events", []))
+ res["suspicious_paths"] = suspicious_module_paths(
+ res.get("events", []) + res.get("flows", []))
if res["suspicious_paths"]:
a = Alert(type="INJECT_SUSPECT", severity="critical",
message=f"Injected-module suspicion in pid {body.pid} — "
@@ -2333,6 +2639,27 @@ async def deep_inspect(body: PidSecondsBody) -> dict:
return res
[email protected]("/security/sandbox", dependencies=_AUTH)
+async def sandbox_run(body: SandboxBody) -> dict:
+ """EN: Detonate an executable inside the network-denial sandbox —
+ Linux `unshare -U -n` (unprivileged userns) or macOS
+ `sandbox-exec` deny-network. Bounded runtime + output; the binary
+ runs unprivileged with zero egress. Explicit user action only —
+ Snitch never detonates on its own.
+ FR: Détoner un exécutable dans la sandbox sans réseau — `unshare -U -n`
+ Linux ou `sandbox-exec` deny-network macOS. Durée + sortie bornées ;
+ le binaire tourne non privilégié, égress zéro. Action utilisateur
+ explicite uniquement — Snitch ne détone jamais seul."""
+ import os
+ from detection.contain import run_sandboxed
+ if not os.path.isabs(body.path):
+ raise HTTPException(400, "path must be absolute")
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(
+ None, run_sandboxed, body.path,
+ [a[:256] for a in body.args[:8]], body.seconds)
+
+
@app.get("/security/sinkhole", dependencies=_AUTH)
async def sinkhole_status() -> dict:
"""EN: Sinkhole responder state — which loopback listeners are bound
@@ -2368,27 +2695,38 @@ async def slm_status() -> dict:
@app.get("/security/iocpack", dependencies=_AUTH)
-async def iocpack_export() -> dict:
- """EN: Export a privacy-preserving IOC pack (Bloom + randomized
- response) built from this machine's firewall rules + alert
- indicators. The user shares the JSON themselves — nothing is sent.
- FR: Exporter un paquet d'IOC préservant la vie privée (Bloom +
- randomized response) construit depuis les règles pare-feu +
- indicateurs d'alertes de cette machine. L'utilisateur partage le
- JSON lui-même — rien n'est envoyé."""
+async def iocpack_export(format: str = "bloom") -> dict:
+ """EN: Export a privacy-preserving IOC pack built from this machine's
+ firewall rules + alert indicators — `format=bloom` (default)
+ produces a deniable Bloom+randomized-response pack; `format=proof`
+ produces a salted Merkle commitment pack (exact membership,
+ selective disclosure). The user shares the JSON themselves —
+ nothing is sent.
+ FR: Exporter un paquet d'IOC depuis les règles pare-feu + indicateurs
+ d'alertes — `format=bloom` (défaut) produit un paquet déni plausible
+ ; `format=proof` un paquet d'engagement Merkle salé (appartenance
+ exacte, divulgation sélective). L'utilisateur partage le JSON
+ lui-même — rien n'est envoyé."""
loop = asyncio.get_running_loop()
indicators = await loop.run_in_executor(None, _collect_indicators)
+ if format == "proof":
+ return iocshare.build_proof_pack(indicators)
return iocshare.build_pack(indicators)
@app.post("/security/iocpack/import", dependencies=_AUTH)
async def iocpack_import(body: IocImportBody) -> dict:
"""EN: Check this machine's observed destinations against a received
- community pack — returns probabilistic hints, never auto-blocks.
+ community pack — Bloom packs return probabilistic hints, proof
+ packs exact matches; never auto-blocks either way.
FR: Confronter les destinations observées à un paquet communautaire
- reçu — renvoie des indices probabilistes, ne bloque jamais seul."""
+ reçu — indices probabilistes pour Bloom, correspondances exactes
+ pour proof ; jamais de blocage automatique."""
candidates = [ip for ip in nodes if ip != "local"]
loop = asyncio.get_running_loop()
+ if isinstance(body.pack, dict) and body.pack.get("format") == "snitch-ioc-proof/1":
+ return await loop.run_in_executor(
+ None, iocshare.check_proof_pack, body.pack, candidates)
return await loop.run_in_executor(
None, iocshare.check_pack, body.pack, candidates)
@@ -2770,6 +3108,38 @@ def _forensics_stix(bundle: dict, ip: Optional[str] = None) -> dict:
}
[email protected]("/forensics/pcap", dependencies=_AUTH)
+async def forensics_pcap(ip: Optional[str] = None,
+ process: Optional[str] = None,
+ seconds: int = 300):
+ """EN: Export the forensic ring as a real .pcap — wireshark/tcpdump
+ open it directly. Filters: remote `ip`, attributed `process`
+ (substring), `seconds` of look-back (cap 3600, the ring itself
+ holds ~4 MB of recent frames). Empty in demo mode — the demo
+ synthesizes packets, it has no wire frames.
+ FR: Exporter l'anneau forensique en vrai .pcap — lisible par
+ wireshark/tcpdump. Filtres : `ip` distante, `process` attribué
+ (sous-chaîne), `seconds` de recul (plafond 3600, l'anneau garde
+ ~4 Mo de trames récentes). Vide en mode démo — la démo synthétise
+ des paquets, elle n'a pas de trames fil."""
+ from fastapi.responses import Response
+ from capture.pcapwriter import pcap_bytes
+ if _sniffer is None or not hasattr(_sniffer, "pcap_frames"):
+ return Response(status_code=204)
+ loop = asyncio.get_running_loop()
+ linktype, frames = await loop.run_in_executor(
+ None, _sniffer.pcap_frames, ip, process,
+ max(1, min(int(seconds or 300), 3600)))
+ if not frames:
+ return Response(status_code=204)
+ body = await loop.run_in_executor(None, pcap_bytes, linktype, frames)
+ return Response(
+ content=body, media_type="application/vnd.tcpdump.pcap",
+ headers={"Content-Disposition":
+ 'attachment; filename="snitch-forensics.pcap"',
+ "X-Snitch-Frames": str(len(frames))})
+
+
# ── WebSocket ────────────────────────────────────────────────────────────────
@app.websocket("/ws")
diff --git a/backend/capture/pcap.py b/backend/capture/pcap.py
index c4f2908..229039e 100644
--- a/backend/capture/pcap.py
+++ b/backend/capture/pcap.py
@@ -330,18 +330,24 @@ class PcapSession:
raw = self._lib.pcap_geterr(self._handle)
return raw.decode(errors="replace") if raw else "unknown error"
- def next_packet(self) -> Optional[tuple[bytes, int]]:
+ def next_packet(self) -> Optional[tuple[bytes, int, float]]:
"""
- EN: Next packet — (payload, wire_length) or None on timeout. Raises
+ EN: Next packet — (payload, wire_length, wire_ts) or None on
+ timeout. `wire_ts` is libpcap's own timestamp (seconds, float)
+ — more accurate than time.time() for forensic exports. Raises
PcapError on capture failure or EOF.
- FR: Paquet suivant — (charge utile, longueur fil) ou None au timeout.
- Lève PcapError en cas d'échec de capture ou de fin de fichier.
+ FR: Paquet suivant — (charge utile, longueur fil, ts fil) ou None
+ au timeout. `wire_ts` est le timestamp propre de libpcap —
+ plus précis que time.time() pour les exports forensiques.
+ Lève PcapError en cas d'échec ou de fin de fichier.
"""
hdr = ctypes.POINTER(PcapPkthdr)()
data = ctypes.POINTER(ctypes.c_ubyte)()
rc = self._lib.pcap_next_ex(self._handle, ctypes.byref(hdr), ctypes.byref(data))
if rc == 1:
- return ctypes.string_at(data, hdr.contents.caplen), hdr.contents.len
+ h = hdr.contents
+ ts = h.ts.tv_sec + h.ts.tv_usec / 1_000_000.0
+ return (ctypes.string_at(data, h.caplen), h.len, ts)
if rc == 0:
return None # EN: timeout / FR: timeout
if rc == -2:
diff --git a/backend/capture/pcapwriter.py b/backend/capture/pcapwriter.py
new file mode 100644
index 0000000..edda4bb
--- /dev/null
+++ b/backend/capture/pcapwriter.py
@@ -0,0 +1,70 @@
+"""
+Snitch — libpcap (.pcap) file writer / écrivain de fichiers pcap.
+
+EN: Classic libpcap savefile format, written in pure Python — the same
+ byte layout tcpdump/Wireshark expects, produced from the frames the
+ capture thread already holds. No libpcap handle needed for writing:
+ the format is a fixed global header followed by per-packet records.
+
+ Byte layout (little-endian, magic 0xa1b2c3d4):
+ global header : magic u32, ver_major u16, ver_minor u16,
+ thiszone i32, sigfigs u32, snaplen u32, network u32
+ per packet : ts_sec u32, ts_usec u32, incl_len u32, orig_len u32,
+ raw frame bytes (incl_len of them)
+
+FR: Format savefile libpcap classique, écrit en Python pur — le même
+ layout d'octets qu'attendent tcpdump/Wireshark, produit depuis les
+ trames que le thread de capture détient déjà. Pas besoin de handle
+ libpcap pour écrire : l'en-tête global fixe est suivi des enregistrements
+ par paquet.
+"""
+
+from __future__ import annotations
+
+import io
+import struct
+from typing import BinaryIO, Iterable
+
+# EN: Classic magic — little-endian variant (microsecond timestamps).
+# FR: Magic classique — variante little-endian (timestamps microseconde).
+_MAGIC = 0xA1B2C3D4
+_SNAPLEN = 65535 # EN: capture whole frames / FR: trames entières
+
+_GLOBAL_HDR = struct.Struct("<IHHiIII")
+_PACKET_HDR = struct.Struct("<IIII")
+
+
+def write_pcap(dest: BinaryIO, linktype: int,
+ frames: Iterable[tuple[float, bytes, int]]) -> int:
+ """
+ EN: Serialize `frames` to `dest` in libpcap format.
+
+ frames : iterable of (unix_ts, frame_bytes, wire_len) — a frame
+ longer than _SNAPLEN is truncated honestly (incl_len <
+ orig_len, exactly like a live capture would store it).
+ dest : binary file object (open(path,'wb') or io.BytesIO).
+ returns: number of packet records written.
+
+ FR: Sérialiser `frames` dans `dest` au format libpcap. Une trame plus
+ longue que _SNAPLEN est tronquée honnêtement (incl_len < orig_len,
+ comme une capture live). Renvoie le nombre de paquets écrits.
+ """
+ dest.write(_GLOBAL_HDR.pack(_MAGIC, 2, 4, 0, 0, _SNAPLEN, linktype))
+ n = 0
+ for ts, buf, wire_len in frames:
+ sec = int(ts)
+ usec = int((ts - sec) * 1_000_000)
+ incl = min(len(buf), _SNAPLEN)
+ dest.write(_PACKET_HDR.pack(sec, usec, incl, max(wire_len, incl)))
+ dest.write(buf[:incl])
+ n += 1
+ return n
+
+
+def pcap_bytes(linktype: int,
+ frames: Iterable[tuple[float, bytes, int]]) -> bytes:
+ """EN: Convenience — whole savefile in memory (rings stay small).
+ FR: Confort — le savefile entier en mémoire (les anneaux restent petits)."""
+ buf = io.BytesIO()
+ write_pcap(buf, linktype, frames)
+ return buf.getvalue()
diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.py
index 412d58c..4210470 100644
--- a/backend/capture/sniffer.py
+++ b/backend/capture/sniffer.py
@@ -31,6 +31,7 @@ import os
import socket
import threading
import time
+from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Callable, Optional
@@ -218,6 +219,16 @@ class PacketSniffer:
self._attribution_probe = None
self._running = False
self._thread: Optional[threading.Thread] = None
+ # EN: Forensic ring — the last ~4 MB of "for us" frames with wire
+ # timestamp + process attribution, kept for /forensics/pcap
+ # exports. Byte-accounted: evict oldest until under budget.
+ # FR: Anneau forensique — les ~4 derniers Mo de trames « pour nous »
+ # avec timestamp fil + attribution processus, gardés pour les
+ # exports /forensics/pcap. Compté en octets : éviction des plus
+ # anciennes.
+ self._ring: deque[tuple] = deque()
+ self._ring_bytes = 0
+ self._ring_lock = threading.Lock()
# EN: Drop accounting — every discarded frame is counted with its
# reason and surfaced in /diagnostics. Security rule: no silent
# skips — an unparsed frame could be the one that mattered.
@@ -306,7 +317,9 @@ class PacketSniffer:
port_expr = " or ".join(f"port {p}" for p in self.ports)
return f"(ip or ip6) and ({port_expr})"
- def _handle_frame(self, buf: bytes, wire_len: int) -> None:
+ _RING_BUDGET = 4 * 1024 * 1024 # EN: forensic ring cap / FR: plafond de l'anneau
+
+ def _handle_frame(self, buf: bytes, wire_len: int, ts: float) -> None:
"""
EN: Decode + normalize one frame. Drops non-IP traffic and packets
that do not involve this host.
@@ -374,8 +387,48 @@ class PacketSniffer:
dhcp=parsed.dhcp,
app_head=parsed.app_head,
))
+ # EN: Forensic ring entry — raw frame + wire ts + attribution, so
+ # /forensics/pcap can export exactly what was on the wire.
+ # FR: Entrée d'anneau forensique — trame brute + ts fil +
+ # attribution, pour que /forensics/pcap exporte exactement ce
+ # qui était sur le fil.
+ remote = dst if direction == "out" else src
+ with self._ring_lock:
+ self._ring.append((ts, buf, wire_len, remote, pid, process_name))
+ self._ring_bytes += len(buf)
+ while self._ring_bytes > self._RING_BUDGET and self._ring:
+ old = self._ring.popleft()
+ self._ring_bytes -= len(old[1])
self.stats["delivered"] += 1
+ def pcap_frames(self, remote_ip: str | None = None,
+ process: str | None = None,
+ seconds: float | None = None) -> tuple[int, list]:
+ """
+ EN: Drain a filtered copy of the forensic ring for pcap export —
+ returns (linktype, [(ts, buf, wire_len)]). Filters by remote
+ IP, attributed process name (case-insensitive substring) and
+ age in seconds. Read-only: the ring keeps rolling.
+ FR: Extraire une copie filtrée de l'anneau pour l'export pcap —
+ renvoie (linktype, [(ts, buf, wire_len)]). Filtres : IP
+ distante, nom de processus attribué (sous-chaîne insensible à
+ la casse), âge en secondes. Lecture seule : l'anneau continue.
+ """
+ linktype = self._session.linktype if self._session else 1
+ cutoff = (time.time() - seconds) if seconds else 0.0
+ proc = process.lower() if process else None
+ out: list[tuple] = []
+ with self._ring_lock:
+ for ts, buf, wire_len, remote, _pid, pname in self._ring:
+ if ts < cutoff:
+ continue
+ if remote_ip and remote != remote_ip:
+ continue
+ if proc and proc not in (pname or "").lower():
+ continue
+ out.append((ts, buf, wire_len))
+ return linktype, out
+
def start(self) -> None:
"""EN: Launch the capture thread. / FR: Lancer le thread de capture."""
if not PCAP_AVAILABLE:
diff --git a/backend/detection/blocklist.py b/backend/detection/blocklist.py
new file mode 100644
index 0000000..f0a00ef
--- /dev/null
+++ b/backend/detection/blocklist.py
@@ -0,0 +1,112 @@
+"""
+EN: Blocklist import — turn a hosts-file or plain domain list into
+ firewall `domain` rules. Two sources, both explicit:
+
+ * LOCAL FILE — a path on this machine (StevenBlack/hosts exports,
+ Pi-hole lists you downloaded yourself…). Reading a file is a
+ local operation: nothing leaves the host.
+ * REMOTE URL — an OPT-IN outbound HTTPS fetch. This is one of the
+ few places Snitch can ever touch the network, so the code is
+ honest about it: the URL is fetched verbatim (no telemetry, no
+ referer), bounded to 4 MiB and 10 s, and the import reports
+ exactly what it did.
+
+ Entries are deduplicated against existing rules and capped
+ (`max_entries`) because every `domain` rule costs a DNS
+ resolution + OS-firewall entries; giant lists (100k+ entries) belong
+ in a resolver, not a per-rule firewall.
+
+FR: Import de blocklist — transformer un fichier hosts ou une liste de
+ domaines en règles `domain` du pare-feu. Deux sources, toutes deux
+ explicites :
+
+ * FICHIER LOCAL — un chemin sur la machine. Purement local.
+ * URL DISTANTE — fetch HTTPS OPT-IN. Un des rares endroits où
+ Snitch peut toucher le réseau : URL fetchée telle quelle, bornée
+ à 4 Mio / 10 s, et l'import rapporte exactement ce qu'il a fait.
+
+ Entrées dédupliquées et plafonnées (`max_entries`) : chaque règle
+ `domain` coûte une résolution DNS + des entrées pare-feu OS.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import re
+import urllib.request
+
+_MAX_BYTES = 4 * 1024 * 1024 # EN: 4 MiB fetch cap / FR: plafond 4 Mio
+_FETCH_TIMEOUT = 10.0
+_DEFAULT_MAX = 500
+_HARD_MAX = 5000
+
+_DOMAIN_RE = re.compile(
+ r"^(?=.{1,253}$)([a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$")
+
+
+def parse_domains(text: str) -> list[str]:
+ """EN: Extract unique valid domains from hosts-file / plain-list
+ text. Skips comments, blank lines, the local host's own entries
+ (localhost etc.) and anything that is not a syntactically valid
+ domain. Order-preserving dedupe.
+ FR: Extraire les domaines valides uniques d'un texte hosts/liste.
+ Ignore commentaires, lignes vides, entrées locales (localhost…) et
+ tout ce qui n'est pas un domaine syntaxiquement valide. Dédup en
+ conservant l'ordre."""
+ seen: set[str] = set()
+ out: list[str] = []
+ for raw in text.splitlines():
+ line = raw.split("#", 1)[0].strip() # EN: strip comments / FR: retirer commentaires
+ if not line:
+ continue
+ parts = line.split()
+ # EN: hosts format "0.0.0.0 domain [aliases…]" vs plain "domain".
+ # FR: format hosts « 0.0.0.0 domaine [alias…] » vs « domaine » seul.
+ if len(parts) > 1 and _looks_like_ip(parts[0]):
+ candidates = parts[1:]
+ else:
+ candidates = parts[:1]
+ for c in candidates:
+ d = c.strip().lower().rstrip(".")
+ if (d in seen or not _DOMAIN_RE.match(d)
+ or d == "localhost" or d.endswith(".localhost")
+ or d in ("localhost.localdomain", "local",
+ "broadcasthost", "ip6-localhost",
+ "ip6-loopback")):
+ continue
+ seen.add(d)
+ out.append(d)
+ return out
+
+
+def _looks_like_ip(token: str) -> bool:
+ try:
+ ipaddress.ip_address(token)
+ return True
+ except ValueError:
+ return False
+
+
+def fetch_url(url: str) -> str:
+ """EN: OPT-IN remote fetch — plain HTTPS GET, bounded. The caller is
+ responsible for surfacing that this performs an outbound request.
+ FR: Fetch distant OPT-IN — GET HTTPS simple, borné. L'appelant doit
+ rendre visible que ceci émet une requête sortante."""
+ if not url.lower().startswith(("https://", "http://")):
+ raise ValueError("url must be http(s)")
+ req = urllib.request.Request(url, headers={"User-Agent": "Snitch/1.3"})
+ with urllib.request.urlopen(req, timeout=_FETCH_TIMEOUT) as r:
+ data = r.read(_MAX_BYTES + 1)
+ if len(data) > _MAX_BYTES:
+ raise ValueError("blocklist too large (>4 MiB)")
+ return data.decode("utf-8", errors="replace")
+
+
+def clamp_max(n: int | None) -> int:
+ """EN: Bound the caller's requested entry cap.
+ FR: Borner le plafond demandé par l'appelant."""
+ try:
+ v = int(n) if n else _DEFAULT_MAX
+ except (TypeError, ValueError):
+ v = _DEFAULT_MAX
+ return max(1, min(v, _HARD_MAX))
diff --git a/backend/detection/contain.py b/backend/detection/contain.py
new file mode 100644
index 0000000..dd561bc
--- /dev/null
+++ b/backend/detection/contain.py
@@ -0,0 +1,124 @@
+"""
+Snitch — network containment sandbox / bac à sable réseau.
+
+EN: The honest user-mode slice of "micro-VM containment": run a suspect
+ binary in a network-less sandbox so an analyst can observe its
+ behaviour (filesystem, dns-ish attempts, crashes) with zero egress.
+ No VM, no driver — just the OS's own isolation:
+
+ * Linux : `unshare --user --net` — an unprivileged user+network
+ namespace; the child sees only loopback. Works without
+ root on any kernel with unprivileged userns enabled
+ (Debian disables it — reported honestly).
+ * macOS : `sandbox-exec` with a `(deny network*)` seatbelt
+ profile — deprecated since Catalina but still enforced
+ on current releases; reported as best-effort.
+ * Windows: no user-mode equivalent exists (Job Objects restrict
+ CPU/memory, not sockets) — unavailable() is honest.
+
+ Safety: the binary runs UNPRIVILEGED with NO network; the wrapper
+ itself only launches it and caps runtime + captured output. The
+ caller decides what to detonate — Snitch never auto-detonates.
+
+FR: La tranche user-mode honnête du « confinement micro-VM » : exécuter
+ un binaire suspect dans un bac à sable sans réseau pour observer son
+ comportement avec zéro égress. Pas de VM, pas de driver — juste
+ l'isolation de l'OS : `unshare --user --net` sous Linux (namespace
+ utilisateur + réseau non privilégié — l'enfant ne voit que loopback),
+ `sandbox-exec` + profil `(deny network*)` sous macOS (déprécié mais
+ encore appliqué). Sous Windows aucun équivalent user-mode n'existe —
+ le statut est honnête. Sécurité : le binaire tourne non privilégié et
+ sans réseau ; le wrapper ne fait que le lancer avec bornes temps +
+ sortie. Snitch ne détone jamais rien tout seul.
+"""
+
+from __future__ import annotations
+
+import platform
+import shutil
+import subprocess
+import time
+
+_SYSTEM = platform.system().lower()
+_MAX_SECONDS = 30
+_MAX_OUT = 4096
+
+# EN: Seatbelt profile — deny every network operation, keep filesystem +
+# process defaults readable/writable (the point is egress, not
+# filesystem damage control).
+# FR: Profil seatbelt — refuse toute opération réseau, garde le reste par
+# défaut (le but est l'égress, pas le verrouillage filesystem).
+_MACOS_PROFILE = ("(version 1)(allow default)(deny network*)"
+ "(deny network-bind)(deny network-outbound)"
+ "(deny network-inbound)")
+
+
+def available() -> tuple[bool, str]:
+ """EN: Honest capability probe — which sandbox primitive exists here.
+ FR: Sonde de capacité honnête — quelle primitive de sandbox existe ici."""
+ if _SYSTEM == "linux":
+ if shutil.which("unshare"):
+ return True, "linux user+net namespace (unshare -U -n)"
+ return False, "no unshare binary"
+ if _SYSTEM == "darwin":
+ if shutil.which("sandbox-exec"):
+ return True, "macOS seatbelt (sandbox-exec deny network*)"
+ return False, "no sandbox-exec binary"
+ return False, ("no user-mode network sandbox on this OS "
+ "(Windows Job Objects can't restrict sockets)")
+
+
+def sandbox_command(path: str, args: list[str]) -> list[str]:
+ """EN: Wrap `path args` in the platform's network-denial sandbox —
+ returns the full command for the API to run or the user to copy.
+ Linux prefers `unshare -U -n` (unprivileged userns); if userns is
+ disabled at boot the child reports EPERM — surfaced as an error,
+ not faked.
+ FR: Envelopper `path args` dans la sandbox réseau de la plateforme —
+ renvoie la commande complète (API ou copie manuelle). Linux
+ préfère `unshare -U -n` ; si les userns non privilégiés sont
+ désactivés au boot, l'enfant renvoie EPERM — rapporté, pas simulé."""
+ if _SYSTEM == "linux":
+ return ["unshare", "--user", "--net", "--map-root-user",
+ "--fork", path, *args]
+ if _SYSTEM == "darwin":
+ return ["sandbox-exec", "-p", _MACOS_PROFILE, path, *args]
+ return [path, *args] # EN: never reached — caller checks available() first
+
+
+def run_sandboxed(path: str, args: list[str],
+ seconds: int = 10) -> dict:
+ """EN: Detonate `path` network-less for ≤_MAX_SECONDS, capturing
+ bounded stdout+stderr — the egress-free behaviour report. The
+ process is killed on timeout; a sandbox primitive failure is
+ returned as an honest error (e.g. userns disabled → EPERM).
+ FR: Détoner `path` sans réseau ≤_MAX_SECONDS, stdout+stderr bornés —
+ le rapport de comportement sans égress. Le processus est tué au
+ timeout ; un échec de primitive est renvoyé en erreur honnête."""
+ ok, why = available()
+ if not ok:
+ return {"ok": False, "error": why}
+ import os
+ if not os.path.isfile(path) or not os.access(path, os.X_OK):
+ return {"ok": False, "error": "not an executable file"}
+ seconds = max(1, min(int(seconds), _MAX_SECONDS))
+ cmd = sandbox_command(path, args[:16])
+ try:
+ t0 = time.monotonic()
+ proc = subprocess.run(cmd, timeout=seconds, capture_output=True,
+ text=False, cwd="/", check=False)
+ dur = round(time.monotonic() - t0, 2)
+ return {"ok": True, "command": cmd, "seconds": dur,
+ "exit_code": proc.returncode,
+ "stdout": proc.stdout[:_MAX_OUT].decode("utf-8", "replace"),
+ "stderr": proc.stderr[:_MAX_OUT].decode("utf-8", "replace"),
+ "note": "ran with no network — connection attempts "
+ "failed inside the sandbox"}
+ except subprocess.TimeoutExpired:
+ return {"ok": True, "command": cmd, "seconds": seconds,
+ "exit_code": None, "stdout": "", "stderr": "",
+ "note": "killed at timeout — network was denied "
+ "throughout"}
+ except OSError as e:
+ return {"ok": False, "command": cmd,
+ "error": f"sandbox launch failed: {e}"}
diff --git a/backend/detection/customrules.py b/backend/detection/customrules.py
new file mode 100644
index 0000000..560e011
--- /dev/null
+++ b/backend/detection/customrules.py
@@ -0,0 +1,210 @@
+"""
+EN: User-defined alert rules — a deliberately SMALL matcher, not a
+ signature language. A rule picks one packet field, one operator and
+ one value; the first enabled rule matching a packet raises a
+ CUSTOM_RULE alert carrying the rule name, so users can build their
+ own detections ("warn me when curl touches port 4444", "flag any
+ process talking to *.onion-ish hosts") without waiting for a Snitch
+ release. Rules are persisted in the settings table and matched
+ in-line in the packet path — they only ALERT, they never block
+ (blocking stays the firewall's job).
+
+ Supported fields : remote_ip, host (SNI or DNS answer name),
+ process_name, remote_port, protocol, direction,
+ size.
+ Supported ops : eq, ne, contains, regex, gt, lt, cidr.
+ 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.
+
+FR: Règles d'alerte définies par l'utilisateur — un filtreur
+ volontairement PETIT, pas un langage de signatures. Une règle choisit
+ un champ de paquet, un opérateur et une valeur ; la première règle
+ active qui matche lève une alerte CUSTOM_RULE portant son nom, pour
+ construire ses propres détections sans attendre une release. Les
+ règles sont persistées dans la table settings et évaluées en ligne
+ dans le chemin paquet — elles ALERTENT seulement, jamais de blocage
+ (c'est le travail du pare-feu). Regex bornée pour qu'une mauvaise
+ règle ne puisse pas DoS le pipeline.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import re
+import time
+import uuid
+from typing import Optional
+
+_FIELDS = ("remote_ip", "host", "process_name", "remote_port",
+ "protocol", "direction", "size")
+_OPS = ("eq", "ne", "contains", "regex", "gt", "lt", "cidr")
+_SEVERITIES = ("info", "warning", "critical")
+_MAX_RULES = 256
+_MAX_PATTERN = 200
+_MAX_COMPILED = 64
+
+
+class CustomRules:
+ """EN: Ordered list of user rules with a bounded regex cache.
+ FR: Liste ordonnée de règles utilisateur avec cache regex borné."""
+
+ def __init__(self):
+ self._rules: list[dict] = []
+ self._compiled: dict[str, "re.Pattern"] = {}
+ self._hits: dict[str, dict] = {} # EN: rid → {count,last} / FR: rid → {count,last}
+
+ # ── persistence / persistance ────────────────────────────────────────────
+
+ def load(self, rules: list) -> None:
+ """EN: Restore persisted rules (validated one by one; broken
+ entries are dropped rather than killing startup).
+ FR: Restaurer les règles persistées (validées une à une ; les
+ entrées cassées sont ignorées plutôt que de tuer le démarrage)."""
+ self._rules = []
+ for r in rules or []:
+ try:
+ self._validate(r)
+ except ValueError:
+ continue
+ self._rules.append(dict(r))
+ self._rules[-1].setdefault("hits", 0)
+
+ def serialized(self) -> list[dict]:
+ return [dict(r) for r in self._rules]
+
+ # ── CRUD ─────────────────────────────────────────────────────────────────
+
+ def _validate(self, rule: dict) -> None:
+ if rule.get("field") not in _FIELDS:
+ raise ValueError(f"unknown field: {rule.get('field')}")
+ if rule.get("op") not in _OPS:
+ raise ValueError(f"unknown op: {rule.get('op')}")
+ if rule.get("severity", "warning") not in _SEVERITIES:
+ raise ValueError(f"unknown severity: {rule.get('severity')}")
+ value = str(rule.get("value", ""))
+ if not value:
+ raise ValueError("empty value")
+ if rule["op"] == "regex":
+ if len(value) > _MAX_PATTERN:
+ raise ValueError("pattern too long")
+ try:
+ re.compile(value)
+ except re.error as exc:
+ raise ValueError(f"bad regex: {exc}") from exc
+ if rule["op"] == "cidr":
+ ipaddress.ip_network(value, strict=False)
+ if rule["op"] in ("gt", "lt") and rule["field"] in ("remote_port", "size"):
+ int(value) # EN: numeric ops need numbers / FR: ops numériques
+
+ def add(self, name: str, field: str, op: str, value: str,
+ severity: str = "warning") -> dict:
+ if len(self._rules) >= _MAX_RULES:
+ raise ValueError("rule limit reached")
+ rule = {
+ "id": uuid.uuid4().hex[:10],
+ "name": (name or "").strip()[:120] or f"{field} {op} {value}",
+ "field": field, "op": op, "value": str(value).strip(),
+ "severity": severity, "enabled": True,
+ "hits": 0, "created": time.time(),
+ }
+ self._validate(rule)
+ self._rules.append(rule)
+ return rule
+
+ def remove(self, rule_id: str) -> bool:
+ for i, r in enumerate(self._rules):
+ if r["id"] == rule_id:
+ self._rules.pop(i)
+ self._hits.pop(rule_id, None)
+ return True
+ return False
+
+ def toggle(self, rule_id: str, enabled: bool) -> Optional[dict]:
+ for r in self._rules:
+ if r["id"] == rule_id:
+ r["enabled"] = bool(enabled)
+ return r
+ return None
+
+ # ── matching / correspondance ────────────────────────────────────────────
+
+ @staticmethod
+ def _field_value(pkt, field: str):
+ """EN: Extract the comparable value from a Packet.
+ FR: Extraire la valeur comparable d'un Packet."""
+ if field == "remote_ip":
+ return pkt.dst_ip if pkt.direction == "out" else pkt.src_ip
+ if field == "host":
+ # EN: TLS SNI first, then any DNS answer name in the packet.
+ # FR: SNI TLS d'abord, puis noms des réponses DNS du paquet.
+ names = [pkt.sni] if pkt.sni else []
+ names += [d[0] for d in (pkt.dns or []) if d and d[0]]
+ return names
+ if field == "process_name":
+ return pkt.process_name or ""
+ if field == "remote_port":
+ return pkt.remote_port
+ if field == "protocol":
+ return pkt.protocol or ""
+ if field == "direction":
+ return pkt.direction or ""
+ if field == "size":
+ return pkt.size
+ return None
+
+ def _match_one(self, rule: dict, actual) -> bool:
+ op, want = rule["op"], rule["value"]
+ values = actual if isinstance(actual, list) else [actual]
+ for v in values:
+ if v is None:
+ continue
+ try:
+ if op == "cidr":
+ if ipaddress.ip_address(str(v)) in \
+ ipaddress.ip_network(want, strict=False):
+ return True
+ elif op in ("gt", "lt"):
+ num = float(v)
+ if (op == "gt" and num > float(want)) or \
+ (op == "lt" and num < float(want)):
+ return True
+ else:
+ s = str(v)
+ wl = want.lower()
+ sl = s.lower()
+ if op == "eq" and sl == wl:
+ return True
+ if op == "ne" and sl != wl:
+ return True
+ if op == "contains" and wl in sl:
+ return True
+ if op == "regex":
+ pat = self._compiled.get(want)
+ if pat is None:
+ if len(self._compiled) >= _MAX_COMPILED:
+ self._compiled.pop(next(iter(self._compiled)))
+ pat = re.compile(want)
+ self._compiled[want] = pat
+ if pat.search(s):
+ return True
+ except (ValueError, TypeError, re.error):
+ continue
+ return False
+
+ def check(self, pkt) -> list[dict]:
+ """EN: All enabled rules matching this packet (usually one per
+ packet is emitted — callers may cap). Hit counters updated.
+ FR: Toutes les règles actives qui matchent ce paquet (en pratique
+ une alerte par paquet — l'appelant borne). Compteurs mis à jour."""
+ out = []
+ for r in self._rules:
+ if not r.get("enabled"):
+ continue
+ if self._match_one(r, self._field_value(pkt, r["field"])):
+ h = self._hits.setdefault(r["id"], {"count": 0, "last": 0.0})
+ h["count"] += 1
+ h["last"] = time.time()
+ r["hits"] = h["count"]
+ out.append({"rule": r, "count": h["count"]})
+ return out
diff --git a/backend/detection/deepinspect.py b/backend/detection/deepinspect.py
index f876112..c37383a 100644
--- a/backend/detection/deepinspect.py
+++ b/backend/detection/deepinspect.py
@@ -84,9 +84,86 @@ function hook(api, lib) {
['connect', 'sendto', 'sendmsg'].forEach(function (a) {
hook(a, null); hook(a, 'libc.so'); hook(a, 'libSystem.B.dylib');
});
-['WSAConnect', 'connect', 'WSASend', 'send'].forEach(function (a) {
+['WSAConnect', 'connect'].forEach(function (a) {
hook(a, 'ws2_32.dll');
});
+
+// ── Payload tracing / Traçage de payload ────────────────────────────────
+// EN: Data-flow evidence (the honest user-mode DTA slice): hook the send
+// boundary itself, record which module emitted the bytes plus a 16-byte
+// head + declared length — enough to prove "this DLL sent these bytes"
+// without storing payloads. Bounded by the global event budget.
+// FR: Preuve de flux de données (la tranche DTA user-mode honnête) : hooker
+// la frontière send elle-même, noter quel module a émis les octets plus
+// une tête de 16 octets + longueur déclarée — suffit pour prouver
+// « cette DLL a envoyé ces octets » sans stocker les payloads. Borné
+// par le budget global d'événements.
+var _sendCount = 0, _SEND_MAX = 200;
+function hookSend(api, lib, bufIdx, lenIdx) {
+ var addr = null;
+ try { addr = lib ? Module.getExportByName(lib, api)
+ : Module.findExportByName(null, api); }
+ catch (e) { addr = null; }
+ if (!addr) return;
+ Interceptor.attach(addr, {
+ onEnter: function (args) {
+ if (++_sendCount > _SEND_MAX) return;
+ var n = args[lenIdx].toInt32();
+ if (n <= 0) return;
+ var head = '';
+ try { head = args[bufIdx].readByteArray(Math.min(n, 16)); }
+ catch (e) { return; }
+ var mod = null;
+ try { mod = Process.findModuleByAddress(this.returnAddress); }
+ catch (e) {}
+ var hex = [];
+ var bytes = new Uint8Array(head);
+ for (var i = 0; i < bytes.length; i++)
+ hex.push(('0' + bytes[i].toString(16)).slice(-2));
+ send({api: api, kind: 'send', n: n, head: hex.join(''),
+ module: mod ? mod.name : '?',
+ path: mod ? mod.path : ''});
+ }
+ });
+}
+// EN: POSIX send(fd,buf,len,flags) — send() on a connected socket carries
+// no sockaddr; sendto(fd,buf,len,flags,sa,salen) has buf/len at 1/2.
+// FR: send POSIX (fd,buf,len,flags) — pas de sockaddr sur socket connectée ;
+// sendto a buf/len en positions 1/2.
+hookSend('send', null, 1, 2); hookSend('send', 'libc.so', 1, 2);
+hookSend('send', 'libSystem.B.dylib', 1, 2);
+hookSend('sendto', null, 1, 2); hookSend('sendto', 'libc.so', 1, 2);
+hookSend('send', 'ws2_32.dll', 1, 2);
+// EN: WSASend(s, lpBuffers, count, ...) — lpBuffers points at a WSABUF
+// array {u32 len; pad; char* buf} on x64.
+// FR: WSASend(s, lpBuffers, count, ...) — tableau de WSABUF
+// {u32 len ; pad ; char* buf} en x64.
+(function hookWSASend() {
+ var addr = null;
+ try { addr = Module.getExportByName('ws2_32.dll', 'WSASend'); }
+ catch (e) { return; }
+ Interceptor.attach(addr, {
+ onEnter: function (args) {
+ if (++_sendCount > _SEND_MAX) return;
+ try {
+ var wsa = ptr(args[1]);
+ var n = wsa.readU32();
+ var buf = wsa.add(Process.pointerSize).readPointer();
+ if (n <= 0 || buf.isNull()) return;
+ var head = buf.readByteArray(Math.min(n, 16));
+ var mod = null;
+ try { mod = Process.findModuleByAddress(this.returnAddress); }
+ catch (e) {}
+ var bytes = new Uint8Array(head), hex = [];
+ for (var i = 0; i < bytes.length; i++)
+ hex.push(('0' + bytes[i].toString(16)).slice(-2));
+ send({api: 'WSASend', kind: 'send', n: n, head: hex.join(''),
+ module: mod ? mod.name : '?',
+ path: mod ? mod.path : ''});
+ } catch (e) {}
+ }
+ });
+})();
"""
@@ -116,12 +193,14 @@ class DeepInspector:
explique les échecs d'attache."""
ok, why = self.available()
if not ok:
- return {"ok": False, "error": why, "events": [], "modules": {}}
+ return {"ok": False, "error": why, "events": [], "flows": [],
+ "modules": {}}
if not self._busy.acquire(blocking=False):
return {"ok": False, "error": "another inspection is running",
- "events": [], "modules": {}}
+ "events": [], "flows": [], "modules": {}}
seconds = max(3, min(int(seconds), _MAX_SECONDS))
events: list[dict] = []
+ flows: list[dict] = []
try:
import frida
try:
@@ -129,10 +208,11 @@ class DeepInspector:
except Exception as e: # noqa: BLE001
return {"ok": False,
"error": f"attach failed: {str(e)[:160]}",
- "events": [], "modules": {}}
+ "events": [], "flows": [], "modules": {}}
try:
script = session.create_script(_JS)
- script.on("message", lambda m, d: self._on_msg(m, events))
+ script.on("message",
+ lambda m, d: self._on_msg(m, events, flows))
script.load()
time.sleep(seconds)
finally:
@@ -143,17 +223,36 @@ class DeepInspector:
finally:
self._busy.release()
modules: dict[str, int] = {}
- for e in events:
+ for e in events + flows:
modules[e["module"]] = modules.get(e["module"], 0) + 1
+ # EN: Flow evidence — sha256 of the captured head makes "these
+ # bytes" tamper-evident without storing the payload itself.
+ # FR: Preuve de flux — sha256 de la tête capturée rend « ces
+ # octets » infalsifiables sans stocker le payload.
+ import hashlib
+ for f in flows:
+ head = f.pop("head", "")
+ try:
+ f["sha256_head"] = hashlib.sha256(
+ bytes.fromhex(head)).hexdigest()
+ except ValueError:
+ f["sha256_head"] = ""
return {"ok": True, "pid": pid, "seconds": seconds,
- "events": events[:_MAX_EVENTS], "modules": modules}
+ "events": events[:_MAX_EVENTS],
+ "flows": flows[:_MAX_EVENTS],
+ "modules": modules}
@staticmethod
- def _on_msg(message: dict, out: list) -> None:
- if message.get("type") == "send" and len(out) < _MAX_EVENTS:
- p = message.get("payload") or {}
- if isinstance(p, dict) and p.get("ip"):
- out.append(p)
+ def _on_msg(message: dict, out: list, flows: list) -> None:
+ if message.get("type") != "send":
+ return
+ p = message.get("payload") or {}
+ if not isinstance(p, dict):
+ return
+ if p.get("ip") and len(out) < _MAX_EVENTS:
+ out.append(p)
+ elif p.get("kind") == "send" and len(flows) < _MAX_EVENTS:
+ flows.append(p)
def suspicious_module_paths(events: list[dict]) -> list[str]:
diff --git a/backend/detection/explain.py b/backend/detection/explain.py
index 8ab6315..4cbae8b 100644
--- a/backend/detection/explain.py
+++ b/backend/detection/explain.py
@@ -519,6 +519,24 @@ EXPLANATIONS: dict[str, dict] = {
"Watch the destination before blocking"],
["Lancer une vérif de réputation locale sur l'indicateur",
"Surveiller la destination avant de bloquer"]),
+
+"CUSTOM_RULE": _e(
+ "Your rule matched",
+ "Votre règle a correspondu",
+ "A packet matched a condition YOU defined in the alert-rules panel "
+ "(field + operator + value). This is your own detection firing — "
+ "not a built-in heuristic.",
+ "Un paquet a correspondu à une condition que VOUS avez définie dans "
+ "le panneau de règles (champ + opérateur + valeur). C'est votre propre "
+ "détection qui se déclenche — pas une heuristique intégrée.",
+ "The rule only alerts; it never blocks. Tune the field/op/value if it "
+ "fires too often, or disable it from the rules list.",
+ "La règle ne fait qu'alerter ; elle ne bloque jamais. Ajustez "
+ "champ/op/valeur si elle se déclenche trop, ou désactivez-la.",
+ ["Check which process triggered it",
+ "Tighten the matcher if noisy"],
+ ["Vérifier quel processus l'a déclenchée",
+ "Resserrer le filtre si trop bavarde"]),
}
diff --git a/backend/detection/firewall.py b/backend/detection/firewall.py
index e00c38c..4d4c03f 100644
--- a/backend/detection/firewall.py
+++ b/backend/detection/firewall.py
@@ -219,6 +219,98 @@ class FirewallManager:
self._lockdown = on
return {"ok": ok, "lockdown": self._lockdown, "error": err}
+ # ── Named profiles / Profils nommés ──────────────────────────────────────
+ #
+ # EN: A profile is a named bundle of ordinary rules + a lockdown state,
+ # expanded through the same add/remove machinery the UI uses — no
+ # hidden code path. `permissive` empties the policy, `balanced`
+ # adds a conservative egress baseline (spam-bot SMTP, common
+ # stratum mining-pool ports), `strict` is balanced + lockdown.
+ # Applying a profile never removes rules it did not create (except
+ # `permissive`, whose whole point is a clean slate).
+ # FR: Un profil est un lot nommé de règles ordinaires + un état de
+ # lockdown, appliqué par la même machinerie add/remove que l'UI —
+ # aucun chemin de code caché. `permissive` vide la politique,
+ # `balanced` ajoute une base sortante prudente (SMTP des botnets
+ # de spam, ports stratum de pools de minage courants), `strict`
+ # = balanced + lockdown. Appliquer un profil ne retire jamais les
+ # règles qu'il n'a pas créées (sauf `permissive`, dont c'est le
+ # but).
+
+ PROFILES: dict[str, dict] = {
+ "permissive": {
+ "lockdown": False,
+ "replace": True,
+ "rules": [],
+ },
+ "balanced": {
+ "lockdown": False,
+ "replace": False,
+ "rules": [
+ # EN: Outbound SMTP — classic spam-botnet egress.
+ # FR: SMTP sortant — égress classique des botnets de spam.
+ {"kind": "port", "value": "25", "action": "block"},
+ # EN: Common stratum mining-pool ports.
+ # FR: Ports stratum de pools de minage courants.
+ {"kind": "port", "value": "3333", "action": "block"},
+ {"kind": "port", "value": "5555", "action": "block"},
+ {"kind": "port", "value": "7777", "action": "block"},
+ {"kind": "port", "value": "14444", "action": "block"},
+ ],
+ },
+ "strict": {
+ "lockdown": True,
+ "replace": False,
+ "rules": [
+ {"kind": "port", "value": "25", "action": "block"},
+ {"kind": "port", "value": "3333", "action": "block"},
+ {"kind": "port", "value": "5555", "action": "block"},
+ {"kind": "port", "value": "7777", "action": "block"},
+ {"kind": "port", "value": "14444", "action": "block"},
+ ],
+ },
+ }
+
+ def apply_profile(self, name: str) -> dict:
+ """EN: Expand a named profile into real rules + lockdown state.
+ Existing identical rules are reused (dedup on kind/value/action);
+ `permissive` removes every rule first. Returns a summary.
+ FR: Déplier un profil nommé en vraies règles + état lockdown. Les
+ règles identiques existantes sont réutilisées ; `permissive`
+ supprime d'abord toutes les règles. Renvoie un résumé."""
+ spec = self.PROFILES.get((name or "").lower().strip())
+ if spec is None:
+ raise ValueError(f"unknown profile: {name}")
+ removed = 0
+ if spec["replace"]:
+ with self._lock:
+ ids = [r["id"] for r in self._rules]
+ for rid in ids:
+ if self.remove_rule(rid):
+ removed += 1
+ added = 0
+ for tpl in spec["rules"]:
+ if self._find_rule(tpl["kind"], tpl["value"], tpl["action"]):
+ continue # EN: already there / FR: déjà présente
+ self.add_rule(tpl["kind"], tpl["value"], tpl["action"])
+ added += 1
+ lockdown_res = None
+ if spec["lockdown"] is not None:
+ lockdown_res = self.set_lockdown(bool(spec["lockdown"]))
+ return {"profile": name, "added": added, "removed": removed,
+ "lockdown": lockdown_res}
+
+ def _find_rule(self, kind: str, value: str, action: str) -> Optional[dict]:
+ """EN: First rule with the same kind/normalized value/action —
+ profile dedup helper. / FR: Première règle de même
+ kind/valeur/action — dédup des profils."""
+ with self._lock:
+ for r in self._rules:
+ if (r["kind"] == kind and r["action"] == action
+ and str(r["value"]).lower() == str(value).lower()):
+ return r
+ return None
+
# ── Packet matching / Correspondance paquets ─────────────────────────────
def check_packet(self, pkt) -> Optional[dict]:
diff --git a/backend/detection/iocshare.py b/backend/detection/iocshare.py
index 1b601cc..2e78343 100644
--- a/backend/detection/iocshare.py
+++ b/backend/detection/iocshare.py
@@ -123,3 +123,107 @@ def check_pack(pack: dict, candidates: list[str]) -> dict:
"checked": len(candidates[:2048]),
"note": "membership is probabilistic (false positives "
"expected) — treat as hints, not verdicts"}
+
+
+# ── Commitment packs (cryptographic, selective disclosure) ──────────────────
+# EN: Second pack format — for peers who want EXACT answers instead of
+# probabilistic ones. Each indicator becomes a salted SHA-256 leaf
+# `H(salt || indicator)`; the pack publishes every leaf + its salt +
+# a Merkle root over the sorted leaves as a tamper-evident commitment.
+#
+# Verifier side: for each candidate x and each entry, recompute
+# H(salt||x) — a match is a *proof* of membership (no false
+# positives). Unlisted indicators stay hidden unless the attacker
+# already guesses them (the salt only blocks precomputed tables —
+# dictionary guessing is inherent to any selective-disclosure scheme).
+#
+# Honest wording: a cryptographic commitment + membership proof, NOT
+# an interactive zero-knowledge protocol.
+# FR: Second format — pour des pairs qui veulent des réponses EXACTES.
+# Chaque indicateur devient une feuille salée `H(salt || indicateur)` ;
+# le paquet publie feuilles + sels + racine Merkle sur les feuilles
+# triées (engagement inviolable). Une correspondance *prouve*
+# l'appartenance — zéro faux-positif. Schéma d'engagement, PAS un
+# protocole ZK interactif.
+
+_PROOF_FORMAT = "snitch-ioc-proof/1"
+
+
+def _leaf(salt: bytes, indicator: str) -> bytes:
+ """EN: Salted leaf hash — hides the raw indicator behind a per-entry
+ secret. / FR: Hash de feuille salé — cache l'indicateur brut derrière
+ un secret par entrée."""
+ return hashlib.sha256(salt + indicator.strip().lower().encode()).digest()
+
+
+def _merkle(leaves: list[bytes]) -> str:
+ """EN: Root over the sorted leaves — one commitment that pins down the
+ whole set (any edit to any leaf changes the root).
+ FR: Racine sur les feuilles triées — un engagement unique qui fixe
+ tout l'ensemble (toute modification de feuille change la racine)."""
+ if not leaves:
+ return hashlib.sha256(b"empty").hexdigest()
+ lvl = sorted(leaves)
+ while len(lvl) > 1:
+ if len(lvl) % 2:
+ lvl.append(lvl[-1])
+ lvl = [hashlib.sha256(lvl[i] + lvl[i + 1]).digest()
+ for i in range(0, len(lvl), 2)]
+ return lvl[0].hex()
+
+
+def build_proof_pack(indicators: list[str]) -> dict:
+ """EN: Commitment pack — exact-membership sharing. The sharer's salts
+ are disclosed inside the pack, so a verifier can *prove* their
+ candidates are present while unsuspected indicators can't be
+ enumerated (each needs its own salt + candidate guess).
+ FR: Paquet d'engagement — partage à appartenance exacte. Les sels sont
+ publiés dans le paquet : un vérificateur *prouve* ses candidats, les
+ indicateurs insoupçonnés restent inénumérables."""
+ import secrets
+ entries = []
+ for ind in indicators[:4096]:
+ salt = secrets.token_bytes(16)
+ entries.append({"leaf": _leaf(salt, ind).hex(), "salt": salt.hex()})
+ return {
+ "format": _PROOF_FORMAT,
+ "created": int(time.time()),
+ "count": len(entries),
+ "root": _merkle([bytes.fromhex(e["leaf"]) for e in entries]),
+ "entries": entries,
+ }
+
+
+def check_proof_pack(pack: dict, candidates: list[str]) -> dict:
+ """EN: Exact membership check — returns hits with a verifiable leaf,
+ plus the root so the caller can re-commit the pack they received.
+ FR: Vérification d'appartenance exacte — renvoie les hits avec la
+ feuille vérifiable + la racine pour re-valider le paquet reçu."""
+ if pack.get("format") != _PROOF_FORMAT:
+ return {"ok": False, "hints": [], "error": "unsupported pack format"}
+ entries = pack.get("entries")
+ if not isinstance(entries, list) or len(entries) > 4096:
+ return {"ok": False, "hints": [], "error": "bad entries"}
+ # EN: Re-commit — the published root must match the leaves shipped.
+ # FR: Re-engagement — la racine publiée doit correspondre aux feuilles.
+ try:
+ leaves = [bytes.fromhex(e["leaf"]) for e in entries]
+ salts = [bytes.fromhex(e["salt"]) for e in entries]
+ except (KeyError, ValueError):
+ return {"ok": False, "hints": [], "error": "corrupt entries"}
+ if _merkle(leaves) != pack.get("root"):
+ return {"ok": False, "hints": [], "error": "root mismatch — "
+ "pack was tampered"}
+ hits = []
+ for item in candidates[:2048]:
+ low = item.strip().lower()
+ for salt, leaf in zip(salts, leaves):
+ if hashlib.sha256(salt + low.encode()).digest() == leaf:
+ hits.append({"indicator": item,
+ "confidence": "proven — salted leaf + "
+ "merkle commitment"})
+ break
+ return {"ok": True, "hints": hits,
+ "checked": len(candidates[:2048]),
+ "note": "membership is cryptographically exact — "
+ "a hit proves the sharer listed that indicator"}
diff --git a/backend/detection/llm_local.py b/backend/detection/llm_local.py
index 4c12409..9dba0d4 100644
--- a/backend/detection/llm_local.py
+++ b/backend/detection/llm_local.py
@@ -11,9 +11,11 @@ EN: Local SLM enrichment — a REAL small language model, not a simulated
* OPT-IN — disabled by default; the deterministic bilingual
templates (explain.py) always remain the fallback, so nothing
breaks when the model is down.
- * NO BUNDLED MODEL — Snitch never downloads weights itself; the
- user points it at their own local server. Model names are
- user-provided or auto-detected from /api/tags.
+ * TWO LOCAL BACKENDS — `ollama` talks to a loopback endpoint;
+ `embedded` loads a user-provided GGUF file through the optional
+ `llama-cpp-python` package — zero network at all. Snitch never
+ downloads weights itself: the user points it at a model they
+ fetched on their own.
FR: Enrichissement SLM local — un VRAI petit modèle de langage, pas un
simulacre. Si l'utilisateur fait tourner Ollama (ou toute API
@@ -25,8 +27,10 @@ FR: Enrichissement SLM local — un VRAI petit modèle de langage, pas un
jamais la machine. Vérifié à chaque configure().
* OPT-IN — désactivé par défaut ; les gabarits bilingues
déterministes (explain.py) restent le repli permanent.
- * PAS DE MODÈLE EMBARQUÉ — Snitch ne télécharge jamais de poids ;
- l'utilisateur pointe vers son propre serveur local.
+ * DEUX BACKENDS LOCAUX — `ollama` parle à un endpoint loopback ;
+ `embedded` charge un fichier GGUF fourni par l'utilisateur via le
+ paquet optionnel `llama-cpp-python` — zéro réseau. Snitch ne
+ télécharge jamais de poids.
"""
from __future__ import annotations
@@ -66,18 +70,29 @@ class LocalSlm:
self._enabled = False
self._endpoint = "http://127.0.0.1:11434"
self._model = "" # EN: empty → autodetect / FR: vide → autodétecté
+ self._mode = "ollama" # EN: ollama | embedded / FR: ollama | embedded
+ self._model_path = "" # EN: user GGUF path / FR: chemin GGUF utilisateur
+ self._llama = None # EN: lazy Llama() / FR: Llama() paresseux
self._cache: dict[tuple, tuple[float, str]] = {}
# ── config / configuration ───────────────────────────────────────────────
def configure(self, enabled: bool, endpoint: str = "",
- model: str = "") -> None:
+ model: str = "", mode: str = "",
+ model_path: str = "") -> None:
with self._lock:
self._enabled = bool(enabled)
if endpoint and _is_loopback(endpoint):
self._endpoint = endpoint.rstrip("/")
if model is not None:
self._model = model.strip()
+ if mode in ("ollama", "embedded"):
+ if mode != self._mode:
+ self._llama = None # EN: backend switch → reload / FR: changement → recharger
+ self._mode = mode
+ if model_path and model_path != self._model_path:
+ self._model_path = model_path.strip()
+ self._llama = None # EN: new weights → reload / FR: nouveaux poids → recharger
# ── status / état ────────────────────────────────────────────────────────
@@ -100,15 +115,47 @@ class LocalSlm:
affiché, jamais caché)."""
with self._lock:
enabled, endpoint, model = self._enabled, self._endpoint, self._model
+ mode, mpath = self._mode, self._model_path
reachable = False
detected = ""
if enabled:
- detected = self._detect_model() if not model else ""
- reachable = bool(model or detected)
+ if mode == "embedded":
+ import os
+ reachable = bool(mpath) and os.path.isfile(mpath)
+ else:
+ detected = self._detect_model() if not model else ""
+ reachable = bool(model or detected)
return {"enabled": enabled, "reachable": reachable,
- "endpoint": endpoint,
- "model": model or detected,
- "loopback_only": True}
+ "endpoint": endpoint, "mode": mode,
+ "model": model or detected or mpath,
+ "loopback_only": mode != "embedded" or True}
+
+ # ── embedded backend / backend embarqué ───────────────────────────────────
+
+ def _load_embedded(self) -> object | None:
+ """EN: Lazy-load the user-supplied GGUF via llama-cpp-python —
+ first call pays the load cost (~seconds); the model object is
+ reused afterwards. Returns None when the package or the file
+ is missing — the caller falls back to templates.
+ FR: Charge le GGUF fourni par l'utilisateur via llama-cpp-python —
+ le premier appel paie le coût de chargement ; l'objet est
+ réutilisé ensuite. Renvoie None si paquet/fichier absent."""
+ with self._lock:
+ if self._llama is not None:
+ return self._llama
+ path = self._model_path
+ try:
+ from llama_cpp import Llama
+ except ImportError:
+ return None
+ try:
+ llama = Llama(model_path=path, n_ctx=512, n_threads=2,
+ verbose=False)
+ except Exception: # noqa: BLE001
+ return None
+ with self._lock:
+ self._llama = llama
+ return llama
# ── generation / génération ──────────────────────────────────────────────
@@ -124,11 +171,7 @@ class LocalSlm:
return None
endpoint = self._endpoint
model = self._model
- if not _is_loopback(endpoint):
- return None
- model = model or self._detect_model()
- if not model:
- return None
+ mode = self._mode
import hashlib
key = (alert_type, lang,
hashlib.sha256(json.dumps(details, sort_keys=True,
@@ -144,16 +187,36 @@ class LocalSlm:
f"and what the user should check. No preamble.\n"
f"ALERT TYPE: {alert_type}\nDETAILS: {json.dumps(details, default=str)[:600]}"
)
- try:
- body = json.dumps({"model": model, "prompt": prompt,
- "stream": False}).encode()
- req = urllib.request.Request(f"{endpoint}/api/generate",
- data=body,
- headers={"Content-Type": "application/json"})
- with urllib.request.urlopen(req, timeout=_TIMEOUT) as r:
- text = (json.loads(r.read()).get("response") or "").strip()
- except Exception: # noqa: BLE001
- return None
+ text = None
+ if mode == "embedded":
+ # EN: Zero-network path — inference runs fully in-process.
+ # FR: Chemin zéro-réseau — l'inférence tourne entièrement en
+ # processus.
+ llama = self._load_embedded()
+ if llama is not None:
+ try:
+ out = llama(prompt, max_tokens=160,
+ stop=["\n\n"], temperature=0.3)
+ text = (out.get("choices", [{}])[0]
+ .get("text") or "").strip()
+ except Exception: # noqa: BLE001
+ text = None
+ else:
+ if not _is_loopback(endpoint):
+ return None
+ model = model or self._detect_model()
+ if not model:
+ return None
+ try:
+ body = json.dumps({"model": model, "prompt": prompt,
+ "stream": False}).encode()
+ req = urllib.request.Request(f"{endpoint}/api/generate",
+ data=body,
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req, timeout=_TIMEOUT) as r:
+ text = (json.loads(r.read()).get("response") or "").strip()
+ except Exception: # noqa: BLE001
+ return None
if text:
with self._lock:
self._cache[key] = (time.time(), text)
diff --git a/backend/resolver/dns_geo.py b/backend/resolver/dns_geo.py
index 57b65e4..6392748 100644
--- a/backend/resolver/dns_geo.py
+++ b/backend/resolver/dns_geo.py
@@ -303,6 +303,14 @@ def resolve_geo(ip: str) -> dict:
try:
rec = asn.get(ip) or {}
geo["org"] = rec.get("autonomous_system_organization")
+ # EN: AS number too — "AS15169 Google" is a stronger signal
+ # than the org string alone (and survives renames).
+ # FR: Le numéro d'AS aussi — « AS15169 Google » est un signal
+ # plus fort que la seule chaîne d'org (et survit aux
+ # renommages).
+ num = rec.get("autonomous_system_number")
+ if num:
+ geo["asn"] = int(num)
except Exception as exc:
logger.debug("asn lookup failed for %s: %s", ip, exc)
diff --git a/backend/run_backend.py b/backend/run_backend.py
index b01d999..5d0ef8e 100644
--- a/backend/run_backend.py
+++ b/backend/run_backend.py
@@ -99,11 +99,18 @@ if __name__ == '__main__':
# EN: Loopback-only by default everywhere — Electron AND Docker/dev.
# Set SNITCH_BIND=0.0.0.0 to expose (token auth still applies).
+ # The persisted `lan_bind` setting (written by POST /remote/pairing)
+ # is honoured at the lowest precedence — env and argv always win.
# FR: Loopback uniquement par défaut partout — Electron ET Docker/dev.
# Poser SNITCH_BIND=0.0.0.0 pour exposer (le jeton reste exigé).
+ # Le réglage persisté `lan_bind` (écrit par POST /remote/pairing)
+ # est honoré en dernière priorité — env et argv gagnent toujours.
+ import storage.db as _db
+ _lan_bind = _db.get_setting("lan_bind", "") or ""
uvicorn.run(
app,
- host=os.environ.get('SNITCH_BIND') or argv_bind or '127.0.0.1',
+ host=(os.environ.get('SNITCH_BIND') or argv_bind
+ or _lan_bind or '127.0.0.1'),
port=int(os.environ.get('SNITCH_PORT') or argv_port or '8000'),
log_level='warning',
)
diff --git a/backend/tests/test_security_features.py b/backend/tests/test_security_features.py
index b0f3333..251ab61 100644
--- a/backend/tests/test_security_features.py
+++ b/backend/tests/test_security_features.py
@@ -838,3 +838,300 @@ def test_parser_app_head_cleartext_only():
assert p.app_head.startswith(b'{"method"')
p2 = parse_frame(DLT_EN10MB, frame(b"\x16\x03\x01" + b"\x00" * 40))
assert p2.app_head == b""
+
+
+# ── Firewall profiles / Profils pare-feu ────────────────────────────────────
+
+def test_profile_balanced_adds_baseline(tmp_path, monkeypatch):
+ """EN: `balanced` expands to baseline port rules + lockdown stays off.
+ FR: `balanced` se déplie en règles de ports de base + lockdown éteint."""
+ fw = _fw(tmp_path, monkeypatch)
+ res = fw.apply_profile("balanced")
+ rules, lockdown = fw.serialized()
+ assert res["added"] == len(FirewallManager.PROFILES["balanced"]["rules"])
+ assert lockdown is False
+ assert all(r["kind"] == "port" for r in rules)
+
+
+def test_profile_strict_enables_lockdown(tmp_path, monkeypatch):
+ """EN: `strict` = baseline + lockdown ON. / FR: `strict` = base + lockdown."""
+ fw = _fw(tmp_path, monkeypatch)
+ fw.apply_profile("strict")
+ _, lockdown = fw.serialized()
+ assert lockdown is True
+
+
+def test_profile_permissive_clears_all(tmp_path, monkeypatch):
+ """EN: `permissive` wipes every rule and drops lockdown — clean slate.
+ FR: `permissive` efface toutes les règles et le lockdown — table rase."""
+ fw = _fw(tmp_path, monkeypatch)
+ fw.apply_profile("strict")
+ res = fw.apply_profile("permissive")
+ rules, lockdown = fw.serialized()
+ assert rules == [] and lockdown is False and res["removed"] > 0
+
+
+def test_profile_dedup_keeps_existing(tmp_path, monkeypatch):
+ """EN: Re-applying a profile reuses identical rules — no duplicates.
+ FR: Ré-appliquer un profil réutilise les règles identiques — pas de doublon."""
+ fw = _fw(tmp_path, monkeypatch)
+ fw.apply_profile("balanced")
+ res = fw.apply_profile("balanced")
+ assert res["added"] == 0
+ assert len(fw.serialized()[0]) == len(
+ FirewallManager.PROFILES["balanced"]["rules"])
+
+
+def test_profile_unknown_rejected(tmp_path, monkeypatch):
+ """EN: Unknown profile name → ValueError → 400 at the API layer.
+ FR: Nom de profil inconnu → ValueError → 400 côté API."""
+ fw = _fw(tmp_path, monkeypatch)
+ try:
+ fw.apply_profile("paranoid")
+ except ValueError:
+ return
+ raise AssertionError("expected ValueError")
+
+
+# ── Custom alert rules / Règles d'alerte utilisateur ────────────────────────
+
+def test_custom_rules_lifecycle_and_match():
+ """EN: add → match by host SNI → hit counter → toggle off → no match.
+ FR: ajout → match par SNI → compteur → désactivation → plus de match."""
+ from detection.customrules import CustomRules
+ cr = CustomRules()
+ r = cr.add("watch onions", "host", "contains", ".onion", "critical")
+ p = pkt()
+ p.sni = "deadbeef.onion"
+ hits = cr.check(p)
+ assert hits and hits[0]["rule"]["name"] == "watch onions"
+ assert r["hits"] == 1
+ cr.toggle(r["id"], False)
+ assert cr.check(p) == []
+
+
+def test_custom_rules_cidr_and_numeric():
+ """EN: cidr op on remote_ip + gt op on remote_port both match.
+ FR: l'op cidr sur remote_ip et gt sur remote_port matchent tous deux."""
+ from detection.customrules import CustomRules
+ cr = CustomRules()
+ cr.add("range", "remote_ip", "cidr", "91.198.174.0/24")
+ cr.add("highport", "remote_port", "gt", "8000")
+ assert len(cr.check(pkt())) == 1 # EN: ip only / FR: ip seule
+ assert len(cr.check(pkt(port=9999))) == 2 # EN: both / FR: les deux
+
+
+def test_custom_rules_validation():
+ """EN: Bad field/op/regex/cidr all rejected at creation.
+ FR: Mauvais champ/op/regex/cidr tous rejetés à la création."""
+ import pytest as _pt
+ from detection.customrules import CustomRules
+ cr = CustomRules()
+ for kw in (dict(field="nope"), dict(field="host", op="nope"),
+ dict(field="host", op="regex", value="["),
+ dict(field="remote_ip", op="cidr", value="999.0.0.0/8"),
+ dict(field="host", value="")):
+ with _pt.raises(ValueError):
+ cr.add("x", kw.get("field", "host"), kw.get("op", "eq"),
+ kw.get("value", "v"))
+
+
+def test_custom_rules_load_drops_broken():
+ """EN: load() skips invalid persisted entries rather than crashing.
+ FR: load() ignore les entrées persistées invalides plutôt que planter."""
+ from detection.customrules import CustomRules
+ cr = CustomRules()
+ cr.load([{"field": "host", "op": "contains", "value": "evil",
+ "name": "ok", "severity": "warning", "enabled": True},
+ {"field": "bogus", "op": "eq", "value": "x"}])
+ assert len(cr.serialized()) == 1
+
+
+# ── Blocklist / Liste de blocage ─────────────────────────────────────────────
+
+def test_blocklist_parse_hosts_format():
+ """EN: hosts-style lines, comments and plain lists all parse; local
+ entries and invalid domains are dropped, order preserved, deduped.
+ FR: lignes hosts, commentaires et listes simples parsés ; les entrées
+ locales et domaines invalides sont écartés, ordre conservé, dédup."""
+ from detection.blocklist import parse_domains
+ text = """
+# a comment / un commentaire
+0.0.0.0 ads.example tracker.example
+127.0.0.1 localhost
+127.0.0.1 bad.example
+malware.example
+0.0.0.0 ads.example
+not a domain !!
+0.0.0.0 -bad-.example
+"""
+ out = parse_domains(text)
+ assert "ads.example" in out and "bad.example" in out
+ assert "malware.example" in out
+ assert "localhost" not in out and "not" not in out
+ assert out.count("ads.example") == 1
+
+
+def test_blocklist_clamp_bounds():
+ """EN: clamp_max respects default + hard cap.
+ FR: clamp_max respecte le défaut + le plafond dur."""
+ from detection.blocklist import clamp_max
+ assert clamp_max(None) == 500
+ assert clamp_max(10) == 10
+ assert clamp_max(999999) == 5000
+
+
+def test_blocklist_fetch_requires_http():
+ """EN: fetch_url rejects non-http(s) schemes outright.
+ FR: fetch_url rejette carrément les schémas non http(s)."""
+ import pytest as _pt
+ from detection.blocklist import fetch_url
+ with _pt.raises(ValueError):
+ fetch_url("file:///etc/passwd")
+
+
+# ── IOC proof packs / Paquets de preuve IOC ──────────────────────────────────
+
+def test_ioc_proof_pack_proves_membership():
+ """EN: A listed indicator verifies EXACTLY (no false positives); an
+ unlisted one never matches. Root is a tamper-evident commitment.
+ FR: Un indicateur listé se vérifie EXACTEMENT ; un non-listé ne
+ matche jamais. La racine est un engagement inviolable."""
+ pack = iocshare.build_proof_pack(["1.2.3.4", "evil.example"])
+ res = iocshare.check_proof_pack(pack, ["1.2.3.4", "clean.example"])
+ assert res["ok"] is True
+ assert [h["indicator"] for h in res["hints"]] == ["1.2.3.4"]
+
+
+def test_ioc_proof_pack_tamper_detected():
+ """EN: Flipping a leaf breaks the Merkle commitment → honest error.
+ FR: Inverser une feuille casse l'engagement Merkle → erreur honnête."""
+ pack = iocshare.build_proof_pack(["1.2.3.4"])
+ pack["entries"][0]["leaf"] = "00" * 32
+ res = iocshare.check_proof_pack(pack, ["1.2.3.4"])
+ assert res["ok"] is False and "tampered" in res["error"]
+
+
+def test_ioc_proof_pack_rejects_bloom():
+ """EN: A bloom pack handed to the proof checker is refused politely.
+ FR: Un paquet bloom passé au vérificateur proof est refusé proprement."""
+ pack = iocshare.build_pack(["1.2.3.4"])
+ res = iocshare.check_proof_pack(pack, ["1.2.3.4"])
+ assert res["ok"] is False
+
+
+# ── Embedded SLM / SLM embarqué ──────────────────────────────────────────────
+
+def test_slm_embedded_status_reports_file(tmp_path):
+ """EN: embedded mode reports reachable only when the GGUF path exists.
+ FR: le mode embedded ne rapporte joignable que si le GGUF existe."""
+ slm = LocalSlm()
+ slm.configure(True, mode="embedded", model_path=str(tmp_path / "m.gguf"))
+ assert slm.status()["reachable"] is False
+ (tmp_path / "m.gguf").write_bytes(b"GGUF")
+ assert slm.status()["reachable"] is True
+
+
+def test_slm_embedded_enrich_without_package(tmp_path):
+ """EN: without llama-cpp-python installed, enrich() degrades to None —
+ caller falls back to templates. / FR: sans llama-cpp-python,
+ enrich() dégrade en None — repli sur les gabarits."""
+ slm = LocalSlm()
+ f = tmp_path / "m.gguf"
+ f.write_bytes(b"x")
+ slm.configure(True, mode="embedded", model_path=str(f))
+ slm._load_embedded = lambda: None # EN: simulate missing dep / FR: simuler l'absence
+ assert slm.enrich("BEACON", {"ip": "1.2.3.4"}) is None
+
+
+def test_slm_mode_switch_reloads(tmp_path):
+ """EN: switching modes or model path drops the cached Llama object.
+ FR: changer de mode ou de chemin invalide l'objet Llama caché."""
+ slm = LocalSlm()
+ slm._llama = object()
+ slm.configure(True, mode="embedded", model_path="/a")
+ assert slm._llama is None
+
+
+# ── Network sandbox / Sandbox réseau ─────────────────────────────────────────
+
+def test_contain_platform_support():
+ """EN: available() reports the real mechanism per OS — never claims
+ support that isn't there. / FR: available() rapporte le mécanisme
+ réel par OS — jamais de support fantaisiste."""
+ import sys
+ import detection.contain as contain
+ if sys.platform.startswith("linux"):
+ ok, why = contain.available()
+ assert isinstance(ok, bool) and why
+ else:
+ ok, why = contain.available()
+ assert isinstance(ok, bool) and why
+
+
+def test_contain_rejects_nonexistent(tmp_path):
+ """EN: detonating a missing file fails honestly before any exec.
+ FR: détoner un fichier absent échoue honnêtement avant tout exec."""
+ from detection.contain import run_sandboxed
+ res = run_sandboxed(str(tmp_path / "nope"), [], 5)
+ assert res["ok"] is False and "executable" in res["error"]
+
+
+def test_contain_wraps_command(monkeypatch, tmp_path):
+ """EN: On Linux the command is wrapped in `unshare --user --net`;
+ on macOS in `sandbox-exec` with a deny-network profile. Mock the
+ runner so nothing actually executes.
+ FR: Sous Linux la commande est enveloppée dans `unshare --user --net` ;
+ sous macOS dans `sandbox-exec` deny-network. Le lanceur est mocké."""
+ import sys
+ import detection.contain as contain
+
+ exe = tmp_path / "tool"
+ exe.write_text("#!/bin/sh\n")
+ exe.chmod(0o755)
+
+ captured = {}
+
+ class FakeProc:
+ returncode = 0
+ stdout = b""
+ stderr = b""
+
+ def _fake_run(cmd, **kw):
+ captured["cmd"] = cmd
+ return FakeProc()
+
+ monkeypatch.setattr(contain.subprocess, "run", _fake_run)
+ res = contain.run_sandboxed(str(exe), ["--x"], 5)
+ if res["ok"]:
+ cmd = captured["cmd"]
+ if sys.platform.startswith("linux"):
+ assert cmd[0] == "unshare" and "--net" in cmd
+ elif sys.platform == "darwin":
+ assert cmd[0] == "sandbox-exec" and "deny network" in cmd[2]
+ # EN: ok=False is equally valid — no sandbox support on this host.
+ # FR: ok=False est tout aussi valide — pas de sandbox sur cet hôte.
+
+
+# ── PCAP writer / Écrivain PCAP ──────────────────────────────────────────────
+
+def test_pcapwriter_roundtrip():
+ """EN: Written pcap parses back — magic, version, linktype, frame
+ timestamps and payloads all intact. / FR: le pcap écrit se relit —
+ magic, version, linktype, timestamps et payloads intacts."""
+ import io
+ import struct
+ from capture.pcapwriter import write_pcap
+ buf = io.BytesIO()
+ frames = [(1700000000.5, b"\xde\xad\xbe\xef" * 8, 32),
+ (1700000001.25, b"\x01\x02" * 4, 8)]
+ write_pcap(buf, 1, frames)
+ data = buf.getvalue()
+ magic, vmaj, vmin, _tz, _sig, snap, link = struct.unpack("<IHHiIII", data[:24])
+ assert magic == 0xA1B2C3D4 and vmaj == 2 and vmin == 4 and link == 1
+ off = 24
+ for (ts, payload, wire) in frames:
+ sec, usec, incl, orig = struct.unpack("<IIII", data[off:off + 16])
+ assert sec == int(ts) and incl == len(payload) and orig == wire
+ off += 16 + incl
+ assert off == len(data)
diff --git a/backend/version.py b/backend/version.py
index 3d8da55..f016669 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.3.0"
+__version__ = "1.4.0"
diff --git a/contrib/macos-filter/FilterDataProvider.swift b/contrib/macos-filter/FilterDataProvider.swift
new file mode 100644
index 0000000..08b45cb
--- /dev/null
+++ b/contrib/macos-filter/FilterDataProvider.swift
@@ -0,0 +1,95 @@
+//
+// FilterDataProvider.swift
+// Snitch macOS content-filter skeleton — research only, NOT shipped.
+//
+// EN: Minimal NEFilterDataProvider showing where Snitch verdicts would
+// land. Every new flow arrives in handleNewFlow(_:); you map the
+// flow's sourceAppAuditToken to a process, look it up in the rule
+// set pushed by the Snitch backend (over XPC — that transport is
+// the real work, not shown here), and return a verdict.
+//
+// Requires: Apple Developer account, the
+// com.apple.developer.networking.networkextension entitlement
+// with "content-filter", a system-extension host app, and user
+// approval in System Settings → Network Filters.
+//
+// References: Apple SimpleFirewall (WWDC), elastic/endpoint,
+// NuAppFirewall (GPL-2.0 — reference only).
+//
+// FR: NEFilterDataProvider minimal montrant où les verdicts Snitch
+// arriveraient. Chaque nouveau flux passe par handleNewFlow(_:) ;
+// on mappe sourceAppAuditToken vers un processus, on consulte les
+// règles poussées par le backend Snitch (via XPC — non montré), et
+// on renvoie un verdict.
+//
+// Requiert : compte Apple Developer, entitlement content-filter,
+// app hôte system-extension, approbation utilisateur.
+//
+
+import NetworkExtension
+
+/// EN: Rule snapshot shared with the Snitch backend — in a real build
+/// this is fed over XPC and hot-swapped on policy change.
+/// FR: Instantané de règles partagé avec le backend — dans un vrai
+/// build il arrive par XPC et est remplacé à chaud à chaque
+/// changement de politique.
+struct SnitchPolicy {
+ /// EN: Bundle IDs / signing identifiers allowed outbound. Empty =
+ /// allow-all skeleton behaviour.
+ /// FR: Identifiants autorisés en sortie. Vide = comportement
+ /// squelette tout-autoriser.
+ var blockedHosts: Set<String> = []
+ var lockdown: Bool = false
+}
+
+final class FilterDataProvider: NEFilterDataProvider {
+
+ private var policy = SnitchPolicy()
+
+ // EN: Provider lifecycle — bring up your XPC listener and load the
+ // last-known policy here, BEFORE flows start arriving.
+ // FR: Cycle de vie — monter l'écouteur XPC et charger la dernière
+ // politique connue ici, AVANT l'arrivée des flux.
+ override func startFilter(completionHandler: @escaping (Error?) -> Void) {
+ completionHandler(nil)
+ }
+
+ override func stopFilter(with reason: NEProviderStopReason,
+ completionHandler: @escaping () -> Void) {
+ completionHandler()
+ }
+
+ // EN: THE decision point — called for every new socket flow covered
+ // by the filter's NEFilterSettings. Must stay fast; expensive
+ // attribution work belongs in `.pause()` → async → `.resume()`
+ // (see Apple's flow-pause pattern).
+ // FR: LE point de décision — appelé pour chaque nouveau flux couvert
+ // par les NEFilterSettings. Doit rester rapide ; le travail
+ // d'attribution coûteux passe par `.pause()` → async → `.resume()`.
+ override func handleNewFlow(_ flow: NEFilterFlow,
+ completionHandler: @escaping (NEFilterNewFlowVerdict) -> Void) {
+ guard let socketFlow = flow as? NEFilterSocketFlow,
+ let remote = socketFlow.remoteEndpoint as? NWHostEndpoint else {
+ completionHandler(.allow())
+ return
+ }
+
+ // EN: Per-app verdict — sourceAppAuditToken identifies the
+ // originating process (NSRunningApplication / proc_pidinfo
+ // resolves it). Skeleton only demonstrates the hook.
+ // FR: Verdict par app — sourceAppAuditToken identifie le
+ // processus d'origine (résolu via NSRunningApplication /
+ // proc_pidinfo). Le squelette ne montre que le point d'ancrage.
+ _ = socketFlow.sourceAppAuditToken
+
+ if policy.lockdown {
+ completionHandler(.drop())
+ return
+ }
+ if policy.blockedHosts.contains(remote.hostname.lowercased()) {
+ completionHandler(.drop())
+ return
+ }
+ completionHandler(.allow())
+ }
+}
diff --git a/contrib/macos-filter/README.md b/contrib/macos-filter/README.md
new file mode 100644
index 0000000..f0d5ebe
--- /dev/null
+++ b/contrib/macos-filter/README.md
@@ -0,0 +1,91 @@
+# Snitch macOS content filter — skeleton
+
+[English](#english) · [Français](#français)
+
+---
+
+## English
+
+This directory contains a **reference skeleton** for a NetworkExtension
+`NEFilterDataProvider` — the only Apple-supported way to filter
+**outbound** traffic per-application on macOS. Snitch's built-in
+enforcement uses `pf` (destination-level, not process-aware); this
+extension is what real per-app outbound control would require.
+
+### Honest status
+
+**Scaffolding, not a shipping component.** To actually run this you need:
+
+- A paid **Apple Developer** account (the Network Extension entitlements
+ `com.apple.developer.networking.networkextension` with
+ `content-filter` are entitlement-gated).
+- A **system extension** host app + activation flow (`OSSystemExtensionRequest`),
+ notarization for distribution outside the App Store, and — on macOS —
+ user approval in System Settings → Network Filters.
+- `NEFilterDataProvider` decisions are per-flow verdicts
+ (`allow`/`drop`/`filterRules`); Snitch's user-mode rule engine would
+ feed verdicts over XPC to this provider.
+
+Verified alternative assessment: `socketfilterfw` (Application Firewall)
+only filters **inbound** connections — it cannot do per-app outbound.
+There is no user-mode equivalent.
+
+### Authoritative references
+
+- Apple `SimpleFirewall` sample (WWDC) → `cntrump/SimpleFirewall` mirror
+- Apple `SimpleTunnel` → `partyspy/SimpleTunnel` (NE packaging flow)
+- `elastic/endpoint` — a real `NEFilterDataProvider` in production
+- `nufuturo-ufcg/NuAppFirewall` — a full open-source macOS firewall built
+ on this API (**GPL-2.0** — reference only, do not copy code into this
+ AGPL project without a licence review)
+
+### Shape
+
+`FilterDataProvider.swift` shows the two decision points:
+
+- `handleNewFlow(_:)` — inspect `flow.remoteEndpoint` + the audit-token
+ → process mapping, return a `NEFilterNewFlowVerdict`.
+- Rule updates arrive over XPC from the Snitch backend (not shown —
+ that transport is the real work).
+
+---
+
+## Français
+
+Ce répertoire contient un **squelette de référence** pour un
+`NEFilterDataProvider` NetworkExtension — la seule voie prise en charge
+par Apple pour filtrer le trafic **sortant** par application sur macOS.
+L'application des règles intégrée de Snitch utilise `pf` (au niveau
+destination, sans notion de processus) ; cette extension est ce que le
+contrôle sortant par-app réel exigerait.
+
+### État honnête
+
+**Échafaudage, pas un composant livré.** Pour l'exécuter réellement il
+faut :
+
+- Un compte **Apple Developer** payant (les entitlements
+ `com.apple.developer.networking.networkextension` avec
+ `content-filter` sont restreints).
+- Une app hôte **system extension** + le flux d'activation
+ (`OSSystemExtensionRequest`), la notarization, et l'approbation
+ utilisateur dans Réglages Système → Filtres réseau.
+- Les verdicts `NEFilterDataProvider` sont par flux
+ (`allow`/`drop`) ; le moteur de règles Snitch les alimenterait via XPC.
+
+Alternative vérifiée : `socketfilterfw` (pare-feu applicatif) ne filtre
+que l'**entrant** — aucun équivalent user-mode pour le sortant par-app.
+
+### Références
+
+- Sample Apple `SimpleFirewall` (WWDC) → miroir `cntrump/SimpleFirewall`
+- `partyspy/SimpleTunnel` (flux packaging NE)
+- `elastic/endpoint` — vrai `NEFilterDataProvider` en production
+- `nufuturo-ufcg/NuAppFirewall` — pare-feu macOS complet sur cette API
+ (**GPL-2.0** — référence seulement, ne pas copier dans ce projet AGPL)
+
+### Structure
+
+`FilterDataProvider.swift` montre le point de décision
+`handleNewFlow(_:)` : inspecter `flow.remoteEndpoint` + le mapping
+audit-token → processus, puis renvoyer un verdict.
diff --git a/contrib/snitch-contain b/contrib/snitch-contain
new file mode 100755
index 0000000..950fbf1
--- /dev/null
+++ b/contrib/snitch-contain
@@ -0,0 +1,45 @@
+#!/bin/sh
+# Snitch — network-denial detonation wrapper / exécution sans réseau.
+#
+# EN: Run a suspect binary with ZERO network egress so you can observe
+# what it does (files it touches, domains it tries — they all fail)
+# without letting anything out. This is the manual twin of
+# POST /security/sandbox.
+#
+# Linux : unprivileged user+network namespace (unshare -U -n) — the
+# child sees only loopback. Needs a kernel with unprivileged
+# userns enabled (default on most distros; Debian disables it,
+# see kernel.unprivileged_userns_clone).
+# macOS : sandbox-exec seatbelt profile (deny network*) — deprecated
+# by Apple but still enforced on current releases.
+#
+# Usage: ./snitch-contain /path/to/binary [args...]
+#
+# FR: Exécuter un binaire suspect avec ZERO égress réseau pour observer
+# son comportement sans rien laisser sortir — le pendant manuel de
+# POST /security/sandbox. Linux : namespace utilisateur+réseau non
+# privilégié (l'enfant ne voit que loopback). macOS : profil seatbelt
+# deny-network. Usage : ./snitch-contain /chemin/binaire [args...]
+
+set -eu
+
+if [ $# -lt 1 ]; then
+ echo "usage: $0 /path/to/binary [args...]" >&2
+ exit 64
+fi
+BIN="$1"; shift
+
+case "$(uname -s)" in
+ Linux)
+ exec unshare --user --net --map-root-user --fork "$BIN" "$@"
+ ;;
+ Darwin)
+ exec sandbox-exec -p \
+ "(version 1)(allow default)(deny network*)(deny network-bind)(deny network-outbound)(deny network-inbound)" \
+ "$BIN" "$@"
+ ;;
+ *)
+ echo "snitch-contain: no user-mode network sandbox on $(uname -s)" >&2
+ exit 65
+ ;;
+esac
diff --git a/contrib/wfp-callout/README.md b/contrib/wfp-callout/README.md
new file mode 100644
index 0000000..8fe1071
--- /dev/null
+++ b/contrib/wfp-callout/README.md
@@ -0,0 +1,97 @@
+# Snitch WFP kernel callout — skeleton
+
+[English](#english) · [Français](#français)
+
+---
+
+## English
+
+This directory contains a **reference skeleton** for a real Windows
+Filtering Platform kernel callout driver — the piece the user-mode
+`fwpuclnt.dll` filters in `backend/detection/wfp.py` deliberately are
+*not*. A callout runs inside the kernel's classify path and can inspect,
+block, or modify traffic per-connection with guarantees user-mode
+filters cannot give.
+
+### Honest status
+
+**This is scaffolding, not a production driver.** It compiles against
+the WDK and registers/unregisters a callout correctly, but:
+
+- It does **not** ship in Snitch releases. Snitch's Windows enforcement
+ today is the user-mode WFP filter layer — no driver required.
+- A real callout driver must be **signed**: test-signed for your own
+ machine (`bcdedit /set testsigning on` + a self-signed cert), or
+ attestation/EV-signed for distribution. Unsigned drivers do not load
+ on retail Windows.
+- The classify callback here only permits traffic — deciding *what* to
+ block is policy, and policy belongs in user mode where Snitch rules
+ already live.
+
+### Authoritative references (read before writing callout code)
+
+- Microsoft `Windows-driver-samples` → `network/trans/inspect`
+ (the canonical traffic-inspection callout: classify → clone →
+ block → inject-later pattern)
+- `JaredWright/WFPStarterKit` — a minimal ~100-line callout that is
+ much easier to learn from than the full sample
+- `docs.microsoft.com` WFP architecture docs: callouts, layers
+ (`FWPS_LAYER_ALE_AUTH_CONNECT_V4` is the layer Snitch cares about —
+ outbound connect authorization), filter conditions
+
+### Build (for research only)
+
+1. Install Visual Studio + the WDK (matching SDK/WDK versions).
+2. Add this `callout.c` to a **KMDF/Empty WDM driver** project — or
+ simpler, start from `WFPStarterKit`'s project and replace its
+ classify body.
+3. Test-sign, enable `testsigning`, `sc create` / `sc start`.
+4. Register the callout at `FWPS_LAYER_ALE_AUTH_CONNECT_V4`, then add a
+ user-mode filter referencing it (`FWPM_FILTER` with
+ `providerContext`/`calloutKey`) from `fwpuclnt.dll` — the same DLL
+ `backend/detection/wfp.py` already drives.
+
+---
+
+## Français
+
+Ce répertoire contient un **squelette de référence** pour un vrai
+pilote callout WFP noyau — la pièce que les filtres user-mode
+`fwpuclnt.dll` de `backend/detection/wfp.py` ne sont *volontairement
+pas*. Un callout s'exécute dans le chemin de classification du noyau et
+peut inspecter, bloquer ou modifier le trafic par connexion avec des
+garanties qu'un filtre user-mode ne donne pas.
+
+### État honnête
+
+**C'est un échafaudage, pas un pilote de production.** Il compile avec
+le WDK et enregistre/désenregistre un callout correctement, mais :
+
+- Il n'est **pas** livré dans les releases Snitch. L'application des
+ règles Windows aujourd'hui = la couche de filtres WFP user-mode — sans
+ pilote.
+- Un vrai pilote callout exige une **signature** : test-signing sur sa
+ propre machine (`bcdedit /set testsigning on` + certificat
+ auto-signé), ou signature attestation/EV pour distribuer. Windows
+ retail refuse les pilotes non signés.
+- Le callback ici ne fait qu'autoriser — décider *quoi* bloquer est de
+ la politique, et la politique appartient au user-mode où vivent déjà
+ les règles Snitch.
+
+### Références autorisées (à lire avant d'écrire un callout)
+
+- `Windows-driver-samples` de Microsoft → `network/trans/inspect`
+- `JaredWright/WFPStarterKit` — callout minimal ~100 lignes
+- Documentation WFP Microsoft : callouts, couches
+ (`FWPS_LAYER_ALE_AUTH_CONNECT_V4` est celle qui intéresse Snitch —
+ autorisation de connexion sortante)
+
+### Build (recherche uniquement)
+
+1. Visual Studio + WDK (versions SDK/WDK concordantes).
+2. Ajouter `callout.c` à un projet pilote WDM vide — ou partir de
+ `WFPStarterKit` et remplacer le corps de classify.
+3. Test-signer, activer `testsigning`, `sc create` / `sc start`.
+4. Enregistrer le callout sur `FWPS_LAYER_ALE_AUTH_CONNECT_V4`, puis
+ ajouter un filtre user-mode qui le référence depuis `fwpuclnt.dll` —
+ la même DLL que `backend/detection/wfp.py` pilote déjà.
diff --git a/contrib/wfp-callout/callout.c b/contrib/wfp-callout/callout.c
new file mode 100644
index 0000000..f681221
--- /dev/null
+++ b/contrib/wfp-callout/callout.c
@@ -0,0 +1,179 @@
+/*
+ * Snitch — WFP kernel callout skeleton (research only, NOT shipped).
+ *
+ * EN: Minimal WFP callout registration for the ALE_AUTH_CONNECT_V4 layer —
+ * the outbound-connect authorization point. The classify callback here
+ * PERMITS everything: deciding what to block is policy, and Snitch
+ * policy lives in user mode (backend/detection/wfp.py drives
+ * fwpuclnt.dll). This file shows the register → classify → unregister
+ * skeleton that Microsoft's network/trans/inspect sample and
+ * JaredWright/WFPStarterKit implement in full.
+ *
+ * Build: WDK KMDF/WDM driver project; test-sign for your own machine
+ * (bcdedit /set testsigning on), attestation/EV signing for
+ * distribution. An unsigned driver will not load on retail Windows.
+ *
+ * FR: Enregistrement minimal d'un callout WFP sur la couche
+ * ALE_AUTH_CONNECT_V4 — le point d'autorisation de connexion sortante.
+ * Le callback classify AUTORISE tout : la politique vit en user-mode.
+ * Compile avec le WDK ; signature de test exigée pour charger.
+ */
+
+#include <ntddk.h>
+
+/* EN: WFP headers ship in the WDK under km/ — fwpkclnt for the kernel
+ * callout API, fwpsk for the layer/sublayer GUIDs.
+ * FR: Les en-têtes WFP du WDK sous km/ — fwpkclnt pour l'API callout
+ * noyau, fwpsk pour les GUID de couches. */
+#include <fwpvi.h>
+#include <fwpsk.h>
+#include <fwpmk.h>
+#include <fwpkclnt.h>
+
+/* EN: Callout GUID — a real driver generates its own with uuidgen and
+ * keeps it stable across releases. This is a placeholder.
+ * FR: GUID du callout — un vrai pilote génère le sien avec uuidgen et le
+ * garde stable entre versions. Placeholder ici. */
+// {5fb216a0-0000-0000-0000-000000000001}
+static const GUID SNITCH_CALLOUT_KEY = {
+ 0x5fb216a0, 0x0000, 0x0000,
+ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}
+};
+
+static PDEVICE_OBJECT g_device = NULL;
+static UINT32 g_callout_id = 0; /* EN: runtime id chosen by WFP / FR: id choisi par WFP */
+
+/* EN: classifyFn — called in the kernel datapath for every connection the
+ * registered callout's filters match. MUST be fast and non-blocking;
+ * real decisions are either immediate (permit/block via
+ * classifyOut->actionType) or pended via clone-block-reinject (see the
+ * inspect sample). We permit everything.
+ * FR: classifyFn — appelé dans le chemin données noyau pour chaque
+ * connexion matchée. DOIT être rapide et non bloquant ; les vraies
+ * décisions sont immédiates (permit/block) ou différées via
+ * clone-block-reinject (cf. sample inspect). Ici on autorise tout. */
+static void NTAPI
+SnitchClassify(
+ _In_ const FWPS_INCOMING_VALUES *fixedValues,
+ _In_ const FWPS_INCOMING_METADATA_VALUES *metaValues,
+ _Inout_opt_ void *layerData,
+ _In_opt_ const void *classifyContext,
+ _In_ const FWPS_FILTER *filter,
+ _In_ UINT64 flowContext,
+ _Inout_ FWPS_CLASSIFY_OUT *classifyOut)
+{
+ UNREFERENCED_PARAMETER(fixedValues);
+ UNREFERENCED_PARAMETER(metaValues);
+ UNREFERENCED_PARAMETER(layerData);
+ UNREFERENCED_PARAMETER(classifyContext);
+ UNREFERENCED_PARAMETER(filter);
+ UNREFERENCED_PARAMETER(flowContext);
+
+ /* EN: Honest skeleton — the right to hard-permit must be claimed
+ * before setting actionType.
+ * FR: Squelette honnête — le droit d'écrire la décision doit être
+ * revendiqué avant de fixer actionType. */
+ if (classifyOut->rights & FWPS_RIGHT_ACTION_WRITE) {
+ classifyOut->actionType = FWP_ACTION_PERMIT;
+ }
+}
+
+/* EN: notifyFn — WFP lifecycle notifications for filters that reference
+ * this callout. / FR: notifyFn — notifications de cycle de vie des
+ * filtres référençant ce callout. */
+static NTSTATUS NTAPI
+SnitchNotify(
+ _In_ FWPS_CALLOUT_NOTIFY_TYPE notifyType,
+ _In_ const GUID *filterKey,
+ _Inout_ FWPS_FILTER *filter)
+{
+ UNREFERENCED_PARAMETER(notifyType);
+ UNREFERENCED_PARAMETER(filterKey);
+ UNREFERENCED_PARAMETER(filter);
+ return STATUS_SUCCESS;
+}
+
+/* EN: flowDeleteFn — mandatory even with no per-flow state.
+ * FR: flowDeleteFn — obligatoire même sans état par flux. */
+static void NTAPI
+SnitchFlowDelete(
+ _In_ UINT16 layerId,
+ _In_ UINT32 calloutId,
+ _In_ UINT64 flowContext)
+{
+ UNREFERENCED_PARAMETER(layerId);
+ UNREFERENCED_PARAMETER(calloutId);
+ UNREFERENCED_PARAMETER(flowContext);
+}
+
+static NTSTATUS
+SnitchRegisterCallout(_In_ PDEVICE_OBJECT device)
+{
+ FWPS_CALLOUT callout = {0};
+
+ callout.calloutKey = SNITCH_CALLOUT_KEY;
+ callout.flags = 0;
+ callout.classifyFn = SnitchClassify;
+ callout.notifyFn = SnitchNotify;
+ callout.flowDeleteFn = SnitchFlowDelete;
+
+ return FwpsCalloutRegister(device, &callout, &g_callout_id);
+}
+
+static void
+SnitchUnregisterCallout(void)
+{
+ /* EN: Removes the callout object AND every filter still referencing
+ * it — safe teardown order matters (callout id vs key form).
+ * FR: Retire le callout ET tous les filtres qui le référencent —
+ * l'ordre de démontage compte. */
+ FwpsCalloutUnregisterById(g_callout_id);
+}
+
+static void NTAPI
+SnitchUnload(_In_ PDRIVER_OBJECT driver)
+{
+ UNREFERENCED_PARAMETER(driver);
+ SnitchUnregisterCallout();
+ if (g_device != NULL) {
+ IoDeleteDevice(g_device);
+ g_device = NULL;
+ }
+}
+
+NTSTATUS NTAPI
+DriverEntry(
+ _In_ PDRIVER_OBJECT driver,
+ _In_ PUNICODE_STRING registryPath)
+{
+ NTSTATUS status;
+ UNICODE_STRING name;
+
+ UNREFERENCED_PARAMETER(registryPath);
+
+ driver->DriverUnload = SnitchUnload;
+
+ RtlInitUnicodeString(&name, L"\\Device\\SnitchCallout");
+ status = IoCreateDevice(driver, 0, &name, FILE_DEVICE_UNKNOWN,
+ 0, FALSE, &g_device);
+ if (!NT_SUCCESS(status)) {
+ return status;
+ }
+
+ status = SnitchRegisterCallout(g_device);
+ if (!NT_SUCCESS(status)) {
+ IoDeleteDevice(g_device);
+ g_device = NULL;
+ return status;
+ }
+
+ /* EN: Registration alone does nothing — a user-mode FWPM_FILTER on
+ * FWPS_LAYER_ALE_AUTH_CONNECT_V4 must reference this callout's key
+ * (action.calloutKey) before classifyFn ever fires. That part is
+ * the user-mode side backend/detection/wfp.py would grow.
+ * FR: L'enregistrement seul ne fait rien — un FWPM_FILTER user-mode
+ * sur FWPS_LAYER_ALE_AUTH_CONNECT_V4 doit référencer la clé de ce
+ * callout pour que classifyFn soit invoqué. C'est la partie
+ * user-mode que backend/detection/wfp.py ferait croître. */
+ return STATUS_SUCCESS;
+}
diff --git a/docs/FIREWALL.de.md b/docs/FIREWALL.de.md
index 31963b3..126d3c6 100644
--- a/docs/FIREWALL.de.md
+++ b/docs/FIREWALL.de.md
@@ -104,3 +104,15 @@ Alle sind **standardmäßig aus oder selbstlimitierend**, degradieren ehrlich un
- **Hardware-Zähler** — `POST /security/perf` sampelt Zyklen/Instruktionen via `perf_event_open` (Linux).
- **Lokales LLM** — opt-in (`slm_enabled`): `/security/explain` ruft einen Ollama-Endpunkt **nur Loopback** — Remote-Endpunkte abgelehnt.
- **IOC-Pakete** — `GET /security/iocpack` exportiert Bloom + randomized response (nie Klartext); `POST /security/iocpack/import` prüft Ziele probabilistisch.
+
+### Policy- & Reaktions-Neuerungen (v1.4)
+
+- **Benannte Profile** — `POST /firewall/profile`: `permissive` (sauberer Tisch), `balanced` (vorsichtige Egress-Basis) oder `strict` (Basis + Lockdown); werden mit Dedup in gewöhnliche Regeln ausgerollt.
+- **Eigene Alarmregeln** — `GET/POST/DELETE /alerts/rules`: Feld + Operator + Wert → `CUSTOM_RULE`-Alarme (nur Alarm, nie Blockierung).
+- **Blocklisten-Import** — `POST /firewall/blocklist`: lokale Datei (rein lokal) oder opt-in URL (HTTPS-Fetch ≤4 MiB, als `remote_fetch` markiert) → `domain`-Regeln, dedupliziert, Limit 500–5000.
+- **PCAP-Export** — `GET /forensics/pcap` (Filter `ip`/`process`): ~4-MiB-Ringpuffer als Wireshark-`.pcap`.
+- **Fernkopplung** — `POST /remote/pairing` persistiert `lan_bind` für den nächsten Start; Token bleibt Pflicht. `GET /remote/pairing` meldet Bind + LAN-IPs.
+- **Sandbox ohne Netzwerk** — `POST /security/sandbox` führt Binärdateien mit null Egress aus (`unshare -n` Linux, `sandbox-exec` macOS; `contrib/snitch-contain` manuell).
+- **Eingebettetes Modell** — `slm_mode=embedded` lädt ein Nutzer-`.gguf` via `llama-cpp-python` — null Netzwerk.
+- **Native Skelette** — `contrib/wfp-callout/` (WFP-Callout in C + Signierung) und `contrib/macos-filter/` (`NEFilterDataProvider` Swift + Entitlements): Forschungs-Scaffolding, nicht ausgeliefert.
+- **ASN** — mit `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb` tragen Knoten `asn` neben `org`.
diff --git a/docs/FIREWALL.es.md b/docs/FIREWALL.es.md
index a417cf3..71339f8 100644
--- a/docs/FIREWALL.es.md
+++ b/docs/FIREWALL.es.md
@@ -105,3 +105,15 @@ Todas están **desactivadas por defecto o se autolimitan**, degradan honestament
- **Contadores hardware** — `POST /security/perf` muestrea ciclos/instrucciones vía `perf_event_open` (Linux).
- **LLM local** — opt-in (`slm_enabled`): `/security/explain` llama a un endpoint Ollama **solo loopback** — endpoints remotos rechazados.
- **Paquetes IOC** — `GET /security/iocpack` exporta un Bloom + randomized response (nunca en claro); `POST /security/iocpack/import` comprueba destinos de forma probabilística.
+
+### Novedades de política y respuesta (v1.4)
+
+- **Perfiles nombrados** — `POST /firewall/profile`: `permissive` (tabla rasa), `balanced` (base de salida prudente) o `strict` (base + lockdown); se expanden en reglas ordinarias con deduplicación.
+- **Reglas de alerta personalizadas** — `GET/POST/DELETE /alerts/rules`: campo + operador + valor → alertas `CUSTOM_RULE` (solo alerta, nunca bloquea).
+- **Importar blocklist** — `POST /firewall/blocklist`: archivo local (local puro) o URL opt-in (fetch HTTPS ≤4 MiB, señalado `remote_fetch`) → reglas `domain`, deduplicadas, tope 500–5000.
+- **Export PCAP** — `GET /forensics/pcap` (filtros `ip`/`process`): anillo de tramas ~4 MiB como `.pcap` para Wireshark.
+- **Emparejamiento remoto** — `POST /remote/pairing` persiste `lan_bind` para el próximo inicio; el token sigue obligatorio. `GET /remote/pairing` reporta bind + IPs LAN.
+- **Sandbox sin red** — `POST /security/sandbox` ejecuta un binario con cero egress (`unshare -n` Linux, `sandbox-exec` macOS; `contrib/snitch-contain` manual).
+- **Modelo embebido** — `slm_mode=embedded` carga un `.gguf` del usuario vía `llama-cpp-python` — cero red.
+- **Esqueletos nativos** — `contrib/wfp-callout/` (callout WFP en C + firma) y `contrib/macos-filter/` (`NEFilterDataProvider` Swift + entitlements): scaffolding de investigación, no se distribuyen.
+- **ASN** — con `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb`, los nodos llevan `asn` además de `org`.
diff --git a/docs/FIREWALL.ja.md b/docs/FIREWALL.ja.md
index 0254e24..f276d48 100644
--- a/docs/FIREWALL.ja.md
+++ b/docs/FIREWALL.ja.md
@@ -102,3 +102,15 @@ OS ネイティブファイアウォールへ best-effort で適用されます:
- **ハードウェアカウンタ** — `POST /security/perf` が `perf_event_open` でサイクル/命令数をサンプル (Linux)。
- **ローカル LLM** — opt-in(`slm_enabled`):`/security/explain` は Ollama 互換エンドポイントを **loopback のみ** 呼び出し — リモートは拒否。
- **IOC パック** — `GET /security/iocpack` が Bloom + randomized response でエクスポート(平文なし);`POST /security/iocpack/import` が宛先を確率的に照合。
+
+### ポリシー&レスポンスの追加 (v1.4)
+
+- **名前付きプロファイル** — `POST /firewall/profile`: `permissive`(初期化)、`balanced`(控えめな送信ベースライン)、`strict`(ベースライン+ロックダウン)。通常ルールに展開・重複排除。
+- **カスタムアラートルール** — `GET/POST/DELETE /alerts/rules`: フィールド+演算子+値 → `CUSTOM_RULE` アラート(通知のみ、ブロックなし)。
+- **ブロックリストのインポート** — `POST /firewall/blocklist`: ローカルファイル(完全ローカル)またはオプトイン URL(≤4 MiB HTTPS、`remote_fetch` と明記)→ `domain` ルール。重複排除・上限 500–5000。
+- **PCAP エクスポート** — `GET /forensics/pcap`(`ip`/`process` フィルタ): ~4 MiB リングバッファを Wireshark 用 `.pcap` で。
+- **リモートペアリング** — `POST /remote/pairing` が `lan_bind` を永続化(次回起動時適用);トークンは引き続き必須。`GET /remote/pairing` が bind と LAN IP を報告。
+- **ネットワーク遮断サンドボックス** — `POST /security/sandbox` がバイナリを送信ゼロで実行(Linux `unshare -n`、macOS `sandbox-exec`;手動版 `contrib/snitch-contain`)。
+- **埋め込みモデル** — `slm_mode=embedded` がユーザーの `.gguf` を `llama-cpp-python` で読込 — ネットワーク一切なし。
+- **ネイティブスケルトン** — `contrib/wfp-callout/`(C の WFP callout+署名メモ)と `contrib/macos-filter/`(`NEFilterDataProvider` Swift+entitlement メモ):研究用スキャフォールド、出荷なし。
+- **ASN** — `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb` がある場合、ノードに `org` に加え `asn` を付与。
diff --git a/docs/FIREWALL.md b/docs/FIREWALL.md
index 1d56f3e..855adb9 100644
--- a/docs/FIREWALL.md
+++ b/docs/FIREWALL.md
@@ -168,7 +168,52 @@ never ship data off the machine:
- **IOC packs** — `GET /security/iocpack` exports indicators as a Bloom
filter + randomized response (ε≈4.6 — deniable, never raw);
`POST /security/iocpack/import` checks observed destinations against a
- received pack, probabilistically, and never auto-blocks.
+ received pack, probabilistically, and never auto-blocks. A second
+ `format=proof` pack carries salted SHA-256 leaves + a Merkle
+ commitment: membership is cryptographically exact and tampering is
+ detected. Not an interactive ZK protocol — a commitment scheme.
+
+### Policy & response additions (v1.4)
+
+- **Named profiles** — `POST /firewall/profile` applies `permissive`
+ (clean slate), `balanced` (conservative egress baseline: outbound
+ SMTP + common stratum pool ports) or `strict` (baseline + lockdown).
+ Profiles expand into ordinary rules via the same machinery the UI
+ uses — no hidden code path — and dedup against identical rules.
+- **Custom alert rules** — `GET/POST/DELETE /alerts/rules` plus a
+ per-rule toggle. One field (`remote_ip`, `host`, `process_name`,
+ `remote_port`, `protocol`, `direction`, `size`), one operator
+ (`eq`, `ne`, `contains`, `regex`, `gt`, `lt`, `cidr`), one value →
+ `CUSTOM_RULE` alerts with hit counters. Validated at creation,
+ bounded regex cache, **alert-only** — blocking stays the firewall's.
+- **Blocklist import** — `POST /firewall/blocklist` turns a local
+ hosts/domain file (a pure local read) or an opt-in URL (bounded
+ 4 MiB HTTPS fetch — one of the few outbound requests Snitch can ever
+ emit, flagged `remote_fetch` in the response) into `domain` rules.
+ Deduplicated, capped 500–5000 entries.
+- **PCAP export** — `GET /forensics/pcap` (optional `ip=`/`process=`
+ filters) serves the bounded ~4 MiB raw-frame ring as a
+ Wireshark-ready `.pcap` with real capture timestamps.
+- **Remote pairing** — `POST /remote/pairing` persists `lan_bind`
+ (`0.0.0.0` or a local LAN address) applied at the *next* backend
+ start — uvicorn cannot rebind a live socket, and the API says so.
+ Token auth remains mandatory; pairing only widens the listen
+ address. `GET /remote/pairing` reports effective bind + LAN IPs.
+- **Network-denial sandbox** — `POST /security/sandbox {path,seconds}`
+ runs a chosen executable with **zero egress**: unprivileged
+ `unshare --user --net` on Linux, `sandbox-exec` deny-network on
+ macOS. Bounded runtime + output; honest unsupported-error elsewhere.
+ `contrib/snitch-contain` is the manual equivalent.
+- **Embedded model** — `slm_mode=embedded` loads a user-provided
+ `.gguf` via optional `llama-cpp-python` — explanations fully
+ in-process, zero network. Snitch never downloads weights.
+- **Native filter skeletons** — `contrib/wfp-callout/` (C WFP kernel
+ callout + signing notes) and `contrib/macos-filter/` (Swift
+ `NEFilterDataProvider` + entitlements notes). Research scaffolding
+ for anyone who wants to build the signed/platform components;
+ not shipped, not loaded by Snitch.
+- **ASN attribution** — when `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb`
+ is present, nodes carry `asn` (AS number) alongside `org`.
---
@@ -346,3 +391,49 @@ honnêtement et n'envoient jamais de données hors de la machine :
filtre de Bloom + randomized response (ε≈4,6 — déni plausible, jamais
en clair) ; `POST /security/iocpack/import` confronte les destinations
observées à un paquet reçu, en probabiliste, sans blocage automatique.
+ Un second format `format=proof` porte des feuilles SHA-256 salées +
+ un engagement Merkle : appartenance cryptographiquement exacte et
+ falsification détectée. Pas un protocole ZK — un schéma d'engagement.
+
+### Ajouts politique & réponse (v1.4)
+
+- **Profils nommés** — `POST /firewall/profile` applique `permissive`
+ (table rase), `balanced` (base sortante prudente : SMTP sortant +
+ ports de pools stratum courants) ou `strict` (base + lockdown). Les
+ profils se déplient en règles ordinaires par la même machinerie que
+ l'UI — aucun chemin caché — avec dédup des règles identiques.
+- **Règles d'alerte personnalisées** — `GET/POST/DELETE /alerts/rules`
+ + bascule par règle. Un champ (`remote_ip`, `host`, `process_name`,
+ `remote_port`, `protocol`, `direction`, `size`), un opérateur
+ (`eq`, `ne`, `contains`, `regex`, `gt`, `lt`, `cidr`), une valeur →
+ alertes `CUSTOM_RULE` avec compteurs. Validées à la création, cache
+ regex borné, **alerte seule** — le blocage reste au pare-feu.
+- **Import de blocklist** — `POST /firewall/blocklist` convertit un
+ fichier hosts/domaines local (lecture purement locale) ou une URL
+ opt-in (fetch HTTPS borné à 4 Mio — l'une des rares requêtes sortantes
+ que Snitch puisse émettre, signalée `remote_fetch`) en règles
+ `domain`. Dédupliquées, plafonnées à 500–5000 entrées.
+- **Export PCAP** — `GET /forensics/pcap` (filtres `ip=`/`process=`
+ optionnels) sert l'anneau de trames brutes ~4 Mio en `.pcap` prêt
+ pour Wireshark avec les timestamps réels de capture.
+- **Pairing distant** — `POST /remote/pairing` persiste `lan_bind`
+ (`0.0.0.0` ou une adresse LAN locale) appliqué au *prochain*
+ démarrage du backend — uvicorn ne peut re-binder un socket actif, et
+ l'API le dit. Le jeton reste obligatoire ; le pairing n'élargit que
+ l'adresse d'écoute. `GET /remote/pairing` rapporte bind + IP LAN.
+- **Sandbox sans réseau** — `POST /security/sandbox {path,seconds}`
+ exécute un binaire choisi avec **zéro égress** : `unshare
+ --user --net` non privilégié sous Linux, `sandbox-exec` deny-network
+ sous macOS. Durée + sortie bornées ; erreur honnête ailleurs.
+ `contrib/snitch-contain` est l'équivalent manuel.
+- **Modèle embarqué** — `slm_mode=embedded` charge un `.gguf` fourni
+ par l'utilisateur via `llama-cpp-python` optionnel — explications
+ entièrement en processus, zéro réseau. Snitch ne télécharge jamais
+ de poids.
+- **Squelettes de filtres natifs** — `contrib/wfp-callout/` (callout
+ WFP noyau en C + notes de signature) et `contrib/macos-filter/`
+ (`NEFilterDataProvider` Swift + notes entitlements). Échafaudage de
+ recherche pour qui veut construire les composants signés ;
+ non livrés, non chargés par Snitch.
+- **Attribution ASN** — quand `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb`
+ est présente, les nœuds portent `asn` (numéro d'AS) en plus de `org`.
diff --git a/docs/FIREWALL.pt-BR.md b/docs/FIREWALL.pt-BR.md
index 7e4a386..0ea7a7c 100644
--- a/docs/FIREWALL.pt-BR.md
+++ b/docs/FIREWALL.pt-BR.md
@@ -106,3 +106,15 @@ Todas estão **desativadas por padrão ou autolimitadas**, degradam honestamente
- **Contadores de hardware** — `POST /security/perf` amostra ciclos/instruções via `perf_event_open` (Linux).
- **LLM local** — opt-in (`slm_enabled`): `/security/explain` chama um endpoint Ollama **somente loopback** — endpoints remotos rejeitados.
- **Pacotes IOC** — `GET /security/iocpack` exporta Bloom + randomized response (nunca em claro); `POST /security/iocpack/import` verifica destinos probabilisticamente.
+
+### Novidades de política e resposta (v1.4)
+
+- **Perfis nomeados** — `POST /firewall/profile`: `permissive` (tábua rasa), `balanced` (base de saída prudente) ou `strict` (base + lockdown); expandem em regras comuns com deduplicação.
+- **Regras de alerta personalizadas** — `GET/POST/DELETE /alerts/rules`: campo + operador + valor → alertas `CUSTOM_RULE` (só alerta, nunca bloqueia).
+- **Importar blocklist** — `POST /firewall/blocklist`: arquivo local (leitura puramente local) ou URL opt-in (fetch HTTPS ≤4 MiB, marcado `remote_fetch`) → regras `domain`, deduplicadas, teto 500–5000.
+- **Exportar PCAP** — `GET /forensics/pcap` (filtros `ip`/`process`): anel de ~4 MiB como `.pcap` para Wireshark.
+- **Pareamento remoto** — `POST /remote/pairing` persiste `lan_bind` para a próxima inicialização; token continua obrigatório. `GET /remote/pairing` reporta bind + IPs da LAN.
+- **Sandbox sem rede** — `POST /security/sandbox` executa um binário com egress zero (`unshare -n` Linux, `sandbox-exec` macOS; `contrib/snitch-contain` manual).
+- **Modelo embutido** — `slm_mode=embedded` carrega um `.gguf` do usuário via `llama-cpp-python` — zero rede.
+- **Esqueletos nativos** — `contrib/wfp-callout/` (callout WFP em C + assinatura) e `contrib/macos-filter/` (`NEFilterDataProvider` Swift + entitlements): scaffolding de pesquisa, não distribuídos.
+- **ASN** — com `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb`, os nós carregam `asn` além de `org`.
diff --git a/docs/FIREWALL.ru.md b/docs/FIREWALL.ru.md
index 6bc9768..aa74328 100644
--- a/docs/FIREWALL.ru.md
+++ b/docs/FIREWALL.ru.md
@@ -103,3 +103,15 @@ endpoint'ы получают `{alert, source, text}`. Сбои пишутся в
- **Аппаратные счётчики** — `POST /security/perf` сэмплирует циклы/инструкции через `perf_event_open` (Linux).
- **Локальный LLM** — opt-in (`slm_enabled`): `/security/explain` вызывает Ollama-эндпоинт **только loopback** — удалённые отклоняются.
- **Пакеты IOC** — `GET /security/iocpack` экспортирует Bloom + randomized response (не в открытом виде); `POST /security/iocpack/import` проверяет цели вероятностно.
+
+### Новинки политики и реагирования (v1.4)
+
+- **Именные профили** — `POST /firewall/profile`: `permissive` (чистый лист), `balanced` (осторожная база исходящих) или `strict` (база + lockdown); разворачиваются в обычные правила с дедупликацией.
+- **Свои правила алертов** — `GET/POST/DELETE /alerts/rules`: поле + оператор + значение → алерты `CUSTOM_RULE` (только алерт, никогда не блокируют).
+- **Импорт блоклистов** — `POST /firewall/blocklist`: локальный файл (чисто локально) или opt-in URL (HTTPS-запрос ≤4 МиБ, помечен `remote_fetch`) → правила `domain`, дедупликация, лимит 500–5000.
+- **Экспорт PCAP** — `GET /forensics/pcap` (фильтры `ip`/`process`): кольцевой буфер ~4 МиБ в `.pcap` для Wireshark.
+- **Удалённое сопряжение** — `POST /remote/pairing` сохраняет `lan_bind` до следующего запуска; токен обязателен. `GET /remote/pairing` сообщает bind + LAN-адреса.
+- **Песочница без сети** — `POST /security/sandbox` запускает бинарник с нулевым egress (`unshare -n` Linux, `sandbox-exec` macOS; `contrib/snitch-contain` вручную).
+- **Встроенная модель** — `slm_mode=embedded` загружает `.gguf` пользователя через `llama-cpp-python` — ноль сети.
+- **Нативные скелеты** — `contrib/wfp-callout/` (WFP callout на C + подпись) и `contrib/macos-filter/` (`NEFilterDataProvider` Swift + entitlements): исследовательский каркас, не поставляется.
+- **ASN** — с `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb` узлы несут `asn` в дополнение к `org`.
diff --git a/docs/FIREWALL.zh-CN.md b/docs/FIREWALL.zh-CN.md
index 2ccfcb9..3c355a5 100644
--- a/docs/FIREWALL.zh-CN.md
+++ b/docs/FIREWALL.zh-CN.md
@@ -95,3 +95,15 @@ Snitch **不**在用户态过滤数据包。规则会被尽力下发到操作系
- **硬件计数器** — `POST /security/perf` 通过 `perf_event_open` 采样周期/指令数 (Linux)。
- **本地 LLM** — 可选(`slm_enabled`):`/security/explain` 调用 Ollama 兼容端点,**仅限 loopback** — 远程端点被拒绝。
- **IOC 包** — `GET /security/iocpack` 以 Bloom + randomized response 导出(绝不明文);`POST /security/iocpack/import` 概率性地检查目标。
+
+### 策略与响应新增 (v1.4)
+
+- **命名配置文件** — `POST /firewall/profile`:`permissive`(清空)、`balanced`(保守出站基线)或 `strict`(基线+锁定);展开为普通规则并去重。
+- **自定义告警规则** — `GET/POST/DELETE /alerts/rules`:字段+运算符+值 → `CUSTOM_RULE` 告警(仅告警,绝不阻断)。
+- **导入屏蔽列表** — `POST /firewall/blocklist`:本地文件(纯本地)或可选 URL(≤4 MiB HTTPS 抓取,响应标记 `remote_fetch`)→ `domain` 规则,去重,上限 500–5000。
+- **PCAP 导出** — `GET /forensics/pcap`(`ip`/`process` 过滤):~4 MiB 环形缓冲区输出为 Wireshark 可用的 `.pcap`。
+- **远程配对** — `POST /remote/pairing` 持久化 `lan_bind`(下次启动生效);令牌仍然必需。`GET /remote/pairing` 报告绑定地址与 LAN IP。
+- **无网络沙箱** — `POST /security/sandbox` 以零出站运行二进制(Linux `unshare -n`、macOS `sandbox-exec`;手动版 `contrib/snitch-contain`)。
+- **内置模型** — `slm_mode=embedded` 通过 `llama-cpp-python` 加载用户 `.gguf` — 完全零网络。
+- **原生骨架** — `contrib/wfp-callout/`(C 版 WFP callout+签名说明)与 `contrib/macos-filter/`(Swift `NEFilterDataProvider`+entitlement 说明):研究用脚手架,不随产品分发。
+- **ASN** — 存在 `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb` 时,节点除 `org` 外还带 `asn`。
diff --git a/electron/package.json b/electron/package.json
index 3ce2c92..7903c02 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch",
- "version": "1.3.0",
+ "version": "1.4.0",
"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.json
index 4f54e86..342d55b 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch-frontend",
- "version": "1.3.0",
+ "version": "1.4.0",
"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/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsx
index 6c83a8c..de65224 100644
--- a/frontend/src/components/AlertPanel.jsx
+++ b/frontend/src/components/AlertPanel.jsx
@@ -20,7 +20,7 @@ import {
Globe, WifiOff, Wifi, ScanLine,
Activity, Unlock, TrendingUp, Camera, ShieldAlert,
FileWarning, Fingerprint, Cpu, HelpCircle,
- Pickaxe, Magnet, Syringe, Package,
+ Pickaxe, Magnet, Syringe, Package, ListFilter,
} from 'lucide-react'
import { useT } from '../i18n'
import { apiBase, authHeaders } from '../api'
@@ -60,6 +60,7 @@ const TYPE_ICONS = {
MINING_SUSPECT: Pickaxe,
SINKHOLE_HIT: Magnet,
INJECT_SUSPECT: Syringe,
+ CUSTOM_RULE: ListFilter,
}
/**
diff --git a/frontend/src/components/Firewall.jsx b/frontend/src/components/Firewall.jsx
index bb584e6..dd46f93 100644
--- a/frontend/src/components/Firewall.jsx
+++ b/frontend/src/components/Firewall.jsx
@@ -52,18 +52,30 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
const [iocResult, setIocResult] = useState(null)
const [err, setErr] = useState('')
const [audit, setAudit] = useState(null)
+ const [blSource, setBlSource] = useState('path')
+ const [blValue, setBlValue] = useState('')
+ const [blAction, setBlAction] = useState('block')
+ const [blResult, setBlResult] = useState(null)
+ const [aRules, setARules] = useState([])
+ const [arName, setArName] = useState('')
+ const [arField, setArField] = useState('host')
+ const [arOp, setArOp] = useState('contains')
+ const [arValue, setArValue] = useState('')
+ const [arSev, setArSev] = useState('warning')
const refresh = useCallback(async () => {
const base = await apiBase()
const headers = await authHeaders()
try {
- const [r, s] = await Promise.all([
+ const [r, s, ar] = await Promise.all([
fetch(`${base}/firewall/rules`, { headers }).then(x => x.json()),
fetch(`${base}/firewall/status`, { headers }).then(x => x.json()),
+ fetch(`${base}/alerts/rules`, { headers }).then(x => x.json()),
])
setRules(r.rules || [])
setLockdown(!!r.lockdown)
setStatus(s)
+ setARules(ar.rules || [])
onLockdownChange?.(!!r.lockdown)
} catch { /* leave previous state */ }
}, [onLockdownChange])
@@ -172,6 +184,85 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
} catch (ex) { setErr(String(ex.message || ex)) }
}
+ /**
+ * EN: Named profiles expand to ordinary rules + lockdown state —
+ * `strict` enables lockdown, so it gets the same confirmation.
+ * FR: Les profils nommés se déplient en règles ordinaires + état
+ * lockdown — `strict` active le lockdown, donc même confirmation.
+ */
+ async function applyProfile(name) {
+ if (name === 'strict' && !lockdown
+ && !window.confirm(t('fw_lockdown_confirm'))) return
+ setErr('')
+ try {
+ await post('/firewall/profile', { name })
+ refresh()
+ } catch (ex) { setErr(String(ex.message || ex)) }
+ }
+
+ /**
+ * EN: Blocklist import — a local file is purely local; a URL is an
+ * OPT-IN outbound fetch the backend flags as `remote_fetch`.
+ * The user must opt in explicitly before we allow it.
+ * FR: Import de blocklist — un fichier local est purement local ;
+ * une URL est un fetch sortant OPT-IN que le backend signale via
+ * `remote_fetch`. Opt-in explicite exigé.
+ */
+ async function importBlocklist() {
+ setBlResult(null)
+ setErr('')
+ const body = { action: blAction, max_entries: 500 }
+ if (blSource === 'url') {
+ if (!window.confirm(t('bl_url_confirm'))) return
+ body.url = blValue.trim()
+ } else {
+ body.path = blValue.trim()
+ }
+ if (!body.url && !body.path) return
+ try {
+ setBlResult(await post('/firewall/blocklist', body))
+ setBlValue('')
+ refresh()
+ } catch (ex) { setErr(String(ex.message || ex)) }
+ }
+
+ async function addAlertRule(e) {
+ e.preventDefault()
+ if (!arValue.trim()) return
+ setErr('')
+ try {
+ await post('/alerts/rules', {
+ name: arName.trim(), field: arField, op: arOp,
+ value: arValue.trim(), severity: arSev,
+ })
+ setArName(''); setArValue('')
+ refresh()
+ } catch (ex) { setErr(String(ex.message || ex)) }
+ }
+
+ async function deleteAlertRule(id) {
+ await post(`/alerts/rules/${encodeURIComponent(id)}`, null, 'DELETE')
+ refresh()
+ }
+
+ async function exportPcap() {
+ // EN: Forensic pcap — raw frames from the bounded ring buffer,
+ // exactly what was on the wire. Same authenticated-blob pattern.
+ // FR: Pcap forensique — trames brutes du tampon borné, exactement ce
+ // qui était sur le fil. Même motif blob authentifié.
+ const base = await apiBase()
+ const res = await fetch(`${base}/forensics/pcap`,
+ { headers: await authHeaders() })
+ if (res.status === 204) { setErr(t('fw_pcap_empty')); return }
+ if (!res.ok) { setErr(res.statusText); return }
+ const blob = await res.blob()
+ const a = document.createElement('a')
+ a.href = URL.createObjectURL(blob)
+ a.download = 'snitch-capture.pcap'
+ a.click()
+ URL.revokeObjectURL(a.href)
+ }
+
const row = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '1px solid var(--bg)' }
const label = { fontSize: 12, color: 'var(--text)', fontWeight: 600 }
const hint = { fontSize: 10, color: 'var(--text-muted)', marginTop: 2 }
@@ -222,6 +313,27 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
</button>
</div>
+ {/* EN: Named profiles — one-tap policy bundles expanded into
+ ordinary rules by the backend (no hidden code path).
+ FR: Profils nommés — lots de règles en un clic dépliés par le
+ backend en règles ordinaires (aucun chemin caché). */}
+ <div style={{ ...row, borderBottom: 'none', paddingTop: 0 }}>
+ <div>
+ <div style={label}>{t('fw_profiles')}</div>
+ <div style={hint}>{t('fw_profiles_hint')}</div>
+ </div>
+ <div style={{ display: 'flex', gap: 4 }}>
+ {['permissive', 'balanced', 'strict'].map(p => (
+ <button key={p} onClick={() => applyProfile(p)} style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 5, color: p === 'strict' ? '#ef4444' : 'var(--text-muted)',
+ fontSize: 9, fontWeight: 700, padding: '4px 7px',
+ cursor: 'pointer', textTransform: 'uppercase',
+ }}>{t(`fw_profile_${p}`)}</button>
+ ))}
+ </div>
+ </div>
+
{/* EN: Platform honesty — the backend reports whether native
enforcement is available on this OS/privilege level.
FR: Honnêteté plateforme — le backend rapporte si l'application
@@ -309,6 +421,93 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
</div>
))}
+ {/* EN: Blocklist import — a local hosts/domain file is a pure
+ local read; a URL is an OPT-IN outbound fetch (confirmed
+ before sending; the response flags `remote_fetch`).
+ FR: Import de blocklist — un fichier hosts/domaines local est
+ une lecture purement locale ; une URL est un fetch
+ sortant OPT-IN (confirmé avant envoi ; `remote_fetch`
+ signalé dans la réponse). */}
+ <div style={{ borderTop: '1px solid var(--border)', marginTop: 10, paddingTop: 8 }}>
+ <div style={label}>{t('bl_title')}</div>
+ <div style={hint}>{t('bl_hint')}</div>
+ <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
+ <select value={blSource} onChange={e => setBlSource(e.target.value)} aria-label={t('bl_source')} style={{ ...input, maxWidth: 76 }}>
+ <option value="path">{t('bl_src_file')}</option>
+ <option value="url">{t('bl_src_url')}</option>
+ </select>
+ <input value={blValue} onChange={e => setBlValue(e.target.value)}
+ placeholder={blSource === 'url' ? 'https://…' : '/path/to/hosts'}
+ aria-label={t('bl_source')} style={{ ...input, flex: 1 }} />
+ <select value={blAction} onChange={e => setBlAction(e.target.value)} aria-label={t('fw_action')} style={{ ...input, maxWidth: 80 }}>
+ <option value="block">{t('fw_action_block')}</option>
+ <option value="sinkhole">{t('fw_action_sinkhole')}</option>
+ </select>
+ <button onClick={importBlocklist} disabled={!blValue.trim()} style={{
+ background: blValue.trim() ? '#3b82f6' : 'var(--bg)', border: 'none',
+ borderRadius: 6, color: blValue.trim() ? '#fff' : 'var(--text-faint)',
+ padding: '6px 10px', cursor: 'pointer', fontSize: 10, fontWeight: 700,
+ }}>{t('bl_import')}</button>
+ </div>
+ {blResult && (
+ <div style={{ ...hint, marginTop: 4 }}>
+ {t('bl_result', blResult.added, blResult.skipped)}
+ {blResult.truncated && ` · ${t('bl_truncated')}`}
+ {blResult.remote_fetch && ` · ${t('bl_remote')}`}
+ </div>
+ )}
+ </div>
+
+ {/* EN: Custom alert rules — user-defined matchers that raise
+ CUSTOM_RULE alerts (alert-only, never block).
+ FR: Règles d'alerte personnalisées — filtres définis par
+ l'utilisateur qui lèvent des alertes CUSTOM_RULE (alerte
+ seule, jamais de blocage). */}
+ <div style={{ borderTop: '1px solid var(--border)', marginTop: 10, paddingTop: 8 }}>
+ <div style={label}>{t('ar_title')}</div>
+ <div style={hint}>{t('ar_hint')}</div>
+ <form onSubmit={addAlertRule} style={{ display: 'flex', gap: 4, marginTop: 6, flexWrap: 'wrap' }}>
+ <input value={arName} onChange={e => setArName(e.target.value)}
+ placeholder={t('ar_name_ph')} aria-label={t('ar_name_ph')}
+ style={{ ...input, flex: '1 1 100%' }} />
+ <select value={arField} onChange={e => setArField(e.target.value)} aria-label={t('ar_field')} style={{ ...input }}>
+ {['remote_ip', 'host', 'process_name', 'remote_port', 'protocol', 'direction', 'size'].map(f =>
+ <option key={f} value={f}>{f}</option>)}
+ </select>
+ <select value={arOp} onChange={e => setArOp(e.target.value)} aria-label={t('ar_op')} style={{ ...input }}>
+ {['eq', 'ne', 'contains', 'regex', 'gt', 'lt', 'cidr'].map(o =>
+ <option key={o} value={o}>{o}</option>)}
+ </select>
+ <input value={arValue} onChange={e => setArValue(e.target.value)}
+ placeholder={t('ar_value_ph')} aria-label={t('ar_value_ph')}
+ style={{ ...input, flex: 1 }} />
+ <select value={arSev} onChange={e => setArSev(e.target.value)} aria-label={t('ar_sev')} style={{ ...input }}>
+ <option value="info">{t('sev_info')}</option>
+ <option value="warning">{t('sev_warning')}</option>
+ <option value="critical">{t('sev_critical')}</option>
+ </select>
+ <button type="submit" style={{
+ background: '#3b82f6', border: 'none', borderRadius: 6,
+ color: '#fff', padding: '6px 10px', cursor: 'pointer',
+ display: 'flex', alignItems: 'center',
+ }}><Plus size={12} /></button>
+ </form>
+ {aRules.map(r => (
+ <div key={r.id} style={{ ...row, padding: '5px 0' }}>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <span style={{ fontSize: 10, color: 'var(--text)' }}>{r.name}</span>
+ <div style={hint}>
+ {r.field} {r.op} {r.value}
+ {r.hits > 0 && ` · ${t('ar_hits', r.hits)}`}
+ </div>
+ </div>
+ <button onClick={() => deleteAlertRule(r.id)} aria-label={t('fw_delete')} style={{
+ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', padding: 2,
+ }}><Trash2 size={12} /></button>
+ </div>
+ ))}
+ </div>
+
{/* Security audit / Audit de sécurité */}
<div style={{ ...row, display: 'block', borderTop: '1px solid var(--border)', marginTop: 12 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
@@ -359,6 +558,12 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
textTransform: 'uppercase',
}}>{f}</button>
))}
+ <button onClick={exportPcap} title={t('fw_pcap_hint')} style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 5, color: 'var(--text-muted)', fontSize: 9,
+ fontWeight: 700, padding: '3px 8px', cursor: 'pointer',
+ textTransform: 'uppercase',
+ }}>pcap</button>
</div>
{/* EN: Privacy-preserving IOC pack — export shares indicators as
a noised Bloom filter (never raw); import checks observed
diff --git a/frontend/src/components/Settings.jsx b/frontend/src/components/Settings.jsx
index ab1ddc4..fcf6515 100644
--- a/frontend/src/components/Settings.jsx
+++ b/frontend/src/components/Settings.jsx
@@ -44,22 +44,27 @@ export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchl
const [watchInput, setWatchInput] = useState('')
const [updStatus, setUpdStatus] = useState(null)
const [updCheck, setUpdCheck] = useState(true)
+ const [pairing, setPairing] = useState(null)
+ const [sbPath, setSbPath] = useState('')
+ const [sbResult, setSbResult] = useState(null)
useEffect(() => {
;(async () => {
const base = await apiBase()
const headers = await authHeaders()
try {
- const [s, g, i] = await Promise.all([
+ const [s, g, i, p] = await Promise.all([
fetch(`${base}/settings`, { headers }).then(r => r.json()),
fetch(`${base}/geo/status`, { headers }).then(r => r.json()),
fetch(`${base}/capture/interfaces`, { headers }).then(r => r.json()),
+ fetch(`${base}/remote/pairing`, { headers }).then(r => r.json()),
])
setSettings(s.settings || {})
setRetention(s.settings?.retention_hours ?? 24)
setUploadMb(s.settings?.upload_threshold_mb ?? 50)
setGeoStatus(g)
setIfaces(i.interfaces || [])
+ setPairing(p)
} catch { setSettings({}) }
if (window.snitch?.getAutoLaunch) {
setAutoLaunch(await window.snitch.getAutoLaunch())
@@ -137,6 +142,49 @@ export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchl
URL.revokeObjectURL(a.href)
}
+ /**
+ * EN: Remote pairing — opt-in LAN exposure persisted as `lan_bind`.
+ * The backend cannot rebind a live socket, so the answer's
+ * `restart_required` is surfaced verbatim.
+ * FR: Pairing distant — exposition LAN opt-in persistée en `lan_bind`.
+ * Le backend ne peut pas re-binder un socket actif, donc
+ * `restart_required` est affiché tel quel.
+ */
+ async function setPairingOn(on) {
+ const base = await apiBase()
+ const res = await fetch(`${base}/remote/pairing`, {
+ method: 'POST',
+ headers: await authHeaders({ 'Content-Type': 'application/json' }),
+ body: JSON.stringify({ enabled: on, bind: '0.0.0.0' }),
+ }).then(r => r.json())
+ const p = await fetch(`${base}/remote/pairing`, { headers: await authHeaders() }).then(r => r.json())
+ setPairing({ ...p, _justSet: res.lan_bind })
+ }
+
+ /**
+ * EN: Sandbox detonation — run a binary with zero network egress
+ * (network namespace on Linux, sandbox-exec on macOS). Bounded
+ * runtime; the result says honestly whether egress was denied.
+ * FR: Détonation en sandbox — exécuter un binaire avec zéro égress
+ * réseau (namespace réseau sous Linux, sandbox-exec sous macOS).
+ * Durée bornée ; le résultat dit honnêtement si l'égress était
+ * bloqué.
+ */
+ async function detonate(e) {
+ e.preventDefault()
+ if (!sbPath.trim()) return
+ setSbResult({ running: true })
+ const base = await apiBase()
+ try {
+ const res = await fetch(`${base}/security/sandbox`, {
+ method: 'POST',
+ headers: await authHeaders({ 'Content-Type': 'application/json' }),
+ body: JSON.stringify({ path: sbPath.trim(), seconds: 10 }),
+ }).then(r => r.json())
+ setSbResult(res)
+ } catch (ex) { setSbResult({ ok: false, error: String(ex.message || ex) }) }
+ }
+
const row = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--bg)' }
const label = { fontSize: 12, color: 'var(--text)', fontWeight: 600 }
const hint = { fontSize: 10, color: 'var(--text-muted)', marginTop: 2 }
@@ -489,35 +537,139 @@ export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchl
</button>
</div>
{settings?.slm_enabled && (
- <form onSubmit={e => {
- e.preventDefault()
- save('slm_endpoint', e.target.elements.slme.value.trim())
- save('slm_model', e.target.elements.slmm.value.trim())
- }} style={{ display: 'flex', gap: 6, marginTop: 8 }}>
- <input
- name="slme"
- defaultValue={settings?.slm_endpoint ?? ''}
- placeholder="http://127.0.0.1:11434"
- aria-label={t('slm_endpoint')}
- style={{ flex: 2, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none' }}
- />
- <input
- name="slmm"
- defaultValue={settings?.slm_model ?? ''}
- placeholder="llama3.2"
- aria-label={t('slm_model')}
- style={{ flex: 1, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none' }}
- />
- <button type="submit" style={{
- background: 'var(--bg)', border: '1px solid var(--border)',
- borderRadius: 6, color: 'var(--text-dim)', padding: '6px 12px',
- fontSize: 10, cursor: 'pointer',
- }}>{t('save')}</button>
- </form>
+ <>
+ {/* EN: Backend choice — `ollama` reaches a loopback server;
+ `embedded` loads a user-provided GGUF via
+ llama-cpp-python (zero network at all).
+ FR: Choix du backend — `ollama` joint un serveur
+ loopback ; `embedded` charge un GGUF fourni par
+ l'utilisateur via llama-cpp-python (zéro réseau). */}
+ <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
+ {['ollama', 'embedded'].map(m => (
+ <button key={m} onClick={() => {
+ setSettings(s => ({ ...s, slm_mode: m }))
+ save('slm_mode', m)
+ }} style={{
+ flex: 1, background: (settings?.slm_mode ?? 'ollama') === m ? '#3b82f6' : 'var(--bg)',
+ border: '1px solid var(--border)', borderRadius: 6,
+ color: (settings?.slm_mode ?? 'ollama') === m ? '#fff' : 'var(--text-dim)',
+ padding: '5px 0', fontSize: 10, cursor: 'pointer', fontWeight: 600,
+ }}>{m === 'ollama' ? t('slm_mode_ollama') : t('slm_mode_embedded')}</button>
+ ))}
+ </div>
+ {(settings?.slm_mode ?? 'ollama') === 'embedded' ? (
+ <form onSubmit={e => {
+ e.preventDefault()
+ save('slm_model_path', e.target.elements.slmp.value.trim())
+ }} style={{ display: 'flex', gap: 6, marginTop: 6 }}>
+ <input
+ name="slmp"
+ defaultValue={settings?.slm_model_path ?? ''}
+ placeholder="/path/to/model.gguf"
+ aria-label={t('slm_model_path')}
+ style={{ flex: 1, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none' }}
+ />
+ <button type="submit" style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 6, color: 'var(--text-dim)', padding: '6px 12px',
+ fontSize: 10, cursor: 'pointer',
+ }}>{t('save')}</button>
+ </form>
+ ) : (
+ <form onSubmit={e => {
+ e.preventDefault()
+ save('slm_endpoint', e.target.elements.slme.value.trim())
+ save('slm_model', e.target.elements.slmm.value.trim())
+ }} style={{ display: 'flex', gap: 6, marginTop: 6 }}>
+ <input
+ name="slme"
+ defaultValue={settings?.slm_endpoint ?? ''}
+ placeholder="http://127.0.0.1:11434"
+ aria-label={t('slm_endpoint')}
+ style={{ flex: 2, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none' }}
+ />
+ <input
+ name="slmm"
+ defaultValue={settings?.slm_model ?? ''}
+ placeholder="llama3.2"
+ aria-label={t('slm_model')}
+ style={{ flex: 1, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none' }}
+ />
+ <button type="submit" style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 6, color: 'var(--text-dim)', padding: '6px 12px',
+ fontSize: 10, cursor: 'pointer',
+ }}>{t('save')}</button>
+ </form>
+ )}
+ </>
)}
<div style={{ ...hint, marginTop: 4 }}>{t('slm_privacy')}</div>
</div>
+ {/* Remote pairing / Pairing distant */}
+ <div style={{ ...row, display: 'block' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={label}>{t('pair_title')}</div>
+ <div style={hint}>{t('pair_hint')}</div>
+ </div>
+ <button
+ onClick={() => setPairingOn(!(pairing?.persisted_bind))}
+ role="switch" aria-checked={!!pairing?.persisted_bind}
+ style={{
+ width: 36, height: 20, borderRadius: 10, border: 'none',
+ background: pairing?.persisted_bind ? '#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: pairing?.persisted_bind ? 19 : 3,
+ transition: 'left 0.15s',
+ }} />
+ </button>
+ </div>
+ {pairing?.persisted_bind && (
+ <div style={{ ...hint, marginTop: 6 }}>
+ {t('pair_lan_ips', (pairing.lan_ips || []).join(', ') || '—')}
+ {' · '}{t('pair_port', pairing.port)}
+ {pairing.restart_required && (
+ <div style={{ color: '#f59e0b', marginTop: 3 }}>{t('pair_restart')}</div>
+ )}
+ </div>
+ )}
+ <div style={{ ...hint, marginTop: 4 }}>{t('pair_privacy')}</div>
+ </div>
+
+ {/* Sandbox detonation / Détonation en sandbox */}
+ <div style={{ ...row, display: 'block' }}>
+ <div style={label}>{t('sb_title')}</div>
+ <div style={hint}>{t('sb_hint')}</div>
+ <form onSubmit={detonate} style={{ display: 'flex', gap: 6, marginTop: 8 }}>
+ <input value={sbPath} onChange={e => setSbPath(e.target.value)}
+ placeholder="/path/to/binary" aria-label={t('sb_path')}
+ style={{ flex: 1, background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 6, color: 'var(--text)', padding: '6px 10px', fontSize: 11, outline: 'none' }} />
+ <button type="submit" disabled={!sbPath.trim() || sbResult?.running} style={{
+ background: sbPath.trim() ? '#3b82f6' : 'var(--bg)', border: 'none',
+ borderRadius: 6, color: sbPath.trim() ? '#fff' : 'var(--text-faint)',
+ padding: '6px 12px', fontSize: 10, cursor: 'pointer', fontWeight: 600,
+ }}>{sbResult?.running ? '…' : t('sb_run')}</button>
+ </form>
+ {sbResult && !sbResult.running && (
+ <div style={{ ...hint, marginTop: 4, color: sbResult.ok ? '#4ade80' : '#f59e0b' }}>
+ {sbResult.ok
+ ? t('sb_done', sbResult.exit_code ?? '?')
+ : (sbResult.error || t('sb_failed'))}
+ {sbResult.stderr && (
+ <div style={{ fontFamily: 'monospace', marginTop: 2, color: 'var(--text-muted)' }}>
+ {String(sbResult.stderr).slice(0, 200)}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
{/* Updates (Electron only) / Mises à jour (Electron seul) */}
{window.snitch?.getUpdateStatus && (
<div style={{ ...row, display: 'block' }}>
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 6d0c50c..7c28fdd 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -374,4 +374,48 @@ export default {
slm_endpoint: 'Endpunkt',
slm_model: 'Modell',
slm_privacy: 'Läuft nur wenn aktiviert; Alarm-Metadaten gehen an Ihr lokales Modell, niemals von der Maschine weg.',
+ slm_mode_ollama: 'Ollama-Server',
+ slm_mode_embedded: 'Eingebettetes GGUF',
+ slm_model_path: 'Modelldatei (.gguf)',
+ fw_profiles: 'Profile',
+ fw_profiles_hint: 'Ein-Klick-Richtlinienpakete — in gewöhnliche Regeln ausgerollt.',
+ fw_profile_permissive: 'Permissiv',
+ fw_profile_balanced: 'Ausgewogen',
+ fw_profile_strict: 'Strikt',
+ fw_pcap_empty: 'Noch keine Frames — der Ringpuffer hält nur aktuellen Verkehr',
+ fw_pcap_hint: 'Letzte Rohframes als .pcap laden — begrenzter Ringpuffer, Wireshark-fertig',
+ bl_title: 'Blockliste importieren',
+ bl_hint: 'Hosts-Datei oder Domainliste in Firewall-Regeln umwandeln (max. 500).',
+ bl_source: 'Quelle',
+ bl_src_file: 'Datei',
+ bl_src_url: 'URL',
+ bl_import: 'Importieren',
+ bl_url_confirm: 'Das Abrufen dieser URL lässt Snitch eine AUSGEHENDE Anfrage senden — eine der wenigen überhaupt. Fortfahren?',
+ bl_result: (a, s) => `${a} Regeln hinzugefügt · ${s} bereits vorhanden`,
+ bl_truncated: 'Liste am Limit gekürzt',
+ bl_remote: 'Remote-Abruf durchgeführt',
+ ar_title: 'Eigene Alarmregeln',
+ ar_hint: 'CUSTOM_RULE-Alarme für eigene Muster auslösen — nur Alarm, nie Blockierung.',
+ ar_name_ph: 'Regelname (optional)',
+ ar_field: 'Feld',
+ ar_op: 'Operator',
+ ar_value_ph: 'Wert',
+ ar_sev: 'Schweregrad',
+ ar_hits: n => `${n} Treffer`,
+ sev_info: 'Info',
+ sev_warning: 'Warnung',
+ sev_critical: 'Kritisch',
+ pair_title: 'Fernkopplung (LAN)',
+ pair_hint: 'Anderen Geräten im LAN den Zugriff auf diese API erlauben — Token bleibt Pflicht.',
+ pair_lan_ips: ips => `Erreichbar unter: ${ips}`,
+ pair_port: p => `Port ${p}`,
+ pair_restart: 'Gilt ab dem nächsten Backend-Neustart — ein aktiver Socket kann nicht neu gebunden werden.',
+ pair_privacy: 'Standardmäßig nur Loopback; Aktivieren exponiert die API im LAN (Token-Auth bleibt).',
+ sb_title: 'Sandbox ohne Netzwerk',
+ sb_hint: 'Binärdatei mit null Netzwerk-Egress ausführen — Verhalten ohne Risiko beobachten.',
+ sb_path: 'Pfad zur Programmdatei',
+ sb_run: 'Ausführen',
+ sb_done: code => `In Sandbox ausgeführt — Exit ${code}`,
+ sb_failed: 'Sandbox auf dieser Plattform nicht verfügbar',
+ alertmsg_CUSTOM_RULE: d => `Eigene Regel ausgelöst: ${d.rule?.name || 'unbenannte Regel'}`,
}
diff --git a/frontend/src/locales/en.js b/frontend/src/locales/en.js
index e6b4ba4..22cdabe 100644
--- a/frontend/src/locales/en.js
+++ b/frontend/src/locales/en.js
@@ -378,4 +378,48 @@ export default { // Navigation
slm_endpoint: 'Endpoint',
slm_model: 'Model',
slm_privacy: 'Runs only when enabled; alert metadata goes to your local model, never off-machine.',
+ slm_mode_ollama: 'Ollama server',
+ slm_mode_embedded: 'Embedded GGUF',
+ slm_model_path: 'Model file (.gguf)',
+ fw_profiles: 'Profiles',
+ fw_profiles_hint: 'One-tap policy bundles — expanded into ordinary rules.',
+ fw_profile_permissive: 'Permissive',
+ fw_profile_balanced: 'Balanced',
+ fw_profile_strict: 'Strict',
+ fw_pcap_empty: 'No frames captured yet — the ring holds recent traffic only',
+ fw_pcap_hint: 'Download recent raw frames as .pcap — bounded ring buffer, Wireshark-ready',
+ bl_title: 'Blocklist import',
+ bl_hint: 'Turn a hosts file or domain list into firewall rules (max 500).',
+ bl_source: 'Source',
+ bl_src_file: 'File',
+ bl_src_url: 'URL',
+ bl_import: 'Import',
+ bl_url_confirm: 'Fetching this URL makes Snitch emit an OUTBOUND request — one of the few it can ever send. Continue?',
+ bl_result: (a, s) => `${a} rules added · ${s} already present`,
+ bl_truncated: 'list truncated at the cap',
+ bl_remote: 'remote fetch performed',
+ ar_title: 'Custom alert rules',
+ ar_hint: 'Raise CUSTOM_RULE alerts on your own matches — alert-only, never blocks.',
+ ar_name_ph: 'Rule name (optional)',
+ ar_field: 'Field',
+ ar_op: 'Operator',
+ ar_value_ph: 'Value',
+ ar_sev: 'Severity',
+ ar_hits: n => `${n} hits`,
+ sev_info: 'info',
+ sev_warning: 'warning',
+ sev_critical: 'critical',
+ pair_title: 'Remote pairing (LAN)',
+ pair_hint: 'Let other devices on your LAN reach this API — token still required.',
+ pair_lan_ips: ips => `Reachable at: ${ips}`,
+ pair_port: p => `port ${p}`,
+ pair_restart: 'Applies at next backend restart — a live socket cannot be rebound.',
+ pair_privacy: 'Loopback-only by default; enabling exposes the API to your LAN with token auth still enforced.',
+ sb_title: 'Network-denial sandbox',
+ sb_hint: 'Run a binary with zero network egress — observe behaviour without exposure.',
+ sb_path: 'Executable path',
+ sb_run: 'Detonate',
+ sb_done: code => `Ran in sandbox — exit ${code}`,
+ sb_failed: 'Sandbox unavailable on this platform',
+ alertmsg_CUSTOM_RULE: d => `Custom rule matched: ${d.rule?.name || 'unnamed rule'}`,
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index c67614d..0066914 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -372,4 +372,48 @@ export default { // Navegación
slm_endpoint: 'Endpoint',
slm_model: 'Modelo',
slm_privacy: 'Solo funciona si está activado; los metadatos de alertas van a tu modelo local, nunca fuera de la máquina.',
+ slm_mode_ollama: 'Servidor Ollama',
+ slm_mode_embedded: 'GGUF integrado',
+ slm_model_path: 'Archivo de modelo (.gguf)',
+ fw_profiles: 'Perfiles',
+ fw_profiles_hint: 'Paquetes de políticas de un toque — expandidos en reglas ordinarias.',
+ fw_profile_permissive: 'Permisivo',
+ fw_profile_balanced: 'Equilibrado',
+ fw_profile_strict: 'Estricto',
+ fw_pcap_empty: 'Sin tramas capturadas — el anillo solo guarda tráfico reciente',
+ fw_pcap_hint: 'Descargar tramas recientes como .pcap — búfer circular acotado, listo para Wireshark',
+ bl_title: 'Importar blocklist',
+ bl_hint: 'Convierte un archivo hosts o lista de dominios en reglas de firewall (máx. 500).',
+ bl_source: 'Fuente',
+ bl_src_file: 'Archivo',
+ bl_src_url: 'URL',
+ bl_import: 'Importar',
+ bl_url_confirm: 'Descargar esta URL hace que Snitch emita una petición SALIENTE — una de las pocas que puede enviar. ¿Continuar?',
+ bl_result: (a, s) => `${a} reglas añadidas · ${s} ya existentes`,
+ bl_truncated: 'lista truncada al límite',
+ bl_remote: 'descarga remota realizada',
+ ar_title: 'Reglas de alerta personalizadas',
+ ar_hint: 'Lanza alertas CUSTOM_RULE con tus propios patrones — solo alerta, nunca bloquea.',
+ ar_name_ph: 'Nombre de la regla (opcional)',
+ ar_field: 'Campo',
+ ar_op: 'Operador',
+ ar_value_ph: 'Valor',
+ ar_sev: 'Severidad',
+ ar_hits: n => `${n} coincidencias`,
+ sev_info: 'info',
+ sev_warning: 'aviso',
+ sev_critical: 'crítica',
+ pair_title: 'Emparejamiento remoto (LAN)',
+ pair_hint: 'Permite que otros dispositivos de tu LAN alcancen esta API — el token sigue siendo obligatorio.',
+ pair_lan_ips: ips => `Accesible en: ${ips}`,
+ pair_port: p => `puerto ${p}`,
+ pair_restart: 'Se aplica en el próximo reinicio del backend — un socket activo no puede reenlazarse.',
+ pair_privacy: 'Solo loopback por defecto; activarlo expone la API a tu LAN con autenticación por token.',
+ sb_title: 'Sandbox sin red',
+ sb_hint: 'Ejecuta un binario con cero salida de red — observa sin exponerte.',
+ sb_path: 'Ruta del ejecutable',
+ sb_run: 'Detonar',
+ sb_done: code => `Ejecutado en sandbox — salida ${code}`,
+ sb_failed: 'Sandbox no disponible en esta plataforma',
+ alertmsg_CUSTOM_RULE: d => `Regla personalizada activada: ${d.rule?.name || 'regla sin nombre'}`,
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index cda2fd8..ea16779 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -374,4 +374,48 @@ export default { // Navigation
slm_endpoint: 'Endpoint',
slm_model: 'Modèle',
slm_privacy: "Actif seulement si activé ; les métadonnées d'alerte vont à votre modèle local, jamais hors-machine.",
+ slm_mode_ollama: 'Serveur Ollama',
+ slm_mode_embedded: 'GGUF embarqué',
+ slm_model_path: 'Fichier modèle (.gguf)',
+ fw_profiles: 'Profils',
+ fw_profiles_hint: 'Lots de règles en un clic — dépliés en règles ordinaires.',
+ fw_profile_permissive: 'Permissif',
+ fw_profile_balanced: 'Équilibré',
+ fw_profile_strict: 'Strict',
+ fw_pcap_empty: "Aucune trame capturée — l'anneau ne garde que le trafic récent",
+ fw_pcap_hint: 'Télécharger les trames récentes en .pcap — tampon borné, lisible par Wireshark',
+ bl_title: 'Import de blocklist',
+ bl_hint: 'Transformer un fichier hosts ou une liste de domaines en règles pare-feu (max 500).',
+ bl_source: 'Source',
+ bl_src_file: 'Fichier',
+ bl_src_url: 'URL',
+ bl_import: 'Importer',
+ bl_url_confirm: "Fetcher cette URL fait émettre à Snitch une requête SORTANTE — l'une des rares possibles. Continuer ?",
+ bl_result: (a, s) => `${a} règles ajoutées · ${s} déjà présentes`,
+ bl_truncated: 'liste tronquée au plafond',
+ bl_remote: 'fetch distant effectué',
+ ar_title: "Règles d'alerte personnalisées",
+ ar_hint: 'Lever des alertes CUSTOM_RULE sur vos propres motifs — alerte seule, jamais de blocage.',
+ ar_name_ph: 'Nom de la règle (optionnel)',
+ ar_field: 'Champ',
+ ar_op: 'Opérateur',
+ ar_value_ph: 'Valeur',
+ ar_sev: 'Sévérité',
+ ar_hits: n => `${n} déclenchements`,
+ sev_info: 'info',
+ sev_warning: 'avertissement',
+ sev_critical: 'critique',
+ pair_title: 'Pairing distant (LAN)',
+ pair_hint: 'Permettre aux appareils du LAN de joindre cette API — jeton toujours exigé.',
+ pair_lan_ips: ips => `Joignable sur : ${ips}`,
+ pair_port: p => `port ${p}`,
+ pair_restart: 'Appliqué au prochain redémarrage du backend — un socket actif ne peut être re-lié.',
+ pair_privacy: 'Loopback uniquement par défaut ; activer expose l\'API au LAN (jeton toujours exigé).',
+ sb_title: 'Sandbox sans réseau',
+ sb_hint: 'Exécuter un binaire avec zéro égress réseau — observer sans exposition.',
+ sb_path: "Chemin de l'exécutable",
+ sb_run: 'Détoner',
+ sb_done: code => `Exécuté en sandbox — sortie ${code}`,
+ sb_failed: 'Sandbox indisponible sur cette plateforme',
+ alertmsg_CUSTOM_RULE: d => `Règle personnalisée déclenchée : ${d.rule?.name || 'règle sans nom'}`,
}
diff --git a/frontend/src/locales/ja.js b/frontend/src/locales/ja.js
index fb5fd48..7a7a3c8 100644
--- a/frontend/src/locales/ja.js
+++ b/frontend/src/locales/ja.js
@@ -374,4 +374,48 @@ export default {
slm_endpoint: 'エンドポイント',
slm_model: 'モデル',
slm_privacy: '有効時のみ動作;アラートのメタデータはローカルモデルのみに送られ、マシン外には出ません。',
+ slm_mode_ollama: 'Ollama サーバー',
+ slm_mode_embedded: '埋め込み GGUF',
+ slm_model_path: 'モデルファイル (.gguf)',
+ fw_profiles: 'プロファイル',
+ fw_profiles_hint: 'ワンタップのポリシーバンドル — 通常のルールに展開されます。',
+ fw_profile_permissive: '許容',
+ fw_profile_balanced: 'バランス',
+ fw_profile_strict: '厳格',
+ fw_pcap_empty: 'キャプチャされたフレームなし — リングは直近のトラフィックのみ保持',
+ fw_pcap_hint: '最近のフレームを .pcap でダウンロード — 上限付きリングバッファ、Wireshark 対応',
+ bl_title: 'ブロックリストのインポート',
+ bl_hint: 'hosts ファイルやドメインリストをファイアウォールルールに変換 (最大500件)。',
+ bl_source: 'ソース',
+ bl_src_file: 'ファイル',
+ bl_src_url: 'URL',
+ bl_import: 'インポート',
+ bl_url_confirm: 'この URL を取得すると Snitch が外部へ送信リクエストを行います — 数少ない例外の一つです。続行しますか?',
+ bl_result: (a, s) => `${a} 件のルールを追加 · ${s} 件は既存`,
+ bl_truncated: '上限で切り詰められました',
+ bl_remote: 'リモート取得を実行しました',
+ ar_title: 'カスタムアラートルール',
+ ar_hint: '独自の条件で CUSTOM_RULE アラートを発火 — 通知のみ、ブロックはしません。',
+ ar_name_ph: 'ルール名 (任意)',
+ ar_field: 'フィールド',
+ ar_op: '演算子',
+ ar_value_ph: '値',
+ ar_sev: '重要度',
+ ar_hits: n => `${n} 回ヒット`,
+ sev_info: '情報',
+ sev_warning: '警告',
+ sev_critical: '重大',
+ pair_title: 'リモートペアリング (LAN)',
+ pair_hint: 'LAN 内の他デバイスからこの API へのアクセスを許可 — トークンは引き続き必須。',
+ pair_lan_ips: ips => `アクセス先: ${ips}`,
+ pair_port: p => `ポート ${p}`,
+ pair_restart: '次回のバックエンド再起動時に適用 — 起動中のソケットは再バインドできません。',
+ pair_privacy: 'デフォルトはループバックのみ;有効化するとトークン認証付きで API が LAN に公開されます。',
+ sb_title: 'ネットワーク遮断サンドボックス',
+ sb_hint: '外部送信ゼロでバイナリを実行 — 露出せずに挙動を観察。',
+ sb_path: '実行ファイルのパス',
+ sb_run: '実行',
+ sb_done: code => `サンドボックスで実行 — 終了コード ${code}`,
+ sb_failed: 'このプラットフォームではサンドボックスを利用できません',
+ alertmsg_CUSTOM_RULE: d => `カスタムルールに一致: ${d.rule?.name || '無名のルール'}`,
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index b7f5ea5..2205c67 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -374,4 +374,48 @@ export default {
slm_endpoint: 'Endpoint',
slm_model: 'Modelo',
slm_privacy: 'Funciona apenas se ativado; metadados de alertas vão ao seu modelo local, nunca para fora da máquina.',
+ slm_mode_ollama: 'Servidor Ollama',
+ slm_mode_embedded: 'GGUF embutido',
+ slm_model_path: 'Arquivo de modelo (.gguf)',
+ fw_profiles: 'Perfis',
+ fw_profiles_hint: 'Pacotes de política de um toque — expandidos em regras comuns.',
+ fw_profile_permissive: 'Permissivo',
+ fw_profile_balanced: 'Equilibrado',
+ fw_profile_strict: 'Restrito',
+ fw_pcap_empty: 'Nenhum frame capturado — o anel só guarda tráfego recente',
+ fw_pcap_hint: 'Baixar frames recentes como .pcap — buffer circular limitado, pronto para Wireshark',
+ bl_title: 'Importar blocklist',
+ bl_hint: 'Transforme um arquivo hosts ou lista de domínios em regras de firewall (máx. 500).',
+ bl_source: 'Fonte',
+ bl_src_file: 'Arquivo',
+ bl_src_url: 'URL',
+ bl_import: 'Importar',
+ bl_url_confirm: 'Baixar esta URL faz o Snitch emitir uma requisição de SAÍDA — uma das poucas que ele pode enviar. Continuar?',
+ bl_result: (a, s) => `${a} regras adicionadas · ${s} já existentes`,
+ bl_truncated: 'lista truncada no limite',
+ bl_remote: 'busca remota realizada',
+ ar_title: 'Regras de alerta personalizadas',
+ ar_hint: 'Dispare alertas CUSTOM_RULE com seus próprios padrões — só alerta, nunca bloqueia.',
+ ar_name_ph: 'Nome da regra (opcional)',
+ ar_field: 'Campo',
+ ar_op: 'Operador',
+ ar_value_ph: 'Valor',
+ ar_sev: 'Severidade',
+ ar_hits: n => `${n} ocorrências`,
+ sev_info: 'info',
+ sev_warning: 'aviso',
+ sev_critical: 'crítico',
+ pair_title: 'Pareamento remoto (LAN)',
+ pair_hint: 'Permite que outros dispositivos da sua LAN alcancem esta API — o token continua obrigatório.',
+ pair_lan_ips: ips => `Acessível em: ${ips}`,
+ pair_port: p => `porta ${p}`,
+ pair_restart: 'Aplica no próximo reinício do backend — um socket ativo não pode ser re-vinculado.',
+ pair_privacy: 'Apenas loopback por padrão; ativar expõe a API à sua LAN com autenticação por token.',
+ sb_title: 'Sandbox sem rede',
+ sb_hint: 'Execute um binário com zero saída de rede — observe sem se expor.',
+ sb_path: 'Caminho do executável',
+ sb_run: 'Detonar',
+ sb_done: code => `Executado no sandbox — saída ${code}`,
+ sb_failed: 'Sandbox indisponível nesta plataforma',
+ alertmsg_CUSTOM_RULE: d => `Regra personalizada acionada: ${d.rule?.name || 'regra sem nome'}`,
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index dc35181..4a7b92d 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -374,4 +374,48 @@ export default {
slm_endpoint: 'Endpoint',
slm_model: 'Модель',
slm_privacy: 'Работает только при включении; метаданные алертов идут в вашу локальную модель, никогда наружу.',
+ slm_mode_ollama: 'Сервер Ollama',
+ slm_mode_embedded: 'Встроенный GGUF',
+ slm_model_path: 'Файл модели (.gguf)',
+ fw_profiles: 'Профили',
+ fw_profiles_hint: 'Пакеты правил в один клик — разворачиваются в обычные правила.',
+ fw_profile_permissive: 'Свободный',
+ fw_profile_balanced: 'Сбалансированный',
+ fw_profile_strict: 'Строгий',
+ fw_pcap_empty: 'Кадров пока нет — кольцевой буфер хранит только недавний трафик',
+ fw_pcap_hint: 'Скачать недавние кадры как .pcap — ограниченный кольцевой буфер, готов к Wireshark',
+ bl_title: 'Импорт блоклиста',
+ bl_hint: 'Преобразовать hosts-файл или список доменов в правила файрвола (макс. 500).',
+ bl_source: 'Источник',
+ bl_src_file: 'Файл',
+ bl_src_url: 'URL',
+ bl_import: 'Импорт',
+ bl_url_confirm: 'Загрузка этого URL заставит Snitch отправить ИСХОДЯЩИЙ запрос — один из немногих возможных. Продолжить?',
+ bl_result: (a, s) => `${a} правил добавлено · ${s} уже существовали`,
+ bl_truncated: 'список обрезан до лимита',
+ bl_remote: 'выполнена удалённая загрузка',
+ ar_title: 'Пользовательские правила алертов',
+ ar_hint: 'Поднимает алерты CUSTOM_RULE по вашим шаблонам — только алерт, никогда не блокирует.',
+ ar_name_ph: 'Имя правила (необязательно)',
+ ar_field: 'Поле',
+ ar_op: 'Оператор',
+ ar_value_ph: 'Значение',
+ ar_sev: 'Важность',
+ ar_hits: n => `${n} срабатываний`,
+ sev_info: 'инфо',
+ sev_warning: 'предупреждение',
+ sev_critical: 'критично',
+ pair_title: 'Удалённое сопряжение (LAN)',
+ pair_hint: 'Разрешить устройствам в LAN обращаться к этому API — токен по-прежнему обязателен.',
+ pair_lan_ips: ips => `Доступно по адресам: ${ips}`,
+ pair_port: p => `порт ${p}`,
+ pair_restart: 'Применится при следующем перезапуске бэкенда — активный сокет нельзя перепривязать.',
+ pair_privacy: 'По умолчанию только loopback; включение открывает API в LAN (токен обязателен).',
+ sb_title: 'Песочница без сети',
+ sb_hint: 'Запустить бинарник с нулевым исходящим трафиком — наблюдать без риска.',
+ sb_path: 'Путь к исполняемому файлу',
+ sb_run: 'Запустить',
+ sb_done: code => `Выполнено в песочнице — код ${code}`,
+ sb_failed: 'Песочница недоступна на этой платформе',
+ alertmsg_CUSTOM_RULE: d => `Сработало своё правило: ${d.rule?.name || 'безымянное правило'}`,
}
diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.js
index bf47a5b..3ee547e 100644
--- a/frontend/src/locales/zh-CN.js
+++ b/frontend/src/locales/zh-CN.js
@@ -374,4 +374,48 @@ export default {
slm_endpoint: '端点',
slm_model: '模型',
slm_privacy: '仅在启用时运行;告警元数据仅发送到您的本地模型,绝不离开机器。',
+ slm_mode_ollama: 'Ollama 服务器',
+ slm_mode_embedded: '内置 GGUF',
+ slm_model_path: '模型文件 (.gguf)',
+ fw_profiles: '配置文件',
+ fw_profiles_hint: '一键策略包 — 展开为普通规则。',
+ fw_profile_permissive: '宽松',
+ fw_profile_balanced: '均衡',
+ fw_profile_strict: '严格',
+ fw_pcap_empty: '尚未捕获帧 — 环形缓冲区仅保存最近流量',
+ fw_pcap_hint: '将最近的原始帧下载为 .pcap — 有界环形缓冲区,可用于 Wireshark',
+ bl_title: '导入屏蔽列表',
+ bl_hint: '将 hosts 文件或域名列表转换为防火墙规则(最多 500 条)。',
+ bl_source: '来源',
+ bl_src_file: '文件',
+ bl_src_url: 'URL',
+ bl_import: '导入',
+ bl_url_confirm: '获取此 URL 会让 Snitch 发出出站请求 — 这是极少数例外之一。继续?',
+ bl_result: (a, s) => `已添加 ${a} 条规则 · ${s} 条已存在`,
+ bl_truncated: '列表已按上限截断',
+ bl_remote: '已执行远程获取',
+ ar_title: '自定义告警规则',
+ ar_hint: '按您自己的条件触发 CUSTOM_RULE 告警 — 仅告警,绝不阻断。',
+ ar_name_ph: '规则名称(可选)',
+ ar_field: '字段',
+ ar_op: '运算符',
+ ar_value_ph: '值',
+ ar_sev: '严重级别',
+ ar_hits: n => `命中 ${n} 次`,
+ sev_info: '信息',
+ sev_warning: '警告',
+ sev_critical: '严重',
+ pair_title: '远程配对 (LAN)',
+ pair_hint: '允许 LAN 内其他设备访问此 API — 令牌仍然必需。',
+ pair_lan_ips: ips => `可通过以下地址访问:${ips}`,
+ pair_port: p => `端口 ${p}`,
+ pair_restart: '将在下次后端重启时生效 — 活动套接字无法重新绑定。',
+ pair_privacy: '默认仅回环地址;启用后 API 将向 LAN 开放(仍强制令牌认证)。',
+ sb_title: '无网络沙箱',
+ sb_hint: '以零出站网络运行二进制文件 — 安全观察其行为。',
+ sb_path: '可执行文件路径',
+ sb_run: '引爆',
+ sb_done: code => `已在沙箱中运行 — 退出码 ${code}`,
+ sb_failed: '此平台不支持沙箱',
+ alertmsg_CUSTOM_RULE: d => `自定义规则命中:${d.rule?.name || '未命名规则'}`,
}