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.3.0: WFP filters, eBPF probe, Frida inspect, mining & IOC packs

MoneyLisaf18854c54fe8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 068f92d..8465ef4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,24 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
## [Unreleased]
+## [1.3.0] — 2026-10-22
+
+### Added / Ajouté
+
+- **Windows Filtering Platform / Filtrage WFP (Windows)** — `detection/wfp.py` drives `fwpuclnt.dll` directly via ctypes: outbound ALE filters matched per app path, remote IP/CIDR and port, created with deterministic keys (deleted cleanly on rule removal) and orphan-purged by enumeration. Replaces `netsh` as the Windows backend when elevated; honest `applied=False` otherwise. User-mode filter management only — no kernel callout. / `detection/wfp.py` pilote `fwpuclnt.dll` en ctypes : filtres ALE sortants par chemin d'appli, IP/CIDR et port, clés déterministes (suppression propre) + purge des filtres orphelins par énumération. Remplace `netsh` sous Windows avec élévation ; `applied=False` honnête sinon. Gestion user-mode seule — pas de callout noyau.
+- **eBPF connect probe / Sonde eBPF connect** — optional BCC `tcpconnect`-style kprobe (`backend/capture/ebpf_probe.py`, setting `ebpf_probe`, Linux + root + python3-bcc) that attributes `connect()` calls of short-lived processes the socket table misses; ambiguous destinations are never guessed. Status at `GET /security/ebpf`. / Kprobe BCC optionnel qui attribue les `connect()` des processus éphémères ratés par la table des sockets ; jamais de supposition en cas d'ambiguïté. État via `GET /security/ebpf`.
+- **Frida deep inspection / Inspection profonde Frida** — `POST /security/deep_inspect` attaches to one PID for ≤60 s (opt-in `frida` package) and reports which loaded module issued each `connect()`/`WSAConnect()`; module paths under staging dirs yield `INJECT_SUSPECT`. / `POST /security/deep_inspect` attache à un PID ≤60 s et rapporte quel module chargé a émis chaque `connect()`/`WSAConnect()` ; chemins de staging → `INJECT_SUSPECT`.
+- **Sinkhole responder / Répondeur sinkhole** — loopback HTTP listener (:80) and TLS/SNI probe (:443) activated while a `sinkhole` rule is enabled; every redirected attempt becomes a `SINKHOLE_HIT` alert with Host/URI or SNI plus process attribution. / Écoute HTTP (:80) et sonde SNI (:443) en loopback tant qu'une règle `sinkhole` est active ; chaque tentative devient une alerte `SINKHOLE_HIT` avec Host/URI ou SNI + processus.
+- **Loaded-module integrity / Intégrité des modules chargés** — Merkle root over a process's file-backed executable mappings → `MODULE_CHANGED`; mapped paths under temp/memfd/staging locations → `MODULE_SUSPECT`. Bounded, read-only. / Racine Merkle sur les mappings exécutables fichier-basés → `MODULE_CHANGED` ; chemins temp/memfd/staging → `MODULE_SUSPECT`. Borné, lecture seule.
+- **Cryptomining detection / Détection de cryptominage** — bounded cleartext `app_head` parser field: stratum JSON (`mining.subscribe`) → `MINING_STRATUM` (critical); known pool ports mark suspects that sustained process CPU corroborates into `MINING_SUSPECT` — port alone never alerts. / Champ `app_head` borné : JSON stratum → `MINING_STRATUM` (critique) ; ports de pools + CPU soutenue → `MINING_SUSPECT` — un port seul n'alerte jamais.
+- **Hardware counters / Compteurs matériels** — `POST /security/perf` samples cycles/instructions/cache-misses for a PID via `perf_event_open` (ctypes, Linux, gated by `perf_event_paranoid`) to corroborate mining suspicion. / `POST /security/perf` échantillonne cycles/instructions/cache-misses d'un PID via `perf_event_open` (ctypes, Linux) pour corroborer la suspicion de minage.
+- **Local LLM enrichment / Enrichissement LLM local** — opt-in (`slm_enabled`): `/security/explain` can enrich its bilingual explanation through an Ollama-compatible endpoint **restricted to loopback** — remote endpoints are rejected. Deterministic templates remain the default and the fallback. / Opt-in : `/security/explain` enrichit ses explications via un endpoint Ollama **loopback uniquement** — les endpoints distants sont rejetés. Les gabarits restent le défaut.
+- **Privacy-preserving IOC packs / Paquets IOC préservant la vie privée** — `GET /security/iocpack` exports this machine's indicators as a Bloom filter + randomized response (ε≈4.6, plausible deniability — never raw IOCs); `POST /security/iocpack/import` checks observed destinations against a received pack, probabilistically, never auto-blocks. / `GET /security/iocpack` exporte les indicateurs en filtre de Bloom + randomized response (jamais en clair) ; `/security/iocpack/import` confronte les destinations à un paquet reçu, en probabiliste, sans blocage automatique.
+- **Egress throttling / Bridage sortant** — rule `action: "throttle"` with `rate` kbit/s polices a destination via Linux `tc` clsact/flower filters (applied/removed per rule, delta-applied on domain re-resolution). Rejected on port/process rules; `applied=False` off Linux. / Action `throttle` + `rate` kbit/s bride une destination via `tc` clsact/flower sous Linux. Rejetée sur port/processus ; `applied=False` hors Linux.
+- **UI for the new surface / UI des nouvelles fonctionnalités** — deep-inspect button per process, throttle action + rate in the rule form, IOC pack export/import in the Firewall panel, eBPF and local-LLM settings; 29 new i18n keys × 8 locales (322 total, parity-checked). / Bouton d'inspection profonde par processus, action throttle + débit, export/import de paquet IOC, réglages eBPF et LLM local ; 29 nouvelles clés × 8 locales (322 au total, parité vérifiée).
+
+## [1.2.0] — 2026-10-22
+
### Added / Ajouté
- **Outbound firewall orchestration / Orchestration du pare-feu sortant** — user rules (`ip`, `cidr`, `domain`, `process`, `port`) applied to the OS-native firewall best-effort: `netsh advfirewall` on Windows, `iptables` on Linux, a generated `pf` anchor on macOS. Persisted, re-applied at startup, honest `applied=False` when privileges are missing (matching + `BLOCKED_ATTEMPT` counters still work). / Règles utilisateur (`ip`, `cidr`, `domain`, `process`, `port`) appliquées au pare-feu natif OS au mieux : `netsh` sous Windows, `iptables` sous Linux, ancre `pf` sous macOS. Persistées, réappliquées au démarrage, `applied=False` honnête sans privilèges (matching + compteurs `BLOCKED_ATTEMPT` actifs).
diff --git a/PRIVACY.de.md b/PRIVACY.de.md
index 41e502d..582d097 100644
--- a/PRIVACY.de.md
+++ b/PRIVACY.de.md
@@ -41,6 +41,22 @@ einträgst (Discord, Slack, Telegram-Bot-Endpoint oder beliebige URL) und
den Schalter umlegst, werden Warn-/Kritik-Alarmtexte in Echtzeit an diesen
Endpoint gePOSTet. Bei ausgeschaltetem Schalter geht nichts raus.
+**Lokale LLM-Anreicherung (Opt-in, standardmäßig aus).** Bei
+`slm_enabled` können Alarm-*Metadaten* (Typ, Prozess, Ziel) an ein
+Ollama-kompatibles Modell gehen — **ausschließlich Loopback**: der
+Backend lehnt jeden Endpunkt ab, der nicht nach 127.0.0.1 / ::1
+auflöst. Deterministische Vorlagen bleiben der Standard.
+
+**IOC-Pakete werden von Snitch nie übertragen.** `GET /security/iocpack`
+kodiert deine Indikatoren als Bloom-Filter + randomized response
+(ε≈4,6) und übergibt dir die Datei — du entscheidest, ob und wohin.
+Ein Import liefert nur probabilistische Hinweise; nie Auto-Blocking.
+
+**Inspektionssonden bleiben lesend und lokal.** Die eBPF-Sonde, die
+Frida-Inspektion, `perf_event_open`-Zähler, Modul-Integritätsscans und
+der Sinkhole-Responder *lesen* nur lokalen Zustand und lauschen auf
+127.0.0.1 — keiner sendet Daten.
+
**Geolokalisierung ist zu 100 % offline.** Liegt eine `.mmdb` von DB-IP
Lite oder MaxMind GeoLite2 in `<data_dir>/geo/`, laufen Lookups lokal. Ohne
Datenbank zeigen IPs schlicht keinen Ort. Es gibt keinen HTTP-Geodienst —
diff --git a/PRIVACY.es.md b/PRIVACY.es.md
index 5c67d3e..2571ef0 100644
--- a/PRIVACY.es.md
+++ b/PRIVACY.es.md
@@ -42,6 +42,22 @@ URL) y activas el interruptor, los textos de alertas warning/críticas se
POSTean a ese endpoint en tiempo real. Nada se envía con el interruptor
apagado.
+**Enriquecimiento LLM local (opt-in, desactivado por defecto).** Con
+`slm_enabled`, los *metadatos* de alertas (tipo, proceso, destino) pueden
+enviarse a un modelo compatible con Ollama — **solo loopback**: el backend
+rechaza cualquier endpoint que no resuelva a 127.0.0.1 / ::1. Los
+gabarits deterministas siguen siendo el valor por defecto.
+
+**Los paquetes IOC nunca los transmite Snitch.** `GET /security/iocpack`
+codifica tus indicadores en un filtro Bloom + randomized response (ε≈4,6)
+y te entrega el archivo — tú decides si compartirlo. Importar un paquete
+solo devuelve pistas probabilísticas; nunca bloquea automáticamente.
+
+**Las sondas de inspección son de solo lectura y locales.** La sonda
+eBPF, la inspección Frida, los contadores `perf_event_open`, los escaneos
+de integridad de módulos y el respondedor sinkhole solo *leen* estado
+local y escuchan en 127.0.0.1 — ninguno envía datos.
+
**La geolocalización es 100 % offline.** Una vez un `.mmdb` de DB-IP Lite
o MaxMind GeoLite2 en `<data_dir>/geo/`, las consultas son locales. Sin
base, las IP simplemente no muestran ubicación. No hay servicio HTTP de
diff --git a/PRIVACY.ja.md b/PRIVACY.ja.md
index 51a6ea2..2d9ddbf 100644
--- a/PRIVACY.ja.md
+++ b/PRIVACY.ja.md
@@ -40,6 +40,23 @@ Slack、Telegram ボットエンドポイント、任意 URL)を貼りスイ
warning/critical アラートのテキストがそのエンドポイントへリアルタイム
POST されます。スイッチ OFF の間は一切送信しません。
+**ローカル LLM エンリッチ(オプトイン、デフォルト OFF)。**
+`slm_enabled` 有効時、アラートの*メタデータ*(種別・プロセス・宛先)は
+Ollama 互換モデルへ送られる場合があります — **loopback アドレスのみ**:
+127.0.0.1 / ::1 に解決しないエンドポイントはバックエンドが拒否します。
+決定的テンプレートが引き続きデフォルトです。
+
+**IOC パックは Snitch が送信することはありません。**
+`GET /security/iocpack` はローカル指標を Bloom フィルター +
+randomized response(ε≈4.6)でエンコードしてファイルを渡します —
+共有するかはあなた次第。インポートは確率的ヒントのみで、自動
+ブロックしません。
+
+**検査プローブは読み取り専用・ローカル。** eBPF プローブ、Frida
+インスペクション、`perf_event_open` カウンタ、モジュール整合性
+スキャン、シンクホールレスポンダはローカル状態を*読む*だけで
+127.0.0.1 で待ち受けます — データを送るものはありません。
+
**ジオロケーションは 100% オフライン。** DB-IP Lite または MaxMind
GeoLite2 の `.mmdb` が `<data_dir>/geo/` にあれば、ルックアップはローカル
で完結。DB が無ければ IP は単に位置を表示しません。HTTP ジオロケーション
diff --git a/PRIVACY.md b/PRIVACY.md
index b1521c6..5feb72c 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -41,6 +41,25 @@ URL (Discord, Slack, Telegram bot endpoint or any URL) and flip the switch,
warning/critical alert texts are POSTed to that endpoint in real time.
Nothing is sent while the switch is off.
+**Local LLM enrichment (opt-in, off by default).** When `slm_enabled` is
+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.
+
+**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.
+
+**Inspection probes stay read-only and local.** The eBPF connect probe,
+Frida deep-inspection, `perf_event_open` counters, module/Merkle integrity
+scans and the loopback sinkhole responder only *read* local state and
+listen on 127.0.0.1 — none of them sends data anywhere.
+
**Geolocation is offline-only.** Once a DB-IP Lite or MaxMind GeoLite2
`.mmdb` file sits in `<data_dir>/geo/`, lookups happen locally against that
file. Without it, IPs simply show no location. There is no HTTP geolocation
@@ -106,6 +125,26 @@ et basculez l'interrupteur, les textes des alertes warning/critiques sont
POSTés vers cet endpoint en temps réel. Rien n'est envoyé tant que
l'interrupteur est éteint.
+**Enrichissement LLM local (opt-in, désactivé par défaut).** Quand
+`slm_enabled` est activé, les *métadonnées* d'alerte (type, processus,
+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.
+
+**Les paquets IOC ne sont jamais transmis par Snitch.**
+`GET /security/iocpack` construit un encodage filtre de Bloom +
+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.
+
+**Les sondes d'inspection restent en lecture seule et locales.** La sonde
+eBPF, l'inspection Frida, les compteurs `perf_event_open`, les scans
+d'intégrité module/Merkle et le répondeur sinkhole ne font que *lire*
+l'état local et écouter sur 127.0.0.1 — aucun n'envoie de données.
+
**La géolocalisation est 100 % hors ligne.** Une fois un fichier `.mmdb`
DB-IP Lite ou MaxMind GeoLite2 dans `<data_dir>/geo/`, les recherches se
font localement. Sans base, les IP n'affichent simplement pas de position.
diff --git a/PRIVACY.pt-BR.md b/PRIVACY.pt-BR.md
index d6de77d..e2e76d6 100644
--- a/PRIVACY.pt-BR.md
+++ b/PRIVACY.pt-BR.md
@@ -42,6 +42,23 @@ URL) e liga o interruptor, os textos de alertas warning/críticos são
POSTados ao endpoint em tempo real. Nada é enviado com o interruptor
desligado.
+**Enriquecimento LLM local (opt-in, desligado por padrão).** Com
+`slm_enabled`, os *metadados* de alertas (tipo, processo, destino) podem
+ser enviados a um modelo compatível com Ollama — **somente loopback**:
+o backend rejeita qualquer endpoint que não resolva para 127.0.0.1 /
+::1. Os gabarits determinísticos continuam como padrão.
+
+**Pacotes IOC nunca são transmitidos pelo Snitch.**
+`GET /security/iocpack` codifica seus indicadores em filtro de Bloom +
+randomized response (ε≈4,6) e entrega o arquivo — você decide se
+compartilha. A importação só devolve pistas probabilísticas; nunca
+bloqueia automaticamente.
+
+**As sondas de inspeção são somente leitura e locais.** A sonda eBPF,
+a inspeção Frida, contadores `perf_event_open`, varreduras de
+integridade de módulos e o respondedor sinkhole apenas *leem* estado
+local e escutam em 127.0.0.1 — nenhuma envia dados.
+
**A geolocalização é 100 % offline.** Com um `.mmdb` de DB-IP Lite ou
MaxMind GeoLite2 em `<data_dir>/geo/`, as consultas são locais. Sem base,
os IPs simplesmente não mostram localização. Não existe serviço HTTP de
diff --git a/PRIVACY.ru.md b/PRIVACY.ru.md
index 2397440..a3ad750 100644
--- a/PRIVACY.ru.md
+++ b/PRIVACY.ru.md
@@ -42,6 +42,22 @@ URL webhook'а (Discord, Slack, endpoint Telegram-бота или любой URL
POST'ом на этот endpoint в реальном времени. При выключенном
переключателе ничего не отправляется.
+**Локальное обогащение LLM (opt-in, выключено по умолчанию).** При
+`slm_enabled` *метаданные* алертов (тип, процесс, назначение) могут
+отправляться модели, совместимой с Ollama — **только loopback**: backend
+отклоняет любой endpoint, не резолвящийся в 127.0.0.1 / ::1.
+Детерминистические шаблоны остаются стандартом.
+
+**Пакеты IOC никогда не передаются Snitch.** `GET /security/iocpack`
+кодирует ваши индикаторы в фильтр Блума + randomized response (ε≈4,6)
+и отдаёт файл — вы решаете, делиться ли им. Импорт возвращает лишь
+вероятностные подсказки; автоблокировки нет.
+
+**Зонды инспекции остаются read-only и локальными.** Зонд eBPF,
+инспекция Frida, счётчики `perf_event_open`, проверки целостности
+модулей и респондер sinkhole лишь *читают* локальное состояние и слушают
+на 127.0.0.1 — никто не отправляет данные.
+
**Геолокация — только офлайн.** Как только `.mmdb` DB-IP Lite или MaxMind
GeoLite2 окажется в `<data_dir>/geo/`, запросы выполняются локально. Без
базы IP просто не показывают местоположение. HTTP-сервиса геолокации нет —
diff --git a/PRIVACY.zh-CN.md b/PRIVACY.zh-CN.md
index 66af2f6..77681ca 100644
--- a/PRIVACY.zh-CN.md
+++ b/PRIVACY.zh-CN.md
@@ -34,6 +34,19 @@ UI 中掩码显示)。没有提供商或密钥则零查询——`ti.check()`
warning/critical 告警文本会实时 POST 到该端点。开关关闭时不发送
任何内容。
+**本地 LLM 增强(选择性开启,默认关闭)。** 启用 `slm_enabled` 后,
+告警*元数据*(类型、进程、目标)可能发送到 Ollama 兼容模型 ——
+**仅限 loopback 地址**:后端会拒绝任何不解析到 127.0.0.1 / ::1 的
+端点。确定性模板仍为默认。
+
+**IOC 包绝不会由 Snitch 传输。** `GET /security/iocpack` 将本地指标
+编码为 Bloom 过滤器 + randomized response(ε≈4.6)并把文件交给你
+—— 是否分享由你决定。导入仅返回概率性提示,绝不自动封禁。
+
+**检查探针保持只读且本地。** eBPF 探针、Frida 深度检查、
+`perf_event_open` 计数器、模块完整性扫描和沉洞响应器只*读取*本地
+状态并监听 127.0.0.1 —— 没有任何数据被发送。
+
**地理定位 100% 离线。** 只要 `<data_dir>/geo/` 中存在 DB-IP Lite 或
MaxMind GeoLite2 的 `.mmdb` 文件,查询全部在本地完成。没有数据库时,
IP 只是不显示位置。不存在任何 HTTP 地理定位服务——ip-api.com 被移除
diff --git a/ROADMAP.md b/ROADMAP.md
index aa49e6b..f331c23 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -41,25 +41,28 @@ Also live / également en place : Docker image on GHCR, Homebrew tap (`brew inst
- Blocklist imports (StevenBlack hosts, EasyList) — needs a privacy/licensing review first / import de blocklists — revue vie privée/licence requise
- Firewall profiles (strict/travel vs developer/permissive) / profils pare-feu (strict/voyage vs dev/permissif)
-## � Research — documented, not implemented / documenté, pas implémenté
-
-Ideas that would take Snitch toward a desktop EDR/XDR. They are tracked
-here honestly — **none of them is implemented**, each needs its own design,
-native components and often a second binary artifact / Idées qui mèneraient
-Snitch vers un EDR/XDR de bureau. Suivies ici honnêtement — **aucune n'est
-implémentée**, chacune exige sa conception, des composants natifs et souvent
-un second artefact binaire :
-
-- **eBPF probes (Linux)** — `sys_enter_connect`/`accept` kernel-space capture, bypass-resistant; needs a compiled BPF program + root / sondes eBPF — capture noyau in-contournable ; exige un programme BPF compilé + root
-- **WFP callout (Windows)** — real kernel packet filtering instead of `netsh` rule orchestration; needs a signed kernel driver / callout WFP — filtrage noyau réel au lieu de l'orchestration `netsh` ; exige un driver signé
-- **NetworkExtension (macOS)** — `NEFilterProvider` for per-bundle filtering; needs Apple Developer ID + entitlements / `NEFilterProvider` pour filtrer par bundle ; exige Developer ID + entitlements
-- **Memory/flow correlation** — *partially shipped*: RWX memory scan (Linux `/proc/<pid>/maps`) + name/exe mismatch + exe hash watch are live; unsigned-DLL / full memory forensics stay here / *partiellement livré* : scan mémoire RWX + mismatch nom/exe + veille de hash sont actifs ; inspection DLL complète reste ici
-- **Dynamic Taint Analysis** — prove exfiltration byte-for-byte; heavy research / analyse de teinture dynamique — prouver l'exfiltration octet par octet ; recherche lourde
-- **Local SecOps SLM** — a 1–3 B param model explaining alerts in natural language; *deterministic bilingual explanations ship today* (`/security/explain`), the model stays research / SLM SecOps local — modèle 1–3 Md ; *des explications déterministes bilingues sont livrées* (`/security/explain`), le modèle reste en recherche
-- **ZKP fleet intel** — share detections across a peer fleet without revealing endpoints / intel de flotte en ZKP — partager les détections sans révéler les endpoints
-- **PMU/hardware counters** — ransomware tells below the OS (speculation, crypto bursts) / compteurs matériels PMU — signaux de ransomware sous l'OS
-- **Merkle integrity of loaded modules** — *partially shipped*: executable SHA-256 baselines detect on-disk replacement (`BINARY_CHANGED`); full module-tree verification stays here / *partiellement livré* : les baselines SHA-256 d'exécutables détectent le remplacement sur disque (`BINARY_CHANGED`) ; la vérification complète des modules reste ici
-- **Sinkholing / micro-containment** — *partially shipped*: `sinkhole` rule action redirects domains (hosts) and IPs (iptables DNAT, Linux) to loopback; a real honeypot responder and micro-VM containment stay here / *partiellement livré* : l'action `sinkhole` redirige domaines (hosts) et IP (DNAT iptables, Linux) vers loopback ; un vrai honeypot répondeur et le confinement micro-VM restent ici
+## 🔬 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 :
+
+- **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
+- **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
+- **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
+- **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
## 🚫 Out of scope / hors périmètre
diff --git a/backend/api/main.py b/backend/api/main.py
index a4d49b1..a10f5c0 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -89,9 +89,16 @@ 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 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 explain as alert_explain
+from detection import iocshare
+from detection.llm_local import LocalSlm
+from detection.miner import MinerDetector
+from detection import perfprobe
+from detection.sinkresponder import SinkholeResponder
from detection.threatintel import ThreatIntel
from api.notify import notifier
from paths import data_dir
@@ -123,6 +130,16 @@ ti = ThreatIntel()
# FR: Veille d'intégrité des processus en lecture seule — baselines de hash
# d'exes, mismatch nom/exe, maps RWX Linux. Inspection locale, état borné.
integrity = IntegrityWatcher()
+# EN: Optional/kernel-adjacent security modules — every one degrades
+# honestly when its platform requirement isn't met (see each module).
+# FR: Modules de sécurité optionnels/proches noyau — chacun dégrade
+# honnêtement quand sa prérequis plateforme manque (cf. chaque module).
+ebpf = EbpfProbe() # EN: kprobe connect attribution (Linux+bcc)
+ # FR: attribution connect par kprobe
+deep = DeepInspector() # EN: Frida module-origin attribution / FR: attribution de module Frida
+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
_loop: asyncio.AbstractEventLoop | None = None
_sniffer: PacketSniffer | None = None
_scanner: ARPScanner | None = None
@@ -202,17 +219,40 @@ class IgnoreBody(BaseModel):
class FirewallRuleBody(BaseModel):
- """EN: /firewall/rules payload — block or sinkhole an IP, domain suffix
- or process. `action` defaults to "block"; "sinkhole" redirects the
- destination to loopback (hosts file for domains, iptables DNAT on
- Linux for IPs).
- FR: Charge utile de /firewall/rules — bloquer ou trou-noircir une IP,
- un suffixe de domaine ou un processus. `action` = « block » (défaut) ;
- « sinkhole » redirige vers loopback (hosts pour les domaines, DNAT
- iptables sous Linux pour les IP)."""
+ """EN: /firewall/rules payload — block, sinkhole or throttle an IP,
+ domain suffix or process. `action` defaults to "block"; "sinkhole"
+ redirects the destination to loopback (hosts file for domains, DNAT
+ on Linux for IPs); "throttle" rate-limits to `rate` kbit/s (Linux tc).
+ FR: Charge utile de /firewall/rules — bloquer, trou-noircir ou limiter
+ une IP, un suffixe de domaine ou un processus. `action` = « block »
+ (défaut) ; « sinkhole » redirige vers loopback ; « throttle » limite
+ à `rate` kbit/s (tc Linux)."""
kind: str
value: str
action: str = "block"
+ rate: int = 64
+
+
+class PidSecondsBody(BaseModel):
+ """EN: PID + bounded duration for inspect/sample endpoints.
+ FR: PID + durée bornée pour les endpoints d'inspection/échantillonnage."""
+ pid: int
+ seconds: int = 20
+
+
+class ExplainBody(BaseModel):
+ """EN: /security/explain payload — alert type + context detail + lang.
+ FR: Charge utile de /security/explain — type + contexte + langue."""
+ type: str
+ detail: dict = Field(default_factory=dict)
+ lang: str = "en"
+
+
+class IocImportBody(BaseModel):
+ """EN: /security/iocpack/import payload — a received pack to check
+ local indicators against. / FR: Charge utile d'import IOC — un paquet
+ reçu à confronter aux indicateurs locaux."""
+ pack: dict = Field(default_factory=dict)
class FirewallToggleBody(BaseModel):
@@ -888,6 +928,22 @@ def _process_batch(packets: list[Packet]) -> None:
db.log_alert(ad)
out_alerts.append(ad)
+ # EN: Mining signals — cleartext stratum in the payload head and
+ # 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).
+ for f in miner.analyze_packet(pkt):
+ a = Alert(
+ type=f["type"], severity=f["severity"],
+ message=f"Mining: {f['type'].replace('_', ' ').title()} — "
+ f"{f.get('process')}: {f.get('detail', '')}",
+ node_id=remote_ip, details=f)
+ _flag_alert(a, nodes)
+ ad = a.to_dict()
+ db.log_alert(ad)
+ out_alerts.append(ad)
+ asyncio.get_running_loop().create_task(_notify(ad))
+
# EN: Outbound packets with attribution feed the integrity watch —
# the watcher itself is bounded (one inspection per pid lifetime).
# FR: Les paquets sortants attribués alimentent la veille d'intégrité —
@@ -966,6 +1022,7 @@ async def _drain_loop() -> None:
message « batch ». Remplace l'ancienne tempête coroutine+broadcast
par paquet.
"""
+ ticks = 0
while not _shutdown:
batch: list[Packet] = []
for _ in range(DRAIN_MAX_PACKETS):
@@ -978,9 +1035,39 @@ async def _drain_loop() -> None:
await broadcast(_process_batch(batch))
except Exception as exc:
logger.exception("packet batch failed: %s", exc)
+ ticks += 1
+ # EN: ~10 s — pool-port suspects get their CPU corroboration in an
+ # executor (cpu_percent samples briefly; never on the loop).
+ # FR: ~10 s — les suspects port-pool reçoivent leur corroboration
+ # CPU dans un executor (cpu_percent échantillonne ; jamais sur
+ # la boucle).
+ if ticks % 40 == 0:
+ asyncio.get_running_loop().create_task(_miner_corroborate())
await asyncio.sleep(DRAIN_INTERVAL_S)
+async def _miner_corroborate() -> None:
+ """EN: Sample CPU for pool-port suspects off the event loop; each
+ corroborated case becomes a MINING_SUSPECT alert.
+ FR: Échantillonner la CPU des suspects port-pool hors boucle ; chaque
+ cas corroboré devient une alerte MINING_SUSPECT."""
+ loop = asyncio.get_running_loop()
+ try:
+ findings = await loop.run_in_executor(None, miner.cpu_corroborate)
+ except Exception as exc:
+ logger.debug("miner corroboration failed: %s", exc)
+ return
+ for f in findings:
+ a = Alert(type=f["type"], severity=f["severity"],
+ message=f"Mining suspect — {f.get('process')}: "
+ f"{f.get('detail', '')}",
+ node_id=f.get("ip"), details=f)
+ d = a.to_dict()
+ db.log_alert(d)
+ await broadcast({"type": "alert", "alert": d})
+ await _notify(d)
+
+
def _evict_weakest_node() -> None:
"""
EN: Remove the lowest-byte, non-alerted, non-local node (and its edges)
@@ -1164,6 +1251,33 @@ def _flush_loop() -> None:
changed)
except Exception as exc:
logger.debug("domain refresh failed: %s", exc)
+ # EN: Sinkhole responder lifecycle — listen while at least one
+ # enabled sinkhole rule exists, drain its hits into alerts.
+ # FR: Cycle de vie du répondeur sinkhole — écouter tant qu'une
+ # règle sinkhole active existe, vider ses hits en alertes.
+ try:
+ rules_now, _ld = fw.serialized()
+ has_sink = any(r.get("action") == "sinkhole" and r.get("enabled", True)
+ for r in rules_now)
+ if has_sink:
+ sink.start()
+ else:
+ sink.stop()
+ for hit in sink.pop_hits():
+ a = Alert(
+ type="SINKHOLE_HIT", severity="warning",
+ message=f"Sinkholed connection observed: "
+ f"{hit.get('host') or hit.get('kind')} — "
+ f"{hit.get('process') or 'pid ' + str(hit.get('pid'))}",
+ node_id=None, details=hit)
+ d = a.to_dict()
+ db.log_alert(d)
+ if _loop:
+ asyncio.run_coroutine_threadsafe(
+ broadcast({"type": "alert", "alert": d}), _loop)
+ asyncio.run_coroutine_threadsafe(_notify(d), _loop)
+ except Exception as exc:
+ logger.debug("sinkhole responder tick failed: %s", exc)
def _cleanup_loop() -> None:
@@ -1198,6 +1312,16 @@ def _start_capture() -> None:
else:
_sniffer = PacketSniffer(callback=on_packet, ports=_port_filter,
iface=db.get_setting("interface"))
+ # EN: eBPF attribution probe — kernel sees every connect() even
+ # from processes that die before the next socket-table refresh.
+ # Opt-in-able via settings, silently no-ops without bcc/root.
+ # FR: Sonde d'attribution eBPF — le noyau voit chaque connect() même
+ # des processus morts avant le prochain rafraîchissement de la
+ # table. Réglable, silencieusement inactive sans bcc/root.
+ if db.get_setting("ebpf_probe", True):
+ if ebpf.start():
+ _sniffer.set_attribution_probe(ebpf)
+ logger.info("eBPF connect probe active")
threading.Thread(target=_sniffer.start, daemon=True).start()
_scanner = ARPScanner(callback=on_device, interval=30)
threading.Thread(target=_scanner.start, daemon=True).start()
@@ -1298,6 +1422,11 @@ def _load_settings() -> None:
notifier.configure(db.get_setting("webhook_url", "") or "",
bool(db.get_setting("webhook_enabled", False)),
db.get_setting("telegram_chat_id", "") or "")
+ # EN: Local SLM enrichment — loopback-only by construction, opt-in.
+ # 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 "")
if _port_filter:
logger.info("restored port filter: %s", _port_filter)
@@ -1345,6 +1474,8 @@ async def _shutdown_all() -> None:
global _shutdown
_shutdown = True
_stop_capture()
+ ebpf.stop()
+ sink.stop()
if _media_monitor:
_media_monitor.stop()
# EN: Final drain + flush so nothing in flight is lost.
@@ -1472,6 +1603,22 @@ async def post_settings(body: SettingsBody) -> dict:
db.get_setting("telegram_chat_id", "") or "")
if key == "integrity_watch":
integrity.configure(bool(value))
+ if key == "ebpf_probe":
+ # EN: Live toggle — start the probe or stop it; never raises
+ # (bcc/root absence is reported by /security/ebpf instead).
+ # FR: Bascule à chaud — démarre ou arrête la sonde ; ne lève
+ # jamais (bcc/root absents rapportés par /security/ebpf).
+ if value:
+ ebpf.start()
+ if _sniffer is not None and hasattr(
+ _sniffer, "set_attribution_probe"):
+ _sniffer.set_attribution_probe(ebpf)
+ else:
+ ebpf.stop()
+ if key in ("slm_enabled", "slm_endpoint", "slm_model"):
+ slm.configure(bool(db.get_setting("slm_enabled", False)),
+ db.get_setting("slm_endpoint", "") or "",
+ db.get_setting("slm_model", "") or "")
return {"ok": True}
@app.get("/capture/status", dependencies=_AUTH)
@@ -1984,7 +2131,7 @@ async def firewall_add_rule(body: FirewallRuleBody) -> dict:
loop = asyncio.get_running_loop()
try:
rule = await loop.run_in_executor(
- None, fw.add_rule, body.kind, body.value, body.action)
+ None, fw.add_rule, body.kind, body.value, body.action, body.rate)
except ValueError as exc:
raise HTTPException(400, str(exc))
rules, lockdown = fw.serialized()
@@ -2148,6 +2295,147 @@ async def integrity_check(body: PidBody) -> dict:
return {"pid": body.pid, "findings": findings}
[email protected]("/security/ebpf", dependencies=_AUTH)
+async def ebpf_status() -> dict:
+ """EN: eBPF connect-probe status — availability reason is always
+ reported honestly (linux-only, root, python3-bcc).
+ FR: État de la sonde eBPF — la raison d'indisponibilité est toujours
+ rapportée honnêtement (linux, root, python3-bcc)."""
+ return ebpf.status()
+
+
[email protected]("/security/deep_inspect", dependencies=_AUTH)
+async def deep_inspect(body: PidSecondsBody) -> dict:
+ """EN: Bounded Frida inspection — attach to ONE pid for ≤60 s and
+ report which module (exe/DLL) initiated each connection attempt,
+ plus staging-path flags for injected code. Requires the optional
+ `frida` package and the OS's usual debugger permissions.
+ FR: Inspection Frida bornée — attache à UN pid ≤60 s et rapporte quel
+ module (exe/DLL) a initié chaque connexion, plus les signalements
+ de chemins de staging pour le code injecté. Exige le paquet
+ `frida` optionnel et les droits de débogage usuels de l'OS."""
+ if body.pid <= 3 or body.pid == os.getpid():
+ raise HTTPException(400, "refusing to inspect a system/critical pid")
+ 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", []))
+ if res["suspicious_paths"]:
+ a = Alert(type="INJECT_SUSPECT", severity="critical",
+ message=f"Injected-module suspicion in pid {body.pid} — "
+ f"module(s) in staging paths made connections",
+ details={"pid": body.pid,
+ "paths": res["suspicious_paths"]})
+ d = a.to_dict()
+ db.log_alert(d)
+ await broadcast({"type": "alert", "alert": d})
+ await _notify(d)
+ return res
+
+
[email protected]("/security/sinkhole", dependencies=_AUTH)
+async def sinkhole_status() -> dict:
+ """EN: Sinkhole responder state — which loopback listeners are bound
+ (80 HTTP / 443 SNI) plus the recent captured hits.
+ FR: État du répondeur sinkhole — quels écouteurs loopback sont liés
+ (80 HTTP / 443 SNI) plus les hits capturés récents."""
+ return sink.status()
+
+
[email protected]("/security/perf", dependencies=_AUTH)
+async def perf_sample(body: PidSecondsBody) -> dict:
+ """EN: Hardware-counter sample for one pid — cycles, instructions,
+ cache-misses over ≤10 s via perf_event_open (Linux; gated by
+ kernel.perf_event_paranoid). Corroborates MINING_SUSPECT.
+ FR: Échantillon de compteurs matériels pour un pid — cycles,
+ instructions, cache-misses sur ≤10 s via perf_event_open (Linux ;
+ sous réserve de kernel.perf_event_paranoid)."""
+ if body.pid <= 3:
+ raise HTTPException(400, "refusing to sample a kernel pid")
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(
+ None, perfprobe.sample, body.pid, min(body.seconds, 10))
+
+
[email protected]("/security/slm", dependencies=_AUTH)
+async def slm_status() -> dict:
+ """EN: Local SLM (Ollama-compatible) status — enabled, loopback
+ endpoint, reachable model. Never hides "unreachable".
+ FR: État du SLM local (compatible Ollama) — activé, endpoint loopback,
+ modèle joignable. Ne cache jamais « injoignable »."""
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(None, slm.status)
+
+
[email protected]("/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é."""
+ loop = asyncio.get_running_loop()
+ indicators = await loop.run_in_executor(None, _collect_indicators)
+ return iocshare.build_pack(indicators)
+
+
[email protected]("/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.
+ FR: Confronter les destinations observées à un paquet communautaire
+ reçu — renvoie des indices probabilistes, ne bloque jamais seul."""
+ candidates = [ip for ip in nodes if ip != "local"]
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(
+ None, iocshare.check_pack, body.pack, candidates)
+
+
+def _collect_indicators() -> list[str]:
+ """EN: Local indicators worth sharing — firewall rule targets,
+ alert IPs of the serious types, changed-binary hashes. Bounded.
+ FR: Indicateurs locaux partageables — cibles des règles pare-feu,
+ IP des alertes sérieuses, hash des binaires modifiés. Borné."""
+ out: list[str] = []
+ rules, _ld = fw.serialized()
+ for r in rules:
+ v = str(r.get("value", ""))
+ if v and r.get("kind") in ("ip", "cidr", "domain"):
+ out.append(v)
+ try:
+ for a in db.get_alerts(500):
+ d = a.get("details") or {}
+ for key in ("ip", "host", "exe", "actual"):
+ v = d.get(key)
+ if isinstance(v, str) and v:
+ out.append(v)
+ except Exception: # noqa: BLE001
+ pass
+ return list(dict.fromkeys(out))[:4096]
+
+
[email protected]("/security/explain", dependencies=_AUTH)
+async def security_explain_post(body: ExplainBody) -> dict:
+ """EN: Alert explanation — deterministic bilingual templates always;
+ `llm` carries the optional localhost-SLM natural-language variant
+ when slm_enabled and the model answers (else absent).
+ FR: Explication d'alerte — gabarits bilingues déterministes toujours ;
+ `llm` porte la variante SLM local quand activé et joignable."""
+ rec = alert_explain.explain(body.type)
+ if rec is None:
+ raise HTTPException(404, f"no explanation for alert type {body.type!r}")
+ out = {"type": body.type.upper(), **rec}
+ loop = asyncio.get_running_loop()
+ llm = await loop.run_in_executor(
+ None, slm.enrich, body.type, body.detail,
+ body.lang if body.lang in ("en", "fr") else "en")
+ if llm:
+ out["llm"] = llm
+ return out
+
+
@app.get("/security/explain", dependencies=_AUTH)
async def security_explain(type: str = "") -> dict:
"""EN: Plain-language, bilingual explanation for one alert type —
@@ -2412,7 +2700,8 @@ def _forensics_stix(bundle: dict, ip: Optional[str] = None) -> dict:
SIEM ; volontairement pas un graphe complet."""
import uuid
ts = bundle["generated_at"]
- _uid = lambda s: str(uuid.uuid5(uuid.NAMESPACE_DNS, f"snitch.local/{s}"))
+ def _uid(s: str) -> str:
+ return str(uuid.uuid5(uuid.NAMESPACE_DNS, f"snitch.local/{s}"))
objects: list[dict] = [{
"type": "identity", "spec_version": "2.1",
"id": f"identity--{_uid('exporter')}",
diff --git a/backend/capture/ebpf_probe.py b/backend/capture/ebpf_probe.py
new file mode 100644
index 0000000..06691c5
--- /dev/null
+++ b/backend/capture/ebpf_probe.py
@@ -0,0 +1,226 @@
+"""
+EN: Optional eBPF connect probe (Linux only, opt-in). When the `bcc`
+ package and root privileges are present, Snitch attaches kprobes to
+ tcp_v4_connect / tcp_v6_connect — the kernel functions performing
+ connect() — and streams (pid, comm, dst) events into a small ring.
+ The sniffer consults that ring when its psutil socket-table lookup
+ misses: short-lived processes (curl, malware droppers) vanish before
+ psutil snapshots them, but the kprobe sees every connect() attempt,
+ even the ones that fail.
+
+ If bcc/kernel headers/root are missing, the probe reports
+ available=False and the pipeline keeps working with psutil only —
+ graceful, honest degradation. Nothing is simulated.
+
+ Layout follows iovisor/bcc's tcpconnect.py (Apache-2.0): same kprobes,
+ same perf-buffer mechanism, reduced to the fields Snitch needs.
+
+FR: Sonde eBPF optionnelle pour connect() (Linux seulement, opt-in). Quand
+ le paquet `bcc` et les droits root sont présents, Snitch attache des
+ kprobes à tcp_v4_connect / tcp_v6_connect — les fonctions noyau qui
+ réalisent connect() — et streame les événements (pid, comm, dst) vers
+ un petit anneau. Le sniffer le consulte quand la table psutil rate :
+ les processus courts disparaissent avant l'instantané psutil, mais la
+ kprobe voit chaque tentative, même celles qui échouent.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import ipaddress
+import os
+import platform
+import threading
+import time
+
+# EN: Recent connect events keyed by (dst_ip, dst_port) — TTL-bounded.
+# FR: Événements connect récents indexés (dst_ip, dst_port) — TTL borné.
+_EVENT_TTL = 60.0
+
+# EN: Minimal eBPF program — one kprobe per address family, emitting the
+# connect() destination. tcpconnect.py traces more fields; we need
+# only pid+comm+dst for attribution.
+# FR: Programme eBPF minimal — une kprobe par famille, émettant la
+# destination du connect(). tcpconnect.py trace plus de champs ; seuls
+# pid+comm+dst servent à l'attribution.
+_BPF_SRC = r"""
+#include <uapi/linux/ptrace.h>
+#include <net/sock.h>
+#include <bcc/proto.h>
+
+struct snitch_evt {
+ u32 pid;
+ char comm[16];
+ u16 dport;
+ u8 ipver;
+ u8 daddr[16];
+};
+
+BPF_PERF_OUTPUT(events);
+
+static int trace_connect(struct pt_regs *ctx, struct sock *sk, int v6) {
+ struct snitch_evt ev = {};
+ ev.pid = bpf_get_current_pid_tgid() >> 32;
+ bpf_get_current_comm(&ev.comm, sizeof(ev.comm));
+ ev.dport = ntohs(sk->__sk_common.skc_dport);
+ ev.ipver = v6;
+ if (v6) {
+ bpf_probe_read_kernel(&ev.daddr, 16,
+ (void *)sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
+ } else {
+ bpf_probe_read_kernel(&ev.daddr, 4,
+ (void *)&sk->__sk_common.skc_daddr);
+ }
+ events.perf_submit(ctx, &ev, sizeof(ev));
+ return 0;
+}
+
+int kprobe__tcp_v4_connect(struct pt_regs *ctx, struct sock *sk) {
+ return trace_connect(ctx, sk, 4);
+}
+int kprobe__tcp_v6_connect(struct pt_regs *ctx, struct sock *sk) {
+ return trace_connect(ctx, sk, 6);
+}
+"""
+
+
+class _Event(ctypes.Structure):
+ """EN: ctypes mirror of struct snitch_evt for perf-buffer decoding.
+ FR: Miroir ctypes de struct snitch_evt pour décoder le perf buffer."""
+ _fields_ = [("pid", ctypes.c_uint32), ("comm", ctypes.c_char * 16),
+ ("dport", ctypes.c_uint16), ("ipver", ctypes.c_uint8),
+ ("daddr", ctypes.c_uint8 * 16)]
+
+
+class EbpfProbe:
+ """EN: Lifecycle + lookup for the connect probe. start() compiles the
+ BPF program (needs kernel headers — that is the honest requirement) and
+ spawns a poll thread; lookup(ip, port) returns (pid, comm) when a recent
+ connect() event matches.
+ FR: Cycle de vie + consultation de la sonde. start() compile le
+ programme BPF (en-têtes noyau requis — c'est l'exigence honnête) et
+ lance un thread de poll ; lookup(ip, port) renvoie (pid, comm) si un
+ événement connect() récent correspond."""
+
+ def __init__(self):
+ self._bpf = None
+ self._thread: threading.Thread | None = None
+ self._stop = threading.Event()
+ self._events: dict[tuple[str, int], tuple[int, str, float]] = {}
+ # EN: (ip,port) pairs seen from ≥2 distinct pids — attribution
+ # there would be a coin flip (any shared 443), so we refuse it.
+ # FR: Paires (ip,port) vues depuis ≥2 pids — l'attribution y serait
+ # aléatoire (tout 443 partagé), on la refuse donc.
+ self._ambiguous: set[tuple[str, int]] = set()
+ self._lock = threading.Lock()
+ self._err: str | None = None
+
+ # ── availability / disponibilité ─────────────────────────────────────────
+
+ @staticmethod
+ def available() -> tuple[bool, str]:
+ """EN: Honest capability check — Linux + root + bcc importable.
+ FR: Vérification honnête — Linux + root + bcc importable."""
+ if platform.system().lower() != "linux":
+ return False, "linux only"
+ if os.geteuid() != 0:
+ return False, "requires root"
+ try:
+ import bcc # noqa: F401
+ except ImportError:
+ return False, "python3-bcc not installed"
+ return True, ""
+
+ def status(self) -> dict:
+ ok, why = self.available()
+ with self._lock:
+ n = len(self._events)
+ return {"available": ok, "reason": None if ok else why,
+ "active": self._bpf is not None, "events_buffered": n,
+ "error": self._err}
+
+ # ── lifecycle / cycle de vie ─────────────────────────────────────────────
+
+ def start(self) -> bool:
+ """EN: Compile + attach. Returns False with _err set when the kernel
+ can't run the probe (no headers, lockdown, old kernel).
+ FR: Compile + attache. False + _err si le noyau refuse (pas
+ d'en-têtes, lockdown, noyau ancien)."""
+ if self._bpf is not None:
+ return True
+ ok, why = self.available()
+ if not ok:
+ self._err = why
+ return False
+ try:
+ from bcc import BPF
+ self._bpf = BPF(text=_BPF_SRC)
+ self._bpf["events"].open_perf_buffer(self._on_evt)
+ except Exception as e: # noqa: BLE001
+ self._err = str(e)[:200]
+ self._bpf = None
+ return False
+ self._stop.clear()
+ self._thread = threading.Thread(target=self._poll, daemon=True,
+ name="snitch-ebpf")
+ self._thread.start()
+ return True
+
+ def stop(self) -> None:
+ self._stop.set()
+ self._bpf = None
+
+ def _poll(self) -> None:
+ while not self._stop.is_set() and self._bpf is not None:
+ try:
+ self._bpf.perf_buffer_poll(timeout=500)
+ except Exception: # noqa: BLE001
+ time.sleep(1)
+
+ # ── events / événements ──────────────────────────────────────────────────
+
+ def _on_evt(self, cpu, data, size) -> None:
+ ev = _Event.from_buffer_copy(
+ ctypes.string_at(data, ctypes.sizeof(_Event)))
+ ip = str(ipaddress.ip_address(
+ bytes(ev.daddr[:4] if ev.ipver == 4 else ev.daddr)))
+ comm = ev.comm.split(b"\x00", 1)[0].decode("utf-8", "replace")
+ key = (ip, ev.dport)
+ with self._lock:
+ prev = self._events.get(key)
+ if prev and prev[0] != ev.pid:
+ # EN: Two different processes hit the same destination —
+ # never guess which one owns a later packet.
+ # FR: Deux processus distincts vers la même destination —
+ # ne jamais deviner lequel émettra le paquet suivant.
+ self._ambiguous.add(key)
+ self._events.pop(key, None)
+ elif key not in self._ambiguous:
+ self._events[key] = (ev.pid, comm, time.time())
+ # EN: Cheap bound — drop the oldest third past 4096 entries.
+ # FR: Borne simple — on jette le tiers le plus vieux après 4096.
+ if len(self._events) > 4096:
+ items = sorted(self._events.items(), key=lambda kv: kv[1][2])
+ self._events = dict(items[len(items) // 3:])
+ self._ambiguous &= set(self._events)
+
+ def lookup(self, ip: str, port: int | None) -> tuple[int | None, str | None]:
+ """EN: (pid, comm) for a recent connect() to this destination —
+ the attribution the socket table misses for short-lived processes.
+ FR: (pid, comm) d'un connect() récent vers cette destination —
+ l'attribution que la table des sockets rate pour les processus
+ courts."""
+ if port is None:
+ return None, None
+ key = (ip, int(port))
+ with self._lock:
+ if key in self._ambiguous:
+ return None, None
+ hit = self._events.get(key)
+ if not hit:
+ return None, None
+ pid, comm, ts = hit
+ if time.time() - ts > _EVENT_TTL:
+ del self._events[key]
+ return None, None
+ return pid, comm
diff --git a/backend/capture/parser.py b/backend/capture/parser.py
index f6e143d..5d5dc5b 100644
--- a/backend/capture/parser.py
+++ b/backend/capture/parser.py
@@ -82,6 +82,15 @@ class ParsedPacket:
# EN: (hostname, requested_ip|None, mac) from a client DHCP message.
# FR: (nom d'hôte, ip demandée|None, mac) d'un message DHCP client.
dhcp: Optional[tuple] = None
+ # EN: First ≤64 bytes of a PLAINTEXT TCP payload — used internally by
+ # the stratum/mining detector only. NEVER stored or broadcast:
+ # it exists to answer "does this flow speak a known-bad cleartext
+ # protocol?" and is dropped with the packet. TLS is skipped.
+ # FR: Premiers ≤64 octets d'un payload TCP EN CLAIR — utilisé
+ # uniquement en interne par le détecteur stratum/minage. JAMAIS
+ # stocké ni diffusé : sert à répondre « ce flux parle-t-il un
+ # protocole malveillant en clair ? », puis jeté. TLS ignoré.
+ app_head: bytes = b""
def parse_frame(linktype: int, buf: bytes) -> Optional[ParsedPacket]:
@@ -254,15 +263,24 @@ def _parse_transport(payload: bytes, proto: int, src: str, dst: str,
# any port — be liberal, check both endpoints' payload anyway).
# FR: Filtre rapide : un enregistrement TLS commence par 0x16 0x03 xx
# sur le port 443 (ou SNI sur tout port — rester souple).
+ sni = None
+ app_head = b""
if tcp_payload[:2] == b"\x16\x03":
sni = parse_tls_sni(tcp_payload)
+ elif tcp_payload:
+ # EN: Cleartext protocol fingerprinting needs only the head —
+ # stratum/HTTP/IRC banners all declare themselves early.
+ # FR: La signature de protocole en clair n'a besoin que de la
+ # tête — stratum/HTTP/IRC se déclarent tôt.
+ app_head = tcp_payload[:64]
dns = []
if sport == 53 or dport == 53:
# EN: DNS-over-TCP has a 2-byte length prefix. / FR: DNS sur TCP a un préfixe de longueur de 2 octets.
dns = parse_dns(tcp_payload[2:]) if len(tcp_payload) > 2 else []
- return ParsedPacket(src, dst, "TCP", wire_len, sport, dport, flags, dns, sni)
+ return ParsedPacket(src, dst, "TCP", wire_len, sport, dport, flags,
+ dns, sni, None, app_head)
if proto == IPPROTO_UDP:
if len(payload) < 8:
diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.py
index 909a066..412d58c 100644
--- a/backend/capture/sniffer.py
+++ b/backend/capture/sniffer.py
@@ -100,6 +100,11 @@ class Packet:
# FR: (nom d'hôte, ip demandée|None, mac) appris d'un message DHCP
# client — nomme l'appareil avant même mDNS/LLMNR.
dhcp: Optional[tuple] = None
+ # EN: ≤64B of cleartext payload for in-process protocol fingerprinting
+ # (stratum miner detection). Internal only — never broadcast.
+ # FR: ≤64 o. de payload en clair pour la signature de protocole en
+ # interne (détection mineur stratum). Interne — jamais diffusé.
+ app_head: bytes = b""
def get_local_ips() -> set[str]:
@@ -206,6 +211,11 @@ class PacketSniffer:
self.local_ips = get_local_ips()
self._session: Optional[PcapSession] = None
self._conn_table = ConnectionTable()
+ # EN: Optional kernel-level attribution probe (eBPF) — consulted when
+ # the socket table misses. Set via set_attribution_probe().
+ # FR: Sonde d'attribution noyau optionnelle (eBPF) — consultée quand
+ # la table des sockets rate. Réglée via set_attribution_probe().
+ self._attribution_probe = None
self._running = False
self._thread: Optional[threading.Thread] = None
# EN: Drop accounting — every discarded frame is counted with its
@@ -218,6 +228,13 @@ class PacketSniffer:
self.stats = {"frames": 0, "delivered": 0, "parse_failed": 0,
"not_for_us": 0}
+ def set_attribution_probe(self, probe) -> None:
+ """EN: Register an object exposing lookup(ip, port) → (pid, name)
+ used as fallback when the connection table misses.
+ FR: Enregistre un objet exposant lookup(ip, port) → (pid, nom)
+ utilisé en repli quand la table des connexions rate."""
+ self._attribution_probe = probe
+
@staticmethod
def _default_iface() -> Optional[str]:
"""
@@ -328,6 +345,16 @@ class PacketSniffer:
pid, process_name = None, None
if local_port and parsed.protocol in ("TCP", "UDP"):
pid, process_name = self._conn_table.lookup(local_port, parsed.protocol)
+ # EN: eBPF fallback — the socket table misses processes that died
+ # between refreshes (short-lived connects); the kprobe ring saw
+ # every connect() call. Only unambiguous events are used.
+ # FR: Repli eBPF — la table des sockets rate les processus morts
+ # entre deux rafraîchissements ; l'anneau kprobe a vu chaque
+ # connect(). Seuls les événements non ambigus servent.
+ if pid is None and direction == "out" and parsed.protocol == "TCP" \
+ and self._attribution_probe is not None:
+ pid, process_name = self._attribution_probe.lookup(
+ dst, parsed.dst_port)
self.callback(Packet(
src_ip=src,
@@ -345,6 +372,7 @@ class PacketSniffer:
sni=parsed.sni,
dns=parsed.dns,
dhcp=parsed.dhcp,
+ app_head=parsed.app_head,
))
self.stats["delivered"] += 1
diff --git a/backend/detection/deepinspect.py b/backend/detection/deepinspect.py
new file mode 100644
index 0000000..f876112
--- /dev/null
+++ b/backend/detection/deepinspect.py
@@ -0,0 +1,174 @@
+"""
+EN: Deep process inspection — the honest user-mode stand-in for dynamic
+ taint analysis. Instead of simulating DTA, Snitch uses Frida (optional,
+ user-installed) to attach to ONE suspicious process for a bounded
+ window and instrument its socket entry points (connect / WSAConnect /
+ sendto / sendmsg). For every outbound connection attempt it reports
+ WHICH MODULE called the API — the return address resolves to the exe
+ or a loaded DLL. That is exactly what catches injected code: a clean
+ "chrome.exe" whose connections originate from a DLL living in %TEMP%
+ is a red flag no packet inspection can produce.
+
+ Bounded: max 60 s attach, max 500 events, one inspect at a time.
+ Frida's own permission model applies (same user, debugger rights;
+ hardened/SIP-protected macOS processes refuse attachment — reported
+ honestly). Nothing is simulated when Frida is absent.
+
+FR: Inspection profonde de processus — le remplaçant user-mode honnête de
+ l'analyse de teinte dynamique. Au lieu de simuler la DTA, Snitch
+ utilise Frida (optionnel, installé par l'utilisateur) pour s'attacher
+ à UN processus suspect pendant une fenêtre bornée et instrumenter ses
+ points d'entrée socket (connect / WSAConnect / sendto / sendmsg). Pour
+ chaque tentative de connexion sortante, il rapporte QUEL MODULE a
+ appelé l'API — l'adresse de retour résout vers l'exe ou une DLL
+ chargée. C'est précisément ce qui attrape le code injecté : un
+ « chrome.exe » sain dont les connexions viennent d'une DLL dans %TEMP%
+ est un signal qu'aucune inspection de paquets ne peut produire.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+
+_MAX_SECONDS = 60
+_MAX_EVENTS = 500
+
+# EN: Frida JS payload — hooks every plausible socket entry point on the
+# platform, parses the sockaddr, and sends back the calling module.
+# Defensive: missing exports are skipped, malformed sockaddr ignored.
+# FR: Payload JS Frida — hooke chaque point d'entrée socket plausible,
+# analyse le sockaddr et renvoie le module appelant. Défensif : les
+# exports absents sont ignorés, les sockaddr malformés sautés.
+_JS = r"""
+var AF_INET = 2, AF_INET6_WIN = 23, AF_INET6_UNIX = 10;
+function parseSockaddr(p) {
+ try {
+ var fam = p.readU16();
+ if (fam === AF_INET) {
+ return {ip: [p.add(4).readU8(), p.add(5).readU8(),
+ p.add(6).readU8(), p.add(7).readU8()].join('.'),
+ port: (p.add(2).readU8() << 8) | p.add(3).readU8()};
+ }
+ if (fam === AF_INET6_WIN || fam === AF_INET6_UNIX) {
+ var b = [];
+ for (var i = 8; i < 24; i += 2)
+ b.push(p.add(i).readU16().toString(16));
+ return {ip: b.join(':'),
+ port: (p.add(2).readU8() << 8) | p.add(3).readU8()};
+ }
+ } catch (e) {}
+ return null;
+}
+function hook(api, lib) {
+ 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) {
+ var sa = parseSockaddr(ptr(args[1]));
+ if (!sa || !sa.ip || sa.ip === '0.0.0.0') return;
+ var mod = null;
+ try { mod = Process.findModuleByAddress(this.returnAddress); }
+ catch (e) {}
+ send({api: api, ip: sa.ip, port: sa.port,
+ module: mod ? mod.name : '?',
+ path: mod ? mod.path : ''});
+ }
+ });
+}
+// EN: POSIX sockets (Linux libc / macOS libsystem) + WinSock2.
+// FR: sockets POSIX (libc Linux / libsystem macOS) + WinSock2.
+['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) {
+ hook(a, 'ws2_32.dll');
+});
+"""
+
+
+class DeepInspector:
+ """EN: One-shot bounded Frida inspection of a PID. inspect() blocks for
+ `seconds` (called from an executor) then detaches and returns the
+ collected {api, ip, port, module, path} events plus a per-module tally.
+ FR: Inspection Frida bornée d'un PID. inspect() bloque `seconds`
+ (appelé depuis un executor) puis se détache et renvoie les événements
+ {api, ip, port, module, path} + le décompte par module."""
+
+ def __init__(self):
+ self._busy = threading.Lock()
+
+ @staticmethod
+ def available() -> tuple[bool, str]:
+ try:
+ import frida # noqa: F401
+ return True, ""
+ except ImportError:
+ return False, "frida not installed (pip install frida)"
+
+ def inspect(self, pid: int, seconds: int = 20) -> dict:
+ """EN: Attach → hook → collect → detach. Never raises; error string
+ explains attach failures (permissions, hardened process, gone pid).
+ FR: Attach → hook → collecte → détache. Ne lève jamais ; l'erreur
+ explique les échecs d'attache."""
+ ok, why = self.available()
+ if not ok:
+ return {"ok": False, "error": why, "events": [], "modules": {}}
+ if not self._busy.acquire(blocking=False):
+ return {"ok": False, "error": "another inspection is running",
+ "events": [], "modules": {}}
+ seconds = max(3, min(int(seconds), _MAX_SECONDS))
+ events: list[dict] = []
+ try:
+ import frida
+ try:
+ session = frida.attach(pid)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False,
+ "error": f"attach failed: {str(e)[:160]}",
+ "events": [], "modules": {}}
+ try:
+ script = session.create_script(_JS)
+ script.on("message", lambda m, d: self._on_msg(m, events))
+ script.load()
+ time.sleep(seconds)
+ finally:
+ try:
+ session.detach()
+ except Exception: # noqa: BLE001
+ pass
+ finally:
+ self._busy.release()
+ modules: dict[str, int] = {}
+ for e in events:
+ modules[e["module"]] = modules.get(e["module"], 0) + 1
+ return {"ok": True, "pid": pid, "seconds": seconds,
+ "events": events[:_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 suspicious_module_paths(events: list[dict]) -> list[str]:
+ """EN: Flag module paths that executable code should never load from —
+ temp dirs, user-writable caches, /dev/shm, downloads. These are the
+ classic injection/extraction staging spots.
+ FR: Signale les chemins de modules d'où du code exécutable ne devrait
+ jamais se charger — temp, caches accessibles, /dev/shm, téléchargements."""
+ bad_markers = ("\\temp\\", "\\tmp\\", "/tmp/", "/dev/shm/",
+ "\\appdata\\local\\temp", "\\downloads\\",
+ "/downloads/", "\\roaming\\", "/.cache/")
+ seen, bad = set(), []
+ for e in events:
+ path = (e.get("path") or "").lower()
+ if path and path not in seen and any(m in path for m in bad_markers):
+ seen.add(path)
+ bad.append(e["path"])
+ return bad
diff --git a/backend/detection/explain.py b/backend/detection/explain.py
index bc8fc08..8ab6315 100644
--- a/backend/detection/explain.py
+++ b/backend/detection/explain.py
@@ -376,6 +376,149 @@ EXPLANATIONS: dict[str, dict] = {
["Vérifier si le processus est une app JIT connue (alertes info)",
"Exporter le forensique du processus",
"Tuer + bloquer si ce n'est pas un navigateur/runtime"]),
+
+"MODULE_SUSPECT": _e(
+ "Module loaded from a staging path",
+ "Module chargé depuis un chemin de staging",
+ "A file-backed library inside the process lives in a location executable "
+ "code should never use: temp dirs, /dev/shm, Downloads, browser caches — "
+ "classic dropper/injection staging.",
+ "Une bibliothèque chargée dans le processus vit dans un emplacement où du "
+ "code exécutable ne devrait jamais être : temp, /dev/shm, Downloads, "
+ "caches de navigateurs — staging classique de dropper/injection.",
+ "Legitimate apps keep their DLLs/.so under Program Files, /usr/lib or "
+ "their own bundle — almost nothing real loads code from %TEMP%.",
+ "Les applications légitimes gardent leurs DLL/.so sous Program Files, "
+ "/usr/lib ou leur propre bundle — presque rien de réel ne charge du code "
+ "depuis %TEMP%.",
+ ["List the flagged module paths in the finding",
+ "Hash the modules and check them against VirusTotal yourself",
+ "Kill + firewall the process if the module is unexpected"],
+ ["Lister les chemins de modules signalés dans le constat",
+ "Hasher les modules et les vérifier sur VirusTotal soi-même",
+ "Tuer + bloquer le processus si le module est inattendu"]),
+
+"MODULE_CHANGED": _e(
+ "Mapped-module set changed",
+ "Ensemble de modules modifié",
+ "The Merkle root over this process's file-backed modules changed versus "
+ "its recorded baseline — a DLL/.so was replaced on disk or a new module "
+ "appeared since baseline.",
+ "La racine Merkle des modules fichier-basés du processus a changé par "
+ "rapport à la baseline — une DLL/.so a été remplacée sur disque ou un "
+ "nouveau module est apparu.",
+ "Updates legitimately swap modules — correlate with a recent software "
+ "update. Absent one, an in-session module swap is a strong tamper signal.",
+ "Les mises à jour remplacent légitimement des modules — corréler avec une "
+ "update récente. Sans elle, un remplacement en session est un fort signal "
+ "d'altération.",
+ ["Check for a recent app/OS update covering these modules",
+ "Compare expected vs actual roots in the finding",
+ "Export forensics for the module list"],
+ ["Vérifier une mise à jour récente couvrant ces modules",
+ "Comparer les racines attendue/réelle dans le constat",
+ "Exporter le forensique pour la liste des modules"]),
+
+"MINING_STRATUM": _e(
+ "Cleartext mining protocol observed",
+ "Protocole de minage en clair observé",
+ "The connection payload contains the JSON-RPC stratum dialect miners "
+ "speak to pools (\"mining.subscribe\", \"mining.authorize\"…) — a "
+ "near-conclusive cryptomining signature.",
+ "Le payload de la connexion contient le dialecte JSON-RPC stratum que les "
+ "mineurs parlent aux pools (« mining.subscribe », « mining.authorize »…) "
+ "— signature quasi-concluante de cryptominage.",
+ "Nothing legitimate speaks stratum on a workstation. Encrypted stratum "
+ "(TLS) stays invisible to this check — cleartext is what miners still "
+ "use on many pools.",
+ "Rien de légitime ne parle stratum sur un poste. Le stratum chiffré (TLS) "
+ "reste invisible à ce contrôle — le clair reste utilisé par beaucoup de "
+ "pools.",
+ ["Identify the process and kill it if unwanted",
+ "Block the pool IP/port with a firewall rule",
+ "Export forensics — miners usually reinstall via a dropper"],
+ ["Identifier le processus et le tuer s'il est indésirable",
+ "Bloquer l'IP/port du pool par une règle pare-feu",
+ "Exporter le forensique — les mineurs se réinstallent via dropper"]),
+
+"MINING_SUSPECT": _e(
+ "Pool port + sustained CPU",
+ "Port de pool + CPU soutenue",
+ "A process keeps talking to a well-known mining-pool port while burning "
+ "sustained CPU — the combination is suspect even though neither signal "
+ "alone would be.",
+ "Un processus parle à un port de pool de minage connu tout en brûlant de "
+ "la CPU de façon soutenue — la combinaison est suspecte, même si aucun "
+ "signal seul ne le serait.",
+ "IRC/game traffic shares pool ports legitimately — sustained high CPU is "
+ "the corroboration. A warning, not a verdict.",
+ "Le trafic IRC/jeu partage ces ports légitimement — la CPU soutenue est "
+ "la corroboration. Un avertissement, pas un verdict.",
+ ["Check the process's CPU in the process list",
+ "Run a perf sample (/security/perf) for hardware counters",
+ "Block the destination if the usage is unexplained"],
+ ["Vérifier la CPU du processus dans la liste",
+ "Lancer un échantillon perf (/security/perf) pour les compteurs",
+ "Bloquer la destination si l'usage est inexpliqué"]),
+
+"SINKHOLE_HIT": _e(
+ "Sinkholed connection observed",
+ "Connexion sinkholée observée",
+ "A process connected to a destination you sinkholed — the loopback "
+ "responder captured its HTTP Host/path or TLS SNI, revealing what the "
+ "blocked app was trying to reach.",
+ "Un processus s'est connecté à une destination sinkholée — le répondeur "
+ "loopback a capturé son Host/chemin HTTP ou SNI TLS, révélant ce que "
+ "l'appli bloquée cherchait.",
+ "This is the sinkhole doing its job: the attempt is contained AND "
+ "observed. Repeated hits from one process deserve a process-level rule.",
+ "C'est le sinkhole qui fait son travail : la tentative est contenue ET "
+ "observée. Des hits répétés d'un même processus méritent une règle "
+ "processus.",
+ ["Read the captured host/path in the finding",
+ "Create a process rule if the same app keeps retrying",
+ "Deep-inspect the process if it adapts to the sinkhole"],
+ ["Lire l'hôte/chemin capturé dans le constat",
+ "Créer une règle processus si l'app retente sans cesse",
+ "Inspecter le processus s'il s'adapte au sinkhole"]),
+
+"INJECT_SUSPECT": _e(
+ "Connection from a staged module",
+ "Connexion depuis un module stagé",
+ "During deep inspection, an outbound connection originated from a module "
+ "loaded out of a temp/cache/download staging path — the signature of "
+ "injected code phoning home through a legit-looking process.",
+ "Pendant l'inspection profonde, une connexion sortante provenait d'un "
+ "module chargé depuis un chemin de staging temp/cache/download — la "
+ "signature de code injecté qui appelle sa base via un processus "
+ "d'apparence légitime.",
+ "This is Frida-level evidence, not a packet guess: the calling module "
+ "itself was resolved. Almost no legitimate software connects from %TEMP%.",
+ "C'est une preuve de niveau Frida, pas une estimation paquet : le module "
+ "appelant lui-même a été résolu. Presque aucun logiciel légitime ne "
+ "connecte depuis %TEMP%.",
+ ["Review the flagged module paths",
+ "Kill the host process and quarantine the module file",
+ "Expect re-injection — check the parent process tree"],
+ ["Examiner les chemins de modules signalés",
+ "Tuer le processus hôte et mettre le module en quarantaine",
+ "Anticiper la réinjection — vérifier l'arbre des processus parents"]),
+
+"COMMUNITY_IOC": _e(
+ "Community pack hint",
+ "Indice du paquet communautaire",
+ "A destination matched a shared IOC pack — Bloom + randomized response "
+ "means membership is probabilistic, not proof.",
+ "Une destination a correspondu à un paquet d'IOC partagé — Bloom + "
+ "randomized response rendent l'appartenance probabiliste, pas certaine.",
+ "Treat as a hint: false positives are expected by design. Corroborate "
+ "with local signals before acting.",
+ "À traiter comme un indice : les faux positifs sont attendus par "
+ "conception. Corroborer avec des signaux locaux avant d'agir.",
+ ["Run a local reputation check on the indicator",
+ "Watch the destination before blocking"],
+ ["Lancer une vérif de réputation locale sur l'indicateur",
+ "Surveiller la destination avant de bloquer"]),
}
diff --git a/backend/detection/firewall.py b/backend/detection/firewall.py
index 1b08548..e00c38c 100644
--- a/backend/detection/firewall.py
+++ b/backend/detection/firewall.py
@@ -1,9 +1,12 @@
"""
EN: Firewall orchestration — Snitch does NOT filter packets in user-space;
it drives the OS-native firewall instead:
- * Windows → `netsh advfirewall` (Windows Defender Firewall rules),
+ * Windows → WFP USER-MODE filters via `fwpuclnt.dll` ctypes (ALE
+ connect layers, per-app ALE_APP_ID, per-key deletes —
+ see detection/wfp.py), `netsh advfirewall` as fallback,
* Linux → `iptables` OUTPUT chain (a dedicated SNITCH_LOCK chain for
- lockdown, per-destination DROP rules otherwise),
+ lockdown, per-destination DROP rules otherwise) +
+ `tc` clsact/flower policing for throttle rules,
* macOS → `pf` anchors (a generated ruleset loaded with pfctl).
Rules are persisted in the settings table ("firewall_rules") so they
survive restarts. Every apply/remove is best-effort: failures are
@@ -16,17 +19,20 @@ EN: Firewall orchestration — Snitch does NOT filter packets in user-space;
"domain" resolved to IPs at apply time AND re-resolved
periodically (refresh_domains) so CDN rotation
and DNS changes don't silently unblock a name
- "process" process name/path (netsh `program=` on Windows,
- owner match on Linux — name resolved to PIDs)
+ "process" process name/path (WFP ALE_APP_ID on Windows —
+ names resolved to exe paths — iptables owner
+ match on Linux; unsupported on macOS pf)
"port" remote port
Rule actions: "block" drop the traffic (default)
"sinkhole" redirect instead of dropping — domains go to
127.0.0.1 via a marked block in the hosts file
(all OSes), IPs/CIDRs via iptables DNAT in the
- nat OUTPUT chain (Linux only; other platforms
- report applied=False honestly). Sinkholing keeps
- the connection "answered" by localhost so an
- analyst can watch what the malware expects.
+ nat OUTPUT chain (Linux only). The loopback
+ responder (detection/sinkresponder.py) then logs
+ the request's Host/path/SNI → SINKHOLE_HIT.
+ "throttle" rate-limit instead of blocking — Linux `tc`
+ clsact egress police per destination (rule["rate"]
+ kbit/s); other platforms report applied=False.
"lockdown" drops ALL outbound traffic to non-private destinations —
loopback and LAN stay up so the UI remains reachable.
@@ -87,6 +93,14 @@ class FirewallManager:
self._block_alerts: dict[str, float] = {}
# EN: rule_id → count of matching packets seen / FR: paquets vus par règle
self._blocked_counts: dict[str, int] = {}
+ # EN: WFP user-mode backend (Windows) — opened lazily on first apply;
+ # None = not tried, False = unavailable, WfpBackend = active.
+ # FR: Backend WFP user-mode (Windows) — ouvert au premier apply ;
+ # None = pas tenté, False = indisponible, WfpBackend = actif.
+ self._wfp: object | None = None
+ # EN: tc state for throttle rules — iface cached after first setup.
+ # FR: État tc pour les règles throttle — iface mise en cache.
+ self._tc_iface: str | None = None
# ── Introspection / Introspection ────────────────────────────────────────
@@ -129,26 +143,28 @@ class FirewallManager:
# ── Public rule ops / Opérations publiques ───────────────────────────────
- def add_rule(self, kind: str, value: str, action: str = "block") -> dict:
+ def add_rule(self, kind: str, value: str, action: str = "block",
+ rate: int = 64) -> dict:
"""EN: Create + apply a rule. `value` depends on kind (see module doc),
- `action` is "block" (default) or "sinkhole". Returns the persisted
- rule dict including its apply result.
- FR: Créer + appliquer une règle. `action` = « block » (défaut) ou
- « sinkhole ». Retourne la règle persistée avec le résultat."""
+ `action` is "block" (default), "sinkhole" or "throttle" (rate kbit/s).
+ Returns the persisted rule dict including its apply result.
+ FR: Créer + appliquer une règle. `action` = « block » (défaut),
+ « sinkhole » ou « throttle » (rate en kbit/s)."""
kind = kind.lower().strip()
value = str(value).strip()
action = (action or "block").lower().strip()
if kind not in ("ip", "cidr", "domain", "process", "port"):
raise ValueError(f"unknown rule kind: {kind}")
- if action not in ("block", "sinkhole"):
+ if action not in ("block", "sinkhole", "throttle"):
raise ValueError(f"unknown rule action: {action}")
- if action == "sinkhole" and kind in ("process", "port"):
- raise ValueError(f"sinkhole is not meaningful for kind {kind}")
+ if action != "block" and kind in ("process", "port"):
+ raise ValueError(f"{action} is not meaningful for kind {kind}")
rule = {
"id": uuid.uuid4().hex[:10],
"kind": kind,
"value": value,
"action": action,
+ "rate": max(1, min(int(rate or 64), 1_000_000)), # EN: kbit/s / FR: kbit/s
"enabled": True,
"applied": False,
"error": None,
@@ -295,6 +311,9 @@ class FirewallManager:
if action == "sinkhole":
rule["applied"], rule["error"] = self._sinkhole_apply(rule)
return
+ if action == "throttle":
+ rule["applied"], rule["error"] = self._throttle_apply(rule)
+ return
targets = rule.get("resolved") if kind == "domain" else [value]
if kind == "domain" and not targets:
rule["applied"], rule["error"] = False, "domain did not resolve"
@@ -308,6 +327,13 @@ class FirewallManager:
def _apply_one(self, kind: str, target: str, rid: str) -> tuple[bool, str]:
if self._platform == "windows":
+ # EN: WFP user-mode first — per-app ALE_APP_ID + atomic per-key
+ # deletes; netsh stays as the honest fallback.
+ # FR: WFP user-mode d'abord — ALE_APP_ID par app + suppressions
+ # atomiques par clé ; netsh reste le repli honnête.
+ ok, err = self._wfp_apply(kind, target, rid)
+ if ok is not None:
+ return ok, err
name = f"SnitchRule-{rid}"
if kind == "process":
return self._run(["netsh", "advfirewall", "firewall", "add", "rule",
@@ -334,6 +360,140 @@ class FirewallManager:
return self._pf_apply()
return False, f"unsupported platform {self._platform}"
+ # ── Windows WFP backend / Backend WFP Windows ────────────────────────────
+
+ def _wfp(self):
+ """EN: Lazy engine open — returns the backend, False when unavailable
+ (non-Windows, missing admin, absent dll), and remembers the verdict.
+ FR: Ouverture paresseuse du moteur — renvoie le backend, False si
+ indisponible, et mémorise le verdict."""
+ if self._wfp is not None:
+ return self._wfp or None
+ try:
+ from detection.wfp import WfpBackend
+ except ImportError:
+ try:
+ from .wfp import WfpBackend # type: ignore
+ except ImportError:
+ self._wfp = False
+ return None
+ if not WfpBackend.available():
+ self._wfp = False
+ return None
+ backend = WfpBackend()
+ ok, _err = backend.open()
+ self._wfp = backend if ok else False
+ return self._wfp or None
+
+ def _resolve_exe(self, name_or_path: str) -> Optional[str]:
+ """EN: WFP ALE_APP_ID needs a real exe path — resolve bare process
+ names through the running process table (netsh needed the same).
+ FR: ALE_APP_ID exige un chemin d'exe — les noms nus sont résolus
+ via la table des processus (netsh l'exigeait déjà)."""
+ if os.sep in name_or_path or "/" in name_or_path:
+ return name_or_path
+ try:
+ import psutil
+ for p in psutil.process_iter(["name", "exe"]):
+ if (p.info.get("name") or "").lower() == name_or_path.lower():
+ return p.info.get("exe")
+ except Exception: # noqa: BLE001
+ pass
+ return None
+
+ def _wfp_apply(self, kind: str, target: str, rid: str):
+ """EN: Apply through WFP. Returns (ok, err) or (None, reason) when
+ WFP can't serve this rule — the caller then falls back to netsh.
+ FR: Applique via WFP. Renvoie (ok, err) ou (None, raison) quand
+ WFP ne peut pas servir — l'appelant replie alors sur netsh."""
+ wfp = self._wfp()
+ if wfp is None:
+ return None, "wfp unavailable"
+ if kind == "process":
+ exe = self._resolve_exe(target)
+ if not exe:
+ return False, f"no running process/exe for {target}"
+ conds = [{"app": exe}]
+ elif kind == "port":
+ conds = [{"port": int(target)}]
+ else: # EN: ip/cidr/domain / FR: idem
+ conds = [{"remote": target}]
+ ok, err = wfp.add_block(rid, conds)
+ return ok, err
+
+ def _wfp_delete(self, rule: dict) -> None:
+ """EN: Delete all WFP filters a rule may have created — keys are
+ deterministic, unknown ones are simply absent.
+ FR: Supprime tous les filtres WFP créés par la règle — les clés
+ sont déterministes, les absentes ignorées."""
+ wfp = self._wfp()
+ if wfp is None:
+ return
+ from detection.wfp import WfpBackend
+ tags = WfpBackend.tags_for(rule["kind"], rule["value"],
+ rule.get("resolved"))
+ wfp.delete(rule["id"], tags)
+
+ # ── Throttle (tc) / Limitation (tc) ─────────────────────────────────────
+
+ def _tc_setup(self) -> tuple[bool, str]:
+ """EN: One-time clsact qdisc on the default-route interface — the
+ modern, filterable egress hook (no root-qdisc takeover like htb).
+ FR: qdisc clsact unique sur l'interface de la route par défaut —
+ le point d'accroche sortant filtrable moderne (pas de reprise de
+ la qdisc root comme htb)."""
+ if self._tc_iface:
+ return True, ""
+ ok, out = self._run(["ip", "-o", "route", "show", "default"])
+ if not ok or not out:
+ return False, "no default route / ip tool missing"
+ try:
+ self._tc_iface = out.split()[4]
+ except IndexError:
+ return False, "cannot parse default route"
+ self._run(["tc", "qdisc", "add", "dev", self._tc_iface, "clsact"])
+ # EN: "File exists" is fine — filters attach either way.
+ # FR: « File exists » est acceptable — les filtres s'attachent pareil.
+ return True, ""
+
+ def _throttle_apply(self, rule: dict) -> tuple[bool, str]:
+ """EN: Police egress to this destination at rule["rate"] kbit/s —
+ clsact + flower dst_ip + police action. Linux only, honest False
+ elsewhere. FR: Police la sortie vers cette destination à
+ rule["rate"] kbit/s — clsact + flower dst_ip + action police.
+ Linux seulement, False honnête ailleurs."""
+ if self._platform != "linux":
+ return False, "throttle needs tc/clsact (linux only)"
+ ok, err = self._tc_setup()
+ if not ok:
+ return False, err
+ idx = (int(rule["id"], 16) % 9900) + 100 # EN: stable prio / FR: prio stable
+ rule["tc_pref"] = idx
+ targets = rule.get("resolved") if rule["kind"] == "domain" else [rule["value"]]
+ ok_all, err_all = True, ""
+ for t in targets:
+ proto = "ipv6" if ":" in t else "ip"
+ ok, err = self._run([
+ "tc", "filter", "add", "dev", self._tc_iface, "egress",
+ "protocol", proto, "pref", str(idx), "flower",
+ "dst_ip", t.split("/")[0],
+ "action", "police", "rate", f"{rule['rate']}kbit",
+ "burst", "32k", "conform-exceed", "drop"])
+ ok_all = ok_all and ok
+ err_all = err or err_all
+ return ok_all, err_all or None
+
+ def _throttle_remove(self, rule: dict) -> None:
+ """EN: Remove this rule's tc filter by its stored pref.
+ FR: Supprime le filtre tc de la règle par son pref mémorisé."""
+ idx = rule.get("tc_pref")
+ if self._platform != "linux" or not idx or not self._tc_iface:
+ return
+ for proto in ("ip", "ipv6"):
+ self._run(["tc", "filter", "del", "dev", self._tc_iface,
+ "egress", "protocol", proto, "pref", str(idx),
+ "flower"])
+
# ── Sinkhole / Trou noir ─────────────────────────────────────────────────
def _hosts_path(self) -> Optional[Path]:
@@ -443,6 +603,16 @@ class FirewallManager:
r["resolved"] = new
continue
if not self._demo:
+ if r.get("action") == "throttle":
+ # EN: tc filters are per-IP — re-apply the whole flower
+ # set (same pref → add replaces; stale IPs removed
+ # by delete+re-add cycle).
+ # FR: Les filtres tc sont par IP — réapplication du jeu
+ # flower complet (même pref → l'ajout remplace).
+ self._throttle_remove(r)
+ r["resolved"] = new
+ self._throttle_apply(r)
+ continue
if self._platform == "linux":
rid = r["id"]
for t in sorted(set(old) - set(new)):
@@ -454,14 +624,26 @@ class FirewallManager:
"-j", "DROP", "-m", "comment",
"--comment", f"snitch-{rid}"])
elif self._platform == "windows":
- # EN: netsh rules are name-keyed, not value-keyed —
- # cheapest correct delta = delete + recreate.
- # FR: Les règles netsh sont indexées par nom — le delta
- # correct le plus simple = supprimer + recréer.
- self._remove(r)
- r["resolved"] = new
- self._apply(r)
- continue
+ if self._wfp() is not None:
+ # EN: True delta — per-IP keys mean stale addresses
+ # are deleted and new ones added atomically.
+ # FR: Vrai delta — les clés par IP suppriment les
+ # adresses périmées et ajoutent les nouvelles.
+ self._wfp_delete({
+ "id": r["id"], "kind": "domain",
+ "value": r["value"], "resolved": old})
+ for t in sorted(set(new) - set(old)):
+ self._wfp().add_block(
+ r["id"], [{"remote": t}])
+ else:
+ # EN: netsh rules are name-keyed, not value-keyed —
+ # cheapest correct delta = delete + recreate.
+ # FR: Les règles netsh sont indexées par nom —
+ # delta correct minimal = supprimer + recréer.
+ self._remove(r)
+ r["resolved"] = new
+ self._apply(r)
+ continue
elif self._platform == "darwin":
r["resolved"] = new
self._pf_apply() # EN: anchor is regenerated whole
@@ -476,8 +658,16 @@ class FirewallManager:
if rule.get("action", "block") == "sinkhole":
self._sinkhole_remove(rule)
return
+ if rule.get("action") == "throttle":
+ self._throttle_remove(rule)
+ return
rid, kind = rule["id"], rule["kind"]
if self._platform == "windows":
+ # EN: WFP filters are deleted by deterministic key — then the
+ # netsh copies (fallback path) get cleaned too.
+ # FR: Les filtres WFP se suppriment par clé déterministe —
+ # puis les copies netsh (chemin de repli) sont nettoyées.
+ self._wfp_delete(rule)
self._run(["netsh", "advfirewall", "firewall", "delete", "rule",
f"name=SnitchRule-{rid}"])
# EN: per-target suffixed copies / FR: copies suffixées par cible
diff --git a/backend/detection/integrity.py b/backend/detection/integrity.py
index f45b8f4..dd3976c 100644
--- a/backend/detection/integrity.py
+++ b/backend/detection/integrity.py
@@ -16,6 +16,18 @@ EN: Process integrity watch — the user-space slice of "is this process
regions reported, known-JIT processes (browsers, node, java,
electron) are reported at "info" severity instead of warning —
RWX pages are legitimate there.
+ 4. SUSPICIOUS MODULE PATHS — every file-backed module mapped into
+ the process (psutil memory_maps on all three OSes) is checked
+ against locations executable code should never live in: temp
+ dirs, %TEMP%/AppData staging, /dev/shm, memfd, Downloads,
+ browser caches → MODULE_SUSPECT.
+ 5. MERKLE MODULE ROOT — SHA-256 of every file-backed module is
+ folded into a Merkle root per process image (baseline persisted
+ like exe hashes). A changed root means a mapped DLL/.so was
+ replaced on disk or a new file-backed module appeared →
+ MODULE_CHANGED. This is the honest user-space subset of "Merkle
+ integrity of loaded modules": file-backed modules only —
+ anonymous reflective injection stays out of scope (documented).
Honest limits, documented to the user:
* The hash compares FILE-ON-DISK states across launches — detecting
@@ -43,6 +55,18 @@ FR: Veille d'intégrité des processus — la partie user-space implémentable
Borné : max 10 régions ; les processus à JIT connus (navigateurs,
node, java, electron) sont signalés en « info » et non
« warning » — leurs pages RWX sont légitimes.
+ 4. CHEMINS DE MODULES SUSPECTS — chaque module chargé fichier-basé
+ (psutil memory_maps sur les trois OS) est confronté aux
+ emplacements où du code exécutable ne devrait jamais vivre :
+ temp, %TEMP%/AppData, /dev/shm, memfd, Downloads, caches de
+ navigateurs → MODULE_SUSPECT.
+ 5. RACINE MERKLE DES MODULES — le SHA-256 de chaque module
+ fichier-basé est replié en une racine Merkle par image de
+ processus (baseline persistée comme les hash d'exe). Une racine
+ modifiée = une DLL/.so remplacée sur disque ou un nouveau module
+ apparu → MODULE_CHANGED. Sous-ensemble user-space honnête de
+ l'intégrité Merkle : modules fichier-basés seulement —
+ l'injection réflexive anonyme reste hors périmètre (documenté).
Limites honnêtes :
* Le hash compare les ÉTATS SUR DISQUE entre lancements — détecter
@@ -93,6 +117,35 @@ _KNOWN_JIT = {
# légitimes comme « python3 » → /usr/bin/python3.11 n'alertent pas.
_VERSION_SUFFIX = re.compile(r"[\d.\-]+$")
+# EN: Locations executable code should NEVER load from — the classic
+# extraction/injection staging spots (checked against lower-cased paths).
+# FR: Emplacements d'où du code exécutable ne devrait JAMAIS se charger —
+# les zones classiques d'extraction/injection (chemins en minuscules).
+_BAD_MODULE_MARKERS = (
+ "\\temp\\", "\\tmp\\", "/tmp/", "/var/tmp/", "/dev/shm/", "memfd:",
+ "\\appdata\\local\\temp", "\\downloads\\", "/downloads/",
+ "\\roaming\\", "/.cache/", "\\inetcache\\", "\\programdata\\",
+)
+
+_MAX_MODULES = 200 # EN: file-backed modules hashed per process / FR: modules hachés par processus
+
+
+def _merkle_root(leaves: list[str]) -> str:
+ """EN: SHA-256 Merkle root over sorted leaf hashes — order-insensitive,
+ so a module reload order change alone cannot trigger a false alert.
+ FR: Racine Merkle SHA-256 sur les feuilles triées — insensible à
+ l'ordre, donc un simple changement d'ordre de chargement n'alerte pas."""
+ if not leaves:
+ return ""
+ level = sorted(leaves)
+ while len(level) > 1:
+ if len(level) % 2:
+ level.append(level[-1])
+ level = [hashlib.sha256(
+ (level[i] + level[i + 1]).encode()).hexdigest()
+ for i in range(0, len(level), 2)]
+ return level[0]
+
def _sha256_file(path: str, _bufsize: int = 1 << 20) -> Optional[str]:
"""EN: Streaming SHA-256 of a file — None on any failure.
@@ -141,6 +194,11 @@ class IntegrityWatcher:
# FR: chemin → (mtime, sha256) — re-hash seulement si le mtime a
# changé ; hasher 200 Mo à chaque paquet serait absurde.
self._hash_cache: OrderedDict[str, tuple[float, Optional[str]]] = OrderedDict()
+ # EN: exe path → {"root": merkle, "n": module count} — module-set
+ # baseline persisted next to exe baselines.
+ # FR: chemin exe → {"root": merkle, "n": nb modules} — baseline de
+ # l'ensemble de modules persistée avec les baselines d'exe.
+ self._merkle: OrderedDict[str, dict] = OrderedDict()
self._findings: OrderedDict[str, dict] = OrderedDict() # key → finding
# ── Config / Configuration ──────────────────────────────────────────────
@@ -158,13 +216,23 @@ class IntegrityWatcher:
with self._lock:
for path, sha in (data or {}).items():
if isinstance(path, str) and isinstance(sha, str):
- self._baselines[path] = sha
+ if path.startswith("merkle:"):
+ self._merkle[path[7:]] = {"root": sha, "n": 0}
+ else:
+ self._baselines[path] = sha
while len(self._baselines) > _MAX_PATHS:
self._baselines.popitem(last=False)
def dump_baselines(self) -> dict:
+ """EN: Exe baselines + module Merkle roots share one persisted
+ dict — merkle entries are prefixed so the formats never collide.
+ FR: Baselines exe + racines Merkle partagent un dict persisté —
+ les entrées merkle sont préfixées pour éviter toute collision."""
with self._lock:
- return dict(self._baselines)
+ out = dict(self._baselines)
+ out.update({f"merkle:{p}": v["root"]
+ for p, v in self._merkle.items()})
+ return out
def status(self) -> dict:
"""EN: Capability + activity report for /security/integrity.
@@ -181,6 +249,8 @@ class IntegrityWatcher:
"exe_hash_watch": True,
"name_mismatch": True,
"rwx_scan": self._platform == "linux",
+ "module_paths": True,
+ "merkle_modules": True,
},
"checked": len(self._checked),
"baselines": len(self._baselines),
@@ -218,6 +288,7 @@ class IntegrityWatcher:
findings += self._check_hash(name, exe, pid)
if self._platform == "linux":
findings += self._check_rwx(pid, name)
+ findings += self._check_modules(pid, name, exe)
for f in findings:
self._record(f)
return findings
@@ -333,6 +404,74 @@ class IntegrityWatcher:
"regions": regions,
}]
+ # ── Check 4+5: module paths + Merkle root / Contrôle 4+5 : modules ────
+
+ def _check_modules(self, pid: int, name: str, exe: str) -> list[dict]:
+ """EN: Enumerate file-backed modules via psutil.memory_maps, then
+ a) flag modules loading from staging paths (MODULE_SUSPECT),
+ b) fold module file hashes into a Merkle root and compare it to
+ the persisted baseline (MODULE_CHANGED). Bounded by _MAX_MODULES;
+ unreadable modules simply don't contribute a leaf.
+ FR: Énumérer les modules fichier-basés via psutil.memory_maps,
+ puis a) signaler les modules chargés depuis des zones de staging
+ (MODULE_SUSPECT), b) replier les hash en racine Merkle comparée à
+ la baseline persistée (MODULE_CHANGED)."""
+ try:
+ import psutil
+ maps = psutil.Process(pid).memory_maps(grouped=True)
+ except Exception: # noqa: BLE001
+ return []
+ paths, suspect = [], []
+ for m in maps:
+ p = getattr(m, "path", "") or ""
+ if not p or p.startswith("["):
+ continue
+ paths.append(p)
+ if any(marker in p.lower() for marker in _BAD_MODULE_MARKERS):
+ suspect.append(p)
+ if len(paths) >= _MAX_MODULES:
+ break
+ findings: list[dict] = []
+ if suspect:
+ findings.append({
+ "type": "MODULE_SUSPECT", "severity": "warning",
+ "pid": pid, "exe": exe,
+ "detail": f"{len(suspect)} module(s) loaded from "
+ "staging locations",
+ "modules": suspect[:10],
+ })
+ # EN: Merkle over the hashed file-backed modules — keyed by the
+ # exe path so PID reuse can't corrupt baselines.
+ # FR: Merkle sur les modules hachés — indexé par chemin d'exe pour
+ # que la réutilisation de PID ne corrompe pas les baselines.
+ if exe and paths:
+ leaves = [h for p in sorted(set(paths))
+ if (h := self._hash_for(p))]
+ if len(leaves) >= 2:
+ root = _merkle_root(leaves)
+ with self._lock:
+ base = self._merkle.get(exe)
+ if base is None:
+ self._merkle[exe] = {"root": root,
+ "n": len(leaves)}
+ while len(self._merkle) > _MAX_PATHS:
+ self._merkle.popitem(last=False)
+ base = {"root": root}
+ known = base["root"]
+ if known != root:
+ findings.append({
+ "type": "MODULE_CHANGED", "severity": "critical",
+ "pid": pid, "exe": exe,
+ "detail": "mapped-module Merkle root changed — a "
+ "file-backed module was replaced or "
+ "a new one appeared",
+ "expected": known, "actual": root,
+ })
+ with self._lock:
+ self._merkle[exe] = {"root": root,
+ "n": len(leaves)}
+ return findings
+
# ── Findings log / Journal des constats ────────────────────────────────
def _record(self, finding: dict) -> None:
diff --git a/backend/detection/iocshare.py b/backend/detection/iocshare.py
new file mode 100644
index 0000000..1b601cc
--- /dev/null
+++ b/backend/detection/iocshare.py
@@ -0,0 +1,125 @@
+"""
+EN: Privacy-preserving IOC sharing — the honest implementable slice of
+ "fleet intelligence". Real zero-knowledge fleet telemetry needs a
+ coordination server and a proof system; what DOES work peer-to-peer,
+ today, with zero infrastructure is a *deniable indicator pack*:
+
+ * Every indicator (IP, domain, exe SHA-256) is hashed into a Bloom
+ filter — nothing stored is reversible.
+ * Randomized response then flips each bit with probability `flip`:
+ a pack provably cannot reveal which exact indicators the source
+ machine saw (local differential privacy, ε ≈ ln((1−f/2)/(f/2))
+ per bit) while membership queries still work probabilistically.
+ * Export = one JSON file the user may publish/share themselves —
+ there is no server, no upload, nothing automatic. Import =
+ checking local candidates against a received pack; hits are
+ returned as "community hints" with a false-positive caveat, never
+ auto-blocked.
+
+ Honest wording: this is differential-privacy IOC exchange, NOT a ZKP
+ scheme — the roadmap keeps the real ZK design as research.
+
+FR: Partage d'IOC préservant la vie privée — la tranche implémentable et
+ honnête de « l'intelligence de flotte ». Une vraie télémétrie ZK
+ exige un serveur de coordination et un système de preuves ; ce qui
+ fonctionne en pair-à-pair, aujourd'hui, sans infrastructure, c'est un
+ *paquet d'indicateurs à déni plausible* :
+
+ * Chaque indicateur (IP, domaine, SHA-256 d'exe) est haché dans un
+ filtre de Bloom — rien de stocké n'est réversible.
+ * La randomized response retourne chaque bit avec probabilité
+ `flip` : un paquet ne peut pas révéler quels indicateurs la
+ machine source a vus (DP locale, ε ≈ ln((1−f/2)/(f/2)) par bit)
+ alors que les requêtes d'appartenance restent probabilistes.
+ * Export = un fichier JSON que l'utilisateur publie lui-même —
+ aucun serveur, aucun upload, rien d'automatique. Import =
+ vérification de candidats locaux contre un paquet reçu ; les
+ correspondances reviennent en « indices communautaires » avec
+ réserve de faux-positifs — jamais bloqués automatiquement.
+
+ Formulation honnête : échange d'IOC sous DP, PAS un schéma ZK — la
+ roadmap garde le vrai design ZK en recherche.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import random
+import time
+
+_BITS = 8192 # EN: filter size — FP rate ~1e-4 at ≤1k items / FR: taille — FP ~1e-4 à ≤1k items
+_HASHES = 4 # EN: k hash functions / FR: k fonctions de hachage
+# EN: Per-bit flip probability — the privacy/usability trade-off: 0.02
+# keeps per-indicator miss ≈ 8 % (0.98⁴) while ε ≈ ln(99) ≈ 4.6 per
+# bit still makes any single pack deniable. Higher values would make
+# honest membership queries useless.
+# FR: Probabilité de flip par bit — compromis vie privée/utilisabilité :
+# 0,02 garde ~8 % de ratés par indicateur (0,98⁴) tout en offrant un
+# déni plausible (ε ≈ ln(99) ≈ 4,6 par bit).
+_FLIP = 0.02
+_FORMAT = "snitch-ioc-pack/1"
+
+
+def _positions(item: str) -> list[int]:
+ """EN: k Bloom positions via double-hashing on SHA-256 — uniform and
+ deterministic across machines. / FR: k positions Bloom par double-
+ hachage SHA-256 — uniforme et déterministe entre machines."""
+ digest = hashlib.sha256(item.strip().lower().encode()).digest()
+ h1, h2 = (int.from_bytes(digest[i:i + 8], "big") for i in (0, 8))
+ return [((h1 + i * h2) % _BITS) for i in range(_HASHES)]
+
+
+def build_pack(indicators: list[str]) -> dict:
+ """EN: Encode indicators → Bloom → randomized response → JSON pack.
+ Bounded to 4096 indicators (beyond that the FP rate grows anyway).
+ FR: Encode les indicateurs → Bloom → randomized response → paquet
+ JSON. Borné à 4096 indicateurs (au-delà le taux de FP croît)."""
+ bits = bytearray(_BITS // 8)
+ for item in indicators[:4096]:
+ for pos in _positions(item):
+ bits[pos // 8] |= 1 << (pos % 8)
+ # EN: Randomized response — each bit flips with _FLIP probability.
+ # This is what makes "was THIS indicator on their machine?"
+ # unanswerable for any single pack.
+ # FR: Randomized response — chaque bit bascule avec probabilité
+ # _FLIP. C'est ce qui rend « cet indicateur était-il sur leur
+ # machine ? » impossible à répondre pour un paquet seul.
+ rng = random.SystemRandom()
+ for i in range(_BITS):
+ if rng.random() < _FLIP:
+ bits[i // 8] ^= 1 << (i % 8)
+ return {
+ "format": _FORMAT,
+ "created": int(time.time()),
+ "count": len(indicators[:4096]),
+ "m": _BITS, "k": _HASHES, "flip": _FLIP,
+ "bits_b64": base64.b64encode(bytes(bits)).decode(),
+ }
+
+
+def check_pack(pack: dict, candidates: list[str]) -> dict:
+ """EN: Probabilistic membership for each candidate against a received
+ pack. Returns {ok, hints, error} — hints carry the DP caveat.
+ FR: Appartenance probabiliste de chaque candidat à un paquet reçu.
+ Renvoie {ok, hints, error} — les indices portent la réserve DP."""
+ if pack.get("format") != _FORMAT:
+ return {"ok": False, "hints": [], "error": "unsupported pack format"}
+ if pack.get("m") != _BITS or pack.get("k") != _HASHES:
+ return {"ok": False, "hints": [], "error": "pack parameters mismatch"}
+ try:
+ bits = base64.b64decode(pack["bits_b64"])
+ except Exception: # noqa: BLE001
+ return {"ok": False, "hints": [], "error": "corrupt bits_b64"}
+ if len(bits) != _BITS // 8:
+ return {"ok": False, "hints": [], "error": "bad bitfield length"}
+ hints = []
+ for item in candidates[:2048]:
+ if all(bits[p // 8] & (1 << (p % 8)) for p in _positions(item)):
+ hints.append({"indicator": item,
+ "confidence": "probabilistic — bloom+noise "
+ "cannot prove presence"})
+ return {"ok": True, "hints": hints,
+ "checked": len(candidates[:2048]),
+ "note": "membership is probabilistic (false positives "
+ "expected) — treat as hints, not verdicts"}
diff --git a/backend/detection/llm_local.py b/backend/detection/llm_local.py
new file mode 100644
index 0000000..4c12409
--- /dev/null
+++ b/backend/detection/llm_local.py
@@ -0,0 +1,162 @@
+"""
+EN: Local SLM enrichment — a REAL small language model, not a simulated
+ one. If the user runs Ollama (or any llama.cpp-server compatible API)
+ on LOOPBACK, alert explanations can be generated in natural language
+ instead of templates. Three hard rules keep it honest and private:
+
+ * LOOPBACK ONLY — the endpoint host must be 127.0.0.1 / ::1 /
+ localhost. Any other host is rejected outright: alert data never
+ leaves the machine. This is checked on every configure() call,
+ not just documented.
+ * 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.
+
+FR: Enrichissement SLM local — un VRAI petit modèle de langage, pas un
+ simulacre. Si l'utilisateur fait tourner Ollama (ou toute API
+ compatible llama.cpp-server) en LOOPBACK, les explications d'alertes
+ peuvent être générées en langage naturel. Trois règles strictes :
+
+ * LOOPBACK SEUL — l'hôte doit être 127.0.0.1 / ::1 / localhost.
+ Tout autre hôte est rejeté : les données d'alerte ne quittent
+ 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.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import json
+import threading
+import time
+import urllib.request
+from urllib.parse import urlparse
+
+_TIMEOUT = 20.0
+_CACHE_TTL = 300.0
+
+
+def _is_loopback(url: str) -> bool:
+ """EN: Hard privacy gate — only literal loopback hosts pass.
+ FR: Verrou vie privée strict — seuls les hôtes loopback littéraux
+ passent."""
+ try:
+ host = urlparse(url).hostname or ""
+ if host in ("localhost", "localhost."):
+ return True
+ return ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ return False
+
+
+class LocalSlm:
+ """EN: Optional Ollama/llama.cpp-server client — status + single-call
+ enrich(). Every network op has a short timeout and degrades to None.
+ FR: Client optionnel Ollama/serveur llama.cpp — status + enrich()
+ simple. Chaque appel réseau a un timeout court et dégrade en None."""
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._enabled = False
+ self._endpoint = "http://127.0.0.1:11434"
+ self._model = "" # EN: empty → autodetect / FR: vide → autodétecté
+ self._cache: dict[tuple, tuple[float, str]] = {}
+
+ # ── config / configuration ───────────────────────────────────────────────
+
+ def configure(self, enabled: bool, endpoint: str = "",
+ model: 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()
+
+ # ── status / état ────────────────────────────────────────────────────────
+
+ def _detect_model(self) -> str:
+ """EN: First model reported by the server — keeps zero-config flow.
+ FR: Premier modèle rapporté par le serveur — reste zéro-config."""
+ try:
+ with urllib.request.urlopen(
+ f"{self._endpoint}/api/tags", timeout=5) as r:
+ models = json.loads(r.read()).get("models", [])
+ return models[0].get("name", "") if models else ""
+ except Exception: # noqa: BLE001
+ return ""
+
+ def status(self) -> dict:
+ """EN: Reachability probe (cheap /api/tags) + current config —
+ powers the Settings panel honesty ("model unreachable" is shown,
+ never hidden). / FR: Sonde de joignabilité + config courante —
+ alimente l'honnêteté des réglages (« modèle injoignable »
+ affiché, jamais caché)."""
+ with self._lock:
+ enabled, endpoint, model = self._enabled, self._endpoint, self._model
+ reachable = False
+ detected = ""
+ if enabled:
+ 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}
+
+ # ── generation / génération ──────────────────────────────────────────────
+
+ def enrich(self, alert_type: str, details: dict, lang: str = "en") -> str | None:
+ """EN: One-shot natural-language explanation of an alert — or None
+ (disabled, unreachable, error) so the caller falls back to
+ templates. Cached briefly per (type,lang,detail-hash).
+ FR: Explication en langage naturel d'une alerte — ou None
+ (désactivé, injoignable, erreur) pour repli sur les gabarits.
+ Cache bref par (type,lang,hash-détails)."""
+ with self._lock:
+ if not self._enabled:
+ 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
+ import hashlib
+ key = (alert_type, lang,
+ hashlib.sha256(json.dumps(details, sort_keys=True,
+ default=str).encode()).hexdigest()[:16])
+ with self._lock:
+ hit = self._cache.get(key)
+ if hit and time.time() - hit[0] < _CACHE_TTL:
+ return hit[1]
+ prompt = (
+ f"You are a security assistant inside a localhost-only network "
+ f"monitor. Explain this alert in {'French' if lang == 'fr' else 'English'} "
+ f"in at most 4 short sentences: what it means, why it fired, "
+ 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
+ if text:
+ with self._lock:
+ self._cache[key] = (time.time(), text)
+ if len(self._cache) > 128:
+ self._cache.pop(next(iter(self._cache)))
+ return text or None
diff --git a/backend/detection/miner.py b/backend/detection/miner.py
new file mode 100644
index 0000000..8bbfbf1
--- /dev/null
+++ b/backend/detection/miner.py
@@ -0,0 +1,166 @@
+"""
+EN: Cryptomining detection — three orthogonal signals, escalating severity
+ as they combine. No single signal is enough to accuse a process:
+
+ 1. STRATUM PROTOCOL — the cleartext JSON-RPC dialect miners speak to
+ pools ("mining.subscribe", "mining.authorize", "mining.notify",
+ "mining.set_difficulty", ethash "mining.submit"). Seen in the
+ first payload bytes (parser's bounded app_head) → near-certain,
+ critical. Encrypted stratum (TLS) is invisible to this, honestly.
+ 2. POOL PORTS — outbound TCP to well-known mining ports (3333, 5555,
+ 7777, 14444, 45700…) only raises suspicion when combined with
+ sustained high CPU from the same process — alone it false-
+ positives on IRC/game traffic.
+ 3. SUSTAINED CPU — psutil cpu_percent sampled per flagged PID over a
+ drain window; a process burning >70% while talking to a pool port
+ gets MINING_SUSPECT.
+
+ The optional perf probe (detection/perfprobe.py) adds hardware
+ counters (instructions/cycle anomalies) when the kernel allows it.
+
+FR: Détection de cryptominage — trois signaux orthogonaux dont la sévérité
+ monte quand ils se combinent. Aucun signal seul n'accuse :
+
+ 1. PROTOCOLE STRATUM — le dialecte JSON-RPC en clair des mineurs
+ (« mining.subscribe », « mining.authorize », « mining.notify »…)
+ vu dans les premiers octets du payload → quasi-certain, critique.
+ Le stratum chiffré (TLS) est invisible — honnêtement.
+ 2. PORTS DE POOLS — TCP sortant vers des ports de minage connus ne
+ devient suspect que combiné à une CPU élevée soutenue — seul, il
+ faussement positif sur IRC/jeux.
+ 3. CPU SOUTENUE — cpu_percent psutil échantillonné par PID flagué ;
+ >70 % + port de pool = MINING_SUSPECT.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+
+# EN: Stratum cleartext markers searched in the first payload bytes —
+# JSON-RPC method names the mining protocol can't hide (cleartext only).
+# FR: Marqueurs stratum en clair cherchés dans les premiers octets —
+# noms de méthodes JSON-RPC que le protocole ne peut masquer.
+_STRATUM_MARKERS = (
+ b'"mining.subscribe"', b'"mining.authorize"', b'"mining.notify"',
+ b'"mining.set_difficulty"', b'"mining.submit"', b'"mining.ping"',
+ b'mining.subscribe', b'login', b'"blob"', b'"job"', b'"target"',
+)
+
+# EN: Strong markers — presence alone is conclusive (the generic ones
+# above like "login"/"job" only count with a mining.* context word).
+# FR: Marqueurs forts — concluants seuls (les génériques ne comptent
+# qu'avec un contexte mining.*).
+_STRONG = (b'mining.', b'"blob"', b'"job_id"', b'"seed_hash"')
+
+# EN: Well-known stratum/pool TCP ports (xmrig defaults, nanopool,
+# supportxmr, minergate, 2miners…). Port alone never alerts.
+# FR: Ports stratum/pool connus (défauts xmrig, nanopool, supportxmr,
+# minergate, 2miners…). Le port seul n'alerte jamais.
+_POOL_PORTS = {3333, 4444, 5555, 7777, 8333, 9999, 14433, 14444,
+ 45560, 45700}
+
+_CPU_THRESHOLD = 70.0 # EN: sustained % to corroborate / FR: % soutenu corroborant
+_CPU_WINDOW_S = 30.0 # EN: min observation before accusing / FR: observation min avant accusation
+_COOLDOWN = 600.0 # EN: per-process alert cooldown / FR: cooldown par processus
+
+
+class MinerDetector:
+ """EN: Combines stratum signatures, pool ports and sustained CPU into
+ MINING_* findings. analyze_packet() is the per-packet entry point;
+ cpu_corroborate() is polled from the drain loop for flagged PIDs.
+ FR: Combine signatures stratum, ports de pool et CPU soutenue en
+ constats MINING_*. analyze_packet() est le point d'entrée par paquet ;
+ cpu_corroborate() est appelé depuis la boucle de vidage."""
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ # EN: (pid, remote) → first-seen ts — pool-port suspects under
+ # observation before CPU corroboration.
+ # FR: (pid, remote) → premier ts vu — suspects port-pool en
+ # observation avant corroboration CPU.
+ self._suspects: dict[tuple, float] = {}
+ self._last_alert: dict[tuple, float] = {}
+
+ def _cooldown_ok(self, key: tuple) -> bool:
+ now = time.time()
+ with self._lock:
+ if now - self._last_alert.get(key, 0) < _COOLDOWN:
+ return False
+ self._last_alert[key] = now
+ return True
+
+ def analyze_packet(self, pkt) -> list[dict]:
+ """EN: Per-packet checks — stratum signature in cleartext head,
+ pool-port marking for later CPU corroboration.
+ FR: Contrôles par paquet — signature stratum dans la tête en clair,
+ marquage port-pool pour corroboration CPU ultérieure."""
+ out: list[dict] = []
+ direction = getattr(pkt, "direction", "out")
+ if direction != "out" or pkt.protocol != "TCP":
+ return out
+ remote = pkt.dst_ip
+ proc = pkt.process_name or "unknown"
+ pid = pkt.pid
+
+ # EN: Signal 1 — cleartext stratum. Two generic markers OR one
+ # strong mining.* marker → conclusive.
+ # FR: Signal 1 — stratum en clair. Deux marqueurs génériques OU un
+ # marqueur mining.* fort → concluant.
+ head = getattr(pkt, "app_head", b"") or b""
+ if head:
+ strong = any(m in head for m in _STRONG)
+ generic = sum(1 for m in _STRATUM_MARKERS if m in head)
+ if strong or generic >= 2:
+ key = ("stratum", pid, remote)
+ if self._cooldown_ok(key):
+ out.append({
+ "type": "MINING_STRATUM",
+ "severity": "critical",
+ "process": proc, "pid": pid, "ip": remote,
+ "port": pkt.dst_port,
+ "detail": "cleartext stratum mining protocol "
+ "observed in payload",
+ })
+ return out # EN: no need to suspect further
+
+ # EN: Signal 2 — pool port: mark for CPU corroboration, never
+ # enough alone. / FR: Signal 2 — port de pool : marqué pour
+ # corroboration CPU, jamais suffisant seul.
+ if pkt.dst_port in _POOL_PORTS and pid:
+ with self._lock:
+ self._suspects.setdefault((pid, remote), time.time())
+ return out
+
+ def cpu_corroborate(self) -> list[dict]:
+ """EN: Called each drain tick — suspects older than the window get
+ a cpu_percent sample; sustained high CPU + pool port → MINING_SUSPECT.
+ FR: Appelé à chaque tick — les suspects au-delà de la fenêtre sont
+ échantillonnés ; CPU haute soutenue + port de pool → MINING_SUSPECT."""
+ out: list[dict] = []
+ now = time.time()
+ with self._lock:
+ due = [(k, ts) for k, ts in self._suspects.items()
+ if now - ts >= _CPU_WINDOW_S]
+ try:
+ import psutil
+ except ImportError:
+ return out
+ for (pid, remote), _ts in due[:32]:
+ with self._lock:
+ self._suspects.pop((pid, remote), None)
+ try:
+ proc = psutil.Process(pid)
+ cpu = proc.cpu_percent(interval=0.2)
+ name = proc.name()
+ except Exception: # noqa: BLE001 — process gone
+ continue
+ if cpu >= _CPU_THRESHOLD and self._cooldown_ok(("suspect", pid, remote)):
+ out.append({
+ "type": "MINING_SUSPECT",
+ "severity": "warning",
+ "process": name, "pid": pid, "ip": remote,
+ "detail": f"sustained {cpu:.0f}% CPU while talking to "
+ f"a known mining-pool port",
+ })
+ return out
diff --git a/backend/detection/perfprobe.py b/backend/detection/perfprobe.py
new file mode 100644
index 0000000..9fe97c7
--- /dev/null
+++ b/backend/detection/perfprobe.py
@@ -0,0 +1,150 @@
+"""
+EN: Hardware performance counters — the user-mode, dependency-free slice
+ of "PMU anomaly detection". perf_event_open(2) is a plain syscall:
+ no kernel module, no perf binary needed. We attach per-PID counters
+ (cycles, instructions, cache-misses, task-clock) for a bounded window
+ and report the ratios.
+
+ What it honestly buys us: a cryptominer running stratum shows a
+ *sustained* high instructions-per-second rate with regular IPC — the
+ perf numbers corroborate MINING_SUSPECT beyond a one-shot cpu_percent.
+ Anything deeper (speculation anomalies, branch-miss forensics) stays
+ research — documented as such.
+
+ Honest gates: /proc/sys/kernel/perf_event_paranoid must allow per-
+ process counting (≤2 for own processes, ≤1 for all processes); a
+ refusal returns available=False, never a silent zero.
+
+FR: Compteurs matériels — la tranche user-mode sans dépendance de la
+ « détection d'anomalies PMU ». perf_event_open(2) est un simple
+ syscall : ni module noyau, ni binaire perf. On attache des compteurs
+ par PID (cycles, instructions, cache-misses, task-clock) pendant une
+ fenêtre bornée et on rapporte les ratios.
+
+ Ce que ça apporte honnêtement : un mineur stratum montre un débit
+ d'instructions *soutenu* avec un IPC régulier — les chiffres perf
+ corroborent MINING_SUSPECT au-delà d'un cpu_percent instantané. Tout
+ le reste (anomalies de spéculation, forensique des branches) reste en
+ recherche — documenté comme tel.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import fcntl
+import os
+import platform
+import struct
+import time
+
+_SYS_PERF_EVENT_OPEN = 298 # EN: x86_64/aarch64 number / FR: numéro x86_64/aarch64
+_IOC_ENABLE = 0x2400 # EN: PERF_EVENT_IOC_ENABLE / FR: idem
+_IOC_DISABLE = 0x2401 # EN: PERF_EVENT_IOC_DISABLE / FR: idem
+
+# EN: perf_event_attr — only the head fields matter; kernels pad/truncate
+# by attr.size. flags bit0 = disabled (counter starts paused).
+# FR: perf_event_attr — seuls les champs de tête comptent ; le noyau
+# ajuste selon attr.size. flags bit0 = disabled (compteur en pause).
+class _Attr(ctypes.Structure):
+ _fields_ = [("type", ctypes.c_uint32), ("size", ctypes.c_uint32),
+ ("config", ctypes.c_uint64), ("sample", ctypes.c_uint64),
+ ("sample_type", ctypes.c_uint64),
+ ("read_format", ctypes.c_uint64), ("flags", ctypes.c_uint64),
+ ("wakeup", ctypes.c_uint32), ("bp_type", ctypes.c_uint32),
+ ("bp_addr", ctypes.c_uint64), ("bp_len", ctypes.c_uint64),
+ ("branch_sample_type", ctypes.c_uint64),
+ ("sample_regs_user", ctypes.c_uint64),
+ ("sample_stack_user", ctypes.c_uint32),
+ ("clock", ctypes.c_int32),
+ ("sample_regs_intr", ctypes.c_uint64),
+ ("aux_watermark", ctypes.c_uint32),
+ ("sample_max_stack", ctypes.c_uint16),
+ ("reserved", ctypes.c_uint16)]
+
+_TYPE_HW, _TYPE_SW = 0, 1
+_CNT = {"cycles": (_TYPE_HW, 0), "instructions": (_TYPE_HW, 1),
+ "cache_misses": (_TYPE_HW, 3), "task_clock_ms": (_TYPE_SW, 1)}
+
+_libc = None
+
+
+def _open(attr_type: int, config: int, pid: int) -> int:
+ """EN: perf_event_open(type, config, pid, cpu=-1, group=-1, flags=0).
+ FR: perf_event_open(type, config, pid, cpu=-1, groupe=-1, flags=0)."""
+ global _libc
+ if _libc is None:
+ _libc = ctypes.CDLL(None, use_errno=True)
+ attr = _Attr()
+ attr.type = attr_type
+ attr.size = ctypes.sizeof(_Attr)
+ attr.config = config
+ attr.flags = 1 # EN: start disabled / FR: démarre en pause
+ fd = _libc.syscall(_SYS_PERF_EVENT_OPEN, ctypes.byref(attr),
+ pid, -1, -1, 0)
+ if fd < 0:
+ err = ctypes.get_errno()
+ raise OSError(err, os.strerror(err))
+ return fd
+
+
+def available() -> tuple[bool, str]:
+ """EN: Honest gate — Linux + perf_event_paranoid permissive enough.
+ FR: Verrou honnête — Linux + perf_event_paranoid assez permissif."""
+ if platform.system().lower() != "linux":
+ return False, "linux only"
+ try:
+ level = int(open("/proc/sys/kernel/perf_event_paranoid").read())
+ except (OSError, ValueError):
+ return True, "" # EN: can't read → try anyway / FR: illisible → on tente
+ if level > 2:
+ return False, f"perf_event_paranoid={level} blocks unprivileged use"
+ if level > 1 and os.geteuid() != 0:
+ return False, f"perf_event_paranoid={level} needs root for foreign PIDs"
+ return True, ""
+
+
+def sample(pid: int, seconds: float = 1.5) -> dict:
+ """EN: Count cycles/instructions/cache-misses for `pid` over `seconds`.
+ Returns {ok, ipc, instr_per_s, cache_miss_per_s, cpu_ms} — all rates
+ normalized by elapsed task-clock ms so partial-window runs compare.
+ FR: Compte cycles/instructions/cache-misses pour `pid` sur `seconds`.
+ Renvoie {ok, ipc, instr_per_s, cache_miss_per_s, cpu_ms} — taux
+ normalisés par task-clock pour comparer entre fenêtres."""
+ ok, why = available()
+ if not ok:
+ return {"ok": False, "error": why}
+ seconds = max(0.2, min(float(seconds), 10.0))
+ fds: dict[str, int] = {}
+ try:
+ for name, (t, c) in _CNT.items():
+ try:
+ fds[name] = _open(t, c, pid)
+ except OSError as e:
+ if e.errno == 3: # EN: ESRCH — pid gone / FR: pid disparu
+ return {"ok": False, "error": "process exited"}
+ raise
+ for fd in fds.values():
+ fcntl.ioctl(fd, _IOC_ENABLE)
+ time.sleep(seconds)
+ for fd in fds.values():
+ fcntl.ioctl(fd, _IOC_DISABLE)
+ vals = {n: struct.unpack("q", os.read(fd, 8))[0]
+ for n, fd in fds.items()}
+ except OSError as e:
+ return {"ok": False, "error": str(e)[:120]}
+ finally:
+ for fd in fds.values():
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ ms = max(vals["task_clock_ms"] / 1e6, 1.0) # EN: task-clock is ns / FR: task-clock en ns
+ cycles = vals["cycles"] or 1
+ return {
+ "ok": True, "pid": pid, "window_s": seconds,
+ "instructions": vals["instructions"],
+ "instr_per_s": round(vals["instructions"] / ms * 1000),
+ "cache_miss_per_s": round(vals["cache_misses"] / ms * 1000),
+ "ipc": round(vals["instructions"] / cycles, 3),
+ "cpu_ms": round(ms, 1),
+ }
diff --git a/backend/detection/sinkresponder.py b/backend/detection/sinkresponder.py
new file mode 100644
index 0000000..7337e83
--- /dev/null
+++ b/backend/detection/sinkresponder.py
@@ -0,0 +1,201 @@
+"""
+EN: Sinkhole responder — turns "redirect to 127.0.0.1" from a blind drop
+ into a sensor. When Snitch sinkholes a domain/IP, the victim process
+ still connects — it just reaches this tiny listener instead of the
+ real server. We log what it tried to send:
+
+ * :80 → parse the HTTP request line + Host + path (and the first
+ bytes of a POST body — that is the C2 protocol revealing
+ itself), answer a minimal 200 so the client keeps talking
+ on later requests;
+ * :443 → TLS is opaque, but the ClientHello SNI is not: reuse our
+ own TLS parser to recover the intended hostname, then
+ close. We do NOT MITM TLS — no cert forgery, ever.
+
+ Source-port → PID attribution uses a psutil snapshot at accept time.
+ Binding <1024 needs privileges: each listener reports honest
+ listening=True/False, and rules keep working even if we can't listen
+ (the hosts/DNAT redirect still lands the connection on a refused port).
+
+FR: Répondeur de sinkhole — transforme la redirection vers 127.0.0.1 en
+ capteur au lieu d'un trou noir. Quand Snitch sinkhole un domaine/IP,
+ le processus victime se connecte quand même — il atteint ce petit
+ écouteur à la place du vrai serveur. On journalise ce qu'il tente :
+
+ * :80 → ligne de requête HTTP + Host + chemin (et les premiers
+ octets d'un POST — le protocole C2 qui se révèle), réponse
+ 200 minimale pour que le client continue ;
+ * :443 → TLS est opaque, mais le SNI du ClientHello ne l'est pas :
+ notre parseur TLS récupère le nom visé, puis on ferme. Pas
+ de MITM TLS — jamais de certificat forgé.
+
+ L'attribution port-source → PID utilise un instantané psutil à
+ l'accept. Binder <1024 exige des privilèges : chaque écouteur rapporte
+ listening honnêtement, et les règles restent actives même sans écoute.
+"""
+
+from __future__ import annotations
+
+import socket
+import threading
+import time
+
+try: # EN: reuse our own TLS parser
+ from capture.parser import parse_tls_sni # FR: réutilise notre parseur TLS
+except ImportError: # pragma: no cover
+ from ..capture.parser import parse_tls_sni # type: ignore
+
+_MAX_HITS = 200
+_READ_TIMEOUT = 4.0
+
+
+def _pid_for_port(port: int) -> tuple[int | None, str | None]:
+ """EN: Map a loopback source port to the owning process — one psutil
+ snapshot per accepted connection is affordable (sinkholes are rare).
+ FR: Mappe un port source loopback vers son processus — un instantané
+ psutil par connexion acceptée est abordable."""
+ try:
+ import psutil
+ for c in psutil.net_connections("tcp"):
+ if c.laddr and c.laddr.port == port and c.pid:
+ try:
+ return c.pid, psutil.Process(c.pid).name()
+ except psutil.Error:
+ return c.pid, None
+ except Exception: # noqa: BLE001
+ pass
+ return None, None
+
+
+class SinkholeResponder:
+ """EN: Two threaded listeners (80 HTTP / 443 SNI) + a bounded hit ring.
+ start()/stop() are idempotent; hits carry {ts, port, host, path,
+ process, pid, kind}. / FR: Deux écouteurs threadés (80 HTTP / 443 SNI)
+ + anneau de hits borné. start()/stop() idempotents ; les hits portent
+ {ts, port, host, path, process, pid, kind}."""
+
+ def __init__(self):
+ self._socks: list[socket.socket] = []
+ self._threads: list[threading.Thread] = []
+ self._stop = threading.Event()
+ self._hits: list[dict] = []
+ self._lock = threading.Lock()
+ self._listening: dict[int, bool] = {80: False, 443: False}
+
+ # ── lifecycle / cycle de vie ─────────────────────────────────────────────
+
+ def start(self) -> None:
+ if self._threads:
+ return
+ self._stop.clear()
+ for port, handler in ((80, self._handle_http),
+ (443, self._handle_tls)):
+ try:
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind(("127.0.0.1", port))
+ s.listen(16)
+ s.settimeout(1.0)
+ except OSError: # EN: no privilege / FR: pas de privilège
+ self._listening[port] = False
+ continue
+ self._socks.append(s)
+ self._listening[port] = True
+ t = threading.Thread(target=self._accept_loop,
+ args=(s, handler), daemon=True,
+ name=f"snitch-sink-{port}")
+ t.start()
+ self._threads.append(t)
+
+ def stop(self) -> None:
+ self._stop.set()
+ for s in self._socks:
+ try:
+ s.close()
+ except OSError:
+ pass
+ self._socks.clear()
+ self._threads.clear()
+ self._listening = {80: False, 443: False}
+
+ def status(self) -> dict:
+ with self._lock:
+ return {"listening": dict(self._listening),
+ "hits": list(self._hits[-_MAX_HITS:])}
+
+ def pop_hits(self) -> list[dict]:
+ """EN: Drain accumulated hits — each reported once as an alert.
+ FR: Vider les hits accumulés — chacun rapporté une fois en alerte."""
+ with self._lock:
+ hits, self._hits = self._hits, []
+ return hits
+
+ # ── listeners / écouteurs ────────────────────────────────────────────────
+
+ def _accept_loop(self, sock: socket.socket, handler) -> None:
+ while not self._stop.is_set():
+ try:
+ conn, peer = sock.accept()
+ except socket.timeout:
+ continue
+ except OSError:
+ break
+ threading.Thread(target=handler, args=(conn, peer),
+ daemon=True).start()
+
+ def _record(self, kind: str, src_port: int, host: str, extra: dict) -> None:
+ pid, name = _pid_for_port(src_port)
+ with self._lock:
+ self._hits.append({"ts": time.time(), "kind": kind,
+ "src_port": src_port, "host": host,
+ "pid": pid, "process": name, **extra})
+ if len(self._hits) > _MAX_HITS:
+ del self._hits[: len(self._hits) - _MAX_HITS]
+
+ def _handle_http(self, conn: socket.socket, peer) -> None:
+ """EN: Read the request, capture Host+path(+body head), answer 200
+ so the client proceeds — each request becomes a SINKHOLE_HIT.
+ FR: Lit la requête, capture Host+chemin(+tête du corps), répond 200
+ pour que le client poursuive — chaque requête devient un hit."""
+ try:
+ conn.settimeout(_READ_TIMEOUT)
+ data = conn.recv(8192)
+ head = data.decode("latin-1", "replace")
+ first = head.split("\r\n", 1)[0]
+ host = next((ln.split(":", 1)[1].strip()
+ for ln in head.split("\r\n")[1:]
+ if ln.lower().startswith("host:")), "")
+ parts = first.split()
+ method, path = (parts + ["", ""])[:2]
+ body = head.split("\r\n\r\n", 1)[1][:160] if "\r\n\r\n" in head else ""
+ self._record("http", peer[1], host,
+ {"method": method, "path": path,
+ "body_head": body})
+ conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
+ b"Connection: close\r\n\r\nOK")
+ except (OSError, socket.timeout):
+ pass
+ finally:
+ try:
+ conn.close()
+ except OSError:
+ pass
+
+ def _handle_tls(self, conn: socket.socket, peer) -> None:
+ """EN: Read the ClientHello, recover the SNI with our own parser,
+ record it, close. No TLS MITM — we never present a certificate.
+ FR: Lit le ClientHello, récupère le SNI via notre parseur,
+ l'enregistre, ferme. Pas de MITM TLS — jamais de certificat."""
+ try:
+ conn.settimeout(_READ_TIMEOUT)
+ data = conn.recv(4096)
+ sni = parse_tls_sni(data) if data[:2] == b"\x16\x03" else None
+ self._record("tls", peer[1], sni or "",
+ {"cipher_attempt": bool(data)})
+ except (OSError, socket.timeout):
+ pass
+ finally:
+ try:
+ conn.close()
+ except OSError:
+ pass
diff --git a/backend/detection/wfp.py b/backend/detection/wfp.py
new file mode 100644
index 0000000..13c42fe
--- /dev/null
+++ b/backend/detection/wfp.py
@@ -0,0 +1,395 @@
+"""
+EN: Windows Filtering Platform — USER-MODE backend (no driver, no kernel
+ callout). Snitch talks to `fwpuclnt.dll` through ctypes and installs
+ ordinary WFP *filters* at the ALE_AUTH_CONNECT layers — exactly what
+ `netsh advfirewall` does under the hood, but with per-application
+ precision (ALE_APP_ID), per-rule GUID keys and atomic deletes.
+ A true *callout* (packet inspection inside the kernel) still needs a
+ signed driver — that stays a research item; static block filters do not.
+
+ Why this beats `netsh`:
+ * `program=` accepts a name OR path here — we resolve names to the
+ running exe and WFP matches the real ALE_APP_ID (canonicalized
+ device path), not a display string,
+ * filters are added/deleted individually by key (domain re-resolution
+ becomes a true delta instead of delete+recreate),
+ * IPv4 AND IPv6 connect layers are covered — netsh rules created
+ through the advfirewall surface only ever saw IPv4 destinations.
+ Requires an elevated process (same requirement as `netsh`); failures are
+ reported as honest applied=False by the caller.
+
+FR: Windows Filtering Platform — backend USER-MODE (sans driver ni callout
+ noyau). Snitch dialogue avec `fwpuclnt.dll` via ctypes et installe des
+ filtres WFP ordinaires sur les couches ALE_AUTH_CONNECT — exactement ce
+ que fait `netsh advfirewall` en dessous, mais avec une précision par
+ application (ALE_APP_ID), des clés GUID par règle et des suppressions
+ atomiques. Un vrai *callout* (inspection dans le noyau) exige toujours
+ un driver signé — reste en recherche ; les filtres statiques, non.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import ipaddress
+import os
+import socket
+import struct
+import uuid
+from typing import Optional
+
+# ── GUID constants (Windows SDK fwpmk.h — values verified against
+# winsdk-10 + OpenVPN's wfp_block.c) / Constantes GUID ────────────────────
+_LAYER_V4 = "c38d57d1-05a7-4c33-904f-7fbceee60e82" # ALE_AUTH_CONNECT_V4
+_LAYER_V6 = "4a72393b-319f-44bc-84c3-ba54dcb3b6b4" # ALE_AUTH_CONNECT_V6
+_COND_REMOTE_IP = "b235ae9a-1d64-49b8-a44c-5ff3d9095045"
+_COND_REMOTE_PORT = "c35a604d-d22b-4e1a-91b4-68f674ee674b"
+_COND_ALE_APP_ID = "d78e1e87-8644-4ea5-9437-d809ecefc971"
+_SUBLAYER_UNIVERSAL = "eebecc03-ced4-4380-819a-2734397b2b74"
+
+# ── Scalar constants / Constantes scalaires ──────────────────────────────────
+RPC_C_AUTHN_WINNT = 10
+FWPM_SESSION_FLAG_DYNAMIC = 1
+FWP_EMPTY = 0
+FWP_UINT8 = 1
+FWP_UINT16 = 2
+FWP_UINT32 = 3
+FWP_UINT64 = 4 # EN: value passed by POINTER / FR: valeur par pointeur
+FWP_BYTE_ARRAY16_TYPE = 10
+FWP_BYTE_BLOB_TYPE = 11
+FWP_V4_ADDR_MASK = 19
+FWP_V6_ADDR_MASK = 20
+FWP_MATCH_EQUAL = 0
+FWP_ACTION_BLOCK = 0x00001001 # EN: BLOCK | FLAG_TERMINATING / FR: BLOCK | TERMINATING
+FWP_E_FILTER_NOT_FOUND = 0x80320004
+_NAME_PREFIX = "SnitchRule-"
+
+
+def _guid(text: str):
+ """EN: Parse a {xxxxxxxx-…} GUID into the 16-byte Windows layout
+ (first three fields little-endian). / FR: Convertit un GUID texte en
+ layout mémoire Windows (trois premiers champs little-endian)."""
+ return _GUID.from_buffer_copy(uuid.UUID(text).bytes_le)
+
+
+def _rule_key(rid: str, tag: str = ""):
+ """EN: Deterministic filter GUID per (rule, target) — delete-by-key then
+ needs no stored handle and survives restarts.
+ FR: GUID de filtre déterministe par (règle, cible) — la suppression par
+ clé n'exige pas de handle stocké et survit aux redémarrages."""
+ return _GUID.from_buffer_copy(
+ uuid.uuid5(uuid.NAMESPACE_URL, f"snitch-wfp:{rid}:{tag}").bytes_le)
+
+
+# ── ctypes structures — layouts match the SDK on Win64 exactly ──────────────
+# EN: ctypes unions/structures replicate fwpmtypes.h; alignment is natural.
+# FR: les unions/structures ctypes répliquent fwpmtypes.h ; alignement naturel.
+
+class _GUID(ctypes.Structure):
+ _fields_ = [("Data1", ctypes.c_uint32), ("Data2", ctypes.c_uint16),
+ ("Data3", ctypes.c_uint16), ("Data4", ctypes.c_uint8 * 8)]
+
+
+class _BYTE_BLOB(ctypes.Structure):
+ _fields_ = [("size", ctypes.c_uint32), ("data", ctypes.c_void_p)]
+
+
+class _DISPLAY_DATA(ctypes.Structure):
+ _fields_ = [("name", ctypes.c_wchar_p), ("description", ctypes.c_wchar_p)]
+
+
+class _VALUE_UNION(ctypes.Union):
+ _fields_ = [("uint8", ctypes.c_uint8), ("uint16", ctypes.c_uint16),
+ ("uint32", ctypes.c_uint32), ("uint64p", ctypes.c_void_p),
+ ("blobp", ctypes.c_void_p), ("ba16p", ctypes.c_void_p),
+ ("v4amp", ctypes.c_void_p), ("v6amp", ctypes.c_void_p),
+ ("rangep", ctypes.c_void_p)]
+
+
+class _VALUE(ctypes.Structure):
+ _fields_ = [("type", ctypes.c_uint32), ("v", _VALUE_UNION)]
+
+
+class _CONDITION(ctypes.Structure):
+ _fields_ = [("fieldKey", _GUID), ("matchType", ctypes.c_uint32),
+ ("conditionValue", _VALUE)]
+
+
+class _ACTION_UNION(ctypes.Union):
+ _fields_ = [("filterType", _GUID), ("calloutType", _GUID)]
+
+
+class _ACTION(ctypes.Structure):
+ _fields_ = [("type", ctypes.c_uint32), ("u", _ACTION_UNION)]
+
+
+class _CTX_UNION(ctypes.Union):
+ _fields_ = [("rawContext", ctypes.c_uint64),
+ ("providerContextKey", _GUID)]
+
+
+class _FILTER(ctypes.Structure):
+ _fields_ = [("filterKey", _GUID), ("displayData", _DISPLAY_DATA),
+ ("flags", ctypes.c_uint32), ("providerKey", ctypes.c_void_p),
+ ("providerData", _BYTE_BLOB), ("layerKey", _GUID),
+ ("subLayerKey", _GUID), ("weight", _VALUE),
+ ("numFilterConditions", ctypes.c_uint32),
+ ("filterCondition", ctypes.c_void_p), ("action", _ACTION),
+ ("ctx", _CTX_UNION), ("reserved", ctypes.c_void_p),
+ ("filterId", ctypes.c_uint64), ("effectiveWeight", _VALUE)]
+
+
+class _SESSION(ctypes.Structure):
+ _fields_ = [("sessionKey", _GUID), ("displayData", _DISPLAY_DATA),
+ ("flags", ctypes.c_uint32),
+ ("txnWaitTimeoutInMSec", ctypes.c_uint32),
+ ("processId", ctypes.c_uint32), ("sid", ctypes.c_void_p),
+ ("username", ctypes.c_wchar_p), ("kernelMode", ctypes.c_int32)]
+
+
+class _V4_ADDR_MASK(ctypes.Structure):
+ _fields_ = [("addr", ctypes.c_uint32), ("mask", ctypes.c_uint32)]
+
+
+class _V6_ADDR_MASK(ctypes.Structure):
+ _fields_ = [("addr", ctypes.c_uint8 * 16), ("prefixLength", ctypes.c_uint8)]
+
+
+class _BYTE_ARRAY16(ctypes.Structure):
+ _fields_ = [("byteArray16", ctypes.c_uint8 * 16)]
+
+
+class WfpBackend:
+ """EN: Minimal WFP user-mode client — open engine, add block filters with
+ deterministic GUID keys, delete by key, purge stale Snitch filters by
+ enumerating names. Everything is best-effort and never raises.
+ FR: Client WFP user-mode minimal — ouvre le moteur, ajoute des filtres
+ de blocage à clés GUID déterministes, supprime par clé, purge les
+ filtres Snitch périmés en énumérant les noms. Au mieux, ne lève jamais."""
+
+ def __init__(self):
+ self._dll = None
+ self._engine = ctypes.c_void_p()
+ self._keepalive: list = [] # EN: pinned ctypes objects / FR: objets ctypes épinglés
+
+ # ── lifecycle / cycle de vie ─────────────────────────────────────────────
+
+ @staticmethod
+ def available() -> bool:
+ return os.name == "nt"
+
+ def open(self) -> tuple[bool, str]:
+ """EN: Load fwpuclnt + open a non-dynamic session (filters persist —
+ Snitch deletes them explicitly by key). Returns (ok, error).
+ FR: Charge fwpuclnt + ouvre une session non dynamique (les filtres
+ persistent — Snitch les supprime explicitement par clé)."""
+ if self._engine.value:
+ return True, ""
+ if not self.available():
+ return False, "windows only"
+ try:
+ self._dll = ctypes.WinDLL("fwpuclnt")
+ except OSError as e:
+ return False, f"fwpuclnt unavailable: {e}"
+ sess = _SESSION()
+ sess.displayData.name = "Snitch"
+ sess.displayData.description = "Snitch outbound filters"
+ sess.flags = 0 # EN: persistent / FR: persistante
+ sess.processId = os.getpid()
+ engine = ctypes.c_void_p()
+ rc = self._dll.FwpmEngineOpen0(None, RPC_C_AUTHN_WINNT, None,
+ ctypes.byref(sess), ctypes.byref(engine))
+ if rc != 0:
+ return False, f"FwpmEngineOpen0=0x{rc:08x} (admin required)"
+ self._engine = engine
+ self._purge_stale()
+ return True, ""
+
+ def close(self) -> None:
+ if self._dll and self._engine.value:
+ self._dll.FwpmEngineClose0(self._engine)
+ self._engine = ctypes.c_void_p()
+
+ # ── filters / filtres ────────────────────────────────────────────────────
+
+ def add_block(self, rid: str, conds: list[dict]) -> tuple[bool, str]:
+ """EN: Add one BLOCK filter per (layer, address) combination implied
+ by `conds` — a condition dict list like:
+ {"app": path} → ALE_APP_ID on BOTH v4+v6 layers
+ {"remote": cidr} → remote addr (+mask) on the matching layer
+ {"port": 443} → remote port on BOTH layers
+ Returns (ok, error). Filter keys are uuid5(rid, serialized conds).
+ FR: Ajoute un filtre BLOCK par combinaison (couche, adresse) —
+ voir le format ci-dessus. Clés uuid5(rid, conditions sérialisées)."""
+ if not self._engine.value:
+ return False, "engine not open"
+ try:
+ plan = self._plan(conds)
+ except ValueError as e:
+ return False, str(e)
+ keep: list = []
+ try:
+ for layer_s, cfields, tag in plan:
+ f = _FILTER()
+ f.filterKey = _rule_key(rid, tag)
+ f.displayData.name = _NAME_PREFIX + rid
+ f.displayData.description = "Snitch outbound block"
+ f.layerKey = _guid(layer_s)
+ f.subLayerKey = _guid(_SUBLAYER_UNIVERSAL)
+ weight = ctypes.c_uint64(0xFFFFFFFFFFFFFFFF)
+ f.weight.type = FWP_UINT64
+ f.weight.v.uint64p = ctypes.cast(
+ ctypes.pointer(weight), ctypes.c_void_p)
+ keep.append(weight)
+ arr = (_CONDITION * len(cfields))()
+ for i, (key_s, vtype, ptr_or_val, pin) in enumerate(cfields):
+ arr[i].fieldKey = _guid(key_s)
+ arr[i].matchType = FWP_MATCH_EQUAL
+ arr[i].conditionValue.type = vtype
+ self._set_value(arr[i].conditionValue.v, vtype, ptr_or_val)
+ keep.append(pin)
+ f.numFilterConditions = len(cfields)
+ f.filterCondition = ctypes.cast(arr, ctypes.c_void_p)
+ keep.append(arr)
+ f.action.type = FWP_ACTION_BLOCK
+ rc = self._dll.FwpmFilterAdd0(self._engine, ctypes.byref(f),
+ None, None)
+ if rc != 0:
+ return False, f"FwpmFilterAdd0=0x{rc:08x}"
+ return True, ""
+ except OSError as e:
+ return False, str(e)[:200]
+
+ @staticmethod
+ def _set_value(union: _VALUE_UNION, vtype: int, val) -> None:
+ """EN: Fill the value union — scalar types inline, compound by pointer.
+ FR: Remplit l'union — scalaires inline, composés par pointeur."""
+ if vtype == FWP_UINT8:
+ union.uint8 = val
+ elif vtype == FWP_UINT16:
+ union.uint16 = val
+ elif vtype == FWP_UINT32:
+ union.uint32 = val
+ elif vtype == FWP_BYTE_BLOB_TYPE:
+ union.blobp = val
+ elif vtype == FWP_BYTE_ARRAY16_TYPE:
+ union.ba16p = val
+ elif vtype == FWP_V4_ADDR_MASK:
+ union.v4amp = val
+ elif vtype == FWP_V6_ADDR_MASK:
+ union.v6amp = val
+
+ def _plan(self, conds: list[dict]) -> list:
+ """EN: Translate abstract conds → [(layer_guid, [(key,type,val,pin)],
+ tag)] — one filter per address so each key stays unique+deletable.
+ FR: Traduit les conditions → [(couche, [(clé,type,valeur,pin)],
+ tag)] — un filtre par adresse pour des clés uniques/supprimables."""
+ app = next((c["app"] for c in conds if "app" in c), None)
+ remotes = [c["remote"] for c in conds if "remote" in c]
+ port = next((c["port"] for c in conds if "port" in c), None)
+ proto = next((c["proto"] for c in conds if "proto" in c), None)
+ plan = []
+ if app is not None:
+ blob = self._app_blob(app)
+ if blob is None:
+ raise ValueError(f"FwpmGetAppIdFromFileName failed for {app}")
+ fields = [(_COND_ALE_APP_ID, FWP_BYTE_BLOB_TYPE,
+ ctypes.cast(ctypes.byref(blob.contents), ctypes.c_void_p),
+ blob)]
+ plan += [(_LAYER_V4, fields, "app4"), (_LAYER_V6, fields, "app6")]
+ # EN: app blob freed by caller-side pin until add returns — WFP
+ # copies the blob during FwpmFilterAdd0.
+ # FR: blob libéré via le pin côté appelant — WFP le copie
+ # pendant FwpmFilterAdd0.
+ for net_s in remotes:
+ net = ipaddress.ip_network(net_s, strict=False)
+ if net.version == 4:
+ am = _V4_ADDR_MASK(
+ int(net.network_address),
+ struct.unpack("!I", socket.inet_aton(str(net.netmask)))[0])
+ cf = (_COND_REMOTE_IP, FWP_V4_ADDR_MASK,
+ ctypes.cast(ctypes.byref(am), ctypes.c_void_p), am)
+ plan.append((_LAYER_V4, [cf], f"ip-{net}"))
+ else:
+ am = _V6_ADDR_MASK(
+ (ctypes.c_uint8 * 16)(*net.network_address.packed),
+ net.prefixlen)
+ cf = (_COND_REMOTE_IP, FWP_V6_ADDR_MASK,
+ ctypes.cast(ctypes.byref(am), ctypes.c_void_p), am)
+ plan.append((_LAYER_V6, [cf], f"ip-{net}"))
+ if port is not None:
+ for layer, tag in ((_LAYER_V4, "port4"), (_LAYER_V6, "port6")):
+ fields = [(_COND_REMOTE_PORT, FWP_UINT16, int(port), None)]
+ if proto:
+ fields.append(("3971ef2b-623e-4f9a-8cb1-6e79b806b9a7",
+ FWP_UINT8, int(proto), None))
+ plan.append((layer, fields, tag))
+ return plan
+
+ def delete(self, rid: str, tags: list[str]) -> None:
+ """EN: Delete this rule's filters by their deterministic keys —
+ missing keys are fine. / FR: Supprime les filtres par leurs clés
+ déterministes — les absents sont ignorés."""
+ if not self._engine.value:
+ return
+ for tag in tags:
+ key = _rule_key(rid, tag)
+ rc = self._dll.FwpmFilterDeleteByKey0(self._engine,
+ ctypes.byref(key))
+ # EN: FWP_E_FILTER_NOT_FOUND is expected — ignore it.
+ # FR: FWP_E_FILTER_NOT_FOUND est attendu — on l'ignore.
+ _ = rc
+
+ @staticmethod
+ def tags_for(kind: str, value: str,
+ resolved: Optional[list[str]] = None) -> list[str]:
+ """EN: Inverse of _plan's tag generation — which keys might exist
+ for a rule (used for deletes + domain refresh deltas).
+ FR: Inverse de la génération de tags — quelles clés peuvent exister
+ pour une règle (suppressions + deltas de re-résolution)."""
+ if kind == "process":
+ return ["app4", "app6"]
+ if kind == "port":
+ return ["port4", "port6"]
+ nets = resolved if kind == "domain" else [value]
+ return [f"ip-{ipaddress.ip_network(n, strict=False)}" for n in nets]
+
+ def _app_blob(self, path: str):
+ """EN: FwpmGetAppIdFromFileName0 → FWP_BYTE_BLOB* (canonicalized
+ device path the ALE layer matches). None on failure.
+ FR: FwpmGetAppIdFromFileName0 → FWP_BYTE_BLOB* (chemin canonique
+ que la couche ALE matche). None en cas d'échec."""
+ blob = ctypes.POINTER(_BYTE_BLOB)()
+ rc = self._dll.FwpmGetAppIdFromFileName0(path, ctypes.byref(blob))
+ if rc != 0 or not blob:
+ return None
+ self._keepalive.append(blob) # EN: keep alive; freed w/ engine / FR: gardé vivant
+ return blob
+
+ def _purge_stale(self) -> None:
+ """EN: Remove leftover SnitchRule-* filters from previous runs —
+ enumerates the engine and deletes by key on name-prefix match.
+ FR: Retire les filtres SnitchRule-* restés d'exécutions passées —
+ énumère le moteur et supprime par clé sur préfixe de nom."""
+ enum_h = ctypes.c_void_p()
+ rc = self._dll.FwpmFilterCreateEnumHandle0(
+ self._engine, None, ctypes.byref(enum_h))
+ if rc != 0:
+ return
+ try:
+ while True:
+ arr_p = ctypes.POINTER(ctypes.POINTER(_FILTER))()
+ n = ctypes.c_uint32(0)
+ rc = self._dll.FwpmFilterEnum0(
+ self._engine, enum_h, 64, ctypes.byref(arr_p),
+ ctypes.byref(n))
+ if rc != 0 or n.value == 0:
+ break
+ for i in range(n.value):
+ name = arr_p[i].contents.displayData.name or ""
+ if name.startswith(_NAME_PREFIX):
+ key = arr_p[i].contents.filterKey
+ self._dll.FwpmFilterDeleteByKey0(
+ self._engine, ctypes.byref(key))
+ self._dll.FwpmFreeMemory0(ctypes.byref(arr_p))
+ finally:
+ self._dll.FwpmFilterDestroyEnumHandle0(self._engine, enum_h)
diff --git a/backend/tests/test_security_features.py b/backend/tests/test_security_features.py
index 7dad89e..b0f3333 100644
--- a/backend/tests/test_security_features.py
+++ b/backend/tests/test_security_features.py
@@ -11,13 +11,27 @@ FR: Couvre le FirewallManager (matching/lockdown/compteurs — les commandes
checks d'anomalie : DNS_TUNNEL, CLEARTEXT, BASELINE_DEVIATION.
"""
+import ctypes as _ct
+import socket as _socket
import time
+import types as _types
from datetime import datetime, timezone
+import psutil as _psutil
+
+from capture.ebpf_probe import EbpfProbe, _Event
from capture.sniffer import Packet
+from detection import explain as _explain
+from detection import iocshare, perfprobe
from detection.anomaly import AnomalyDetector, BASELINE_LEARN_MIN
+from detection.deepinspect import DeepInspector, suspicious_module_paths
from detection.firewall import FirewallManager
+from detection.integrity import IntegrityWatcher, _merkle_root, _names_match
+from detection.llm_local import LocalSlm, _is_loopback
+from detection.miner import MinerDetector
+from detection.sinkresponder import SinkholeResponder
from detection.threatintel import ThreatIntel
+from detection.wfp import _LAYER_V4, _LAYER_V6, WfpBackend
PUBLIC_IP = "91.198.174.192"
PRIVATE_IP = "192.168.1.55"
@@ -334,7 +348,6 @@ def test_rule_action_defaults_to_block(tmp_path, monkeypatch):
# ── Integrity watch / Veille d'intégrité ────────────────────────────────────
-from detection.integrity import IntegrityWatcher, _names_match
def test_names_match_tolerates_versions():
@@ -405,7 +418,6 @@ def test_integrity_status_capabilities():
# ── Alert explanations / Explications d'alertes ────────────────────────────
-from detection import explain as _explain
def test_explain_covers_every_type_bilingually():
@@ -425,3 +437,404 @@ def test_explain_unknown_type_returns_none():
assert _explain.explain("NOPE") is None
assert _explain.explain("") is None
assert "THREAT_HIT" in _explain.all_types()
+
+
+# ── WFP user-mode (Windows) / WFP user-mode ─────────────────────────────────
+
+
+
+def test_wfp_unavailable_off_windows():
+ """EN: On non-Windows the backend honestly reports unavailable and
+ open() refuses cleanly (no WinDLL attribute to crash on).
+ FR: Hors Windows le backend rapporte honnêtement indisponible et
+ open() refuse proprement."""
+ import os
+ if os.name != "nt":
+ assert WfpBackend.available() is False
+ ok, why = WfpBackend().open()
+ assert ok is False and why
+
+
+def test_wfp_plan_layers_and_tags():
+ """EN: Remote CIDR → one filter on the matching layer; port → filters
+ on BOTH ALE layers (v4+v6). Tags are deterministic for delete-by-key.
+ FR: CIDR distant → un filtre sur la bonne couche ; port → filtres sur
+ les DEUX couches ALE. Tags déterministes pour la suppression par clé."""
+ plan = WfpBackend()._plan([{"remote": "203.0.113.0/24"},
+ {"port": 4444}])
+ layers = [p[0] for p in plan]
+ tags = [p[2] for p in plan]
+ assert _LAYER_V4 in layers and _LAYER_V6 in layers
+ assert "port4" in tags and "port6" in tags
+ assert any(t.startswith("ip-203.0.113.0/24") for t in tags)
+
+
+def test_wfp_tags_for_matches_plan():
+ """EN: tags_for() must enumerate every tag _plan can emit — a missed
+ tag would leak a stale filter. / FR: tags_for() doit énumérer chaque
+ tag que _plan émet — un tag manqué laisserait un filtre périmé."""
+ assert set(WfpBackend.tags_for("process", "x")) == {"app4", "app6"}
+ assert set(WfpBackend.tags_for("port", "443")) == {"port4", "port6"}
+ assert WfpBackend.tags_for("ip", "203.0.113.9/32") == ["ip-203.0.113.9/32"]
+
+
+# ── eBPF probe / Sonde eBPF ─────────────────────────────────────────────────
+
+
+
+def _evt(pid: int, comm: bytes, ip: bytes, port: int) -> _Event:
+ e = _Event()
+ e.pid, e.dport, e.ipver = pid, port, 4
+ e.comm = comm + b"\x00" * (16 - len(comm))
+ e.daddr[:4] = ip
+ return e
+
+
+def test_ebpf_lookup_unique_event():
+ """EN: A unique connect() event attributes (pid, comm) to later
+ packets the socket table missed. / FR: Un connect() unique attribue
+ (pid, comm) aux paquets ratés par la table des sockets."""
+ p = EbpfProbe()
+ e = _evt(4242, b"dropper", bytes([93, 184, 216, 34]), 4444)
+ p._on_evt(0, _ct.addressof(e), _ct.sizeof(e))
+ assert p.lookup("93.184.216.34", 4444) == (4242, "dropper")
+ assert p.lookup("93.184.216.34", 443) == (None, None)
+
+
+def test_ebpf_ambiguous_destination_refused():
+ """EN: Two pids → same (ip,port): attribution would be a coin flip —
+ lookup must refuse. / FR: Deux pids → même (ip,port) : l'attribution
+ serait aléatoire — lookup doit refuser."""
+ p = EbpfProbe()
+ for pid in (100, 200):
+ e = _evt(pid, b"proc", bytes([1, 2, 3, 4]), 443)
+ p._on_evt(0, _ct.addressof(e), _ct.sizeof(e))
+ assert p.lookup("1.2.3.4", 443) == (None, None)
+
+
+def test_ebpf_available_honest():
+ """EN: availability is a (bool, reason) tuple — never a bare guess.
+ FR: disponibilité = tuple (bool, raison) — jamais une estimation."""
+ ok, why = EbpfProbe.available()
+ assert isinstance(ok, bool) and isinstance(why, str)
+
+
+# ── Deep inspect (Frida) / Inspection profonde ──────────────────────────────
+
+
+
+def test_deep_inspect_never_crashes():
+ """EN: Without frida or a dead pid, inspect() returns ok=False with a
+ reason — never raises. / FR: Sans frida ou pid mort, inspect() renvoie
+ ok=False avec une raison — ne lève jamais."""
+ res = DeepInspector().inspect(2 ** 30, seconds=3)
+ assert res["ok"] is False and res["error"]
+ assert res["events"] == []
+
+
+def test_suspicious_module_paths_flags_staging():
+ """EN: Temp/shm/downloads module paths are flagged, system paths not.
+ FR: Les chemins temp/shm/downloads sont signalés, pas les chemins
+ système."""
+ events = [{"path": r"C:\Users\x\AppData\Local\Temp\evil.dll"},
+ {"path": "/tmp/.hidden/libc.so"},
+ {"path": "/usr/lib/libc.so.6"},
+ {"path": ""}]
+ bad = suspicious_module_paths(events)
+ assert len(bad) == 2 and not any("libc.so.6" in p for p in bad)
+
+
+# ── Sinkhole responder / Répondeur sinkhole ─────────────────────────────────
+
+
+
+def test_sink_responder_http_hit(monkeypatch):
+ """EN: An HTTP request to the responder records host+path+process —
+ the sinkhole becomes a sensor. / FR: Une requête HTTP enregistre
+ hôte+chemin+processus — le sinkhole devient un capteur."""
+ monkeypatch.setattr("detection.sinkresponder._pid_for_port",
+ lambda p: (4321, "beacon.exe"))
+ r = SinkholeResponder()
+ srv, cli = _socket.socketpair()
+ try:
+ cli.sendall(b"POST /gate.php HTTP/1.1\r\nHost: c2.evil\r\n"
+ b"Content-Length: 4\r\n\r\ntoken")
+ r._handle_http(srv, ("127.0.0.1", 44444))
+ finally:
+ cli.close()
+ hits = r.pop_hits()
+ assert hits and hits[0]["host"] == "c2.evil"
+ assert hits[0]["method"] == "POST" and hits[0]["path"] == "/gate.php"
+ assert hits[0]["pid"] == 4321 and hits[0]["process"] == "beacon.exe"
+ assert r.pop_hits() == []
+
+
+def test_sink_responder_tls_hit(monkeypatch):
+ """EN: A ClientHello records a tls hit (SNI parsed when present).
+ FR: Un ClientHello enregistre un hit tls (SNI analysé si présent)."""
+ monkeypatch.setattr("detection.sinkresponder._pid_for_port",
+ lambda p: (None, None))
+ r = SinkholeResponder()
+ srv, cli = _socket.socketpair()
+ try:
+ cli.sendall(b"\x16\x03\x01" + b"\x00" * 200) # EN: TLS record head
+ r._handle_tls(srv, ("127.0.0.1", 55555))
+ finally:
+ cli.close()
+ hits = r.pop_hits()
+ assert hits and hits[0]["kind"] == "tls"
+
+
+# ── Miner detector / Détecteur de minage ────────────────────────────────────
+
+
+
+def _mpkt(remote=PUBLIC_IP, port=4444, pid=4242, process="xmr",
+ head=b""):
+ p = pkt(remote=remote, port=port, process=process)
+ p.pid = pid
+ p.app_head = head
+ return p
+
+
+def test_miner_stratum_signature():
+ """EN: Cleartext stratum JSON in the payload head → critical hit.
+ FR: JSON stratum en clair dans la tête du payload → hit critique."""
+ m = MinerDetector()
+ out = m.analyze_packet(_mpkt(head=b'{"id":1,"method":"mining.subscribe",'
+ b'"params":["xmr.1"]}'))
+ assert out[0]["type"] == "MINING_STRATUM"
+ assert out[0]["severity"] == "critical"
+
+
+def test_miner_pool_port_alone_never_alerts():
+ """EN: A pool port without CPU corroboration marks a suspect only.
+ FR: Un port de pool sans corroboration CPU ne fait que marquer."""
+ m = MinerDetector()
+ assert m.analyze_packet(_mpkt(port=4444)) == []
+ assert (4242, PUBLIC_IP) in m._suspects
+
+
+def test_miner_cpu_corroboration(monkeypatch):
+ """EN: Pool port + sustained high CPU → MINING_SUSPECT.
+ FR: Port de pool + CPU haute soutenue → MINING_SUSPECT."""
+ import types
+ import psutil
+ m = MinerDetector()
+ m.analyze_packet(_mpkt(port=4444))
+ m._suspects[(4242, PUBLIC_IP)] = time.time() - 60 # EN: force window
+ fake = types.SimpleNamespace(cpu_percent=lambda interval: 95.0,
+ name=lambda: "xmr")
+ monkeypatch.setattr(psutil, "Process", lambda pid: fake)
+ out = m.cpu_corroborate()
+ assert out[0]["type"] == "MINING_SUSPECT"
+ assert "95%" in out[0]["detail"]
+
+
+def test_miner_low_cpu_acquits(monkeypatch):
+ """EN: Pool port with normal CPU produces no alert — corroboration
+ matters. / FR: Port de pool avec CPU normale = rien — la
+ corroboration compte."""
+ import types
+ import psutil
+ m = MinerDetector()
+ m.analyze_packet(_mpkt(port=4444))
+ m._suspects[(4242, PUBLIC_IP)] = time.time() - 60
+ fake = types.SimpleNamespace(cpu_percent=lambda interval: 8.0,
+ name=lambda: "irc")
+ monkeypatch.setattr(psutil, "Process", lambda pid: fake)
+ assert m.cpu_corroborate() == []
+
+
+# ── perf probe / Sonde perf ─────────────────────────────────────────────────
+
+
+
+def test_perfprobe_available_honest():
+ """EN: tuple (bool, reason); off-Linux it's a clean refusal.
+ FR: tuple (bool, raison) ; hors Linux c'est un refus propre."""
+ ok, why = perfprobe.available()
+ import platform
+ if platform.system().lower() != "linux":
+ assert ok is False
+ res = perfprobe.sample(2 ** 30, seconds=0.2)
+ assert res["ok"] is False
+
+
+# ── Local SLM / SLM local ───────────────────────────────────────────────────
+
+
+
+def test_slm_loopback_gate():
+ """EN: Only literal loopback endpoints are accepted — everything else
+ is rejected so alert data can never leave the machine.
+ FR: Seuls les endpoints loopback littéraux sont acceptés — tout le
+ reste est rejeté pour que les données d'alerte ne partent jamais."""
+ assert _is_loopback("http://127.0.0.1:11434")
+ assert _is_loopback("http://localhost:11434")
+ assert _is_loopback("http://[::1]:11434")
+ assert not _is_loopback("http://192.168.1.1:11434")
+ assert not _is_loopback("http://ollama.internal:11434")
+ assert not _is_loopback("http://evil.example:11434")
+
+
+def test_slm_disabled_and_remote_rejected():
+ """EN: Disabled → None; a non-loopback endpoint is never adopted.
+ FR: Désactivé → None ; un endpoint non-loopback n'est jamais adopté."""
+ s = LocalSlm()
+ assert s.enrich("BEACON", {}) is None
+ s.configure(True, "http://10.0.0.9:11434", "m")
+ assert s._endpoint == "http://127.0.0.1:11434" # EN: kept default
+ assert s.enrich("BEACON", {}) is None # EN: unreachable → None
+
+
+# ── IOC pack / Paquet IOC ───────────────────────────────────────────────────
+
+
+
+def test_iocpack_roundtrip(monkeypatch):
+ """EN: Deterministic build (flip=0) → indicators are findable, foreign
+ ones are not. / FR: Build déterministe (flip=0) → les indicateurs se
+ retrouvent, les étrangers non."""
+ monkeypatch.setattr(iocshare, "_FLIP", 0.0)
+ pack = iocshare.build_pack(["203.0.113.7", "evil.example"])
+ assert pack["format"].startswith("snitch-ioc-pack")
+ res = iocshare.check_pack(pack, ["203.0.113.7", "9.9.9.9"])
+ assert res["ok"]
+ hints = {h["indicator"] for h in res["hints"]}
+ assert "203.0.113.7" in hints and "9.9.9.9" not in hints
+
+
+def test_iocpack_flip_adds_deniability():
+ """EN: With flipping enabled, two builds of the same indicators
+ differ — a pack can't be diffed back to the source list.
+ FR: Avec flip, deux builds des mêmes indicateurs diffèrent — un
+ paquet ne se remonte pas à la liste source."""
+ import base64
+ a = iocshare.build_pack(["1.2.3.4"] * 10)
+ b = iocshare.build_pack(["1.2.3.4"] * 10)
+ assert base64.b64decode(a["bits_b64"]) != base64.b64decode(b["bits_b64"])
+
+
+def test_iocpack_rejects_garbage():
+ """EN: Bad format/params/bits → honest error, not a crash.
+ FR: Format/params/bits mauvais → erreur honnête, pas de crash."""
+ assert iocshare.check_pack({}, ["x"])["ok"] is False
+ pack = {"format": "snitch-ioc-pack/1", "m": 8192, "k": 4,
+ "bits_b64": "AAAA"}
+ assert iocshare.check_pack(pack, ["x"])["ok"] is False
+
+
+# ── Integrity: modules + merkle / Intégrité : modules + merkle ──────────────
+
+
+
+def test_merkle_root_order_independent():
+ """EN: Root is sort-based — reload order can't trigger false alerts.
+ FR: Racine triée — l'ordre de rechargement ne peut pas alerter."""
+ assert _merkle_root(["a", "b", "c"]) == _merkle_root(["c", "a", "b"])
+ assert _merkle_root(["a", "b"]) != _merkle_root(["a", "b", "c"])
+ assert _merkle_root([]) == ""
+
+
+def test_integrity_module_suspect(monkeypatch):
+ """EN: A file-backed module living under /tmp is flagged.
+ FR: Un module fichier-basé sous /tmp est signalé."""
+ w = IntegrityWatcher()
+ maps = [_types.SimpleNamespace(path="/tmp/.x/evil.so"),
+ _types.SimpleNamespace(path="/usr/lib/libc.so.6")]
+ monkeypatch.setattr(
+ _psutil, "Process",
+ lambda pid: _types.SimpleNamespace(
+ memory_maps=lambda grouped=True: maps))
+ out = w._check_modules(999, "app", "")
+ assert out[0]["type"] == "MODULE_SUSPECT"
+ assert "/tmp/.x/evil.so" in out[0]["modules"]
+
+
+def test_integrity_module_merkle_baseline(tmp_path, monkeypatch):
+ """EN: First module set → baseline; a changed module file later →
+ MODULE_CHANGED. / FR: Premier ensemble → baseline ; un fichier de
+ module modifié → MODULE_CHANGED."""
+ m1, m2 = tmp_path / "a.so", tmp_path / "b.so"
+ m1.write_bytes(b"lib-a-v1")
+ m2.write_bytes(b"lib-b-v1")
+ w = IntegrityWatcher()
+ maps = [_types.SimpleNamespace(path=str(m1)),
+ _types.SimpleNamespace(path=str(m2))]
+ monkeypatch.setattr(
+ _psutil, "Process",
+ lambda pid: _types.SimpleNamespace(
+ memory_maps=lambda grouped=True: maps))
+ assert w._check_modules(999, "app", "/usr/bin/app") == [] # baseline
+ m1.write_bytes(b"lib-a-v2-patched")
+ import os as _os
+ _os.utime(m1, (0, 2_000_000_000))
+ out = w._check_modules(999, "app", "/usr/bin/app")
+ assert out[0]["type"] == "MODULE_CHANGED"
+ assert out[0]["severity"] == "critical"
+
+
+# ── Firewall: throttle action / Pare-feu : action throttle ──────────────────
+
+def test_throttle_rejects_port_and_process(tmp_path, monkeypatch):
+ """EN: throttle on port/process is meaningless → ValueError.
+ FR: throttle sur port/processus est insensé → ValueError."""
+ fw = _fw(tmp_path, monkeypatch)
+ for kind in ("process", "port"):
+ try:
+ fw.add_rule(kind, "x", action="throttle")
+ except ValueError:
+ continue
+ raise AssertionError(f"expected ValueError for {kind}")
+
+
+def test_throttle_apply_linux_commands(tmp_path, monkeypatch):
+ """EN: A Linux throttle emits clsact flower police filters at the
+ rule's rate. / FR: Un throttle Linux émet des filtres flower police
+ au débit de la règle."""
+ fw = FirewallManager(str(tmp_path))
+ fw._platform, fw._demo, fw._tc_iface = "linux", False, "eth0"
+ calls: list[list[str]] = []
+ monkeypatch.setattr(fw, "_run", lambda a: (calls.append(a), (True, ""))[1])
+ rule = fw.add_rule("ip", PUBLIC_IP, action="throttle", rate=128)
+ assert rule["applied"] is True
+ flat = [x for call in calls for x in call]
+ assert "police" in flat and "128kbit" in flat
+ assert "egress" in flat and "flower" in flat
+
+
+def test_throttle_off_linux_honest(tmp_path, monkeypatch):
+ """EN: Throttle on macOS reports applied=False, linux-only reason.
+ FR: Throttle sur macOS rapporte applied=False, raison linux."""
+ fw = FirewallManager(str(tmp_path))
+ fw._platform, fw._demo = "darwin", False
+ monkeypatch.setattr(fw, "_pf_apply", lambda: (True, ""))
+ rule = fw.add_rule("ip", PUBLIC_IP, action="throttle")
+ assert rule["applied"] is False and "linux" in (rule["error"] or "")
+
+
+# ── Parser app_head / app_head du parseur ───────────────────────────────────
+
+def test_parser_app_head_cleartext_only():
+ """EN: Cleartext TCP payload head is captured (≤64B) for stratum
+ fingerprinting; TLS stays opaque (app_head empty).
+ FR: La tête d'un payload TCP en clair est capturée (≤64 o.) pour la
+ signature stratum ; TLS reste opaque (app_head vide)."""
+ import struct as _st
+ from capture.parser import parse_frame, DLT_EN10MB
+
+ def frame(payload: bytes) -> bytes:
+ # EN: 20-byte TCP header — offset byte (0x50) sits at position 12.
+ # FR: en-tête TCP de 20 octets — octet d'offset (0x50) en position 12.
+ tcp = _st.pack("!HH", 40000, 3333) + b"\x00" * 8 + b"\x50\x18" \
+ + b"\x00" * 6 + payload
+ ip = bytes([0x45, 0]) + _st.pack("!H", 20 + len(tcp)) + \
+ b"\x00" * 4 + bytes([64, 6]) + b"\x00" * 2 + \
+ bytes([10, 0, 0, 1]) + bytes([93, 184, 216, 34])
+ return b"\xaa" * 12 + b"\x08\x00" + ip + tcp
+
+ p = parse_frame(DLT_EN10MB, frame(b'{"method":"mining.subscribe"}'))
+ 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""
diff --git a/backend/version.py b/backend/version.py
index 7f38fb6..3d8da55 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.2.0"
+__version__ = "1.3.0"
diff --git a/docs/FIREWALL.de.md b/docs/FIREWALL.de.md
index 867b8e9..31963b3 100644
--- a/docs/FIREWALL.de.md
+++ b/docs/FIREWALL.de.md
@@ -91,3 +91,16 @@ in Klartext. Ein *Befundbericht*, keine Zertifizierung.
- **Domain-Re-Auflösung** — `domain`-Regeln werden alle ~10 Min neu aufgelöst; das IP-Delta wird je OS angewendet, damit CDN-Rotation einen Namen nicht stillschweigend freigibt.
- **Integritätswache** (standardmäßig an, schreibgeschützt, lokal) — SHA-256-Baselines vernetzter Executables (`BINARY_CHANGED`), Name/Exe-Mismatches (`NAME_MISMATCH`), `rwxp`-Scan nur Linux (`MEM_RWX`, Info-Stufe für bekannte JIT-Apps). `GET /security/integrity`, `POST /security/integrity/check`.
- **Alert-Erklärungen** — `GET /security/explain?type=X` liefert handgeschriebene zweisprachige (EN/FR) Erklärungen; deterministisch und offline — kein Modell. Die UI zeigt sie hinter der „Warum?“-Schaltfläche.
+
+### Optionale Sonden (v1.3)
+
+Alle sind **standardmäßig aus oder selbstlimitierend**, degradieren ehrlich und senden nie Daten von der Maschine:
+
+- **eBPF-Connect-Sonde** (Linux, `ebpf_probe`) — BCC-`tcpconnect`-Kprobe ordnet `connect()` zu kurzlebiger Prozesse zu. Braucht `python3-bcc` + root; mehrdeutige Ziele werden nie geraten. `GET /security/ebpf`.
+- **Frida-Inspektion** — `POST /security/deep_inspect {pid,seconds}` hängt ≤60 s an EINEN pid und meldet, welches geladene Modul jedes `connect()` auslöste. Staging-Pfade → `INJECT_SUSPECT`.
+- **Sinkhole-Responder** — bei aktiver `sinkhole`-Regel verwandeln Loopback-Listener auf :80/:443 jeden Versuch in einen `SINKHOLE_HIT`-Alarm mit Host/URI oder SNI + Prozess.
+- **Modul-Integrität** — Merkle-Wurzel über ausführbare Mappings → `MODULE_CHANGED`; Pfade unter `/tmp`/memfd → `MODULE_SUSPECT`.
+- **Mining-Erkennung** — Stratum-JSON im Payload-Kopf → `MINING_STRATUM`; Pool-Ports + anhaltende CPU → `MINING_SUSPECT`.
+- **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.
diff --git a/docs/FIREWALL.es.md b/docs/FIREWALL.es.md
index a5ec7ae..a417cf3 100644
--- a/docs/FIREWALL.es.md
+++ b/docs/FIREWALL.es.md
@@ -92,3 +92,16 @@ lenguaje claro. Es un *informe de hallazgos*, no una certificación.
- **Re-resolución de dominios** — las reglas `domain` se re-resuelven cada ~10 min y el delta de IP se aplica por SO, para que la rotación CDN no desbloquee un nombre en silencio.
- **Vigilancia de integridad** (activada por defecto, solo lectura, local) — baselines SHA-256 de ejecutables en red (`BINARY_CHANGED`), nombres/exe divergentes (`NAME_MISMATCH`), scan `rwxp` solo Linux (`MEM_RWX`, nivel info para apps JIT conocidas). `GET /security/integrity`, `POST /security/integrity/check`.
- **Explicaciones de alertas** — `GET /security/explain?type=X` devuelve explicaciones bilingües (EN/FR) escritas a mano; deterministas y offline — no es un modelo. La UI las muestra tras el botón "¿Por qué?".
+
+### Sondas opcionales (v1.3)
+
+Todas están **desactivadas por defecto o se autolimitan**, degradan honestamente y nunca envían datos fuera de la máquina:
+
+- **Sonda eBPF connect** (Linux, ajuste `ebpf_probe`) — kprobe BCC tipo `tcpconnect` que atribuye `connect()` de procesos demasiado efímeros para la tabla de sockets. Requiere `python3-bcc` + root; destinos ambiguos nunca se adivinan. `GET /security/ebpf`.
+- **Inspección Frida** — `POST /security/deep_inspect {pid,seconds}` adjunta a UN pid ≤60 s y reporta qué módulo cargado emitió cada `connect()`. Rutas de módulos en temp/staging → `INJECT_SUSPECT`.
+- **Respondedor sinkhole** — con una regla `sinkhole` activa, listeners loopback en :80/:443 convierten cada intento en alerta `SINKHOLE_HIT` con Host/URI o SNI + proceso.
+- **Integridad de módulos** — raíz Merkle sobre los mapeos ejecutables → `MODULE_CHANGED`; rutas en `/tmp`/memfd → `MODULE_SUSPECT`.
+- **Detección de minería** — JSON stratum en cabecera de payload → `MINING_STRATUM`; puertos de pool + CPU sostenida → `MINING_SUSPECT`.
+- **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.
diff --git a/docs/FIREWALL.ja.md b/docs/FIREWALL.ja.md
index 50eb6c3..0254e24 100644
--- a/docs/FIREWALL.ja.md
+++ b/docs/FIREWALL.ja.md
@@ -89,3 +89,16 @@ OS ネイティブファイアウォールへ best-effort で適用されます:
- **ドメイン再解決** — `domain` ルールは約10分ごとに再解決され、IP 差分が OS ごとに適用されるため、CDN ローテーションで名前のブロックが外れません。
- **整合性監視**(デフォルト有効・読み取り専用・ローカル) — ネットワーク使用実行ファイルの SHA-256 ベースライン(`BINARY_CHANGED`)、名前/exe 不一致(`NAME_MISMATCH`)、Linux のみ `rwxp` スキャン(`MEM_RWX`、既知 JIT アプリは info レベル)。`GET /security/integrity`、`POST /security/integrity/check`。
- **アラート説明** — `GET /security/explain?type=X` が手書きの二言語(EN/FR)説明を返します;決定的でオフライン動作 — モデルではありません。UI の「なぜ?」ボタンから表示。
+
+### オプションのプローブ (v1.3)
+
+すべて **デフォルトで無効または自己制限** で、正直に劣化し、マシン外へデータを送りません:
+
+- **eBPF connect プローブ**(Linux、`ebpf_probe`)— `tcpconnect` 型の BCC kprobe が、ソケットテーブルが取り逃がす短命プロセスの `connect()` を帰属。`python3-bcc` + root が必要。曖昧な宛先は推測しません。`GET /security/ebpf`。
+- **Frida インスペクション** — `POST /security/deep_inspect {pid,seconds}` は1つの pid に ≤60 秒アタッチし、各 `connect()` を発行したロード済みモジュールを報告。staging パス → `INJECT_SUSPECT`。
+- **シンクホールレスポンダ** — `sinkhole` ルール有効中、:80/:443 の loopback リスナーが各試行を `SINKHOLE_HIT`(Host/URI または SNI + プロセス)に変換。
+- **モジュール整合性** — 実行可能マッピングの Merkle ルート → `MODULE_CHANGED`;`/tmp`/memfd のパス → `MODULE_SUSPECT`。
+- **マイニング検知** — payload ヘッド内の stratum JSON → `MINING_STRATUM`;プールポート + 持続的高 CPU → `MINING_SUSPECT`。
+- **ハードウェアカウンタ** — `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` が宛先を確率的に照合。
diff --git a/docs/FIREWALL.md b/docs/FIREWALL.md
index 17dce0b..1d56f3e 100644
--- a/docs/FIREWALL.md
+++ b/docs/FIREWALL.md
@@ -14,10 +14,18 @@ applied to the OS-native firewall, best-effort:
| OS | Mechanism |
|---|---|
-| Windows | `netsh advfirewall` outbound block rules |
-| Linux | `iptables -A OUTPUT -j DROP` (dedicated `SNITCH_LOCK` chain for lockdown) |
+| Windows | **WFP user-mode filters** via `fwpuclnt.dll` (ctypes, elevated) — `netsh advfirewall` remains the fallback |
+| Linux | `iptables -A OUTPUT -j DROP` (dedicated `SNITCH_LOCK` chain for lockdown); `tc` clsact/flower for throttling |
| macOS | generated `pf` anchor loaded with `pfctl` |
+On Windows, `detection/wfp.py` talks to the **Windows Filtering Platform**
+directly — no `netsh` subprocess, no kernel driver: outbound ALE filters
+matched on app path, remote IP/CIDR and remote port, created with
+deterministic keys so a removed rule deletes exactly its own filters, and
+an enumeration sweep purges filters Snitch created but forgot. It is
+*filter management* — Snitch does not run a WFP callout, does not inspect
+payloads in-kernel, and reports `applied=False` when not elevated.
+
Rule kinds: `ip`, `cidr`, `domain`, `process`, `port`. Rules persist in
`snitch.db` and are re-applied at startup. `domain` rules are re-resolved
every ~10 minutes — the resolved IP delta is applied so CDN rotation can't
@@ -28,6 +36,9 @@ to loopback instead — domains via a marked `# snitch-sinkhole` block in the
hosts file (all OSes), IPs/CIDRs via iptables `DNAT` in the nat OUTPUT chain
(Linux only). A sinkholed destination keeps "answering" from 127.0.0.1 so an
analyst can watch what the process expects instead of severing the call.
+`throttle` (Linux only, `rate` kbit/s) polices the destination with a `tc`
+clsact egress flower filter instead of blocking — useful for choking a
+suspect process without tipping it off.
**Honest limits:**
@@ -124,6 +135,41 @@ the live graph: alert-type counts, contacts to high-risk countries,
unresolved hosts, firewall posture — and returns plain-language
recommendations. It is a *finding report*, not a certification.
+### Optional probes (v1.3)
+
+All of these are **off by default or self-gating**, degrade honestly, and
+never ship data off the machine:
+
+- **eBPF connect probe** (Linux, `ebpf_probe` setting) — a BCC
+ `tcpconnect`-style kprobe attributes `connect()` calls of processes too
+ short-lived for the socket table. Needs `python3-bcc` + root; ambiguous
+ destinations (two pids → same `ip:port`) are *never* guessed.
+ `GET /security/ebpf` reports availability with the honest reason.
+- **Frida deep inspection** — `POST /security/deep_inspect {pid,seconds}`
+ attaches to ONE pid for ≤60 s (needs the optional `frida` package +
+ debugger rights) and reports *which loaded module* issued each
+ `connect()`. Module paths under temp/staging dirs → `INJECT_SUSPECT`.
+- **Sinkhole responder** — while a `sinkhole` rule is enabled, loopback
+ listeners on :80 (HTTP) and :443 (TLS/SNI) turn every redirected
+ attempt into a `SINKHOLE_HIT` alert carrying Host/URI or SNI plus the
+ initiating process. `GET /security/sinkhole` shows listeners + hits.
+- **Module integrity** — a Merkle root over each process's file-backed
+ executable mappings → `MODULE_CHANGED` on tamper; mapped paths under
+ `/tmp`, memfd or other staging dirs → `MODULE_SUSPECT`.
+- **Mining detection** — stratum JSON (`mining.subscribe`) in a bounded
+ cleartext payload head → `MINING_STRATUM`; known pool ports + sustained
+ CPU → `MINING_SUSPECT`. A pool port alone never alerts.
+- **Hardware counters** — `POST /security/perf {pid,seconds}` samples
+ cycles/instructions/cache-misses via `perf_event_open` (Linux, gated by
+ `kernel.perf_event_paranoid`) to corroborate mining suspicion.
+- **Local LLM enrichment** — opt-in (`slm_enabled`): `/security/explain`
+ can call an Ollama-compatible endpoint, **loopback only** — remote
+ endpoints are rejected so alert metadata can't leave 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.
+
---
## Français
@@ -139,10 +185,18 @@ appliquées au pare-feu natif de l'OS, au mieux :
| OS | Mécanisme |
|---|---|
-| Windows | règles de blocage sortantes `netsh advfirewall` |
-| Linux | `iptables -A OUTPUT -j DROP` (chaîne dédiée `SNITCH_LOCK` pour le lockdown) |
+| Windows | **filtres WFP user-mode** via `fwpuclnt.dll` (ctypes, élevé) — `netsh advfirewall` reste le repli |
+| Linux | `iptables -A OUTPUT -j DROP` (chaîne dédiée `SNITCH_LOCK` pour le lockdown) ; `tc` clsact/flower pour le bridage |
| macOS | ancre `pf` générée chargée avec `pfctl` |
+Sous Windows, `detection/wfp.py` dialogue avec la **Windows Filtering
+Platform** directement — sans subprocess `netsh`, sans driver noyau :
+filtres ALE sortants par chemin d'appli, IP/CIDR et port, créés avec des
+clés déterministes pour qu'une règle supprimée efface exactement ses
+filtres, plus une purge par énumération des filtres orphelins. C'est de la
+*gestion de filtres* — Snitch ne fait pas de callout WFP, n'inspecte pas
+les payloads en noyau et rapporte `applied=False` sans élévation.
+
Types de règles : `ip`, `cidr`, `domain`, `process`, `port`. Les règles
persistent dans `snitch.db` et sont réappliquées au démarrage. Les règles
`domain` sont re-résolues toutes les ~10 min — le delta d'IP est appliqué
@@ -153,7 +207,9 @@ loopback — domaines via un bloc marqué `# snitch-sinkhole` dans le fichier
hosts (tous OS), IP/CIDR via `DNAT` iptables dans la table nat OUTPUT
(Linux seulement). Une destination sinkholée continue de « répondre »
depuis 127.0.0.1 : l'analyste observe ce que le processus attend au lieu
-de couper l'appel.
+de couper l'appel. `throttle` (Linux seul, `rate` kbit/s) bride la
+destination avec un filtre flower egress `tc` clsact au lieu de bloquer —
+utile pour étouffer un processus suspect sans l'alerter.
**Limites honnêtes :**
@@ -253,3 +309,40 @@ de chaque alerte.
alertes et le graphe : comptes par type, contacts vers pays à risque,
hôtes non résolus, posture pare-feu — et renvoie des recommandations en
langage clair. C'est un *rapport de constats*, pas une certification.
+
+### Sondes optionnelles (v1.3)
+
+Toutes sont **désactivées par défaut ou auto-limitées**, dégradent
+honnêtement et n'envoient jamais de données hors de la machine :
+
+- **Sonde eBPF connect** (Linux, réglage `ebpf_probe`) — un kprobe BCC de
+ type `tcpconnect` attribue les `connect()` des processus trop courts
+ pour la table des sockets. Exige `python3-bcc` + root ; les
+ destinations ambiguës (deux pids → même `ip:port`) ne sont *jamais*
+ devinées. `GET /security/ebpf` rapporte la disponibilité honnêtement.
+- **Inspection Frida** — `POST /security/deep_inspect {pid,seconds}`
+ attache à UN pid ≤60 s (exige le paquet optionnel `frida` + droits de
+ débogage) et rapporte *quel module chargé* a émis chaque `connect()`.
+ Chemins de modules sous temp/staging → `INJECT_SUSPECT`.
+- **Répondeur sinkhole** — tant qu'une règle `sinkhole` est active, des
+ écouteurs loopback sur :80 (HTTP) et :443 (TLS/SNI) transforment chaque
+ tentative redirigée en alerte `SINKHOLE_HIT` avec Host/URI ou SNI +
+ processus. `GET /security/sinkhole` montre écouteurs + hits.
+- **Intégrité des modules** — racine Merkle sur les mappings exécutables
+ fichier-basés d'un processus → `MODULE_CHANGED` en cas d'altération ;
+ chemins sous `/tmp`, memfd ou staging → `MODULE_SUSPECT`.
+- **Détection de minage** — JSON stratum (`mining.subscribe`) dans une
+ tête de payload bornée → `MINING_STRATUM` ; ports de pools + CPU
+ soutenue → `MINING_SUSPECT`. Un port de pool seul n'alerte jamais.
+- **Compteurs matériels** — `POST /security/perf {pid,seconds}`
+ échantillonne cycles/instructions/cache-misses via `perf_event_open`
+ (Linux, sous réserve de `kernel.perf_event_paranoid`) pour corroborer
+ la suspicion de minage.
+- **Enrichissement LLM local** — opt-in (`slm_enabled`) :
+ `/security/explain` peut appeler un endpoint compatible Ollama,
+ **loopback uniquement** — les endpoints distants sont rejetés pour que
+ les métadonnées d'alerte ne quittent jamais la machine.
+- **Paquets IOC** — `GET /security/iocpack` exporte les indicateurs en
+ 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.
diff --git a/docs/FIREWALL.pt-BR.md b/docs/FIREWALL.pt-BR.md
index 90b336e..7e4a386 100644
--- a/docs/FIREWALL.pt-BR.md
+++ b/docs/FIREWALL.pt-BR.md
@@ -93,3 +93,16 @@ certificação.
- **Re-resolução de domínios** — regras `domain` são re-resolvidas a cada ~10 min e o delta de IP é aplicado por SO, para que a rotação de CDN não desbloqueie um nome silenciosamente.
- **Vigilância de integridade** (ativada por padrão, somente leitura, local) — baselines SHA-256 de executáveis em rede (`BINARY_CHANGED`), divergência nome/exe (`NAME_MISMATCH`), scan `rwxp` somente Linux (`MEM_RWX`, nível info para apps JIT conhecidas). `GET /security/integrity`, `POST /security/integrity/check`.
- **Explicações de alertas** — `GET /security/explain?type=X` retorna explicações bilíngues (EN/FR) escritas à mão; determinísticas e offline — não é um modelo. A UI mostra atrás do botão "Por quê?".
+
+### Sondas opcionais (v1.3)
+
+Todas estão **desativadas por padrão ou autolimitadas**, degradam honestamente e nunca enviam dados para fora da máquina:
+
+- **Sonda eBPF connect** (Linux, `ebpf_probe`) — kprobe BCC tipo `tcpconnect` atribui `connect()` de processos efêmeros demais para a tabela de sockets. Requer `python3-bcc` + root; destinos ambíguos nunca são adivinhados. `GET /security/ebpf`.
+- **Inspeção Frida** — `POST /security/deep_inspect {pid,seconds}` anexa a UM pid por ≤60 s e reporta qual módulo carregado emitiu cada `connect()`. Caminhos de staging → `INJECT_SUSPECT`.
+- **Respondedor sinkhole** — com uma regra `sinkhole` ativa, listeners loopback em :80/:443 transformam cada tentativa em alerta `SINKHOLE_HIT` com Host/URI ou SNI + processo.
+- **Integridade de módulos** — raiz Merkle sobre mapeamentos executáveis → `MODULE_CHANGED`; caminhos em `/tmp`/memfd → `MODULE_SUSPECT`.
+- **Detecção de mineração** — JSON stratum no cabeçalho do payload → `MINING_STRATUM`; portas de pools + CPU sustentada → `MINING_SUSPECT`.
+- **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.
diff --git a/docs/FIREWALL.ru.md b/docs/FIREWALL.ru.md
index 9459320..6bc9768 100644
--- a/docs/FIREWALL.ru.md
+++ b/docs/FIREWALL.ru.md
@@ -90,3 +90,16 @@ endpoint'ы получают `{alert, source, text}`. Сбои пишутся в
- **Перерезолв доменов** — правила `domain` перерезолвятся каждые ~10 мин, дельта IP применяется по ОС — ротация CDN не снимет блок silently.
- **Контроль целостности** (включён по умолчанию, read-only, локально) — SHA-256 baselines исполняемых файлов (`BINARY_CHANGED`), несовпадение имени/exe (`NAME_MISMATCH`), скан `rwxp` только Linux (`MEM_RWX`, уровень info для известных JIT-приложений). `GET /security/integrity`, `POST /security/integrity/check`.
- **Объяснения алертов** — `GET /security/explain?type=X` возвращает двуязычные (EN/FR) объяснения, написанные вручную; детерминированно и офлайн — не модель. UI показывает их за кнопкой «Почему?».
+
+### Опциональные зонды (v1.3)
+
+Все **выключены по умолчанию или самоограничены**, деградируют честно и никогда не отправляют данные с машины:
+
+- **Зонд eBPF connect** (Linux, `ebpf_probe`) — kprobe BCC типа `tcpconnect` атрибутирует `connect()` короткоживущих процессов. Нужны `python3-bcc` + root; неоднозначные цели не угадываются. `GET /security/ebpf`.
+- **Инспекция Frida** — `POST /security/deep_inspect {pid,seconds}` присоединяется к ОДНОМУ pid ≤60 с и сообщает, какой модуль инициировал каждый `connect()`. Staging-пути → `INJECT_SUSPECT`.
+- **Респондер sinkhole** — при активной `sinkhole`-правиле loopback-листенеры на :80/:443 превращают каждую попытку в алерт `SINKHOLE_HIT` с Host/URI или SNI + процессом.
+- **Целостность модулей** — корень Меркла над исполняемыми маппингами → `MODULE_CHANGED`; пути в `/tmp`/memfd → `MODULE_SUSPECT`.
+- **Детект майнинга** — stratum JSON в голове payload → `MINING_STRATUM`; порты пулов + устойчивая CPU → `MINING_SUSPECT`.
+- **Аппаратные счётчики** — `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` проверяет цели вероятностно.
diff --git a/docs/FIREWALL.zh-CN.md b/docs/FIREWALL.zh-CN.md
index b4575a1..2ccfcb9 100644
--- a/docs/FIREWALL.zh-CN.md
+++ b/docs/FIREWALL.zh-CN.md
@@ -82,3 +82,16 @@ Snitch **不**在用户态过滤数据包。规则会被尽力下发到操作系
- **域名重解析** — `domain` 规则每约 10 分钟重新解析,按 OS 应用 IP 差值,CDN 轮换不会静默放行域名。
- **完整性监视**(默认开启,只读,本地) — 联网可执行文件的 SHA-256 基线(`BINARY_CHANGED`)、名称/exe 不匹配(`NAME_MISMATCH`)、仅 Linux `rwxp` 扫描(`MEM_RWX`,已知 JIT 应用为 info 级)。`GET /security/integrity`、`POST /security/integrity/check`。
- **告警解释** — `GET /security/explain?type=X` 返回手写的双语(EN/FR)解释;确定性、完全离线 — 非模型。UI 中每条告警的「为什么?」按钮显示。
+
+### 可选探针 (v1.3)
+
+所有探针**默认关闭或自我限制**,降级时如实报告,绝不向机器外发送数据:
+
+- **eBPF connect 探针**(Linux,`ebpf_probe`)— `tcpconnect` 型 BCC kprobe 归属套接字表漏掉的短命进程的 `connect()`。需要 `python3-bcc` + root;模糊目标绝不猜测。`GET /security/ebpf`。
+- **Frida 深度检查** — `POST /security/deep_inspect {pid,seconds}` 附加到单个 pid ≤60 秒,报告每个 `connect()` 由哪个已加载模块发起。staging 路径 → `INJECT_SUSPECT`。
+- **沉洞响应器** — `sinkhole` 规则启用期间,:80/:443 上的 loopback 监听器把每次尝试转为 `SINKHOLE_HIT` 告警(Host/URI 或 SNI + 进程)。
+- **模块完整性** — 可执行映射的 Merkle 根 → `MODULE_CHANGED`;`/tmp`/memfd 路径 → `MODULE_SUSPECT`。
+- **挖矿检测** — payload 头部中的 stratum JSON → `MINING_STRATUM`;矿池端口 + 持续高 CPU → `MINING_SUSPECT`。
+- **硬件计数器** — `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` 概率性地检查目标。
diff --git a/electron/package.json b/electron/package.json
index 63333da..3ce2c92 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch",
- "version": "1.2.0",
+ "version": "1.3.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 d3a351f..4f54e86 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch-frontend",
- "version": "1.2.0",
+ "version": "1.3.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 5ebb7fa..6c83a8c 100644
--- a/frontend/src/components/AlertPanel.jsx
+++ b/frontend/src/components/AlertPanel.jsx
@@ -20,6 +20,7 @@ import {
Globe, WifiOff, Wifi, ScanLine,
Activity, Unlock, TrendingUp, Camera, ShieldAlert,
FileWarning, Fingerprint, Cpu, HelpCircle,
+ Pickaxe, Magnet, Syringe, Package,
} from 'lucide-react'
import { useT } from '../i18n'
import { apiBase, authHeaders } from '../api'
@@ -53,6 +54,12 @@ const TYPE_ICONS = {
BINARY_CHANGED: FileWarning,
NAME_MISMATCH: Fingerprint,
MEM_RWX: Cpu,
+ MODULE_SUSPECT: Package,
+ MODULE_CHANGED: FileWarning,
+ MINING_STRATUM: Pickaxe,
+ MINING_SUSPECT: Pickaxe,
+ SINKHOLE_HIT: Magnet,
+ INJECT_SUSPECT: Syringe,
}
/**
diff --git a/frontend/src/components/Firewall.jsx b/frontend/src/components/Firewall.jsx
index 6150bfc..bb584e6 100644
--- a/frontend/src/components/Firewall.jsx
+++ b/frontend/src/components/Firewall.jsx
@@ -47,6 +47,9 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
const [kind, setKind] = useState('ip')
const [value, setValue] = useState('')
const [action, setAction] = useState('block')
+ const [rate, setRate] = useState(64)
+ const [iocText, setIocText] = useState('')
+ const [iocResult, setIocResult] = useState(null)
const [err, setErr] = useState('')
const [audit, setAudit] = useState(null)
@@ -94,12 +97,41 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
if (!v) return
setErr('')
try {
- await post('/firewall/rules', { kind, value: v, action })
+ await post('/firewall/rules', { kind, value: v, action, rate })
setValue('')
refresh()
} catch (ex) { setErr(String(ex.message || ex)) }
}
+ /**
+ * EN: Download this machine's privacy-preserving IOC pack (Bloom +
+ * randomized response) — the user decides where it goes.
+ * FR: Télécharger le paquet IOC préservant la vie privée de cette
+ * machine (Bloom + randomized response) — l'utilisateur décide où
+ * il va.
+ */
+ async function exportIoc() {
+ const base = await apiBase()
+ const res = await fetch(`${base}/security/iocpack`,
+ { headers: await authHeaders() })
+ 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-ioc-pack.json'
+ a.click()
+ URL.revokeObjectURL(a.href)
+ }
+
+ async function importIoc() {
+ setIocResult(null)
+ try {
+ const pack = JSON.parse(iocText)
+ const r = await post('/security/iocpack/import', { pack })
+ setIocResult(r)
+ } catch (ex) { setIocResult({ ok: false, error: String(ex.message || ex) }) }
+ }
+
async function toggleRule(id, enabled) {
await post(`/firewall/rules/${encodeURIComponent(id)}/toggle`, { enabled })
refresh()
@@ -212,8 +244,15 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
<select value={action} onChange={e => setAction(e.target.value)} aria-label={t('fw_action')} style={{ ...input, maxWidth: 90 }}>
<option value="block">{t('fw_action_block')}</option>
<option value="sinkhole">{t('fw_action_sinkhole')}</option>
+ <option value="throttle">{t('fw_action_throttle')}</option>
</select>
)}
+ {action === 'throttle' && (kind === 'ip' || kind === 'domain') && (
+ <input type="number" min="8" max="1000000" value={rate}
+ onChange={e => setRate(Number(e.target.value) || 64)}
+ title={t('fw_rate_hint')} aria-label={t('fw_rate')}
+ style={{ ...input, width: 56 }} />
+ )}
<input value={value} onChange={e => setValue(e.target.value)}
placeholder={t(`fw_ph_${kind}`)} aria-label={t('fw_value')}
style={{ ...input, flex: 1 }} />
@@ -237,12 +276,13 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
color: r.enabled ? 'var(--blue-text)' : 'var(--text-faint)',
background: 'var(--bg)', borderRadius: 4, padding: '1px 5px',
}}>{r.kind}</span>
- {r.action === 'sinkhole' && (
+ {r.action && r.action !== 'block' && (
<span style={{
fontSize: 9, fontWeight: 700, textTransform: 'uppercase',
- color: '#a855f7', background: 'var(--bg)', borderRadius: 4,
+ color: r.action === 'sinkhole' ? '#a855f7' : '#f59e0b',
+ background: 'var(--bg)', borderRadius: 4,
padding: '1px 5px',
- }}>{t('fw_action_sinkhole')}</span>
+ }}>{t(`fw_action_${r.action}`)}{r.action === 'throttle' && r.rate ? ` ${r.rate}k` : ''}</span>
)}
<span style={{ fontSize: 11, color: r.enabled ? 'var(--text)' : 'var(--text-faint)', fontFamily: 'monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{r.value}
@@ -320,6 +360,43 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
}}>{f}</button>
))}
</div>
+ {/* EN: Privacy-preserving IOC pack — export shares indicators as
+ a noised Bloom filter (never raw); import checks observed
+ destinations against a community pack, probabilistically.
+ FR: Paquet IOC préservant la vie privée — l'export partage les
+ indicateurs en filtre de Bloom bruité (jamais en clair) ;
+ l'import confronte les destinations observées à un paquet
+ communautaire, de façon probabiliste. */}
+ <div style={{ borderTop: '1px solid var(--border)', marginTop: 10, paddingTop: 8 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
+ <span style={label}>{t('ioc_title')}</span>
+ <button onClick={exportIoc} style={{
+ background: 'var(--bg)', border: '1px solid var(--border)',
+ borderRadius: 5, color: 'var(--text-muted)', fontSize: 9,
+ fontWeight: 700, padding: '3px 8px', cursor: 'pointer',
+ }}>{t('ioc_export')}</button>
+ </div>
+ <div style={hint}>{t('ioc_hint')}</div>
+ <textarea value={iocText} onChange={e => setIocText(e.target.value)}
+ placeholder={t('ioc_import_ph')} rows={2}
+ style={{ ...input, width: '100%', boxSizing: 'border-box', marginTop: 4, resize: 'vertical', fontFamily: 'monospace' }} />
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
+ <button onClick={importIoc} disabled={!iocText.trim()} style={{
+ background: iocText.trim() ? '#3b82f6' : 'var(--bg)', border: 'none',
+ borderRadius: 5, color: iocText.trim() ? '#fff' : 'var(--text-faint)',
+ fontSize: 9, fontWeight: 700, padding: '3px 8px', cursor: 'pointer',
+ }}>{t('ioc_check')}</button>
+ {iocResult && (
+ <span style={{ fontSize: 10, color: iocResult.ok ? (iocResult.hints?.length ? '#f59e0b' : '#4ade80') : '#ef4444' }}>
+ {iocResult.ok
+ ? (iocResult.hints?.length
+ ? t('ioc_hints', iocResult.hints.length)
+ : t('ioc_clean'))
+ : t('ioc_bad')}
+ </span>
+ )}
+ </div>
+ </div>
</div>
</div>
</div>
diff --git a/frontend/src/components/Settings.jsx b/frontend/src/components/Settings.jsx
index dde4cd6..ab1ddc4 100644
--- a/frontend/src/components/Settings.jsx
+++ b/frontend/src/components/Settings.jsx
@@ -431,6 +431,93 @@ export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchl
<div style={{ ...hint, marginTop: 4 }}>{t('iw_privacy')}</div>
</div>
+ {/* eBPF probe / Sonde eBPF */}
+ <div style={{ ...row, display: 'block' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={label}>{t('ebpf_title')}</div>
+ <div style={hint}>{t('ebpf_hint')}</div>
+ </div>
+ <button
+ onClick={() => {
+ const v = settings?.ebpf_probe === false
+ setSettings(s => ({ ...s, ebpf_probe: v }))
+ save('ebpf_probe', v)
+ }}
+ role="switch" aria-checked={settings?.ebpf_probe !== false}
+ style={{
+ width: 36, height: 20, borderRadius: 10, border: 'none',
+ background: settings?.ebpf_probe !== false ? '#3b82f6' : 'var(--bg)',
+ outline: '1px solid var(--border)', cursor: 'pointer',
+ position: 'relative', flexShrink: 0,
+ }}>
+ <div style={{
+ width: 14, height: 14, borderRadius: '50%', background: 'var(--text)',
+ position: 'absolute', top: 3, left: settings?.ebpf_probe !== false ? 19 : 3,
+ transition: 'left 0.15s',
+ }} />
+ </button>
+ </div>
+ <div style={{ ...hint, marginTop: 4 }}>{t('ebpf_privacy')}</div>
+ </div>
+
+ {/* Local SLM (Ollama) / SLM local (Ollama) */}
+ <div style={{ ...row, display: 'block' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div>
+ <div style={label}>{t('slm_title')}</div>
+ <div style={hint}>{t('slm_hint')}</div>
+ </div>
+ <button
+ onClick={() => {
+ const v = !settings?.slm_enabled
+ setSettings(s => ({ ...s, slm_enabled: v }))
+ save('slm_enabled', v)
+ }}
+ role="switch" aria-checked={!!settings?.slm_enabled}
+ style={{
+ width: 36, height: 20, borderRadius: 10, border: 'none',
+ background: settings?.slm_enabled ? '#3b82f6' : 'var(--bg)',
+ outline: '1px solid var(--border)', cursor: 'pointer',
+ position: 'relative', flexShrink: 0,
+ }}>
+ <div style={{
+ width: 14, height: 14, borderRadius: '50%', background: 'var(--text)',
+ position: 'absolute', top: 3, left: settings?.slm_enabled ? 19 : 3,
+ transition: 'left 0.15s',
+ }} />
+ </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>
+ )}
+ <div style={{ ...hint, marginTop: 4 }}>{t('slm_privacy')}</div>
+ </div>
+
{/* Updates (Electron only) / Mises à jour (Electron seul) */}
{window.snitch?.getUpdateStatus && (
<div style={{ ...row, display: 'block' }}>
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 04d017d..386e232 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -9,7 +9,7 @@
* listes déroulantes appareils LAN + hôtes externes, et le flux de
* paquets récents.
*/
-import { Wifi, Smartphone, Monitor, Tv, Cpu, HelpCircle, ShieldOff, Shield, Skull, PauseCircle } from 'lucide-react'
+import { Wifi, Smartphone, Monitor, Tv, Cpu, HelpCircle, ShieldOff, Shield, Skull, PauseCircle, Microscope } from 'lucide-react'
import PrivacyScore from './PrivacyScore'
import BandwidthChart from './BandwidthChart'
import { useT } from '../i18n'
@@ -321,6 +321,33 @@ async function procAction(action, pid) {
} catch { /* best effort */ }
}
+/**
+ * EN: Bounded Frida deep-inspection — attaches to the pid for a few
+ * seconds and reports which module initiated each connect(). Shows
+ * the result in a simple dialog; errors are surfaced, not hidden.
+ * FR: Inspection Frida bornée — attache au pid quelques secondes et
+ * rapporte quel module a initié chaque connect(). Résultat affiché
+ * dans une boîte simple ; les erreurs sont montrées, pas cachées.
+ */
+async function deepInspect(pid, t) {
+ if (!pid) return
+ const base = await apiBase()
+ try {
+ const res = await fetch(`${base}/security/deep_inspect`, {
+ method: 'POST',
+ headers: await authHeaders({ 'Content-Type': 'application/json' }),
+ body: JSON.stringify({ pid, seconds: 8 }),
+ })
+ const j = await res.json()
+ if (!res.ok || j.ok === false) {
+ window.alert(j.detail || j.error || t('di_failed'))
+ return
+ }
+ const mods = (j.suspicious_paths || []).join('\n')
+ window.alert(mods ? `${t('di_result')}\n${mods}` : t('di_clean'))
+ } catch { window.alert(t('di_failed')) }
+}
+
/** EN: Selected-node fields + top processes + whitelist/block actions.
* FR: Champs du nœud sélectionné + top processus + actions whitelist/blocage. */
function NodeDetail({ node, onWhitelist }) {
@@ -397,6 +424,11 @@ function NodeDetail({ node, onWhitelist }) {
FR: Tuer/suspendre — seulement si un PID est connu. */}
{stats.pid && (
<>
+ <button onClick={() => deepInspect(stats.pid, t)}
+ title={t('di_inspect')} aria-label={t('di_inspect')}
+ style={{ background: 'none', border: 'none', color: '#a855f7', cursor: 'pointer', padding: 0, display: 'flex' }}>
+ <Microscope size={11} />
+ </button>
<button onClick={() => procAction('suspend', stats.pid)}
title={t('proc_suspend')} aria-label={t('proc_suspend')}
style={{ background: 'none', border: 'none', color: '#f59e0b', cursor: 'pointer', padding: 0, display: 'flex' }}>
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index fbc1ed2..6d0c50c 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -345,4 +345,33 @@ export default {
iw_title: 'Integritätswache',
iw_hint: 'Hasht Executables vernetzter Prozesse, meldet Name/Exe-Mismatches und (Linux) RWX-Speicherbereiche.',
iw_privacy: 'Alle Prüfungen sind lokale, schreibgeschützte Inspektion — nichts wird geändert oder gesendet.',
+ alertmsg_MODULE_SUSPECT: d => `Verdächtiger Modulpfad in ${d.process || 'Prozess'}: ${(d.modules || []).join(', ')}`,
+ alertmsg_MODULE_CHANGED: d => `Integrität geladener Module geändert in ${d.process || 'Prozess'}`,
+ alertmsg_MINING_STRATUM: d => `Krypto-Mining-Protokoll (${d.marker || 'stratum'}) von ${d.process || `pid ${d.pid}`}`,
+ alertmsg_MINING_SUSPECT: d => `Mining-Verhalten: ${d.process || `pid ${d.pid}`} — ${d.detail || 'Pool-Port + anhaltende CPU'}`,
+ alertmsg_SINKHOLE_HIT: d => `Versuchte Verbindung zu versenktem Ziel: ${d.host || d.ip || '?'}`,
+ alertmsg_INJECT_SUSPECT: d => `Verdacht auf injiziertes Modul in pid ${d.pid}: ${(d.paths || []).join(', ')}`,
+ fw_action_throttle: 'Drosseln',
+ fw_rate: 'Rate (kbit/s)',
+ fw_rate_hint: 'Ausgangs-Ratenlimit in kbit/s (Linux tc)',
+ ioc_title: 'Community-IOC-Paket',
+ ioc_export: 'Paket exportieren',
+ ioc_hint: 'Teilt Indikatoren als verrauschten Bloom-Filter — Klartextwerte verlassen die Datei nie. Importprüfungen sind probabilistisch.',
+ ioc_import_ph: 'Empfangenes IOC-Paket einfügen (JSON)…',
+ ioc_check: 'Prüfen',
+ ioc_hints: n => `${n} Ziel(e) entsprechen dem Paket (probabilistisch)`,
+ ioc_clean: 'Keine Übereinstimmung',
+ ioc_bad: 'Ungültiges Paket',
+ di_inspect: 'Tiefeninspektion (Frida)',
+ di_result: 'Verdächtige Modulpfade:',
+ di_clean: 'Kein verdächtiger Modulpfad — sauber oder kein connect() erfasst.',
+ di_failed: 'Tiefeninspektion fehlgeschlagen (frida nicht installiert oder fehlende Rechte)',
+ ebpf_title: 'eBPF-Connect-Sonde',
+ ebpf_hint: 'Nur Linux — ordnet Pakete sehr kurzlebiger Prozesse zu, die die Socket-Tabelle verpasst. Erfordert python3-bcc + root.',
+ ebpf_privacy: 'Kernel-Ereignisse bleiben lokal — nur Zuordnung, nichts wird protokolliert oder gesendet.',
+ slm_title: 'Lokale LLM-Anreicherung',
+ slm_hint: 'Optional: reichert Alarm-Erklärungen mit einem Ollama-kompatiblen Modell an. Nur Loopback — entfernte Endpunkte werden abgelehnt.',
+ 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.',
}
diff --git a/frontend/src/locales/en.js b/frontend/src/locales/en.js
index 45c052e..e6b4ba4 100644
--- a/frontend/src/locales/en.js
+++ b/frontend/src/locales/en.js
@@ -349,4 +349,33 @@ export default { // Navigation
iw_title: 'Integrity watch',
iw_hint: 'Hash executables of networked processes, flag name/exe mismatches and (Linux) RWX memory regions.',
iw_privacy: 'All checks are read-only local inspection — nothing is modified or sent.',
+ alertmsg_MODULE_SUSPECT: d => `Suspicious module path in ${d.process || 'process'}: ${(d.modules || []).join(', ')}`,
+ alertmsg_MODULE_CHANGED: d => `Loaded-module integrity changed in ${d.process || 'process'}`,
+ alertmsg_MINING_STRATUM: d => `Cryptomining protocol (${d.marker || 'stratum'}) from ${d.process || `pid ${d.pid}`}`,
+ alertmsg_MINING_SUSPECT: d => `Mining behaviour: ${d.process || `pid ${d.pid}`} — ${d.detail || 'pool port + sustained CPU'}`,
+ alertmsg_SINKHOLE_HIT: d => `Sinkholed connection attempted: ${d.host || d.ip || '?'}`,
+ alertmsg_INJECT_SUSPECT: d => `Injected-module suspicion in pid ${d.pid}: ${(d.paths || []).join(', ')}`,
+ fw_action_throttle: 'Throttle',
+ fw_rate: 'Rate (kbit/s)',
+ fw_rate_hint: 'Egress rate limit in kbit/s (Linux tc)',
+ ioc_title: 'Community IOC pack',
+ ioc_export: 'Export pack',
+ ioc_hint: 'Shares indicators as a noised Bloom filter — raw values never leave the file. Import checks are probabilistic.',
+ ioc_import_ph: 'Paste a received IOC pack (JSON)…',
+ ioc_check: 'Check',
+ ioc_hints: n => `${n} destination(s) match the pack (probabilistic)`,
+ ioc_clean: 'No match',
+ ioc_bad: 'Invalid pack',
+ di_inspect: 'Deep inspect (Frida)',
+ di_result: 'Suspicious module paths:',
+ di_clean: 'No suspicious module path — clean, or no connect() captured.',
+ di_failed: 'Deep inspection failed (frida not installed or insufficient rights)',
+ ebpf_title: 'eBPF connect probe',
+ ebpf_hint: 'Linux only — attributes packets from very short-lived processes that the socket table misses. Needs python3-bcc + root.',
+ ebpf_privacy: 'Kernel events stay local — attribution only, nothing is logged or sent.',
+ slm_title: 'Local LLM enrichment',
+ slm_hint: 'Optional: enriches alert explanations with an Ollama-compatible model. Loopback only — remote endpoints are rejected.',
+ slm_endpoint: 'Endpoint',
+ slm_model: 'Model',
+ slm_privacy: 'Runs only when enabled; alert metadata goes to your local model, never off-machine.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 9a302a3..c67614d 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -343,4 +343,33 @@ export default { // Navegación
iw_title: 'Vigilancia de integridad',
iw_hint: 'Hashea los ejecutables de procesos con red, señala nombres/exe que no coinciden y (Linux) regiones de memoria RWX.',
iw_privacy: 'Comprobaciones de solo lectura, 100 % locales — nada se modifica ni se envía.',
+ alertmsg_MODULE_SUSPECT: d => `Ruta de módulo sospechosa en ${d.process || 'proceso'}: ${(d.modules || []).join(', ')}`,
+ alertmsg_MODULE_CHANGED: d => `Integridad de módulos cargados alterada en ${d.process || 'proceso'}`,
+ alertmsg_MINING_STRATUM: d => `Protocolo de criptominería (${d.marker || 'stratum'}) desde ${d.process || `pid ${d.pid}`}`,
+ alertmsg_MINING_SUSPECT: d => `Comportamiento de minería: ${d.process || `pid ${d.pid}`} — ${d.detail || 'puerto de pool + CPU sostenida'}`,
+ alertmsg_SINKHOLE_HIT: d => `Conexión intentada hacia un destino hundido: ${d.host || d.ip || '?'}`,
+ alertmsg_INJECT_SUSPECT: d => `Sospecha de módulo inyectado en pid ${d.pid}: ${(d.paths || []).join(', ')}`,
+ fw_action_throttle: 'Limitar',
+ fw_rate: 'Tasa (kbit/s)',
+ fw_rate_hint: 'Límite de tasa de salida en kbit/s (tc Linux)',
+ ioc_title: 'Paquete IOC comunitario',
+ ioc_export: 'Exportar paquete',
+ ioc_hint: 'Comparte indicadores como un filtro Bloom con ruido — los valores en claro nunca salen del archivo. Las comprobaciones de importación son probabilísticas.',
+ ioc_import_ph: 'Pega un paquete IOC recibido (JSON)…',
+ ioc_check: 'Comprobar',
+ ioc_hints: n => `${n} destino(s) coinciden con el paquete (probabilístico)`,
+ ioc_clean: 'Sin coincidencias',
+ ioc_bad: 'Paquete inválido',
+ di_inspect: 'Inspección profunda (Frida)',
+ di_result: 'Rutas de módulos sospechosas:',
+ di_clean: 'Sin rutas de módulo sospechosas — limpio o ningún connect() capturado.',
+ di_failed: 'Inspección profunda fallida (frida no instalado o permisos insuficientes)',
+ ebpf_title: 'Sonda eBPF connect',
+ ebpf_hint: 'Solo Linux — atribuye paquetes de procesos muy efímeros que la tabla de sockets no captura. Requiere python3-bcc + root.',
+ ebpf_privacy: 'Los eventos del kernel se quedan locales — solo atribución, nada se registra ni se envía.',
+ slm_title: 'Enriquecimiento LLM local',
+ slm_hint: 'Opcional: enriquece las explicaciones de alertas con un modelo compatible con Ollama. Solo loopback — endpoints remotos rechazados.',
+ 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.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index a9a6638..cda2fd8 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -345,4 +345,33 @@ export default { // Navigation
iw_title: "Veille d'intégrité",
iw_hint: 'Hash les exécutables des processus en réseau, signale les mismatches nom/exe et (Linux) les régions mémoire RWX.',
iw_privacy: "Contrôles en lecture seule, 100 % locaux — rien n'est modifié ni envoyé.",
+ alertmsg_MODULE_SUSPECT: d => `Chemin de module suspect dans ${d.process || 'processus'} : ${(d.modules || []).join(', ')}`,
+ alertmsg_MODULE_CHANGED: d => `Intégrité des modules chargés modifiée dans ${d.process || 'processus'}`,
+ alertmsg_MINING_STRATUM: d => `Protocole de minage (${d.marker || 'stratum'}) depuis ${d.process || `pid ${d.pid}`}`,
+ alertmsg_MINING_SUSPECT: d => `Comportement de minage : ${d.process || `pid ${d.pid}`} — ${d.detail || 'port de pool + CPU soutenue'}`,
+ alertmsg_SINKHOLE_HIT: d => `Tentative de connexion sinkholée : ${d.host || d.ip || '?'}`,
+ alertmsg_INJECT_SUSPECT: d => `Suspicion de module injecté dans le pid ${d.pid} : ${(d.paths || []).join(', ')}`,
+ fw_action_throttle: 'Brider',
+ fw_rate: 'Débit (kbit/s)',
+ fw_rate_hint: 'Limite de débit sortant en kbit/s (tc Linux)',
+ ioc_title: 'Paquet IOC communautaire',
+ ioc_export: 'Exporter',
+ ioc_hint: "Partage les indicateurs en filtre de Bloom bruité — les valeurs en clair ne quittent jamais le fichier. Vérifications d'import probabilistes.",
+ ioc_import_ph: 'Coller un paquet IOC reçu (JSON)…',
+ ioc_check: 'Vérifier',
+ ioc_hints: n => `${n} destination(s) correspondent au paquet (probabiliste)`,
+ ioc_clean: 'Aucune correspondance',
+ ioc_bad: 'Paquet invalide',
+ di_inspect: 'Inspection profonde (Frida)',
+ di_result: 'Chemins de modules suspects :',
+ di_clean: 'Aucun chemin de module suspect — propre, ou aucun connect() capturé.',
+ di_failed: 'Inspection profonde impossible (frida non installé ou droits insuffisants)',
+ ebpf_title: 'Sonde eBPF connect',
+ ebpf_hint: 'Linux seulement — attribue les paquets des processus très courts que la table des sockets rate. Exige python3-bcc + root.',
+ ebpf_privacy: "Les événements noyau restent locaux — attribution seule, rien n'est journalisé ni envoyé.",
+ slm_title: 'Enrichissement LLM local',
+ slm_hint: "Optionnel : enrichit les explications d'alertes avec un modèle compatible Ollama. Loopback seul — les endpoints distants sont rejetés.",
+ 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.",
}
diff --git a/frontend/src/locales/ja.js b/frontend/src/locales/ja.js
index d61af43..fb5fd48 100644
--- a/frontend/src/locales/ja.js
+++ b/frontend/src/locales/ja.js
@@ -345,4 +345,33 @@ export default {
iw_title: '整合性監視',
iw_hint: 'ネットワーク使用プロセスの実行ファイルをハッシュし、名前/exe の不一致と(Linux のみ)RWX メモリ領域を検知します。',
iw_privacy: 'すべてのチェックは読み取り専用のローカル検査です — 変更も送信もされません。',
+ alertmsg_MODULE_SUSPECT: d => `${d.process || 'プロセス'} 内の不審なモジュールパス: ${(d.modules || []).join(', ')}`,
+ alertmsg_MODULE_CHANGED: d => `${d.process || 'プロセス'} のロード済みモジュール整合性が変化`,
+ alertmsg_MINING_STRATUM: d => `${d.process || `pid ${d.pid}`} からの暗号マイニングプロトコル(${d.marker || 'stratum'})`,
+ alertmsg_MINING_SUSPECT: d => `マイニング挙動: ${d.process || `pid ${d.pid}`} — ${d.detail || 'プールポート + 持続的高CPU'}`,
+ alertmsg_SINKHOLE_HIT: d => `シンクホール宛先への接続試行: ${d.host || d.ip || '?'}`,
+ alertmsg_INJECT_SUSPECT: d => `pid ${d.pid} にインジェクト疑いのモジュール: ${(d.paths || []).join(', ')}`,
+ fw_action_throttle: 'スロットル',
+ fw_rate: 'レート (kbit/s)',
+ fw_rate_hint: '送信レート上限(kbit/s、Linux tc)',
+ ioc_title: 'コミュニティ IOC パック',
+ ioc_export: 'パックをエクスポート',
+ ioc_hint: '指標をノイズ付き Bloom フィルターとして共有 — 平文の値はファイルから出ません。インポート照合は確率的です。',
+ ioc_import_ph: '受信した IOC パックを貼り付け (JSON)…',
+ ioc_check: '照合',
+ ioc_hints: n => `${n} 件の宛先がパックに一致(確率的)`,
+ ioc_clean: '一致なし',
+ ioc_bad: '無効なパック',
+ di_inspect: 'ディープインスペクション (Frida)',
+ di_result: '不審なモジュールパス:',
+ di_clean: '不審なモジュールパスなし — クリーン、または connect() 未捕捉。',
+ di_failed: 'ディープインスペクション失敗(frida 未インストール、または権限不足)',
+ ebpf_title: 'eBPF connect プローブ',
+ ebpf_hint: 'Linux のみ — ソケットテーブルが取り逃がす短命プロセスのパケットを帰属します。python3-bcc + root が必要。',
+ ebpf_privacy: 'カーネルイベントはローカルに留まります — 帰属のみ、記録も送信もされません。',
+ slm_title: 'ローカル LLM エンリッチ',
+ slm_hint: '任意: Ollama 互換モデルでアラート説明を強化します。loopback のみ — リモートエンドポイントは拒否。',
+ slm_endpoint: 'エンドポイント',
+ slm_model: 'モデル',
+ slm_privacy: '有効時のみ動作;アラートのメタデータはローカルモデルのみに送られ、マシン外には出ません。',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 8f28811..b7f5ea5 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -345,4 +345,33 @@ export default {
iw_title: 'Vigilância de integridade',
iw_hint: 'Faz hash dos executáveis de processos em rede, sinaliza nomes/exe divergentes e (Linux) regiões de memória RWX.',
iw_privacy: 'Verificações somente leitura, 100% locais — nada é modificado ou enviado.',
+ alertmsg_MODULE_SUSPECT: d => `Caminho de módulo suspeito em ${d.process || 'processo'}: ${(d.modules || []).join(', ')}`,
+ alertmsg_MODULE_CHANGED: d => `Integridade de módulos carregados alterada em ${d.process || 'processo'}`,
+ alertmsg_MINING_STRATUM: d => `Protocolo de criptomineração (${d.marker || 'stratum'}) de ${d.process || `pid ${d.pid}`}`,
+ alertmsg_MINING_SUSPECT: d => `Comportamento de mineração: ${d.process || `pid ${d.pid}`} — ${d.detail || 'porta de pool + CPU sustentada'}`,
+ alertmsg_SINKHOLE_HIT: d => `Conexão tentada para destino afundado: ${d.host || d.ip || '?'}`,
+ alertmsg_INJECT_SUSPECT: d => `Suspeita de módulo injetado no pid ${d.pid}: ${(d.paths || []).join(', ')}`,
+ fw_action_throttle: 'Limitar',
+ fw_rate: 'Taxa (kbit/s)',
+ fw_rate_hint: 'Limite de taxa de saída em kbit/s (tc Linux)',
+ ioc_title: 'Pacote IOC comunitário',
+ ioc_export: 'Exportar pacote',
+ ioc_hint: 'Compartilha indicadores como filtro de Bloom com ruído — valores em claro nunca saem do arquivo. Verificações de importação são probabilísticas.',
+ ioc_import_ph: 'Cole um pacote IOC recebido (JSON)…',
+ ioc_check: 'Verificar',
+ ioc_hints: n => `${n} destino(s) correspondem ao pacote (probabilístico)`,
+ ioc_clean: 'Sem correspondência',
+ ioc_bad: 'Pacote inválido',
+ di_inspect: 'Inspeção profunda (Frida)',
+ di_result: 'Caminhos de módulos suspeitos:',
+ di_clean: 'Nenhum caminho suspeito — limpo ou nenhum connect() capturado.',
+ di_failed: 'Inspeção profunda falhou (frida não instalado ou permissões insuficientes)',
+ ebpf_title: 'Sonda eBPF connect',
+ ebpf_hint: 'Somente Linux — atribui pacotes de processos muito efêmeros que a tabela de sockets perde. Requer python3-bcc + root.',
+ ebpf_privacy: 'Eventos de kernel ficam locais — apenas atribuição, nada é registrado ou enviado.',
+ slm_title: 'Enriquecimento LLM local',
+ slm_hint: 'Opcional: enriquece explicações de alertas com modelo compatível com Ollama. Apenas loopback — endpoints remotos são rejeitados.',
+ 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.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index e160e9d..dc35181 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -345,4 +345,33 @@ export default {
iw_title: 'Контроль целостности',
iw_hint: 'Хэширует исполняемые файлы сетевых процессов, сигналит о несовпадении имени/exe и (Linux) RWX-регионах памяти.',
iw_privacy: 'Все проверки — локальный доступ только для чтения: ничего не изменяется и не отправляется.',
+ alertmsg_MODULE_SUSPECT: d => `Подозрительный путь модуля в ${d.process || 'процессе'}: ${(d.modules || []).join(', ')}`,
+ alertmsg_MODULE_CHANGED: d => `Изменилась целостность загруженных модулей в ${d.process || 'процессе'}`,
+ alertmsg_MINING_STRATUM: d => `Протокол криптомайнинга (${d.marker || 'stratum'}) от ${d.process || `pid ${d.pid}`}`,
+ alertmsg_MINING_SUSPECT: d => `Поведение майнинга: ${d.process || `pid ${d.pid}`} — ${d.detail || 'порт пула + устойчивая CPU'}`,
+ alertmsg_SINKHOLE_HIT: d => `Попытка соединения с заглушенной целью: ${d.host || d.ip || '?'}`,
+ alertmsg_INJECT_SUSPECT: d => `Подозрение на инъектированный модуль в pid ${d.pid}: ${(d.paths || []).join(', ')}`,
+ fw_action_throttle: 'Ограничить',
+ fw_rate: 'Скорость (kbit/s)',
+ fw_rate_hint: 'Лимит исходящей скорости в kbit/s (Linux tc)',
+ ioc_title: 'Общественный пакет IOC',
+ ioc_export: 'Экспорт пакета',
+ ioc_hint: 'Делится индикаторами как зашумлённый фильтр Блума — открытые значения никогда не покидают файл. Проверки импорта вероятностные.',
+ ioc_import_ph: 'Вставьте полученный пакет IOC (JSON)…',
+ ioc_check: 'Проверить',
+ ioc_hints: n => `${n} назначений совпадают с пакетом (вероятностно)`,
+ ioc_clean: 'Совпадений нет',
+ ioc_bad: 'Некорректный пакет',
+ di_inspect: 'Глубокая инспекция (Frida)',
+ di_result: 'Подозрительные пути модулей:',
+ di_clean: 'Подозрительных путей нет — чисто или connect() не перехвачен.',
+ di_failed: 'Глубокая инспекция не удалась (frida не установлен или недостаточно прав)',
+ ebpf_title: 'Зонд eBPF connect',
+ ebpf_hint: 'Только Linux — атрибутирует пакеты очень короткоживущих процессов, которые таблица сокетов пропускает. Требуется python3-bcc + root.',
+ ebpf_privacy: 'События ядра остаются локальными — только атрибуция, ничего не журналируется и не отправляется.',
+ slm_title: 'Локальное обогащение LLM',
+ slm_hint: 'Опционально: обогащает пояснения алертов моделью, совместимой с Ollama. Только loopback — удалённые endpoint отклоняются.',
+ slm_endpoint: 'Endpoint',
+ slm_model: 'Модель',
+ slm_privacy: 'Работает только при включении; метаданные алертов идут в вашу локальную модель, никогда наружу.',
}
diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.js
index 6e632ed..bf47a5b 100644
--- a/frontend/src/locales/zh-CN.js
+++ b/frontend/src/locales/zh-CN.js
@@ -345,4 +345,33 @@ export default {
iw_title: '完整性监视',
iw_hint: '对联网进程的可执行文件计算哈希,报告名称/exe 不匹配及(Linux)RWX 内存区域。',
iw_privacy: '所有检查均为只读本地检查 — 不修改也不发送任何内容。',
+ alertmsg_MODULE_SUSPECT: d => `${d.process || '进程'} 中的可疑模块路径:${(d.modules || []).join(', ')}`,
+ alertmsg_MODULE_CHANGED: d => `${d.process || '进程'} 的已加载模块完整性发生变化`,
+ alertmsg_MINING_STRATUM: d => `来自 ${d.process || `pid ${d.pid}`} 的加密挖矿协议(${d.marker || 'stratum'})`,
+ alertmsg_MINING_SUSPECT: d => `挖矿行为:${d.process || `pid ${d.pid}`} — ${d.detail || '矿池端口 + 持续高 CPU'}`,
+ alertmsg_SINKHOLE_HIT: d => `尝试连接已被沉洞的目标:${d.host || d.ip || '?'}`,
+ alertmsg_INJECT_SUSPECT: d => `pid ${d.pid} 中的注入模块嫌疑:${(d.paths || []).join(', ')}`,
+ fw_action_throttle: '限速',
+ fw_rate: '速率 (kbit/s)',
+ fw_rate_hint: '出站速率限制(kbit/s,Linux tc)',
+ ioc_title: '社区 IOC 包',
+ ioc_export: '导出包',
+ ioc_hint: '以加噪 Bloom 过滤器共享指标 — 明文值永远不会离开文件。导入检查为概率性。',
+ ioc_import_ph: '粘贴收到的 IOC 包 (JSON)…',
+ ioc_check: '检查',
+ ioc_hints: n => `${n} 个目标与包匹配(概率性)`,
+ ioc_clean: '无匹配',
+ ioc_bad: '无效的包',
+ di_inspect: '深度检查 (Frida)',
+ di_result: '可疑模块路径:',
+ di_clean: '无可疑模块路径 — 干净或未捕获 connect()。',
+ di_failed: '深度检查失败(未安装 frida 或权限不足)',
+ ebpf_title: 'eBPF connect 探针',
+ ebpf_hint: '仅限 Linux — 归属套接字表漏掉的超短生命周期进程数据包。需要 python3-bcc + root。',
+ ebpf_privacy: '内核事件保持本地 — 仅归属,不记录也不发送。',
+ slm_title: '本地 LLM 增强',
+ slm_hint: '可选:使用 Ollama 兼容模型增强告警解释。仅限 loopback — 远程端点被拒绝。',
+ slm_endpoint: '端点',
+ slm_model: '模型',
+ slm_privacy: '仅在启用时运行;告警元数据仅发送到您的本地模型,绝不离开机器。',
}