Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.
Python cybersecurityd3jsebpfedrelectronfastapifirewallfleet-managementlinuxlittle-snitch-alternativemacosnetwork-monitornetwork-securitypacket-captureprivacyreactrustself-hostedsiemwindows
Add integrity watch, sinkhole rules, alert explainability — v1.2.0
MoneyLisa2c3578026b70
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 46a0005..068f92d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.- **Forensics export / Export forensique** — `GET /forensics/export?format=json|csv|stix` bundles process tree, executable SHA-256, matching alerts and traffic history; STIX is a minimal 2.1 bundle (indicators + observed-data) for SIEM import. / `GET /forensics/export?format=json|csv|stix` — arbre de processus, SHA-256 de l'exécutable, alertes et historique ; STIX = bundle 2.1 minimal pour SIEM.- **Firewall & security UI / UI pare-feu & sécurité** — dedicated panel: lockdown switch, rule create/toggle/delete, per-rule blocked counters, platform-support honesty, audit report, forensics download buttons; per-connection Block action in the sidebar. / Panneau dédié : lockdown, création/bascule/suppression de règles, compteurs bloqués par règle, honnêteté plateforme, rapport d'audit, boutons d'export forensique ; action Bloquer par connexion dans la sidebar.- **Five new UI locales / Cinq nouvelles locales** — de, ru, ja, pt-BR, zh-CN (8 total, 280-key parity-checked); dictionaries moved to `frontend/src/locales/*.js` so a new language is a single-file PR. / de, ru, ja, pt-BR, zh-CN (8 au total, parité 280 clés) ; dictionnaires déplacés vers `frontend/src/locales/*.js` — une nouvelle langue = PR d'un fichier.+- **Sinkhole rule action / Action sinkhole** — `POST /firewall/rules` accepts `action: "sinkhole"`: domains are redirected to loopback via a marked `# snitch-sinkhole` block in the hosts file (all OSes), IPs/CIDRs via iptables `DNAT` in the nat OUTPUT chain (Linux only). `sinkhole` on `process`/`port` is rejected; unsupported platforms report `applied=False` honestly. / `action: "sinkhole"` : les domaines sont redirigés vers loopback via un bloc marqué dans le fichier hosts (tous OS), les IP/CIDR via `DNAT` iptables (Linux). Rejeté pour `process`/`port` ; plateformes non gérées → `applied=False` honnête.+- **Domain rules re-resolution / Re-résolution des règles domaine** — enabled `domain` rules re-resolve every ~10 min; the resolved-IP delta is applied per-OS so CDN rotation can't silently unblock a name. / Les règles `domain` actives sont re-résolues toutes les ~10 min ; le delta d'IP est appliqué par OS pour que la rotation CDN ne débloque pas un nom en silence.+- **Process integrity watch / Veille d'intégrité des processus** — on by default (read-only, local): SHA-256 baselines of networked executables (`BINARY_CHANGED`, persisted `integrity_baselines`), name/exe mismatch (`NAME_MISMATCH`), Linux-only `rwxp` maps scan (`MEM_RWX`, info-level for known JIT apps). `GET /security/integrity` reports capabilities; `POST /security/integrity/check` forces a PID re-check; Settings toggle. / Activée par défaut (lecture seule, local) : baselines SHA-256 des exécutables en réseau (`BINARY_CHANGED`, `integrity_baselines` persisté), mismatch nom/exe (`NAME_MISMATCH`), scan `rwxp` Linux (`MEM_RWX`, niveau info pour les apps JIT connues). `GET /security/integrity`, `POST /security/integrity/check`, interrupteur dans Réglages.+- **Alert explanations / Explications d'alertes** — `GET /security/explain?type=X` returns hand-written bilingual (EN/FR) explanations (meaning, why it matters, next steps) for every alert type; deterministic and offline — not a model. The UI shows them behind a "Why?" button on each alert. / `GET /security/explain?type=X` renvoie des explications bilingues (EN/FR) écrites à la main pour chaque type d'alerte ; déterministes et hors-ligne — pas un modèle. Bouton « Pourquoi ? » sur chaque alerte.## [1.1.0] — 2026-10-22diff --git a/ROADMAP.md b/ROADMAP.mdindex 9783f17..aa49e6b 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -53,13 +53,13 @@ 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** — unsigned-DLL / `PAGE_EXECUTE_READWRITE` inspection crossed with suspicious connections / corrélation mémoire/flux — inspection des régions exécutables croisée avec les connexions+- **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 / SLM SecOps local — un modèle 1–3 Md paramètres expliquant les alertes en langage naturel+- **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** — detect hot-patched DLLs before first packet / intégrité Merkle des modules chargés — détecter les DLL patchées avant le premier paquet-- **Sinkholing / micro-containment** — redirect a suspicious flow to a local honeypot instead of killing it / sinkholing / micro-confinement — rediriger un flux suspect vers un honeypot local au lieu de le tuer+- **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- **PCAP export** stays in scope above / l'export PCAP reste dans le périmètre ci-dessus## 🚫 Out of scope / hors périmètrediff --git a/backend/api/main.py b/backend/api/main.pyindex de34e4d..a4d49b1 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -90,6 +90,8 @@ from scanner.arp_scanner import ARPScanner, Device, default_gateway as _default_from scanner.arp_scanner import READ_STATS as _arp_statsfrom detection.anomaly import AnomalyDetector, Alertfrom detection.firewall import FirewallManager+from detection.integrity import IntegrityWatcher+from detection import explain as alert_explainfrom detection.threatintel import ThreatIntelfrom api.notify import notifierfrom paths import data_dir@@ -116,6 +118,11 @@ detector = AnomalyDetector()# des réglages persistés au démarrage (voir _load_settings).fw = FirewallManager(data_dir())ti = ThreatIntel()+# EN: Read-only process integrity watch — exe hash baselines, name/exe+# mismatch, Linux RWX maps. All local inspection, bounded state.+# 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()_loop: asyncio.AbstractEventLoop | None = None_sniffer: PacketSniffer | None = None_scanner: ARPScanner | None = None@@ -195,11 +202,17 @@ class IgnoreBody(BaseModel):class FirewallRuleBody(BaseModel):- """EN: /firewall/rules payload — block an IP, domain suffix or process.- FR: Charge utile de /firewall/rules — bloquer une IP, un suffixe de- domaine ou un processus."""+ """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)."""kind: strvalue: str+ action: str = "block"class FirewallToggleBody(BaseModel):@@ -684,6 +697,11 @@ def _process_batch(packets: list[Packet]) -> None:touched_devices: dict[str, dict] = {}out_packets: list[dict] = []out_alerts: list[dict] = []+ # EN: (pid, name) pairs seen outbound this batch — handed to the+ # integrity watcher once per tick (it dedups per process lifetime).+ # FR: Couples (pid, nom) sortants du lot — transmis à la veille+ # d'intégrité une fois par tick (elle déduplique par processus).+ seen_pids: dict[int, str] = {}for pkt in packets:if pkt.process_name and pkt.process_name in _excluded_processes:@@ -870,6 +888,13 @@ def _process_batch(packets: list[Packet]) -> None:db.log_alert(ad)out_alerts.append(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é —+ # bornée en interne (une inspection par durée de vie du pid).+ if pkt.direction == "out" and pkt.pid and pkt.pid > 3:+ seen_pids[pkt.pid] = pkt.process_name or ""+touched_nodes[node_id] = nodetouched_edges[edge_id] = edgeout_packets.append({@@ -881,6 +906,14 @@ def _process_batch(packets: list[Packet]) -> None:"timestamp": pkt.timestamp,})+ # EN: Integrity checks run AFTER the batch — hashing exe files and+ # reading /proc maps would stall the 4 Hz drain if done inline.+ # FR: Les contrôles d'intégrité tournent APRÈS le lot — hasher des exes+ # et lire /proc maps bloquerait le drain 4 Hz en ligne.+ if seen_pids and integrity.enabled:+ asyncio.get_running_loop().create_task(+ _integrity_scan(list(seen_pids.items())))+return {"type": "batch","nodes": list(touched_nodes.values()),@@ -891,6 +924,38 @@ def _process_batch(packets: list[Packet]) -> None:}+async def _integrity_scan(items: list[tuple[int, str]]) -> None:+ """+ EN: Background integrity pass for the new PIDs of one drain tick —+ psutil/file-hash/maps reads run in an executor; each finding becomes+ a logged + broadcast alert (and webhook notification when eligible).+ FR: Passage d'intégrité en fond pour les nouveaux PID d'un tick —+ psutil/hash/maps tournent dans un executor ; chaque constat devient+ une alerte journalisée + diffusée (et notification webhook).+ """+ loop = asyncio.get_running_loop()+ try:+ findings = await loop.run_in_executor(None, integrity.check_many, items)+ except Exception as exc:+ logger.debug("integrity scan failed: %s", exc)+ return+ for f in findings:+ proc = f.get("process") or f.get("pid")+ alert = Alert(+ type=f["type"],+ severity=f.get("severity", "warning"),+ message=f"Integrity: {f['type'].replace('_', ' ').title()} — "+ f"{proc}: {f.get('detail', '')}",+ node_id=None,+ details=f,+ )+ d = alert.to_dict()+ db.log_alert(d)+ await broadcast({"type": "alert", "alert": d})+ if f.get("severity") != "info":+ await _notify(d)++async def _drain_loop() -> None:"""EN: THE consumer of _pkt_queue — one task, ~4 Hz. Each tick drains up to@@ -1070,8 +1135,10 @@ def _on_media_change(state: MediaState) -> None:def _flush_loop() -> None:"""EN: Periodically flush the traffic accumulator to SQLite.FR: Vider périodiquement l'accumulateur de trafic vers SQLite."""+ ticks = 0while not _shutdown:time.sleep(10)+ ticks += 1try:db.flush()# EN: Snapshot learned process baselines — they power the@@ -1079,8 +1146,24 @@ def _flush_loop() -> None:# FR: Sauvegarder les baselines de processus apprises — elles# alimentent les alertes de déviation entre redémarrages.db.set_setting("app_baselines", detector.dump_baselines())+ db.set_setting("integrity_baselines", integrity.dump_baselines())except Exception as exc:logger.error("db flush failed: %s", exc)+ # EN: Domain rules re-resolve every ~10 min — CDNs rotate IPs, and a+ # stale resolution would silently stop matching the name.+ # FR: Les règles domaine se re-résolvent toutes les ~10 min — les CDN+ # font tourner leurs IP et une résolution périmée cesserait de+ # matcher le nom sans bruit.+ if ticks % 60 == 0:+ try:+ changed = fw.refresh_domains()+ if changed:+ rules, _lockdown = fw.serialized()+ db.set_setting("firewall_rules", rules)+ logger.info("firewall: %d domain rule(s) re-resolved",+ changed)+ except Exception as exc:+ logger.debug("domain refresh failed: %s", exc)def _cleanup_loop() -> None:@@ -1206,6 +1289,12 @@ def _load_settings() -> None:ti.configure(db.get_setting("ti_provider", "none") or "none",db.get_setting("ti_api_key", "") or "")detector.load_baselines(db.get_setting("app_baselines", {}) or {})+ # EN: Integrity watch is ON by default — it is read-only local+ # inspection, so it follows the "safe unless told otherwise" rule.+ # FR: La veille d'intégrité est ON par défaut — inspection locale en+ # lecture seule, donc « sûr sauf indication contraire ».+ integrity.configure(bool(db.get_setting("integrity_watch", True)))+ integrity.load_baselines(db.get_setting("integrity_baselines", {}) or {})notifier.configure(db.get_setting("webhook_url", "") or "",bool(db.get_setting("webhook_enabled", False)),db.get_setting("telegram_chat_id", "") or "")@@ -1381,6 +1470,8 @@ async def post_settings(body: SettingsBody) -> dict:notifier.configure(db.get_setting("webhook_url", "") or "",bool(db.get_setting("webhook_enabled", False)),db.get_setting("telegram_chat_id", "") or "")+ if key == "integrity_watch":+ integrity.configure(bool(value))return {"ok": True}@app.get("/capture/status", dependencies=_AUTH)@@ -1892,7 +1983,8 @@ async def firewall_add_rule(body: FirewallRuleBody) -> dict:FR: Créer une règle {kind: ip|domain|process, value}. Persistée."""loop = asyncio.get_running_loop()try:- rule = await loop.run_in_executor(None, fw.add_rule, body.kind, body.value)+ rule = await loop.run_in_executor(+ None, fw.add_rule, body.kind, body.value, body.action)except ValueError as exc:raise HTTPException(400, str(exc))rules, lockdown = fw.serialized()@@ -2018,6 +2110,56 @@ async def threat_check(body: ThreatCheckBody) -> dict:return {"verdict": verdict, "config": ti.config()}[email protected]("/security/integrity", dependencies=_AUTH)+async def integrity_status() -> dict:+ """EN: Integrity-watch capability + recent findings report. Honest about+ platform support — RWX scan is Linux-only, hash watch everywhere.+ FR: Rapport de capacité + constats de la veille d'intégrité. Honnête sur+ le support plateforme — scan RWX Linux seulement, hash partout."""+ return integrity.status()++[email protected]("/security/integrity/check", dependencies=_AUTH)+async def integrity_check(body: PidBody) -> dict:+ """EN: Manual on-demand integrity check for one PID — hash, name/exe+ match, RWX maps. Runs the checks even if the pid was already seen+ (clears its dedup entry first), so analysts can force a re-check.+ FR: Contrôle d'intégrité manuel à la demande pour un PID — hash,+ correspondance nom/exe, maps RWX. Force la vérification même si le+ pid a déjà été vu (purge son entrée de dédup d'abord)."""+ import psutil+ if body.pid <= 3 or body.pid == os.getpid():+ raise HTTPException(400, "refusing to check a system/critical pid")+ loop = asyncio.get_running_loop()++ def _do() -> list[dict]:+ # EN: Drop the dedup key so a manual check always re-inspects.+ # FR: Retirer la clé de dédup pour qu'un contrôle manuel ré-inspecte.+ with integrity._lock: # noqa: SLF001 — same service+ for k in [k for k in integrity._checked if k[0] == body.pid]:+ integrity._checked.pop(k, None)+ try:+ name = psutil.Process(body.pid).name()+ except psutil.NoSuchProcess:+ return []+ return integrity.check(body.pid, name)++ findings = await loop.run_in_executor(None, _do)+ return {"pid": body.pid, "findings": findings}++[email protected]("/security/explain", dependencies=_AUTH)+async def security_explain(type: str = "") -> dict:+ """EN: Plain-language, bilingual explanation for one alert type —+ deterministic templates, works fully offline (no model involved).+ FR: Explication bilingue en langage clair pour un type d'alerte —+ gabarits déterministes, 100 % hors-ligne (aucun modèle)."""+ rec = alert_explain.explain(type)+ if rec is None:+ raise HTTPException(404, f"no explanation for alert type {type!r}")+ return {"type": type.upper(), **rec}++@app.get("/security/audit", dependencies=_AUTH)async def security_audit() -> dict:"""EN: Hardening report computed from the last 500 alerts + live graph:@@ -2076,6 +2218,11 @@ async def security_audit() -> dict:"platform": fw.status().get("platform"),},"threat_intel": ti.config(),+ "integrity": {+ "enabled": integrity.enabled,+ "checked": integrity.status().get("checked", 0),+ "findings": integrity.status().get("findings", [])[-10:],+ },"recommendations": _audit_recommendations(counts, risky, unlabeled, active_rules, lockdown),}diff --git a/backend/api/notify.py b/backend/api/notify.pyindex 6b2b19e..f1c0483 100644--- a/backend/api/notify.py+++ b/backend/api/notify.py@@ -23,7 +23,6 @@ import jsonimport loggingimport threadingimport urllib.request-from typing import Optionallogger = logging.getLogger("snitch.notify")diff --git a/backend/detection/explain.py b/backend/detection/explain.pynew file mode 100644index 0000000..bc8fc08--- /dev/null+++ b/backend/detection/explain.py@@ -0,0 +1,391 @@+"""+EN: Alert explainability — deterministic, rule-based explanations for every+ alert type the detector can emit. This is deliberately NOT a language+ model: each template is hand-written, bilingual, and bounded — the+ honest version of "explain this alert" that works offline, costs zero+ resources, and can never hallucinate. A local SLM stays on the research+ roadmap; this is what ships today.++ Served by GET /security/explain?type=<ALERT_TYPE> — the frontend uses+ it for the "Why am I seeing this?" affordance on alert cards.++FR: Explicabilité des alertes — explications déterministes par règles pour+ chaque type d'alerte du détecteur. Ce n'est volontairement PAS un modèle+ de langage : chaque gabarit est écrit à la main, bilingue et borné — la+ version honnête de « explique cette alerte » qui marche hors-ligne, ne+ coûte rien et ne peut pas halluciner. Un SLM local reste à la roadmap ;+ voici ce qui est livré aujourd'hui.+"""++from __future__ import annotations+++def _e(title_en, title_fr, what_en, what_fr, why_en, why_fr,+ actions_en, actions_fr) -> dict:+ """EN: One explanation record — bilingual fields, parallel action lists.+ FR: Une explication — champs bilingues, listes d'actions parallèles."""+ return {+ "title_en": title_en, "title_fr": title_fr,+ "what_en": what_en, "what_fr": what_fr,+ "why_en": why_en, "why_fr": why_fr,+ "actions_en": actions_en, "actions_fr": actions_fr,+ }+++EXPLANATIONS: dict[str, dict] = {++"NEW_HOST": _e(+ "First contact with a remote host",+ "Premier contact avec un hôte distant",+ "Snitch saw traffic to an IP it had never observed since the session started.",+ "Snitch a vu du trafic vers une IP jamais observée depuis le début de la session.",+ "Mostly informational — every new server you legitimately visit triggers it. "+ "It becomes meaningful when paired with other alerts or an unexpected process.",+ "Surtout informatif — tout nouveau serveur légitime la déclenche. Elle prend "+ "du sens combinée à d'autres alertes ou à un processus inattendu.",+ ["Check which process opened the connection",+ "Look at the geolocation and resolved domain",+ "If unexpected, check its reputation (Threat intel)"],+ ["Identifier le processus à l'origine de la connexion",+ "Regarder la géolocalisation et le domaine résolu",+ "Si inattendu, vérifier sa réputation (threat intel)"]),++"NEW_LAN_DEVICE": _e(+ "New device joined the LAN",+ "Nouvel appareil sur le LAN",+ "A MAC/IP pair appeared in the ARP table that Snitch had not seen.",+ "Un couple MAC/IP est apparu dans la table ARP, inconnu de Snitch.",+ "Phones, TVs and guests legitimately join networks — but on a network you "+ "control, an unknown device deserves one look.",+ "Téléphones, TV et invités rejoignent légitimement le réseau — mais sur un "+ "réseau que vous contrôlez, un appareil inconnu mérite un œil.",+ ["Compare with devices you own (hostname, MAC vendor)",+ "If unknown, check your router's client list"],+ ["Comparer avec vos appareils (nom d'hôte, fabricant MAC)",+ "Si inconnu, vérifier la liste des clients du routeur"]),++"DEVICE_OFFLINE": _e(+ "A LAN device went silent",+ "Un appareil LAN s'est tu",+ "A previously-seen LAN device disappeared from the ARP table.",+ "Un appareil LAN connu a disparu de la table ARP.",+ "Usually a phone sleeping or a laptop leaving. Relevant only for devices "+ "expected to stay (servers, NAS).",+ "Généralement un téléphone en veille ou un portable qui part. Pertinent "+ "seulement pour les appareils censés rester (serveurs, NAS).",+ ["None needed for mobile devices",+ "For infrastructure, check power/network state"],+ ["Rien à faire pour les mobiles",+ "Pour l'infrastructure, vérifier alimentation et réseau"]),++"PORT_SCAN": _e(+ "Port scan pattern",+ "Motif de scan de ports",+ "One host touched many distinct ports in a short window — the signature of "+ "reconnaissance (nmap-style).",+ "Un hôte a touché de nombreux ports distincts en peu de temps — signature "+ "de reconnaissance (style nmap).",+ "Scans precede attacks. Local scanners are sometimes legit (admin tools) — "+ "remote scanners are not.",+ "Les scans précèdent les attaques. Un scanner local peut être légitime "+ "(outils d'admin) — un scanner distant ne l'est pas.",+ ["Identify the scanning process / host",+ "Block the source IP with a firewall rule",+ "Kill the process if it is local and unknown"],+ ["Identifier le processus / l'hôte qui scanne",+ "Bloquer l'IP source avec une règle pare-feu",+ "Tuer le processus s'il est local et inconnu"]),++"BEACON": _e(+ "Regular-interval connections (beaconing)",+ "Connexions à intervalle régulier (balisage)",+ "Outbound connections to one host at near-constant intervals — the heartbeat "+ "pattern of malware calling its C2.",+ "Connexions sortantes vers un même hôte à intervalles quasi constants — le "+ "pouls typique d'un malware qui appelle son C2.",+ "Legit software also polls (sync, telemetry) — jitter and payload size help "+ "tell them apart: malware beacons are usually tiny and very regular.",+ "Les logiciels légitimes interrogent aussi (sync, télémétrie) — jitter et "+ "taille des paquets aident à distinguer : les beacons sont petits et très réguliers.",+ ["Check the process behind the connections",+ "Compare interval and byte counts with known sync services",+ "Run a threat-intel check on the destination",+ "Consider a firewall rule if unexplained"],+ ["Identifier le processus derrière les connexions",+ "Comparer intervalle et volume avec des services de sync connus",+ "Lancer une vérif threat-intel sur la destination",+ "Envisager une règle pare-feu si inexpliqué"]),++"VOLUME_SPIKE": _e(+ "Traffic volume spike",+ "Pic de volume de trafic",+ "Bytes-per-second to or from a host jumped far above its rolling baseline.",+ "Le débit vers/depuis un hôte a bondi bien au-dessus de sa moyenne mobile.",+ "Bulk transfers are legit (backup, video, updates) — an unexplained burst "+ "to an unknown host is not.",+ "Les gros transferts sont légitimes (backup, vidéo, mises à jour) — un pic "+ "inexpliqué vers un hôte inconnu ne l'est pas.",+ ["Check what the process was doing at that moment",+ "Export forensics for the process if unexplained"],+ ["Vérifier ce que faisait le processus à cet instant",+ "Exporter le forensique du processus si inexpliqué"]),++"MEDIA_EXFIL": _e(+ "Upload while camera/mic active",+ "Envoi de données pendant caméra/micro actifs",+ "Outbound traffic coincided with an active microphone or camera — the "+ "classic spyware pattern of streaming your sensors out.",+ "Du trafic sortant a coïncidé avec un micro ou une caméra actifs — le motif "+ "classique d'un spyware qui exfiltre vos capteurs.",+ "Video calls legitimately do this — the alert matters when the uploading "+ "process is NOT your call app.",+ "Les visioconférences font légitimement cela — l'alerte compte quand le "+ "processus émetteur n'est PAS votre app d'appel.",+ ["Verify which app holds the camera/mic",+ "Check that the uploader is the same application",+ "Kill + block if the process is unknown"],+ ["Vérifier quelle app détient caméra/micro",+ "Vérifier que l'émetteur est la même application",+ "Tuer + bloquer si le processus est inconnu"]),++"UPLOAD_SPIKE": _e(+ "Abnormal outbound volume for a process",+ "Volume sortant anormal pour un processus",+ "A process sent more data than its configured threshold allows — possible "+ "data exfiltration.",+ "Un processus a envoyé plus de données que le seuil configuré — "+ "exfiltration possible.",+ "Cloud sync and backups send a lot — the question is whether THIS process "+ "should be uploading at all.",+ "La sync cloud et les backups envoient beaucoup — la question est de savoir "+ "si CE processus devrait envoyer quoi que ce soit.",+ ["Look at the destination — cloud provider or unknown host?",+ "Adjust the threshold in Settings if this is expected",+ "Export the process bundle (SHA-256, parent tree)"],+ ["Regarder la destination — cloud connu ou hôte inconnu ?",+ "Ajuster le seuil dans Réglages si c'est attendu",+ "Exporter le paquet forensique (SHA-256, arbre parent)"]),++"WATCHLIST_HIT": _e(+ "Watched IP/domain contacted",+ "IP/domaine surveillé contacté",+ "Traffic matched an entry on your personal watchlist.",+ "Le trafic correspond à une entrée de votre liste de surveillance.",+ "You pinned this — either a host you don't trust or one you want visibility on.",+ "Vous l'avez épinglé — soit un hôte auquel vous ne faites pas confiance, "+ "soit un hôte que vous voulez suivre.",+ ["Review why it was watched",+ "Block it with a firewall rule if unwanted"],+ ["Revoir pourquoi il était surveillé",+ "Le bloquer via une règle pare-feu si indésirable"]),++"SUSPICIOUS_PROCESS": _e(+ "Unusual process networking",+ "Activité réseau inhabituelle d'un processus",+ "A process with no network business opened connections (e.g. a calculator, "+ "notepad-class tool).",+ "Un processus sans vocation réseau a ouvert des connexions (calculatrice, "+ "bloc-notes…).",+ "Offline tools going online is a top infection indicator — legit updates "+ "are the main false positive.",+ "Un outil hors-ligne qui se connecte est un indicateur majeur d'infection — "+ "les mises à jour légitimes sont le principal faux positif.",+ ["Check the executable path — is it the real tool?",+ "Run integrity check on the process",+ "Kill and block if unexplained"],+ ["Vérifier le chemin de l'exécutable — est-ce le vrai outil ?",+ "Lancer un contrôle d'intégrité sur le processus",+ "Tuer et bloquer si inexpliqué"]),++"SUSPICIOUS_PORT": _e(+ "Connection on an unusual port",+ "Connexion sur un port inhabituel",+ "A flow used a port that does not match its apparent purpose — e.g. "+ "non-HTTP traffic on 443, or a service port rarely seen outbound.",+ "Un flux utilise un port qui ne correspond pas à son usage apparent — ex. "+ "du non-HTTP sur 443, ou un port rarement vu en sortie.",+ "Attackers hide tunnels on common-looking ports; protocol/port mismatch is "+ "the cheapest way to spot them.",+ "Les attaquants cachent des tunnels sur des ports banals ; le mismatch "+ "protocole/port est le moyen le plus simple de les repérer.",+ ["Look at the actual payload classification",+ "Check if the process is expected to use that port",+ "Consider blocking the port for that process"],+ ["Regarder la classification réelle du trafic",+ "Vérifier que le processus utilise normalement ce port",+ "Envisager de bloquer le port pour ce processus"]),++"DNS_TUNNEL": _e(+ "Possible DNS tunnelling",+ "Tunnel DNS possible",+ "DNS queries with oversized names/labels or unusual frequency — the standard "+ "exfiltration channel that bypasses most firewalls.",+ "Requêtes DNS avec noms/labels surdimensionnés ou fréquence anormale — le "+ "canal d'exfiltration classique qui contourne la plupart des pare-feux.",+ "DNS is allowed almost everywhere, so malware encodes data in subdomains. "+ "Long random-looking labels are the tell.",+ "Le DNS est autorisé presque partout, donc les malwares encodent les données "+ "en sous-domaines. Les labels longs et aléatoires sont le signal.",+ ["Identify the querying process",+ "Inspect the queried domain",+ "Block the process or the resolver if confirmed"],+ ["Identifier le processus qui interroge",+ "Inspecter le domaine interrogé",+ "Bloquer le processus ou le résolveur si confirmé"]),++"CLEARTEXT": _e(+ "Unencrypted protocol in use",+ "Protocole non chiffré utilisé",+ "Outbound traffic on a legacy plaintext port (FTP, Telnet, HTTP, plain "+ "mail) — credentials or content readable on the wire.",+ "Trafic sortant sur un port en clair historique (FTP, Telnet, HTTP, mail "+ "non chiffré) — identifiants ou contenu lisibles sur le réseau.",+ "Anything readable on the wire can be stolen or tampered — on public Wi-Fi "+ "especially.",+ "Tout ce qui est lisible sur le réseau peut être volé ou altéré — sur Wi-Fi "+ "public surtout.",+ ["Check whether an encrypted alternative exists (HTTPS, SFTP, SSH)",+ "Avoid credentials over this connection",+ "Pin a note via the watchlist if it must stay"],+ ["Vérifier qu'une alternative chiffrée existe (HTTPS, SFTP, SSH)",+ "Éviter les identifiants sur cette connexion",+ "Épingler via la watchlist si elle doit rester"]),++"BASELINE_DEVIATION": _e(+ "Process changed its network habits",+ "Le processus a changé d'habitudes réseau",+ "A known process contacted a country or pattern outside its learned "+ "profile — Snitch's per-app baseline flags the drift.",+ "Un processus connu a contacté un pays ou un motif hors de son profil "+ "appris — la baseline par app de Snitch signale la dérive.",+ "Updates change destinations legitimately — but a chat app suddenly "+ "reaching an unusual country deserves a look.",+ "Les mises à jour changent légitimement de destination — mais une app de "+ "chat qui contacte soudain un pays inhabituel mérite un œil.",+ ["Check if the app recently updated",+ "Run integrity check on the executable",+ "Reset its baseline if the new behaviour is intended"],+ ["Vérifier si l'app a récemment été mise à jour",+ "Lancer un contrôle d'intégrité de l'exécutable",+ "Réinitialiser sa baseline si le comportement est voulu"]),++"THREAT_HIT": _e(+ "Threat-intel flagged destination",+ "Destination signalée par la threat intel",+ "The configured reputation provider (AbuseIPDB/OTX/VirusTotal — your own "+ "key, opt-in) reports this IP as suspicious or malicious.",+ "Le fournisseur de réputation configuré (AbuseIPDB/OTX/VirusTotal — votre "+ "clé, opt-in) rapporte cette IP comme suspecte ou malveillante.",+ "Reputation feeds are not perfect, but a flagged C2/proxy/botnet host "+ "merits immediate review.",+ "Les flux de réputation ne sont pas parfaits, mais un hôte signalé "+ "C2/proxy/botnet mérite une revue immédiate.",+ ["Read the provider detail in the alert",+ "Block the IP with a firewall rule",+ "Export forensics for the connecting process"],+ ["Lire le détail du fournisseur dans l'alerte",+ "Bloquer l'IP via une règle pare-feu",+ "Exporter le forensique du processus connecté"]),++"BLOCKED_ATTEMPT": _e(+ "Firewall rule matched a packet",+ "Une règle pare-feu a matché un paquet",+ "Traffic matching an active firewall rule (or lockdown) was observed — "+ "with privileges the OS also dropped it.",+ "Du trafic correspondant à une règle pare-feu active (ou au lockdown) a "+ "été observé — avec privilèges, l'OS l'a aussi droppé.",+ "Confirms the policy works; repeated attempts from a blocked process are "+ "the interesting signal.",+ "Confirme que la politique fonctionne ; les tentatives répétées d'un "+ "processus bloqué sont le signal intéressant.",+ ["Watch the attempt counter on the rule",+ "Investigate the blocked process if it insists",+ "Tune or delete the rule if it is wrong"],+ ["Surveiller le compteur de tentatives de la règle",+ "Investiguer le processus bloqué s'il insiste",+ "Ajuster ou supprimer la règle si elle est fausse"]),++"LOCKDOWN": _e(+ "Lockdown mode enabled",+ "Mode lockdown activé",+ "The panic switch is on — outbound traffic to public IPs is dropped; "+ "loopback and LAN stay alive.",+ "Le bouton panique est actif — le trafic sortant vers les IP publiques est "+ "coupé ; loopback et LAN restent vivants.",+ "Use during an active incident to freeze exfiltration while you investigate.",+ "À utiliser pendant un incident pour figer toute exfiltration le temps "+ "d'investiguer.",+ ["Investigate flagged processes while isolated",+ "Disable when the incident is resolved"],+ ["Investiguer les processus signalés pendant l'isolement",+ "Désactiver quand l'incident est résolu"]),++"BINARY_CHANGED": _e(+ "Executable modified on disk",+ "Exécutable modifié sur disque",+ "The SHA-256 of a running process's executable no longer matches the hash "+ "recorded for that path — the file was replaced or patched.",+ "Le SHA-256 de l'exécutable d'un processus actif ne correspond plus au hash "+ "enregistré pour ce chemin — le fichier a été remplacé ou patché.",+ "Legit updates replace binaries — but an unexplained change under a "+ "running PID is a tampering indicator.",+ "Les mises à jour remplacent légitimement les binaires — mais un changement "+ "inexpliqué sous un PID actif indique une altération.",+ ["Compare with the app's update timeline",+ "Export forensics (parent tree, hash) now",+ "Kill + block if the change is unexplained"],+ ["Comparer avec l'historique de mises à jour de l'app",+ "Exporter le forensique (arbre parent, hash) immédiatement",+ "Tuer + bloquer si le changement est inexpliqué"]),++"NAME_MISMATCH": _e(+ "Process name/executable mismatch",+ "Mismatch nom/exécutable du processus",+ "The process's reported name does not match its executable's basename — "+ "classic masquerading (malware named 'svchost' living outside System32).",+ "Le nom rapporté du processus ne correspond pas au basename de son "+ "exécutable — masquage classique (malware nommé « svchost » hors System32).",+ "Renamed copies and launchers cause rare false positives — location and "+ "parent process tell the truth.",+ "Les copies renommées et launchers causent de rares faux positifs — "+ "l'emplacement et le processus parent disent la vérité.",+ ["Check the executable's path",+ "Export the process bundle to see the parent chain",+ "Kill + block if the binary is unexpected"],+ ["Vérifier le chemin de l'exécutable",+ "Exporter le paquet pour voir la chaîne parente",+ "Tuer + bloquer si le binaire est inattendu"]),++"MEM_RWX": _e(+ "Executable-writable memory region",+ "Région mémoire exécutable-inscriptible",+ "The process maps memory that is simultaneously writable and executable "+ "(rwxp) — the signature of injected shellcode or reflective loading. "+ "Linux only (/proc/pid/maps).",+ "Le processus mappe de la mémoire à la fois inscriptible et exécutable "+ "(rwxp) — signature de shellcode injecté ou de chargement réflexif. "+ "Linux uniquement (/proc/pid/maps).",+ "JIT engines (browsers, node, java) legitimately use RWX pages — reported "+ "at info level for those. For any other process it is a strong anomaly.",+ "Les moteurs JIT (navigateurs, node, java) utilisent légitimement des pages "+ "RWX — signalés en info pour ceux-là. Pour tout autre processus, c'est une "+ "anomalie forte.",+ ["Check whether the process is a known JIT app (info-level alerts)",+ "Export forensics on the process",+ "Kill + block if the process is not a browser/runtimes"],+ ["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"]),+}+++def explain(alert_type: str) -> dict | None:+ """EN: Explanation record for one alert type — None when unknown.+ FR: Explication pour un type d'alerte — None si inconnu."""+ return EXPLANATIONS.get((alert_type or "").upper())+++def all_types() -> list[str]:+ """EN: Alert types with an explanation — used by the audit endpoint.+ FR: Types d'alertes documentés — utilisé par l'endpoint d'audit."""+ return sorted(EXPLANATIONS)diff --git a/backend/detection/firewall.py b/backend/detection/firewall.pyindex 952ef01..1b08548 100644--- a/backend/detection/firewall.py+++ b/backend/detection/firewall.py@@ -13,10 +13,20 @@ EN: Firewall orchestration — Snitch does NOT filter packets in user-space;Rule kinds: "ip" single remote IP"cidr" network (e.g. 185.0.0.0/8)- "domain" resolved to IPs at apply time (best effort)+ "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)"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."lockdown" drops ALL outbound traffic to non-private destinations —loopback and LAN stay up so the UI remains reachable.@@ -37,7 +47,6 @@ import osimport platformimport socketimport subprocess-import tempfileimport threadingimport timeimport uuid@@ -120,19 +129,26 @@ class FirewallManager:# ── Public rule ops / Opérations publiques ───────────────────────────────- def add_rule(self, kind: str, value: str) -> dict:- """EN: Create + apply a rule. `value` depends on kind (see module doc).- Returns the persisted rule dict including its apply result.- FR: Créer + appliquer une règle. Retourne la règle persistée avec le- résultat d'application."""+ def add_rule(self, kind: str, value: str, action: str = "block") -> 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."""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"):+ 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}")rule = {"id": uuid.uuid4().hex[:10],"kind": kind,"value": value,+ "action": action,"enabled": True,"applied": False,"error": None,@@ -275,6 +291,10 @@ class FirewallManager:rule["applied"], rule["error"] = True, Nonereturnkind, value, rid = rule["kind"], rule["value"], rule["id"]+ action = rule.get("action", "block")+ if action == "sinkhole":+ rule["applied"], rule["error"] = self._sinkhole_apply(rule)+ returntargets = rule.get("resolved") if kind == "domain" else [value]if kind == "domain" and not targets:rule["applied"], rule["error"] = False, "domain did not resolve"@@ -314,9 +334,148 @@ class FirewallManager:return self._pf_apply()return False, f"unsupported platform {self._platform}"+ # ── Sinkhole / Trou noir ─────────────────────────────────────────────────++ def _hosts_path(self) -> Optional[Path]:+ """EN: Platform hosts file — where domain sinkholes are written.+ FR: Fichier hosts de la plateforme — là où vont les sinkholes domaine."""+ if self._platform in ("linux", "darwin"):+ return Path("/etc/hosts")+ if self._platform == "windows":+ root = os.environ.get("SystemRoot", r"C:\Windows")+ return Path(root) / "System32" / "drivers" / "etc" / "hosts"+ return None++ def _sinkhole_apply(self, rule: dict) -> tuple[bool, str]:+ """EN: Redirect instead of drop. Domains land in the hosts file+ between `# snitch-sinkhole <id>` markers (removal = strip the block);+ IP/CIDR targets get an iptables DNAT rule to 127.0.0.1 on Linux.+ FR: Rediriger plutôt que dropper. Les domaines vont dans le fichier+ hosts entre marqueurs `# snitch-sinkhole <id>` ; les IP/CIDR reçoivent+ une règle DNAT iptables vers 127.0.0.1 sous Linux."""+ kind, value, rid = rule["kind"], rule["value"], rule["id"]+ if kind == "domain":+ hosts = self._hosts_path()+ if hosts is None:+ return False, f"no hosts file path on {self._platform}"+ # EN: Cover the bare name + www + wildcard-ish parents.+ # FR: Couvrir le nom nu + www + parents type wildcard.+ names = {value, f"www.{value}"}+ lines = [f"# snitch-sinkhole {rid} begin"]+ lines += [f"127.0.0.1 {n}" for n in sorted(names)]+ lines += [f"::1 {n}" for n in sorted(names)]+ lines.append(f"# snitch-sinkhole {rid} end")+ try:+ with open(hosts, "a", encoding="utf-8") as f:+ f.write("\n".join(lines) + "\n")+ return True, ""+ except OSError as e:+ return False, f"hosts file not writable: {e}"+ # EN: ip/cidr sinkhole — DNAT to loopback, Linux nat table only.+ # FR: sinkhole ip/cidr — DNAT vers loopback, table nat Linux seulement.+ if self._platform != "linux":+ return False, "ip sinkhole needs iptables (linux only)"+ return self._run(["iptables", "-w", "-t", "nat", "-I", "OUTPUT",+ "-d", value, "-j", "DNAT",+ "--to-destination", "127.0.0.1",+ "-m", "comment", "--comment", f"snitch-sinkhole-{rid}"])++ def _sinkhole_remove(self, rule: dict) -> None:+ """EN: Undo a sinkhole — strip the marked hosts block or delete the+ DNAT rule. Best-effort, never raises.+ FR: Défaire un sinkhole — retirer le bloc hosts marqué ou supprimer+ la règle DNAT. Au mieux, ne lève jamais."""+ kind, rid, value = rule["kind"], rule["id"], rule["value"]+ if kind == "domain":+ hosts = self._hosts_path()+ if hosts is None:+ return+ try:+ lines = hosts.read_text(encoding="utf-8",+ errors="replace").splitlines()+ out, skip = [], False+ for line in lines:+ if line.strip() == f"# snitch-sinkhole {rid} begin":+ skip = True+ continue+ if line.strip() == f"# snitch-sinkhole {rid} end":+ skip = False+ continue+ if not skip:+ out.append(line)+ hosts.write_text("\n".join(out) + "\n", encoding="utf-8")+ except OSError:+ pass+ elif self._platform == "linux":+ self._run(["iptables", "-w", "-t", "nat", "-D", "OUTPUT",+ "-d", value, "-j", "DNAT",+ "--to-destination", "127.0.0.1",+ "-m", "comment", "--comment", f"snitch-sinkhole-{rid}"])++ # ── Domain re-resolution / Re-résolution des domaines ───────────────────++ def refresh_domains(self) -> int:+ """EN: Re-resolve every enabled domain rule and apply the delta —+ stale IPs removed, new IPs added. Called periodically from the flush+ loop so CDN rotation can't silently unblock a name. Returns the+ number of rules whose resolution changed.+ FR: Re-résoudre chaque règle domaine active et appliquer le delta —+ IP périmées retirées, nouvelles ajoutées. Appelé périodiquement+ depuis la boucle de flush pour que la rotation CDN ne débloque pas+ silencieusement un nom. Retourne le nombre de règles modifiées."""+ with self._lock:+ rules = [r for r in self._rules+ if r.get("enabled", True) and r["kind"] == "domain"]+ changed = 0+ for r in rules:+ new = self._resolve_domain(r["value"])+ old = list(r.get("resolved") or [])+ if set(new) == set(old):+ continue+ changed += 1+ # EN: Sinkhole domains redirect through the hosts file (by name) —+ # re-resolution only refreshes packet-matching visibility,+ # no OS-level delta needed.+ # FR: Les domaines sinkhole redirigent via le fichier hosts (par+ # nom) — la re-résolution ne sert qu'à la visibilité du+ # matching, pas de delta OS nécessaire.+ if r.get("action", "block") == "sinkhole":+ r["resolved"] = new+ continue+ if not self._demo:+ if self._platform == "linux":+ rid = r["id"]+ for t in sorted(set(old) - set(new)):+ self._run(["iptables", "-w", "-D", "OUTPUT", "-d", t,+ "-j", "DROP", "-m", "comment",+ "--comment", f"snitch-{rid}"])+ for t in sorted(set(new) - set(old)):+ self._run(["iptables", "-w", "-I", "OUTPUT", "-d", t,+ "-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+ elif self._platform == "darwin":+ r["resolved"] = new+ self._pf_apply() # EN: anchor is regenerated whole+ # FR: l'ancre est régénérée entière+ continue+ r["resolved"] = new+ return changed+def _remove(self, rule: dict) -> None:if self._demo:return+ if rule.get("action", "block") == "sinkhole":+ self._sinkhole_remove(rule)+ returnrid, kind = rule["id"], rule["kind"]if self._platform == "windows":self._run(["netsh", "advfirewall", "firewall", "delete", "rule",diff --git a/backend/detection/integrity.py b/backend/detection/integrity.pynew file mode 100644index 0000000..f45b8f4--- /dev/null+++ b/backend/detection/integrity.py@@ -0,0 +1,345 @@+"""+EN: Process integrity watch — the user-space slice of "is this process+ what it claims to be?" that is actually implementable without a+ kernel driver:++ 1. EXE HASH WATCH — SHA-256 of the executable backing each PID that+ shows network activity. The first hash seen for a path becomes+ the baseline (persisted); a different hash later means the file+ was replaced/patched on disk → BINARY_CHANGED.+ 2. NAME/EXE MISMATCH — a process whose display name does not match+ its executable's basename is classic masquerading (malware named+ "svchost" living in %TEMP%) → NAME_MISMATCH.+ 3. RWX MEMORY SCAN (Linux only) — anonymous or file-backed regions+ mapped rwxp in /proc/<pid>/maps are the signature of injected+ shellcode / reflective loading → MEM_RWX. Bounded: max 10+ regions reported, known-JIT processes (browsers, node, java,+ electron) are reported at "info" severity instead of warning —+ RWX pages are legitimate there.++ Honest limits, documented to the user:+ * The hash compares FILE-ON-DISK states across launches — detecting+ true in-memory tampering (process hollowing, DLL injection that+ never touches the file) needs driver/memory-forensics tooling,+ which stays on the research roadmap.+ * /proc/<pid>/maps needs ptrace-level privileges — usually the same+ ones packet capture already requires. Access-denied degrades to+ `rwx: None`, never to a crash.+ * Everything is read-only local inspection: no process is modified,+ killed or debugged by this module.++FR: Veille d'intégrité des processus — la partie user-space implémentable+ de « ce processus est-il ce qu'il prétend ? » sans driver noyau :++ 1. SURVEILLANCE DU HASH DE L'EXE — SHA-256 de l'exécutable derrière+ chaque PID avec activité réseau. Le premier hash vu pour un+ chemin devient la baseline (persistée) ; un hash différent plus+ tard = fichier remplacé/patché sur disque → BINARY_CHANGED.+ 2. MISMATCH NOM/EXE — un processus dont le nom affiché ne correspond+ pas au basename de son exécutable = masquage classique →+ NAME_MISMATCH.+ 3. SCAN MÉMOIRE RWX (Linux seulement) — régions rwxp dans+ /proc/<pid>/maps = signature d'injection de shellcode → MEM_RWX.+ 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.++ Limites honnêtes :+ * Le hash compare les ÉTATS SUR DISQUE entre lancements — détecter+ une altération en mémoire vive (hollowing, injection DLL sans+ toucher au fichier) exige un outil mémoire/noyau, qui reste à la+ roadmap recherche.+ * /proc/<pid>/maps exige des privilèges type ptrace — généralement+ ceux déjà requis par la capture. Un refus dégrade en `rwx: None`.+ * Inspection locale en lecture seule : ce module ne modifie, ne tue+ ni ne débogue aucun processus.+"""++from __future__ import annotations++import hashlib+import os+import platform+import re+import threading+import time+from collections import OrderedDict+from pathlib import Path+from typing import Optional++# EN: Bounded containers — a long-running session must not grow these+# forever. / FR: Conteneurs bornés — une longue session ne doit pas+# les faire grossir indéfiniment.+_MAX_CHECKED = 4_000 # (pid, create_time) pairs already inspected+_MAX_PATHS = 2_000 # exe paths with a hash baseline+_MAX_RWX_REGIONS = 10 # regions reported per MEM_RWX alert+_RWX_MIN_SIZE = 64 * 1024 # ignore tiny rwx pages (JIT stubs)++# EN: Processes whose RWX pages are EXPECTED (JIT engines). Reported at+# "info" so they don't drown real findings — not silently skipped,+# the user can still see them.+# FR: Processus dont les pages RWX sont ATTENDUES (moteurs JIT). Signalés+# en « info » pour ne pas noyer les vrais constats — pas ignorés :+# l'utilisateur peut toujours les voir.+_KNOWN_JIT = {+ "chrome", "chromium", "firefox", "msedge", "brave", "opera", "safari",+ "node", "deno", "bun", "java", "javaw", "dotnet", "electron",+ "code", "slack", "discord", "teams", "spotify", "obsidian",+}++# EN: Name→exe comparison tolerates these decorations so legit cases like+# "python3" → /usr/bin/python3.11 don't fire.+# FR: La comparaison nom→exe tolère ces décorations pour que des cas+# légitimes comme « python3 » → /usr/bin/python3.11 n'alertent pas.+_VERSION_SUFFIX = re.compile(r"[\d.\-]+$")+++def _sha256_file(path: str, _bufsize: int = 1 << 20) -> Optional[str]:+ """EN: Streaming SHA-256 of a file — None on any failure.+ FR: SHA-256 en flux d'un fichier — None en cas d'échec."""+ try:+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for chunk in iter(lambda: f.read(_bufsize), b""):+ h.update(chunk)+ return h.hexdigest()+ except (OSError, PermissionError):+ return None+++def _names_match(name: str, exe_basename: str) -> bool:+ """EN: Loose equality — case-insensitive, strips .exe and trailing+ version numbers ("python3" vs "python3.11", "svchost" vs "svchost.exe").+ FR: Égalité souple — insensible à la casse, retire .exe et les suffixes+ de version (« python3 » vs « python3.11 »)."""+ def _norm(s: str) -> str:+ s = s.lower()+ if s.endswith(".exe"):+ s = s[:-4]+ return _VERSION_SUFFIX.sub("", s)+ return _norm(name) == _norm(exe_basename)+++class IntegrityWatcher:+ """EN: Read-only per-process integrity checks, all state bounded.+ FR: Contrôles d'intégrité par processus en lecture seule, état borné."""++ def __init__(self):+ self._lock = threading.Lock()+ self._enabled = True+ self._platform = platform.system().lower()+ # EN: (pid, create_time) → checked — the same long-lived PID is+ # only inspected once per backend run.+ # FR: (pid, create_time) → vérifié — un même PID durable n'est+ # inspecté qu'une fois par exécution du backend.+ self._checked: OrderedDict[tuple, float] = OrderedDict()+ # EN: exe path → baseline sha256 persisted across restarts.+ # FR: chemin exe → sha256 de référence persisté entre redémarrages.+ self._baselines: OrderedDict[str, str] = OrderedDict()+ # EN: path → (mtime, sha256) — re-hash only when the file's mtime+ # changed; hashing a 200 MB binary every packet would be silly.+ # 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()+ self._findings: OrderedDict[str, dict] = OrderedDict() # key → finding++ # ── Config / Configuration ──────────────────────────────────────────────++ def configure(self, enabled: bool) -> None:+ with self._lock:+ self._enabled = bool(enabled)++ @property+ def enabled(self) -> bool:+ with self._lock:+ return self._enabled++ def load_baselines(self, data: dict) -> None:+ with self._lock:+ for path, sha in (data or {}).items():+ if isinstance(path, str) and isinstance(sha, str):+ self._baselines[path] = sha+ while len(self._baselines) > _MAX_PATHS:+ self._baselines.popitem(last=False)++ def dump_baselines(self) -> dict:+ with self._lock:+ return dict(self._baselines)++ def status(self) -> dict:+ """EN: Capability + activity report for /security/integrity.+ FR: Rapport de capacité + activité pour /security/integrity."""+ with self._lock:+ return {+ "enabled": self._enabled,+ "platform": self._platform,+ "capabilities": {+ # EN: Hash + name checks work everywhere; RWX maps scan+ # is Linux-only (needs /proc).+ # FR: Hash + nom fonctionnent partout ; le scan RWX est+ # Linux seulement (besoin de /proc).+ "exe_hash_watch": True,+ "name_mismatch": True,+ "rwx_scan": self._platform == "linux",+ },+ "checked": len(self._checked),+ "baselines": len(self._baselines),+ "findings": list(self._findings.values())[-50:],+ }++ # ── Per-process checks / Contrôles par processus ────────────────────────++ def check(self, pid: int, name: str = "") -> list[dict]:+ """EN: Run all three checks for one PID. Returns finding dicts+ (empty list when clean/already-checked/unavailable). Never raises.+ FR: Lancer les trois contrôles pour un PID. Retourne des constats+ (liste vide si sain/déjà vérifié/indisponible). Ne lève jamais."""+ if not self.enabled or pid <= 3 or pid == os.getpid():+ return []+ try:+ import psutil+ proc = psutil.Process(pid)+ create_time = proc.create_time()+ key = (pid, create_time)+ with self._lock:+ if key in self._checked:+ return []+ self._checked[key] = time.time()+ while len(self._checked) > _MAX_CHECKED:+ self._checked.popitem(last=False)+ name = name or proc.name() or ""+ exe = proc.exe() or ""+ except Exception:+ return []++ findings: list[dict] = []+ if exe:+ findings += self._check_name(name, exe, pid)+ findings += self._check_hash(name, exe, pid)+ if self._platform == "linux":+ findings += self._check_rwx(pid, name)+ for f in findings:+ self._record(f)+ return findings++ def check_many(self, items: list[tuple[int, str]]) -> list[dict]:+ """EN: Batch entry point — one call per drain tick with the new+ (pid, name) pairs seen. Bounded internally.+ FR: Point d'entrée par lot — un appel par tick de vidage avec les+ couples (pid, nom) nouveaux. Borné en interne."""+ out: list[dict] = []+ for pid, name in items[:256]: # EN: cap / FR: borne+ findings = self.check(pid, name)+ for f in findings:+ f.setdefault("process", name)+ out += findings+ return out++ # ── Check 1: name vs exe / Contrôle 1 : nom vs exe ─────────────────────++ def _check_name(self, name: str, exe: str, pid: int) -> list[dict]:+ base = Path(exe).name+ if not name or not base or _names_match(name, base):+ return []+ return [{+ "type": "NAME_MISMATCH",+ "severity": "warning",+ "pid": pid,+ "exe": exe,+ "detail": f"process name '{name}' but executable is '{base}'",+ }]++ # ── Check 2: on-disk hash baseline / Contrôle 2 : hash sur disque ──────++ def _hash_for(self, path: str) -> Optional[str]:+ try:+ mtime = os.stat(path).st_mtime+ except OSError:+ return None+ with self._lock:+ cached = self._hash_cache.get(path)+ if cached and cached[0] == mtime:+ return cached[1]+ sha = _sha256_file(path)+ with self._lock:+ self._hash_cache[path] = (mtime, sha)+ while len(self._hash_cache) > _MAX_PATHS:+ self._hash_cache.popitem(last=False)+ return sha++ def _check_hash(self, name: str, exe: str, pid: int) -> list[dict]:+ sha = self._hash_for(exe)+ if not sha:+ return []+ with self._lock:+ baseline = self._baselines.get(exe)+ if baseline is None:+ self._baselines[exe] = sha+ while len(self._baselines) > _MAX_PATHS:+ self._baselines.popitem(last=False)+ return []+ if baseline == sha:+ return []+ return [{+ "type": "BINARY_CHANGED",+ "severity": "critical",+ "pid": pid,+ "exe": exe,+ "detail": "executable hash changed vs recorded baseline "+ "(file replaced or patched on disk)",+ "expected": baseline, "actual": sha,+ }]++ # ── Check 3: RWX maps (Linux) / Contrôle 3 : maps RWX (Linux) ──────────++ def _check_rwx(self, pid: int, name: str) -> list[dict]:+ """EN: Scan /proc/<pid>/maps for rwxp regions — the cheap, honest+ subset of memory-injection detection that needs no driver.+ FR: Balayer /proc/<pid>/maps à la recherche de régions rwxp — le+ sous-ensemble honnête et sans driver de la détection d'injection."""+ maps_path = Path(f"/proc/{pid}/maps")+ try:+ lines = maps_path.read_text(errors="replace").splitlines()+ except (OSError, PermissionError):+ return []+ regions: list[dict] = []+ for line in lines:+ parts = line.split(None, 5)+ if len(parts) < 2 or "rwx" not in parts[1]:+ continue+ try:+ start_s, end_s = parts[0].split("-", 1)+ size = int(end_s, 16) - int(start_s, 16)+ except (ValueError, IndexError):+ continue+ if size < _RWX_MIN_SIZE:+ continue+ regions.append({"range": parts[0], "size": size,+ "backing": (parts[5] if len(parts) > 5 else "anonymous")})+ if len(regions) >= _MAX_RWX_REGIONS:+ break+ if not regions:+ return []+ # EN: JIT processes get "info" — their RWX pages are by design.+ # FR: Les processus JIT reçoivent « info » — leurs pages RWX sont+ # prévues par conception.+ sev = "info" if (name or "").lower() in _KNOWN_JIT else "warning"+ return [{+ "type": "MEM_RWX",+ "severity": sev,+ "pid": pid,+ "detail": f"{len(regions)} rwx memory region(s) "+ f"({sum(r['size'] for r in regions) // 1024} KiB total)",+ "regions": regions,+ }]++ # ── Findings log / Journal des constats ────────────────────────────────++ def _record(self, finding: dict) -> None:+ finding = dict(finding)+ finding["ts"] = time.time()+ key = f"{finding['type']}:{finding.get('pid')}:{finding.get('exe','')}"+ with self._lock:+ self._findings[key] = finding+ while len(self._findings) > 200:+ self._findings.popitem(last=False)diff --git a/backend/tests/test_security_features.py b/backend/tests/test_security_features.pyindex a9a6bbe..7dad89e 100644--- a/backend/tests/test_security_features.py+++ b/backend/tests/test_security_features.py@@ -254,3 +254,174 @@ def test_baselines_persist_roundtrip():det2.load_baselines(dump)alerts = det2.analyze_packet(pkt(process="app"), {"country_code": "CN"})assert any(a.type == "BASELINE_DEVIATION" for a in alerts)+++# ── Firewall: domain refresh + sinkhole / Rafraîchissement + sinkhole ──────++def test_domain_refresh_updates_resolved(tmp_path, monkeypatch):+ """EN: Re-resolution applies the delta — stale IPs out, new IPs in.+ FR: La re-résolution applique le delta — IP périmées retirées,+ nouvelles ajoutées."""+ resolutions = [["203.0.113.9/32"], ["203.0.113.10/32"]]+ monkeypatch.setattr(+ FirewallManager, "_resolve_domain",+ staticmethod(lambda d: resolutions.pop(0) if resolutions else+ ["203.0.113.10/32"]))+ fw = FirewallManager(str(tmp_path))+ fw._demo = True # EN: skip OS calls+ rule = fw.add_rule("domain", "cdn.example")+ assert rule["resolved"] == ["203.0.113.9/32"]+ assert fw.refresh_domains() == 1+ assert rule["resolved"] == ["203.0.113.10/32"]+ assert fw.refresh_domains() == 0 # EN: stable now+ assert fw.check_packet(pkt(remote="203.0.113.10")) is not None+ assert fw.check_packet(pkt(remote="203.0.113.9")) is None+++def test_sinkhole_domain_writes_hosts_block(tmp_path, monkeypatch):+ """EN: A domain sinkhole writes a marked hosts block; removal strips it.+ FR: Un sinkhole de domaine écrit un bloc hosts marqué ; la suppression+ le retire."""+ hosts = tmp_path / "hosts"+ hosts.write_text("127.0.0.1 localhost\n")+ fw = FirewallManager(str(tmp_path))+ monkeypatch.setattr(fw, "_hosts_path", lambda: hosts)+ rule = fw.add_rule("domain", "ads.example", action="sinkhole")+ assert rule["applied"] is True+ body = hosts.read_text()+ assert f"# snitch-sinkhole {rule['id']} begin" in body+ assert "127.0.0.1 ads.example" in body+ fw._demo = False+ fw._remove(rule)+ body = hosts.read_text()+ assert "ads.example" not in body and "127.0.0.1 localhost" in body+++def test_sinkhole_rejects_process_and_port(tmp_path, monkeypatch):+ """EN: sinkhole is meaningless for process/port kinds.+ FR: sinkhole n'a pas de sens pour processus/port."""+ fw = _fw(tmp_path, monkeypatch)+ for kind in ("process", "port"):+ try:+ fw.add_rule(kind, "x", action="sinkhole")+ except ValueError:+ continue+ raise AssertionError(f"expected ValueError for {kind}")+++def test_sinkhole_ip_unsupported_off_linux(tmp_path, monkeypatch):+ """EN: IP sinkhole on macOS reports an honest applied=False.+ FR: Le sinkhole IP sur macOS rapporte honnêtement applied=False."""+ fw = FirewallManager(str(tmp_path))+ fw._platform = "darwin"+ monkeypatch.setattr(fw, "_hosts_path", lambda: tmp_path / "hosts")+ rule = fw.add_rule("ip", PUBLIC_IP, action="sinkhole")+ assert rule["applied"] is False+ assert "iptables" in (rule["error"] or "")+++def test_rule_action_defaults_to_block(tmp_path, monkeypatch):+ """EN: Rules created without action default to block.+ FR: Les règles créées sans action sont en « block »."""+ fw = _fw(tmp_path, monkeypatch)+ assert fw.add_rule("ip", PUBLIC_IP)["action"] == "block"+ try:+ fw.add_rule("ip", "8.8.8.8", action="bogus")+ except ValueError:+ return+ raise AssertionError("expected ValueError for bogus action")+++# ── Integrity watch / Veille d'intégrité ────────────────────────────────────++from detection.integrity import IntegrityWatcher, _names_match+++def test_names_match_tolerates_versions():+ """EN: python3 ↔ python3.11 / svchost ↔ svchost.exe are the same.+ FR: python3 ↔ python3.11 / svchost ↔ svchost.exe sont identiques."""+ assert _names_match("python3", "python3.11")+ assert _names_match("svchost", "svchost.exe")+ assert _names_match("Chrome", "chrome")+ assert not _names_match("svchost", "svch0st.exe")+++def test_integrity_name_mismatch_fires():+ """EN: A process whose name ≠ exe basename is flagged.+ FR: Un processus dont le nom ≠ basename de l'exe est signalé."""+ w = IntegrityWatcher()+ out = w._check_name("svchost", r"C:\Temp\svch0st.exe", 4242)+ assert out and out[0]["type"] == "NAME_MISMATCH"+ assert w._check_name("python3", "/usr/bin/python3.11", 1) == []+++def test_integrity_binary_changed(tmp_path):+ """EN: First hash becomes the baseline; a different file later → alert.+ FR: Le premier hash devient la baseline ; un fichier différent → alerte."""+ exe = tmp_path / "evil.bin"+ exe.write_bytes(b"version-one")+ w = IntegrityWatcher()+ assert w._check_hash("evil", str(exe), 100) == [] # baseline set+ exe.write_bytes(b"version-two-patched")+ import os as _os+ _os.utime(exe, (0, 2_000_000_000)) # EN: new mtime+ out = w._check_hash("evil", str(exe), 100)+ assert out and out[0]["type"] == "BINARY_CHANGED"+ assert out[0]["severity"] == "critical"+++def test_integrity_baselines_roundtrip(tmp_path):+ """EN: dump/load preserves baselines across watcher instances.+ FR: dump/load conserve les baselines entre instances."""+ exe = tmp_path / "app.bin"+ exe.write_bytes(b"stable")+ w = IntegrityWatcher()+ w._check_hash("app", str(exe), 1)+ w2 = IntegrityWatcher()+ w2.load_baselines(w.dump_baselines())+ exe.write_bytes(b"changed")+ import os as _os+ _os.utime(exe, (0, 2_000_000_000))+ assert w2._check_hash("app", str(exe), 1)[0]["type"] == "BINARY_CHANGED"+++def test_integrity_disabled_is_noop():+ """EN: Disabled watcher returns nothing — setting is honoured live.+ FR: Veille désactivée = silence — le réglage est honoré à chaud."""+ w = IntegrityWatcher()+ w.configure(False)+ assert w.check(1, "x") == []+ w.configure(True)+ assert w.enabled is True+++def test_integrity_status_capabilities():+ """EN: Status is honest about platform support.+ FR: Le statut est honnête sur le support plateforme."""+ s = IntegrityWatcher().status()+ assert s["capabilities"]["exe_hash_watch"] is True+ assert "rwx_scan" in s["capabilities"]+++# ── Alert explanations / Explications d'alertes ────────────────────────────++from detection import explain as _explain+++def test_explain_covers_every_type_bilingually():+ """EN: Every documented type has both languages filled.+ FR: Chaque type documenté a les deux langues remplies."""+ assert len(_explain.EXPLANATIONS) >= 15+ for t, rec in _explain.EXPLANATIONS.items():+ for k in ("title_en", "title_fr", "what_en", "what_fr",+ "why_en", "why_fr"):+ assert rec[k].strip(), f"{t}.{k} empty"+ assert len(rec["actions_en"]) == len(rec["actions_fr"]) > 0+++def test_explain_unknown_type_returns_none():+ """EN: Unknown type → None (endpoint maps it to 404).+ FR: Type inconnu → None (l'endpoint le traduit en 404)."""+ assert _explain.explain("NOPE") is None+ assert _explain.explain("") is None+ assert "THREAT_HIT" in _explain.all_types()diff --git a/backend/version.py b/backend/version.pyindex b19f446..7f38fb6 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.1.0"+__version__ = "1.2.0"diff --git a/docs/FIREWALL.de.md b/docs/FIREWALL.de.mdindex 0cbccc4..867b8e9 100644--- a/docs/FIREWALL.de.md+++ b/docs/FIREWALL.de.md@@ -84,3 +84,10 @@ bekommen `{alert, source, text}`. Fehler werden geloggt, nie fatal.Alarmen und dem Live-Graphen: Zählungen pro Typ, Kontakte inRisikoländer, unaufgelöste Hosts, Firewall-Haltung — plus Empfehlungenin Klartext. Ein *Befundbericht*, keine Zertifizierung.++### Neu in v1.2 / Nouveautés v1.2++- **Aktion `sinkhole`** — `domain`-/`ip`-Regeln können auf Loopback umleiten statt blockieren: Domains über einen markierten `# snitch-sinkhole`-Block in der hosts-Datei (alle OS), IPs/CIDRs über iptables-`DNAT` (nur Linux). `sinkhole` bei `process`/`port` wird abgelehnt; nicht unterstützte Plattformen → ehrliches `applied=False`.+- **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.diff --git a/docs/FIREWALL.es.md b/docs/FIREWALL.es.mdindex 969d09b..a5ec7ae 100644--- a/docs/FIREWALL.es.md+++ b/docs/FIREWALL.es.md@@ -85,3 +85,10 @@ loguean, nunca son fatales.alertas y el grafo: conteos por tipo, contactos con países de riesgo,hosts sin resolver, postura del firewall — y devuelve recomendaciones enlenguaje claro. Es un *informe de hallazgos*, no una certificación.++### Novedades v1.2 / Nouveautés v1.2++- **Acción `sinkhole`** — las reglas `domain`/`ip` pueden redirigir a loopback en lugar de bloquear: dominios vía un bloque marcado `# snitch-sinkhole` en el archivo hosts (todos los SO), IP/CIDR vía `DNAT` iptables (solo Linux). `sinkhole` en `process`/`port` se rechaza; plataformas no soportadas → `applied=False` honesto.+- **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é?".diff --git a/docs/FIREWALL.ja.md b/docs/FIREWALL.ja.mdindex 6785758..50eb6c3 100644--- a/docs/FIREWALL.ja.md+++ b/docs/FIREWALL.ja.md@@ -82,3 +82,10 @@ OS ネイティブファイアウォールへ best-effort で適用されます:0–100 のスコアを算出: 種別カウント、高リスク国との接触、未解決ホスト、ファイアウォール姿勢 — 平易な言葉の推奨付き。*検出レポート*であり、認定ではありません。++### v1.2 の新機能 / Nouveautés v1.2++- **`sinkhole` アクション** — `domain`/`ip` ルールはブロックの代わりに loopback へリダイレクト可能:ドメインは hosts ファイル内の `# snitch-sinkhole` マーカー付きブロックで(全 OS)、IP/CIDR は iptables `DNAT` で(Linux のみ)。`process`/`port` への `sinkhole` は拒否、非対応 OS では正直に `applied=False`。+- **ドメイン再解決** — `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 の「なぜ?」ボタンから表示。diff --git a/docs/FIREWALL.md b/docs/FIREWALL.mdindex f9e9d48..17dce0b 100644--- a/docs/FIREWALL.md+++ b/docs/FIREWALL.md@@ -18,8 +18,16 @@ applied to the OS-native firewall, best-effort:| Linux | `iptables -A OUTPUT -j DROP` (dedicated `SNITCH_LOCK` chain for lockdown) || macOS | generated `pf` anchor loaded with `pfctl` |-Rule kinds: `ip`, `cidr`, `domain` (resolved once at apply time), `process`,-`port`. Rules persist in `snitch.db` and are re-applied at startup.+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+silently unblock a name.++Rule actions: `block` (default) drops the traffic; `sinkhole` redirects it+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.**Honest limits:**@@ -29,8 +37,9 @@ Rule kinds: `ip`, `cidr`, `domain` (resolved once at apply time), `process`,rule raise `BLOCKED_ATTEMPT` alerts with per-rule counters.- macOS `pf` can't match a *process* — process rules on macOS arevisibility-only by design.-- `domain` rules resolve the name once when created; a CDN moving IPs- outruns the rule until it is re-created.+- IP/CIDR `sinkhole` is Linux-only (needs the nat table); other platforms+ record `applied=False` with the reason. `sinkhole` on `process`/`port`+ is rejected — redirecting by process/port is not meaningful.- **Lockdown** drops outbound traffic to *public* IPs only — loopback andLAN stay up so the UI remains reachable.@@ -79,8 +88,36 @@ fatal.inter-arrival times) works even for tiny keep-alive traffic.- `BLOCKED_ATTEMPT`, `LOCKDOWN`, `THREAT_HIT` — alert types added by themodules above.+- `BINARY_CHANGED`, `NAME_MISMATCH`, `MEM_RWX` — emitted by the integrity+ watch below.++### Process integrity watch++`Settings → Integrity watch` (on by default — read-only local inspection)+checks each PID that shows network activity, once per process lifetime:++- **Exe hash watch** — SHA-256 of the executable on disk; the first hash+ per path becomes a persisted baseline (`integrity_baselines`). A changed+ file under a live PID raises `BINARY_CHANGED` (critical).+- **Name/exe mismatch** — process name vs executable basename (tolerates+ `.exe` and version suffixes) → `NAME_MISMATCH` (warning), the classic+ masquerading tell.+- **RWX maps scan** — Linux only: `rwxp` regions in `/proc/<pid>/maps` ≥+ 64 KiB → `MEM_RWX`. Known JIT apps (browsers, node, java, electron) are+ reported at *info* — their RWX pages are by design.-### Security audit+Honest limits: the hash compares on-disk file states — detecting true+in-memory tampering (hollowing, reflective injection that never touches+the file) needs kernel/memory tooling and stays on the research roadmap.+`GET /security/integrity` reports capabilities + findings;+`POST /security/integrity/check` forces a re-check on one PID.++### Alert explanations++`GET /security/explain?type=<ALERT_TYPE>` returns a hand-written bilingual+(EN/FR) explanation — what the alert means, why it matters, concrete next+steps. Deterministic templates, fully offline — **not** a language model;+the UI shows it behind the "Why?" button on every alert.`GET /security/audit` computes a 0–100 score from the last 500 alerts plusthe live graph: alert-type counts, contacts to high-risk countries,@@ -106,9 +143,17 @@ appliquées au pare-feu natif de l'OS, au mieux :| Linux | `iptables -A OUTPUT -j DROP` (chaîne dédiée `SNITCH_LOCK` pour le lockdown) || macOS | ancre `pf` générée chargée avec `pfctl` |-Types de règles : `ip`, `cidr`, `domain` (résolu une fois à l'application),-`process`, `port`. Les règles persistent dans `snitch.db` et sont-réappliquées au démarrage.+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é+pour que la rotation CDN ne débloque pas un nom en silence.++Actions : `block` (défaut) droppe le trafic ; `sinkhole` le redirige vers+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.**Limites honnêtes :**@@ -118,8 +163,9 @@ réappliquées au démarrage.règle lèvent des alertes `BLOCKED_ATTEMPT` avec compteurs par règle.- `pf` sur macOS ne peut pas matcher un *processus* — les règles processusy sont par conception de la visibilité seule.-- Les règles `domain` résolvent le nom une fois à la création ; un CDN qui- change d'IP échappe à la règle jusqu'à sa recréation.+- Le `sinkhole` IP/CIDR est Linux-only (besoin de la table nat) ; les autres+ plateformes enregistrent `applied=False` avec la raison. `sinkhole` sur+ `process`/`port` est rejeté — rediriger par processus/port n'a pas de sens.- **Lockdown** ne coupe le trafic sortant que vers les IP *publiques* —loopback et LAN restent actifs pour garder l'UI joignable.@@ -168,8 +214,40 @@ sont journalisés, jamais fatals.inter-arrivées) même pour un trafic minime.- `BLOCKED_ATTEMPT`, `LOCKDOWN`, `THREAT_HIT` — types d'alertes ajoutéspar les modules ci-dessus.--### Audit de sécurité+- `BINARY_CHANGED`, `NAME_MISMATCH`, `MEM_RWX` — émis par la veille+ d'intégrité ci-dessous.++### Veille d'intégrité des processus++*Réglages → Veille d'intégrité* (activée par défaut — inspection locale+en lecture seule) contrôle chaque PID avec activité réseau, une fois par+durée de vie du processus :++- **Surveillance du hash exe** — SHA-256 de l'exécutable sur disque ; le+ premier hash par chemin devient une baseline persistée+ (`integrity_baselines`). Un fichier modifié sous un PID actif lève+ `BINARY_CHANGED` (critique).+- **Mismatch nom/exe** — nom du processus vs basename de l'exécutable+ (tolère `.exe` et les suffixes de version) → `NAME_MISMATCH` (warning),+ le signe classique de masquage.+- **Scan maps RWX** — Linux seulement : régions `rwxp` de+ `/proc/<pid>/maps` ≥ 64 Kio → `MEM_RWX`. Les apps à JIT connues+ (navigateurs, node, java, electron) sont signalées en *info* — leurs+ pages RWX sont prévues.++Limites honnêtes : le hash compare les états sur disque — détecter une+altération en mémoire vive (hollowing, injection réflexive sans toucher+au fichier) exige un outillage noyau/mémoire, à la roadmap.+`GET /security/integrity` rapporte capacités + constats ;+`POST /security/integrity/check` force une re-vérification sur un PID.++### Explications d'alertes++`GET /security/explain?type=<TYPE>` renvoie une explication bilingue+(EN/FR) écrite à la main — ce que signifie l'alerte, pourquoi elle compte,+les étapes concrètes. Gabarits déterministes, 100 % hors-ligne — **pas**+un modèle de langage ; l'UI l'affiche derrière le bouton « Pourquoi ? »+de chaque alerte.`GET /security/audit` calcule un score 0–100 depuis les 500 dernièresalertes et le graphe : comptes par type, contacts vers pays à risque,diff --git a/docs/FIREWALL.pt-BR.md b/docs/FIREWALL.pt-BR.mdindex cada95f..90b336e 100644--- a/docs/FIREWALL.pt-BR.md+++ b/docs/FIREWALL.pt-BR.md@@ -86,3 +86,10 @@ alertas e do grafo ao vivo: contagens por tipo, contatos com países derisco, hosts não resolvidos, postura do firewall — e devolverecomendações em linguagem clara. É um *relatório de achados*, não umacertificação.++### Novidades v1.2 / Nouveautés v1.2++- **Ação `sinkhole`** — regras `domain`/`ip` podem redirecionar para loopback em vez de bloquear: domínios via bloco marcado `# snitch-sinkhole` no arquivo hosts (todos os SOs), IPs/CIDRs via `DNAT` iptables (somente Linux). `sinkhole` em `process`/`port` é rejeitado; plataformas não suportadas → `applied=False` honesto.+- **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ê?".diff --git a/docs/FIREWALL.ru.md b/docs/FIREWALL.ru.mdindex 4f0802a..9459320 100644--- a/docs/FIREWALL.ru.md+++ b/docs/FIREWALL.ru.md@@ -83,3 +83,10 @@ endpoint'ы получают `{alert, source, text}`. Сбои пишутся вживому графу: счётчики по типам, контакты с рискованными странами,неразрешённые хосты, постура фаервола — и выдаёт рекомендации простымязыком. Это *отчёт находок*, а не сертификация.++### Новое в v1.2 / Nouveautés v1.2++- **Действие `sinkhole`** — правила `domain`/`ip` могут перенаправлять на loopback вместо блокировки: домены через помеченный блок `# snitch-sinkhole` в файле hosts (все ОС), IP/CIDR через `DNAT` iptables (только Linux). `sinkhole` для `process`/`port` отклоняется; неподдерживаемые платформы → честный `applied=False`.+- **Перерезолв доменов** — правила `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 показывает их за кнопкой «Почему?».diff --git a/docs/FIREWALL.zh-CN.md b/docs/FIREWALL.zh-CN.mdindex f6b7244..b4575a1 100644--- a/docs/FIREWALL.zh-CN.md+++ b/docs/FIREWALL.zh-CN.md@@ -75,3 +75,10 @@ Snitch **不**在用户态过滤数据包。规则会被尽力下发到操作系`GET /security/audit` 基于最近 500 条告警和实时图计算 0–100 分:按类型计数、与高风险国家的接触、未解析主机、防火墙姿态——并返回通俗语言的建议。这是一份*发现报告*,而非认证。++### v1.2 新功能 / Nouveautés v1.2++- **`sinkhole` 动作** — `domain`/`ip` 规则可重定向到 loopback 而非阻断:域名通过 hosts 文件中带 `# snitch-sinkhole` 标记的块(所有 OS),IP/CIDR 通过 iptables `DNAT`(仅 Linux)。`process`/`port` 的 `sinkhole` 被拒绝;不支持的平台如实返回 `applied=False`。+- **域名重解析** — `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 中每条告警的「为什么?」按钮显示。diff --git a/electron/package.json b/electron/package.jsonindex 02582fb..63333da 100644--- a/electron/package.json+++ b/electron/package.json@@ -1,7 +1,7 @@{"name": "snitch",- "version": "1.1.0",- "description": "Snitch — real-time network traffic visualizer / visualiseur de trafic réseau en temps réel",+ "version": "1.2.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","scripts": {diff --git a/frontend/package.json b/frontend/package.jsonindex 3643e03..d3a351f 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -1,9 +1,9 @@{"name": "snitch-frontend",- "version": "1.1.0",+ "version": "1.2.0","private": true,"license": "AGPL-3.0-or-later",- "description": "Snitch UI — React + D3.js / Interface React + D3.js",+ "description": "Snitch UI \u2014 React + D3.js / Interface React + D3.js","scripts": {"dev": "vite","build": "vite build",diff --git a/frontend/src/api.js b/frontend/src/api.jsindex 895e6ef..f5da579 100644--- a/frontend/src/api.js+++ b/frontend/src/api.js@@ -24,7 +24,11 @@* 4. window.prompt() — saisie manuelle en dernier recours* La promesse résolue est mise en cache — une SEULE invite peut apparaître.*/-const isElectron = window.location.protocol === 'file:'+// EN: `typeof window` guard — Vitest (Node) imports this module without a+// DOM; everything that touches `window` lazily stays inside functions.+// FR: Garde `typeof window` — Vitest (Node) importe ce module sans DOM ;+// tout ce qui touche `window` paresseusement reste dans des fonctions.+const isElectron = typeof window !== 'undefined' && window.location.protocol === 'file:'// EN: Backend port — Electron picks a FREE port at launch and exposes it via// the preload bridge (window.snitch.getPort()). Browsers/Docker use the@@ -49,7 +53,7 @@ export function getApiPort() {// must not attempt a plaintext ws://.// FR: ws/wss suit le schéma de la page — un déploiement derrière un proxy// HTTPS ne doit pas tenter un ws:// en clair.-const wsScheme = window.location.protocol === 'https:' ? 'wss' : 'ws'+const wsScheme = (typeof window !== 'undefined' && window.location.protocol === 'https:') ? 'wss' : 'ws'export async function apiBase() {if (isElectron) return `http://127.0.0.1:${await getApiPort()}`@@ -64,7 +68,9 @@ export async function wsBase() {export const API_BASE = isElectron ? 'http://127.0.0.1:8000' : ''export const WS_URL = isElectron? `${wsScheme}://127.0.0.1:8000/ws`- : `${wsScheme}://${window.location.host}/ws`+ : typeof window !== 'undefined'+ ? `${wsScheme}://${window.location.host}/ws`+ : ''let _tokenPromise = nulldiff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsxindex add3d97..5ebb7fa 100644--- a/frontend/src/components/AlertPanel.jsx+++ b/frontend/src/components/AlertPanel.jsx@@ -19,8 +19,10 @@ import {Bell, Info, AlertTriangle, AlertCircle, X,Globe, WifiOff, Wifi, ScanLine,Activity, Unlock, TrendingUp, Camera, ShieldAlert,+ FileWarning, Fingerprint, Cpu, HelpCircle,} from 'lucide-react'import { useT } from '../i18n'+import { apiBase, authHeaders } from '../api'// EN: Visual style per severity. / FR: Style visuel par sévérité.const SEVERITY_STYLES = {@@ -48,6 +50,39 @@ const TYPE_ICONS = {CLEARTEXT: Unlock,BASELINE_DEVIATION: Activity,LOCKDOWN: AlertTriangle,+ BINARY_CHANGED: FileWarning,+ NAME_MISMATCH: Fingerprint,+ MEM_RWX: Cpu,+}++/**+ * EN: On-demand bilingual explanation for one alert type — fetched from+ * GET /security/explain (deterministic templates, offline-capable).+ * Picks the <field>_<lang> variant, English fallback.+ * FR: Explication bilingue à la demande pour un type d'alerte — récupérée+ * depuis GET /security/explain (gabarits déterministes, hors-ligne).+ * Choisit la variante <champ>_<lang>, retombe sur l'anglais.+ */+function useExplanation(type, open) {+ const { lang } = useT()+ const [rec, setRec] = useState(null)+ useEffect(() => {+ if (!open || rec) return+ let cancelled = false+ ;(async () => {+ try {+ const base = await apiBase()+ const headers = await authHeaders()+ const r = await fetch(`${base}/security/explain?type=${encodeURIComponent(type)}`, { headers })+ if (r.ok && !cancelled) setRec(await r.json())+ } catch { /* explanation is a nicety — failure stays silent */ }+ })()+ return () => { cancelled = true }+ }, [open, type]) // eslint-disable-line react-hooks/exhaustive-deps+ if (!rec) return null+ const pick = (k) => rec[`${k}_${lang}`] || rec[`${k}_en`]+ const actions = rec[`actions_${lang}`] || rec.actions_en || []+ return { title: pick('title'), what: pick('what'), why: pick('why'), actions }}export function AlertBell({ unread, onClick }) {@@ -161,6 +196,8 @@ function AlertRow({ alert, onIgnore }) {const sev = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.infoconst TypeIcon = TYPE_ICONS[alert.type] || Infoconst SevIcon = sev.Icon+ const [showWhy, setShowWhy] = useState(false)+ const expl = useExplanation(alert.type, showWhy)// EN: Translate the type if a key exists, else show the raw type.// FR: Traduire le type si une clé existe, sinon afficher le type brut.const typeLabel = t(`alert_${alert.type}`) !== `alert_${alert.type}` ? t(`alert_${alert.type}`) : alert.type@@ -186,15 +223,43 @@ function AlertRow({ alert, onIgnore }) {{Object.entries(alert.details).filter(([, v]) => v).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(', ') : v}`).join(' · ')}</div>)}- {!alert._grouped && onIgnore && (- <button onClick={() => onIgnore(alert)} style={{- marginTop: 5, background: 'none', border: '1px solid var(--border)',- borderRadius: 4, padding: '2px 8px', fontSize: 9,- color: 'var(--text-muted)', cursor: 'pointer',+ {showWhy && expl && (+ <div style={{+ marginTop: 5, padding: '6px 8px', fontSize: 10, lineHeight: 1.5,+ background: 'var(--bg)', border: '1px solid var(--border)',+ borderRadius: 6, color: 'var(--text-muted)',}}>- {t('ignore_alert')}- </button>+ <div style={{ fontWeight: 700, color: 'var(--text)', marginBottom: 2 }}>{expl.title}</div>+ <div>{expl.what}</div>+ <div style={{ marginTop: 3 }}>{expl.why}</div>+ {expl.actions.length > 0 && (+ <ul style={{ margin: '4px 0 0', paddingLeft: 14 }}>+ {expl.actions.map((a, i) => <li key={i}>{a}</li>)}+ </ul>+ )}+ </div>)}+ <div style={{ display: 'flex', gap: 6, marginTop: 5 }}>+ {!alert._grouped && (+ <button onClick={() => setShowWhy(v => !v)} title={t('alert_why')} style={{+ background: 'none', border: '1px solid var(--border)',+ borderRadius: 4, padding: '2px 6px', fontSize: 9,+ color: 'var(--text-muted)', cursor: 'pointer',+ display: 'flex', alignItems: 'center', gap: 3,+ }}>+ <HelpCircle size={10} /> {t('alert_why')}+ </button>+ )}+ {!alert._grouped && onIgnore && (+ <button onClick={() => onIgnore(alert)} style={{+ background: 'none', border: '1px solid var(--border)',+ borderRadius: 4, padding: '2px 8px', fontSize: 9,+ color: 'var(--text-muted)', cursor: 'pointer',+ }}>+ {t('ignore_alert')}+ </button>+ )}+ </div></div></div><span style={{ fontSize: 9, color: 'var(--text-faint)', flexShrink: 0, marginTop: 2 }}>diff --git a/frontend/src/components/Firewall.jsx b/frontend/src/components/Firewall.jsxindex 67df600..6150bfc 100644--- a/frontend/src/components/Firewall.jsx+++ b/frontend/src/components/Firewall.jsx@@ -46,6 +46,7 @@ export function FirewallPanel({ onClose, onLockdownChange }) {const [status, setStatus] = useState(null)const [kind, setKind] = useState('ip')const [value, setValue] = useState('')+ const [action, setAction] = useState('block')const [err, setErr] = useState('')const [audit, setAudit] = useState(null)@@ -93,7 +94,7 @@ export function FirewallPanel({ onClose, onLockdownChange }) {if (!v) returnsetErr('')try {- await post('/firewall/rules', { kind, value: v })+ await post('/firewall/rules', { kind, value: v, action })setValue('')refresh()} catch (ex) { setErr(String(ex.message || ex)) }@@ -204,9 +205,15 @@ export function FirewallPanel({ onClose, onLockdownChange }) {{/* Add rule / Ajouter une règle */}<form onSubmit={addRule} style={{ display: 'flex', gap: 6, margin: '10px 0 4px' }}>- <select value={kind} onChange={e => setKind(e.target.value)} aria-label={t('fw_kind')} style={{ ...input, maxWidth: 110 }}>+ <select value={kind} onChange={e => { setKind(e.target.value); if (e.target.value === 'process' || e.target.value === 'port') setAction('block') }} aria-label={t('fw_kind')} style={{ ...input, maxWidth: 110 }}>{RULE_KINDS.map(k => <option key={k} value={k}>{t(`fw_kind_${k}`)}</option>)}</select>+ {(kind === 'ip' || kind === 'domain') && (+ <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>+ </select>+ )}<input value={value} onChange={e => setValue(e.target.value)}placeholder={t(`fw_ph_${kind}`)} aria-label={t('fw_value')}style={{ ...input, flex: 1 }} />@@ -230,6 +237,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' && (+ <span style={{+ fontSize: 9, fontWeight: 700, textTransform: 'uppercase',+ color: '#a855f7', background: 'var(--bg)', borderRadius: 4,+ padding: '1px 5px',+ }}>{t('fw_action_sinkhole')}</span>+ )}<span style={{ fontSize: 11, color: r.enabled ? 'var(--text)' : 'var(--text-faint)', fontFamily: 'monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.value}</span>diff --git a/frontend/src/components/Settings.jsx b/frontend/src/components/Settings.jsxindex a8510fa..dde4cd6 100644--- a/frontend/src/components/Settings.jsx+++ b/frontend/src/components/Settings.jsx@@ -401,6 +401,36 @@ export function SettingsPanel({ onClose, lang, setLang, watchlist = [], onWatchl<div style={{ ...hint, marginTop: 4 }}>{t('wh_privacy')}</div></div>+ {/* Integrity watch / Veille d'intégrité */}+ <div style={{ ...row, display: 'block' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div>+ <div style={label}>{t('iw_title')}</div>+ <div style={hint}>{t('iw_hint')}</div>+ </div>+ <button+ onClick={() => {+ const v = settings?.integrity_watch === false+ setSettings(s => ({ ...s, integrity_watch: v }))+ save('integrity_watch', v)+ }}+ role="switch" aria-checked={settings?.integrity_watch !== false}+ style={{+ width: 36, height: 20, borderRadius: 10, border: 'none',+ background: settings?.integrity_watch !== 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?.integrity_watch !== false ? 19 : 3,+ transition: 'left 0.15s',+ }} />+ </button>+ </div>+ <div style={{ ...hint, marginTop: 4 }}>{t('iw_privacy')}</div>+ </div>+{/* Updates (Electron only) / Mises à jour (Electron seul) */}{window.snitch?.getUpdateStatus && (<div style={{ ...row, display: 'block' }}>diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 8ca3c2e..fbc1ed2 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -332,4 +332,17 @@ export default {alertmsg_CLEARTEXT: d => `Unverschlüsselte ${d.proto}-Verbindung zu ${d.host || d.ip} von ${d.process}`,alertmsg_BASELINE_DEVIATION: d => `${d.process} kontaktierte ein neues Land: ${d.country}`,alertmsg_LOCKDOWN: () => 'Lockdown-Modus AKTIVIERT — aller ausgehender Verkehr blockiert',+ alert_BINARY_CHANGED: 'Binärdatei geändert',+ alert_NAME_MISMATCH: 'Namens-Mismatch',+ alert_MEM_RWX: 'RWX-Speicher',+ alertmsg_BINARY_CHANGED: d => `Executable auf dem Datenträger geändert: ${d.exe || d.process || '?'}`,+ alertmsg_NAME_MISMATCH: d => `Name/Exe-Mismatch: ${d.process} → ${d.exe || '?'}`,+ alertmsg_MEM_RWX: d => `Beschreibbar-ausführbarer Speicher in ${d.process || `pid ${d.pid}`}: ${d.detail || ''}`,+ alert_why: 'Warum?',+ fw_action: 'Aktion',+ fw_action_block: 'Blockieren',+ fw_action_sinkhole: 'Sinkhole',+ 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.',}diff --git a/frontend/src/locales/en.js b/frontend/src/locales/en.jsindex 78caa51..45c052e 100644--- a/frontend/src/locales/en.js+++ b/frontend/src/locales/en.js@@ -336,4 +336,17 @@ export default { // Navigationalertmsg_CLEARTEXT: d => `Unencrypted ${d.proto} connection to ${d.host || d.ip} by ${d.process}`,alertmsg_BASELINE_DEVIATION: d => `${d.process} contacted a new country: ${d.country}`,alertmsg_LOCKDOWN: () => 'Lockdown mode ENABLED — all outbound traffic blocked',+ alert_BINARY_CHANGED: 'Binary changed',+ alert_NAME_MISMATCH: 'Name mismatch',+ alert_MEM_RWX: 'RWX memory',+ alertmsg_BINARY_CHANGED: d => `Executable modified on disk: ${d.exe || d.process || '?'}`,+ alertmsg_NAME_MISMATCH: d => `Name/exe mismatch: ${d.process} → ${d.exe || '?'}`,+ alertmsg_MEM_RWX: d => `Writable-executable memory in ${d.process || `pid ${d.pid}`}: ${d.detail || ''}`,+ alert_why: 'Why?',+ fw_action: 'Action',+ fw_action_block: 'Block',+ fw_action_sinkhole: 'Sinkhole',+ 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.',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex b83d87f..9a302a3 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -330,4 +330,17 @@ export default { // Navegaciónalertmsg_CLEARTEXT: d => `Conexión ${d.proto} sin cifrar hacia ${d.host || d.ip} por ${d.process}`,alertmsg_BASELINE_DEVIATION: d => `${d.process} contactó un país nuevo: ${d.country}`,alertmsg_LOCKDOWN: () => 'Modo lockdown ACTIVADO — todo el tráfico saliente bloqueado',+ alert_BINARY_CHANGED: 'Binario modificado',+ alert_NAME_MISMATCH: 'Nombre no coincide',+ alert_MEM_RWX: 'Memoria RWX',+ alertmsg_BINARY_CHANGED: d => `Ejecutable modificado en disco: ${d.exe || d.process || '?'}`,+ alertmsg_NAME_MISMATCH: d => `Nombre/exe no coinciden: ${d.process} → ${d.exe || '?'}`,+ alertmsg_MEM_RWX: d => `Memoria escribible-ejecutable en ${d.process || `pid ${d.pid}`}: ${d.detail || ''}`,+ alert_why: '¿Por qué?',+ fw_action: 'Acción',+ fw_action_block: 'Bloquear',+ fw_action_sinkhole: 'Sinkhole',+ 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.',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex c670a1b..a9a6638 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -332,4 +332,17 @@ export default { // Navigationalertmsg_CLEARTEXT: d => `Connexion ${d.proto} non chiffrée vers ${d.host || d.ip} par ${d.process}`,alertmsg_BASELINE_DEVIATION: d => `${d.process} a contacté un nouveau pays : ${d.country}`,alertmsg_LOCKDOWN: () => 'Mode lockdown ACTIVÉ — tout le trafic sortant est bloqué',+ alert_BINARY_CHANGED: 'Binaire modifié',+ alert_NAME_MISMATCH: 'Mismatch nom',+ alert_MEM_RWX: 'Mémoire RWX',+ alertmsg_BINARY_CHANGED: d => `Exécutable modifié sur disque : ${d.exe || d.process || '?'}`,+ alertmsg_NAME_MISMATCH: d => `Mismatch nom/exe : ${d.process} → ${d.exe || '?'}`,+ alertmsg_MEM_RWX: d => `Mémoire inscriptible-exécutable dans ${d.process || `pid ${d.pid}`} : ${d.detail || ''}`,+ alert_why: 'Pourquoi ?',+ fw_action: 'Action',+ fw_action_block: 'Bloquer',+ fw_action_sinkhole: 'Sinkhole',+ 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é.",}diff --git a/frontend/src/locales/ja.js b/frontend/src/locales/ja.jsindex 648c85f..d61af43 100644--- a/frontend/src/locales/ja.js+++ b/frontend/src/locales/ja.js@@ -332,4 +332,17 @@ export default {alertmsg_CLEARTEXT: d => `${d.process} による ${d.host || d.ip} への平文 ${d.proto} 接続`,alertmsg_BASELINE_DEVIATION: d => `${d.process} が新しい国へ接続: ${d.country}`,alertmsg_LOCKDOWN: () => 'ロックダウンモード有効 — すべての外向きトラフィックをブロック',+ alert_BINARY_CHANGED: 'バイナリ変更',+ alert_NAME_MISMATCH: '名前不一致',+ alert_MEM_RWX: 'RWX メモリ',+ alertmsg_BINARY_CHANGED: d => `ディスク上の実行ファイルが変更されました: ${d.exe || d.process || '?'}`,+ alertmsg_NAME_MISMATCH: d => `名前/exe 不一致: ${d.process} → ${d.exe || '?'}`,+ alertmsg_MEM_RWX: d => `${d.process || `pid ${d.pid}`} の書き込み可能実行メモリ: ${d.detail || ''}`,+ alert_why: 'なぜ?',+ fw_action: 'アクション',+ fw_action_block: 'ブロック',+ fw_action_sinkhole: 'シンクホール',+ iw_title: '整合性監視',+ iw_hint: 'ネットワーク使用プロセスの実行ファイルをハッシュし、名前/exe の不一致と(Linux のみ)RWX メモリ領域を検知します。',+ iw_privacy: 'すべてのチェックは読み取り専用のローカル検査です — 変更も送信もされません。',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex c59758d..8f28811 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -332,4 +332,17 @@ export default {alertmsg_CLEARTEXT: d => `Conexão ${d.proto} não criptografada para ${d.host || d.ip} por ${d.process}`,alertmsg_BASELINE_DEVIATION: d => `${d.process} contatou um país novo: ${d.country}`,alertmsg_LOCKDOWN: () => 'Modo lockdown ATIVADO — todo o tráfego de saída bloqueado',+ alert_BINARY_CHANGED: 'Binário alterado',+ alert_NAME_MISMATCH: 'Nome não confere',+ alert_MEM_RWX: 'Memória RWX',+ alertmsg_BINARY_CHANGED: d => `Executável modificado em disco: ${d.exe || d.process || '?'}`,+ alertmsg_NAME_MISMATCH: d => `Nome/exe não conferem: ${d.process} → ${d.exe || '?'}`,+ alertmsg_MEM_RWX: d => `Memória gravável-executável em ${d.process || `pid ${d.pid}`}: ${d.detail || ''}`,+ alert_why: 'Por quê?',+ fw_action: 'Ação',+ fw_action_block: 'Bloquear',+ fw_action_sinkhole: 'Sinkhole',+ 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.',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex c780c54..e160e9d 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -332,4 +332,17 @@ export default {alertmsg_CLEARTEXT: d => `Незашифрованное ${d.proto}-соединение с ${d.host || d.ip} от ${d.process}`,alertmsg_BASELINE_DEVIATION: d => `${d.process} связался с новой страной: ${d.country}`,alertmsg_LOCKDOWN: () => 'Режим lockdown ВКЛЮЧЁН — весь исходящий трафик заблокирован',+ alert_BINARY_CHANGED: 'Бинарник изменён',+ alert_NAME_MISMATCH: 'Имя не совпадает',+ alert_MEM_RWX: 'RWX-память',+ alertmsg_BINARY_CHANGED: d => `Исполняемый файл изменён на диске: ${d.exe || d.process || '?'}`,+ alertmsg_NAME_MISMATCH: d => `Имя/exe не совпадают: ${d.process} → ${d.exe || '?'}`,+ alertmsg_MEM_RWX: d => `Исполняемо-записываемая память в ${d.process || `pid ${d.pid}`}: ${d.detail || ''}`,+ alert_why: 'Почему?',+ fw_action: 'Действие',+ fw_action_block: 'Блокировать',+ fw_action_sinkhole: 'Sinkhole',+ iw_title: 'Контроль целостности',+ iw_hint: 'Хэширует исполняемые файлы сетевых процессов, сигналит о несовпадении имени/exe и (Linux) RWX-регионах памяти.',+ iw_privacy: 'Все проверки — локальный доступ только для чтения: ничего не изменяется и не отправляется.',}diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.jsindex 8fef25c..6e632ed 100644--- a/frontend/src/locales/zh-CN.js+++ b/frontend/src/locales/zh-CN.js@@ -332,4 +332,17 @@ export default {alertmsg_CLEARTEXT: d => `${d.process} 与 ${d.host || d.ip} 的未加密 ${d.proto} 连接`,alertmsg_BASELINE_DEVIATION: d => `${d.process} 联系了新国家:${d.country}`,alertmsg_LOCKDOWN: () => '锁定模式已启用 — 所有出站流量被阻断',+ alert_BINARY_CHANGED: '二进制被修改',+ alert_NAME_MISMATCH: '名称不匹配',+ alert_MEM_RWX: 'RWX 内存',+ alertmsg_BINARY_CHANGED: d => `磁盘上的可执行文件已被修改: ${d.exe || d.process || '?'}`,+ alertmsg_NAME_MISMATCH: d => `名称/exe 不匹配: ${d.process} → ${d.exe || '?'}`,+ alertmsg_MEM_RWX: d => `${d.process || `pid ${d.pid}`} 中的可写可执行内存: ${d.detail || ''}`,+ alert_why: '为什么?',+ fw_action: '动作',+ fw_action_block: '阻断',+ fw_action_sinkhole: '黑洞',+ iw_title: '完整性监视',+ iw_hint: '对联网进程的可执行文件计算哈希,报告名称/exe 不匹配及(Linux)RWX 内存区域。',+ iw_privacy: '所有检查均为只读本地检查 — 不修改也不发送任何内容。',}