Skip to content

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

Add v1.5 passive inspection, verdicts and sync features

MoneyLisa8622fdfa9e16
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c7a08a..baf5ec1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,11 +6,29 @@ All notable changes to Snitch. / Toutes les modifications notables de Snitch.
The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
-## [Unreleased]
+## [1.5.0] — 2026-10-22
### Added / Ajouté
+- **Passive TLS certificate inspection / Inspection passive des certificats TLS** — `capture/tlscert.py` reassembles the server's TLS `Certificate` handshake message across TCP segments (bounded 16 KiB/flow, 256 flows, 30 s TTL) and parses the leaf DER with a minimal reader: issuer/subject CN·O, self-signed flag (strict DER equality), dNSName SANs, validity. Self-signed leaves and SAN/SNI mismatches raise `TLS_CERT`. TLS 1.3 encrypts that message — reported as unobservable, never faked. Zero MITM, zero decryption. / `capture/tlscert.py` réassemble le message Certificate du serveur à travers les segments TCP (borné) et parse le DER feuille : issuer/subject, auto-signé, SANs, validité → alerte `TLS_CERT`. TLS 1.3 chiffre ce message — rapporté inobservable, jamais simulé.
+- **ICMP payload capture + tunnel heuristic / Capture payload ICMP + heuristique tunnel** — ICMP/ICMPv6 packets now keep type/code in `flags` (type<<8|code) and their payload head in `app_head`; repeated fat echo payloads (≥24 B, 3+ in 5 min) raise `ICMP_TUNNEL` — the ptunnel/icmpsh exfiltration signature. / Les paquets ICMP/ICMPv6 gardent type/code dans `flags` et la tête du payload dans `app_head` ; des échos gros répétés → `ICMP_TUNNEL`.
+- **High-entropy cleartext detection / Détection haute entropie en clair** — near-random payload heads (≥4.7 bits/byte over ≥48 B) on non-TLS sockets raise `HIGH_ENTROPY` (info) — covert encryption/stego hint; cooled down per host. / Têtes de payload quasi aléatoires sur sockets non TLS → `HIGH_ENTROPY` (info), cooldown par hôte.
+- **Pure-Python isolation forest / Forêt d'isolation pur Python** — `detection/iforest.py` (Liu et al. 2008, ~150 lines, zero deps) + `detection/mlflow.py` score outbound flows on 6 privacy-safe features (port, size, interval, fan-out, hour); inert until 384 flows learned, `ML_ANOMALY` at score ≥0.62 with per-(process,remote) cooldown. Honest scope: unsupervised outlier vs YOUR baseline, complements heuristics. / `detection/iforest.py` (~150 lignes, zéro dépendance) + `detection/mlflow.py` scorant les flux sortants sur 6 features sûres ; inerte avant 384 flux, `ML_ANOMALY` à score ≥0,62 avec cooldown. Non supervisé vs VOTRE baseline.
+- **Ask-on-first-connect (Linux NFQUEUE) / Verdict à la première connexion** — opt-in `ask_enabled` diverts each NEW outbound flow into NFQUEUE 7 (iptables, private ranges + established exempt) and holds it up to `ask_timeout` for `POST /security/ask/verdict` allow/deny — real verdict power, decisions persist per session; timeout drops by default. Requires root + `NetfilterQueue`; `GET /security/ask` reports availability honestly (Windows/macOS need the contrib kernel tracks). / `ask_enabled` détourne chaque NOUVEAU flux vers NFQUEUE 7 et le gèle jusqu'au verdict allow/deny — vrai pouvoir de verdict ; timeout = drop. Root + `NetfilterQueue` requis ; statut honnête via `GET /security/ask`.
+- **eBPF egress enforcement / Enforcement eBPF en sortie** — `detection/ebpf_enforce.py` attaches a `BPF_PROG_TYPE_CGROUP_SKB` program at cgroup2 egress dropping destinations in a kernel map, with `isolate_pid()` reparenting a process into our dedicated cgroup for per-process filtering. Root + bcc + cgroup2; degrades to applied=False. / Programme `cgroup_skb` attaché en egress cgroup2 + `isolate_pid()` — filtrage par processus dans le noyau. Root + bcc requis.
+- **Process-hollowing evidence / Preuve de hollowing** — `POST /security/hollow` diffs a process's file-backed executable pages in `/proc/<pid>/mem` against the same ranges on disk (SHA-256, ≤64 MiB, read-only regions only) — memory≠disk means post-load patching. Linux, on-demand, never raises. / `POST /security/hollow` diff les pages exécutables mémoire vs disque — écart = patch post-chargement. Linux, à la demande.
+- **IOC peer sync (decentralized-lite) / Sync IOC entre pairs** — opt-in `gossip_peers` + `POST /remote/ioc_sync` pushes your salted-Merkle proof pack to explicitly-listed peers' authenticated `/security/iocpack/import`; per-peer results surface in `GET /remote/ioc_sync`. Hash commitments only, no discovery, no central server. / `gossip_peers` + `POST /remote/ioc_sync` pousse le paquet Merkle salé vers les pairs explicitement listés — engagements de hash seulement.
+- **Syslog alerting / Alerting syslog** — `syslog_addr` (`host:port` UDP or `tcp://`) forwards warning/critical alerts as RFC 3164 datagrams (local4 facility, severity-mapped PRI) — the SIEM/Wazuh path, independent of the webhook switch; never breaks detection on failure. / `syslog_addr` relaie les alertes en datagrammes RFC 3164 — chemin SIEM/Wazuh, indépendant du webhook, jamais bloquant.
+- **Geo-aware + actionable custom rules / Règles géo + actionnables** — new `asn`/`country` fields (local .mmdb only), `eq`/`ne`/`contains` ops; `action:"block"` additionally installs a REAL firewall rule on each newly-matched remote IP (deduped per rule+target — the flow-level kill-switch). / Champs `asn`/`country` (mmdb local) ; `action:"block"` installe une vraie règle pare-feu par IP matchée (dédupliquée — kill-switch de flux).
+- **Actionable alerts / Alertes actionnables** — alert details now carry `pid`/`process`; the UI offers one-click **Block IP** (real firewall rule), **Kill**, **Suspend**, and ASK_VERDICT **Allow/Deny** buttons; explanation templates gained remediation actions for all new types. / Les alertes portent `pid`/`process` ; l'UI propose Bloquer IP, Tuer, Suspendre et Autoriser/Refuser ; gabarits d'explication avec actions de remédiation.
+- **nftables backend / Backend nftables** — Linux firewall rules, lockdown, IP-sinkhole DNAT and domain refresh now drive `nft` directly when iptables is absent (dedicated `inet snitch` table, comment-tagged handle cleanup); per-process rules refuse honestly (no PID owner match in nft). / Règles, lockdown, DNAT sinkhole et refresh domaine pilotent `nft` quand iptables est absent ; les règles par processus refusent honnêtement.
+- **firejail sandbox fallback / Repli firejail** — Linux containment falls back to `firejail --net=none --quiet` when `unshare` is unavailable; `available()` reports which backend it will use. / Repli `firejail --net=none` quand `unshare` est absent ; `available()` rapporte le backend choisi.
+
+### Fixed / Corrigé
+
- **Real-OS integration tests / Tests d'intégration OS réels** — new `integration` CI job (per-OS) running `tests/test_integration_os.py` with `SNITCH_OS_INTEGRATION=1`: Linux proves `unshare -n` egress denial, real `iptables` DROP + live connect failure, `tc` clsact/flower, `perf_event_open`; Windows opens the real `fwpuclnt` engine and proves a WFP BLOCK filter with a TCP connect that fails then recovers after key-delete; macOS proves `sandbox-exec` deny-network end-to-end and hosts-file sinkhole apply/remove. Every test cleans up in `finally` and skips honestly when the primitive is unavailable. / Nouveau job CI `integration` par OS exécutant `tests/test_integration_os.py` : `unshare`, `iptables` réels + connexion probée, `tc`, `perf` sous Linux ; moteur WFP + blocage prouvé par connexion TCP sous Windows ; `sandbox-exec` + hosts sous macOS. Nettoyage en `finally`, skip honnête si la primitive manque.
+- **WFP filter enums + byte order / Enums WFP + ordre des octets** — real Windows CI caught `FWP_DATA_TYPE` constants off-by-N (`BYTE_ARRAY16`=11, `BYTE_BLOB`=12, composite addr-mask types at 0x100/0x101) and host-order IPv4 encoding in `FWP_V4_ADDR_AND_MASK` (must be network order); filters now actually match traffic on real Windows. / La CI Windows réelle a attrapé des constantes `FWP_DATA_TYPE` décalées et un encodage IPv4 host-order — les filtres matchent maintenant réellement.
+- **perfprobe Windows import / Import perfprobe Windows** — `fcntl` is now imported lazily inside the Linux path instead of top-level (collection crash on Windows). / `fcntl` importé paresseusement dans le chemin Linux (crash de collecte sous Windows).
## [1.4.0] — 2026-10-23
diff --git a/CITATION.cff b/CITATION.cff
index e0dbba3..2cc59cd 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -17,5 +17,5 @@ keywords:
- privacy
- traffic visualization
- cybersecurity
-version: "1.4.0"
+version: "1.5.0"
date-released: "2026-10-01"
diff --git a/PRIVACY.md b/PRIVACY.md
index 704abd0..696d23d 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -41,6 +41,26 @@ URL (Discord, Slack, Telegram bot endpoint or any URL) and flip the switch,
warning/critical alert texts are POSTed to that endpoint in real time.
Nothing is sent while the switch is off.
+**Syslog output (opt-in, off by default).** Setting `syslog_addr`
+(`host:port` for UDP, `tcp://host:port` for TCP) forwards the same
+warning/critical alert texts as RFC 3164 datagrams to your SIEM — a
+real outbound flow to the configured address, independent of the
+webhook switch.
+
+**IOC peer sync (opt-in, off by default).** Setting `gossip_peers` (a list
+of explicit Snitch backend URLs you control) lets `POST /remote/ioc_sync`
+push your salted-Merkle proof pack to those peers' authenticated import
+endpoint — and ONLY that pack (hash commitments, never raw indicators,
+never hostnames or paths). Peers must be operator-listed; there is no
+discovery and nothing is ever sent to an unlisted address.
+
+**Passive TLS certificate reading stays on the wire.** The handshake
+watcher reads the *server's own* Certificate message in cleartext —
+no interception, no injection, no decryption. TLS 1.3 encrypts that
+message, which we report honestly as unobservable. Metadata (issuer,
+subject, SANs) feeds local anomaly checks only and is never persisted
+as raw certificate bytes.
+
**Local LLM enrichment (opt-in, off by default).** When `slm_enabled` is
set, alert *metadata* (type, process, destination) may be sent to an
Ollama-compatible model endpoint — **restricted to loopback addresses
@@ -145,6 +165,29 @@ et basculez l'interrupteur, les textes des alertes warning/critiques sont
POSTés vers cet endpoint en temps réel. Rien n'est envoyé tant que
l'interrupteur est éteint.
+**Sortie syslog (opt-in, désactivée par défaut).** Régler `syslog_addr`
+(`hôte:port` en UDP, `tcp://hôte:port` en TCP) relaie les mêmes textes
+d'alertes warning/critiques en datagrammes RFC 3164 vers votre SIEM —
+un vrai flux sortant vers l'adresse configurée, indépendant de
+l'interrupteur webhook.
+
+**Sync IOC entre pairs (opt-in, désactivée par défaut).** Régler
+`gossip_peers` (liste explicite d'URL de backends Snitch que vous
+contrôlez) permet à `POST /remote/ioc_sync` de pousser votre paquet
+Merkle salé vers l'endpoint d'import authentifié de ces pairs — et
+UNIQUEMENT ce paquet (engagements de hash, jamais d'indicateurs en
+clair, jamais de noms d'hôte ni de chemins). Les pairs doivent être
+listés par l'opérateur ; aucune découverte, rien n'est jamais envoyé
+à une adresse non listée.
+
+**La lecture passive des certificats TLS reste sur le fil.** L'observateur
+de handshake lit le message Certificate *propre au serveur* en clair —
+pas d'interception, pas d'injection, pas de déchiffrement. TLS 1.3
+chiffre ce message, ce que nous rapportons honnêtement comme
+inobservable. Les métadonnées (émetteur, sujet, SANs) n'alimentent que
+les contrôles d'anomalies locaux et ne sont jamais persistées en
+octets bruts.
+
**Enrichissement LLM local (opt-in, désactivé par défaut).** Quand
`slm_enabled` est activé, les *métadonnées* d'alerte (type, processus,
destination) peuvent être envoyées à un modèle compatible Ollama —
diff --git a/README.md b/README.md
index 89353de..3bba76f 100644
--- a/README.md
+++ b/README.md
@@ -49,6 +49,15 @@ The entire interface is available in **English, Français, Español, Deutsch, Р
| 15/30/60-min Timeline | Sliding history stored locally in SQLite (24 h retention) |
| Anomaly Detection | Flags port scans, beaconing (regular-interval C2), potential exfiltration |
| Advanced Detection | DNS-tunnelling heuristic, cleartext-port spotting, per-app country baseline deviation |
+| Passive TLS Inspection | Leaf-certificate metadata read off the wire (issuer, self-signed, SAN/SNI mismatch) — TLS 1.3 honestly unobservable |
+| ICMP Tunnel Heuristic | Repeated fat echo payloads flagged — the ptunnel/icmpsh exfiltration signature |
+| ML Anomaly Scoring | Pure-Python isolation forest over your own flows (zero deps) — outlier flows flagged after ~400 samples |
+| Entropy Watch | Encrypted-looking payloads on cleartext channels (covert crypto/stego hint) |
+| Ask-on-Connect | **Opt-in** NFQUEUE verdict mode (Linux) — new flows held until you allow/deny, like Little Snitch prompts |
+| Actionable Alerts | One-click Block IP / Kill / Suspend on every alert; custom rules can auto-firewall matched hosts (`asn`/`country` fields included) |
+| Syslog / SIEM | **Opt-in** RFC 3164 output to your syslog/Wazuh collector, UDP or TCP |
+| IOC Peer Sync | **Opt-in** salted-Merkle pack exchange with explicitly-paired Snitch peers — hash commitments only, no central server |
+| Memory Forensics | On-demand process-hollowing check — executable pages in RAM diffed against disk (Linux) |
| Firewall Orchestration | Block rules (IP/CIDR/domain/process/port) applied to the OS firewall — `netsh`/`iptables`/`pf`, persisted, per-rule blocked counters |
| Lockdown Mode | Panic switch — flags & blocks all public outbound traffic, LAN stays up |
| Incident Response | Kill / suspend a process, block an IP — one click from the connection detail |
@@ -257,6 +266,15 @@ Toute l'interface est disponible en **English, Français, Español, Deutsch, Р
| Timeline 15/30/60 min | Historique glissant stocké localement dans SQLite (rétention 24 h) |
| Détection d'anomalies | Signale scans de ports, beaconing (C2 à intervalle régulier), exfiltration potentielle |
| Détection avancée | Heuristique de tunnel DNS, repérage de trafic en clair, déviation de baseline pays par application |
+| Inspection TLS passive | Métadonnées du certificat feuille lues sur le réseau (émetteur, auto-signé, mismatch SAN/SNI) — TLS 1.3 honnêtement inobservable |
+| Heuristique tunnel ICMP | Échos ICMP au payload répété et volumineux signalés — signature d'exfiltration ptunnel/icmpsh |
+| Score d'anomalie ML | Forêt d'isolation pur Python sur vos propres flux (zéro dépendance) — flux aberrants signalés après ~400 échantillons |
+| Veille d'entropie | Payloads d'apparence chiffrée sur canaux en clair (indice de crypto couverte/stégo) |
+| Ask-on-Connect | Verdict NFQUEUE **opt-in** (Linux) — les nouveaux flux sont suspendus jusqu'à votre allow/deny, façon Little Snitch |
+| Alertes actionnables | Bloquer IP / Tuer / Suspendre en un clic sur chaque alerte ; les règles custom peuvent pare-feu automatiquement (champs `asn`/`country` inclus) |
+| Syslog / SIEM | Sortie RFC 3164 **opt-in** vers votre collecteur syslog/Wazuh, UDP ou TCP |
+| Sync IOC entre pairs | Échange de packs Merkle salés **opt-in** avec des pairs Snitch explicitement appairés — engagements de hash uniquement, pas de serveur central |
+| Forensique mémoire | Vérification de process hollowing à la demande — pages exécutables en RAM comparées au disque (Linux) |
| Orchestration pare-feu | Règles de blocage (IP/CIDR/domaine/processus/port) appliquées au pare-feu OS — `netsh`/`iptables`/`pf`, persistées, compteurs de blocages |
| Mode lockdown | Bouton panique — signale & bloque tout le trafic sortant public, le LAN reste actif |
| Réponse à incident | Tuer / suspendre un processus, bloquer une IP — en un clic depuis le détail d'une connexion |
diff --git a/backend/api/main.py b/backend/api/main.py
index 3f7d42d..4c928e4 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -58,6 +58,7 @@ FR: Cœur du backend. Détenir l'état du graphe en mémoire (nœuds / arêtes /
"""
import asyncio
+import math
import ipaddress
import json
import logging
@@ -79,7 +80,7 @@ from fastapi.responses import PlainTextResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
-from api.security import ALLOWED_ORIGIN_REGEX, require_token, ws_authorized
+from api.security import ALLOWED_ORIGIN_REGEX, get_token, require_token, ws_authorized
from capture.sniffer import Packet, PacketSniffer, get_local_ips
import demo
from capture.media_monitor import MediaMonitor, MediaState
@@ -91,6 +92,7 @@ from scanner.arp_scanner import READ_STATS as _arp_stats
from detection.anomaly import AnomalyDetector, Alert
from detection.customrules import CustomRules
from capture.ebpf_probe import EbpfProbe
+from capture.tlscert import san_mismatch as _san_mismatch
from detection.deepinspect import DeepInspector, suspicious_module_paths
from detection.firewall import FirewallManager
from detection.integrity import IntegrityWatcher
@@ -99,6 +101,10 @@ from detection import explain as alert_explain
from detection import iocshare
from detection.llm_local import LocalSlm
from detection.miner import MinerDetector
+from detection.mlflow import FlowAnomaly
+from detection import askmode
+from detection import hollow as hollowmod
+from detection.gossip import PeerSync
from detection import perfprobe
from detection.sinkresponder import SinkholeResponder
from detection.threatintel import ThreatIntel
@@ -143,6 +149,44 @@ sink = SinkholeResponder() # EN: loopback :80/:443 sinkhole listener / FR
miner = MinerDetector() # EN: stratum/pool/CPU mining signals / FR: signaux de minage
slm = LocalSlm() # EN: optional localhost LLM enrichment / FR: enrichissement LLM local
custom_rules = CustomRules() # EN: user-defined alert rules / FR: règles d'alerte utilisateur
+# EN: ML flow scoring (pure-Python isolation forest) + IOC peer sync +
+# NFQUEUE ask-mode — all opt-in / self-limiting, see their modules.
+# FR: Scoring ML des flux (forêt d'isolation pur Python) + sync IOC entre
+# pairs + mode ask NFQUEUE — tous opt-in / auto-limités.
+flow_ml = FlowAnomaly()
+peer_sync = PeerSync(get_token)
+
+
+def _ask_notify(ctx: dict) -> None:
+ """EN: Called from the NFQUEUE verdict thread — hop onto the event loop
+ and surface the pending flow as a broadcast ASK_VERDICT alert.
+ FR: Appelé depuis le thread NFQUEUE — bascule sur la boucle et diffuse
+ le flux en attente comme alerte ASK_VERDICT."""
+ if _loop is None:
+ return
+ a = Alert(type="ASK_VERDICT", severity="warning",
+ message=f"New outbound flow needs a verdict: "
+ f"{ctx['remote_ip']}:{ctx['remote_port']}/{ctx['proto']} "
+ f"(auto-decision in {ctx['timeout_s']}s)",
+ node_id=ctx["remote_ip"],
+ details=dict(ctx))
+ ad = a.to_dict()
+ try:
+ db.log_alert(ad)
+ asyncio.run_coroutine_threadsafe(
+ broadcast({"type": "alert", "alert": ad}), _loop)
+ except Exception: # noqa: BLE001
+ pass
+
+
+ask_mode = askmode.AskMode(_ask_notify)
+# EN: Dedup for custom-rule block actions — one firewall rule per
+# (rule_id, remote_ip), so a chatty flow doesn't pile up rules.
+# FR: Dédup des actions block des règles — une règle pare-feu par
+# (rule_id, ip distante) pour ne pas empiler les règles.
+_rule_blocks: set[tuple] = set()
+_entropy_cooldown: dict[str, float] = {}
+_icmp_window: dict[str, list] = {}
_loop: asyncio.AbstractEventLoop | None = None
_sniffer: PacketSniffer | None = None
_scanner: ARPScanner | None = None
@@ -258,6 +302,17 @@ class IocImportBody(BaseModel):
pack: dict = Field(default_factory=dict)
+class AskVerdictBody(BaseModel):
+ """EN: /security/ask/verdict payload — allow/deny one pending flow.
+ `remember` stores the decision for the session (default True).
+ FR: Charge utile du verdict ask — autoriser/refuser un flux en
+ attente. `remember` mémorise la décision pour la session."""
+ remote_ip: str
+ remote_port: int
+ proto: str = "TCP"
+ allow: bool
+
+
class PairingBody(BaseModel):
"""EN: /remote/pairing payload — opt-in LAN exposure. `enabled`
persists a bind address applied at the NEXT backend start (uvicorn
@@ -306,12 +361,17 @@ class BlocklistBody(BaseModel):
class CustomRuleBody(BaseModel):
"""EN: /alerts/rules payload — one field, one operator, one value.
- FR: Charge utile /alerts/rules — un champ, un opérateur, une valeur."""
+ `action` is "alert" (default) or "block" (installs a real firewall
+ rule on each newly-matched remote IP — the auto kill-switch).
+ FR: Charge utile /alerts/rules — un champ, un opérateur, une valeur.
+ `action` = « alert » (défaut) ou « block » (installe une vraie règle
+ pare-feu sur chaque IP distante matchée — le kill-switch auto)."""
name: str = ""
field: str
op: str
value: str
severity: str = "warning"
+ action: str = "alert"
class ProfileBody(BaseModel):
@@ -993,15 +1053,16 @@ def _process_batch(packets: list[Packet]) -> None:
db.log_alert(ad)
out_alerts.append(ad)
- # EN: Mining signals — cleartext stratum in the payload head and
- # pool-port marking for later CPU corroboration (drain loop).
- # FR: Signaux de minage — stratum en clair dans la tête du payload
- # et marquage port-pool pour corroboration CPU (boucle drain).
# EN: User-defined alert rules — first match per packet raises
- # CUSTOM_RULE carrying the rule name (alert-only, never blocks).
+ # CUSTOM_RULE carrying the rule name. `geo` powers the asn/
+ # country fields; action="block" additionally installs a REAL
+ # firewall rule on the remote IP (deduped per rule+target —
+ # the flow-level kill-switch).
# FR: Règles d'alerte utilisateur — le premier match lève
- # CUSTOM_RULE portant le nom de la règle (alerte, jamais de blocage).
- for m in custom_rules.check(pkt)[:1]:
+ # CUSTOM_RULE portant le nom de la règle. `geo` alimente les
+ # champs asn/country ; action="block" installe en plus une
+ # vraie règle pare-feu sur l'IP distante (dédupliquée).
+ for m in custom_rules.check(pkt, geo)[:1]:
r = m["rule"]
a = Alert(
type="CUSTOM_RULE", severity=r["severity"],
@@ -1010,7 +1071,151 @@ def _process_batch(packets: list[Packet]) -> None:
+ (" by " + pkt.process_name if pkt.process_name else ""),
node_id=remote_ip,
details={"rule": r, "process": pkt.process_name,
- "direction": pkt.direction},
+ "direction": pkt.direction, "pid": pkt.pid,
+ "ip": remote_ip},
+ )
+ _flag_alert(a, nodes)
+ ad = a.to_dict()
+ db.log_alert(ad)
+ out_alerts.append(ad)
+ asyncio.get_running_loop().create_task(_notify(ad))
+ if r.get("action") == "block" and pkt.direction == "out":
+ bk = (r["id"], remote_ip)
+ if bk not in _rule_blocks and len(_rule_blocks) < 4096:
+ _rule_blocks.add(bk)
+ # EN: Kill-switch — real OS rule, best effort (needs
+ # privileges; the alert is still emitted regardless).
+ # FR: Kill-switch — vraie règle OS, au mieux (privilèges
+ # requis ; l'alerte est émise quoi qu'il arrive).
+ asyncio.get_running_loop().run_in_executor(
+ None, fw.add_rule, "ip", remote_ip, "block", 64)
+
+ # EN: Passive TLS certificate findings — self-signed leaf or a
+ # cert whose SANs do not cover the requested SNI (MitM /
+ # C2-with-bad-cert signatures). TLS 1.3 stays None → no alert.
+ # FR: Constatats passifs du certificat TLS — feuille auto-signée
+ # ou SANs ne couvrant pas le SNI demandé (signatures MitM /
+ # C2 à cert douteux). TLS 1.3 → None → pas d'alerte.
+ if pkt.tls_cert:
+ cert = pkt.tls_cert
+ reasons = []
+ if cert.get("self_signed"):
+ reasons.append("self-signed")
+ if _san_mismatch(pkt.sni, cert.get("sans") or []):
+ reasons.append(f"SANs do not cover {pkt.sni}")
+ if reasons:
+ a = Alert(
+ type="TLS_CERT", severity="warning",
+ message=f"TLS certificate anomaly for {pkt.sni or remote_ip}: "
+ f"{', '.join(reasons)} "
+ f"(issuer {cert.get('issuer_cn') or cert.get('issuer_o') or '?'})",
+ node_id=remote_ip,
+ details={"ip": remote_ip, "host": pkt.sni,
+ "issuer": cert.get("issuer_cn") or cert.get("issuer_o"),
+ "subject": cert.get("subject_cn"),
+ "reasons": reasons, "pid": pkt.pid,
+ "process": pkt.process_name},
+ )
+ _flag_alert(a, nodes)
+ ad = a.to_dict()
+ db.log_alert(ad)
+ out_alerts.append(ad)
+ asyncio.get_running_loop().create_task(_notify(ad))
+
+ # EN: High-entropy payload on a cleartext channel — real plaintext
+ # protocols (HTTP, SMTP…) compress and structure, so ~random
+ # bytes on a non-TLS port suggest covert encryption/stego or a
+ # mislabelled tunnel. Bounded: only the ≤64B head, one alert per
+ # host per 10 min.
+ # FR: Payload à haute entropie sur canal en clair — les protocoles
+ # clairs sont structurés ; des octets quasi aléatoires sur un
+ # port non TLS suggèrent du chiffrement couvert/stégo. Borné :
+ # tête ≤64 o, une alerte par hôte / 10 min.
+ if pkt.protocol == "TCP" and pkt.app_head and \
+ not pkt.app_head.startswith(b"\x16\x03") and \
+ pkt.remote_port not in (53, 853):
+ now_s = time.monotonic()
+ if now_s - _entropy_cooldown.get(remote_ip, 0) > 600:
+ head = pkt.app_head
+ freq: dict[int, int] = {}
+ for b in head:
+ freq[b] = freq.get(b, 0) + 1
+ ent = -sum((c / len(head)) * math.log2(c / len(head))
+ for c in freq.values())
+ # EN: ≥4.7 bits/byte with a mostly-full head = compressed or
+ # encrypted-looking material on a cleartext socket.
+ # FR: ≥4,7 bits/octet avec tête quasi pleine = matériau
+ # compressé/chiffré sur socket en clair.
+ if ent >= 4.7 and len(head) >= 48:
+ _entropy_cooldown[remote_ip] = now_s
+ a = Alert(
+ type="HIGH_ENTROPY", severity="info",
+ message=f"High-entropy payload on cleartext channel "
+ f"{pkt.process_name or '?'} → {remote_ip}:"
+ f"{pkt.remote_port} ({ent:.1f} bits/byte)",
+ node_id=remote_ip,
+ details={"ip": remote_ip, "port": pkt.remote_port,
+ "entropy": round(ent, 2),
+ "process": pkt.process_name, "pid": pkt.pid},
+ )
+ _flag_alert(a, nodes)
+ ad = a.to_dict()
+ db.log_alert(ad)
+ out_alerts.append(ad)
+
+ # EN: ICMP tunnel heuristic — echo requests/replies SHOULD carry ~0
+ # or timestamp-sized payloads; bulk data or a sustained stream
+ # of fat echoes is the classic ICMP exfil signature (ptunnel,
+ # icmpsh). Flags encode type<<8|code; types 8/0 = v4 echo.
+ # FR: Heuristique de tunnel ICMP — les échos devraient porter un
+ # payload quasi nul ; des données massives ou un flux soutenu
+ # d'échos gros sont la signature d'exfil ICMP classique.
+ if pkt.protocol == "ICMP" and pkt.app_head:
+ icmp_type = pkt.tcp_flags >> 8
+ if icmp_type in (0, 8, 13, 14) and len(pkt.app_head) >= 24:
+ w = _icmp_window.setdefault(remote_ip, [0, 0.0])
+ w[0] += 1
+ if time.monotonic() - w[1] > 300:
+ w[0], w[1] = 1, time.monotonic()
+ # EN: Alert on the 3rd fat echo in 5 min — one big ping is
+ # normal, a repeating pattern is not.
+ # FR: Alerte au 3e gros écho en 5 min — un gros ping est
+ # normal, pas un motif répété.
+ if w[0] == 3:
+ a = Alert(
+ type="ICMP_TUNNEL", severity="warning",
+ message=f"Possible ICMP tunnelling: repeated fat echo "
+ f"payloads ({len(pkt.app_head)}B observed) "
+ f"involving {remote_ip}",
+ node_id=remote_ip,
+ details={"ip": remote_ip, "icmp_type": icmp_type,
+ "payload_len": len(pkt.app_head),
+ "count_5m": w[0]},
+ )
+ _flag_alert(a, nodes)
+ ad = a.to_dict()
+ db.log_alert(ad)
+ out_alerts.append(ad)
+ asyncio.get_running_loop().create_task(_notify(ad))
+ if len(_icmp_window) > 2048:
+ _icmp_window.pop(next(iter(_icmp_window)))
+
+ # EN: ML flow anomaly — pure-Python isolation forest over this
+ # host's own outbound summaries (port/size/interval/fan-out/
+ # hour). Inert until 384 flows learned; score ≥0.62 → warning.
+ # FR: Anomalie ML de flux — forêt d'isolation pur Python sur les
+ # résumés sortants de cette machine. Inerte avant 384 flux ;
+ # score ≥0,62 → warning.
+ ml_hit = flow_ml.observe(pkt.process_name, remote_ip,
+ pkt.remote_port or 0, pkt.direction,
+ pkt.size)
+ if ml_hit:
+ a = Alert(
+ type="ML_ANOMALY", severity=ml_hit["severity"],
+ message=f"ML flow anomaly: {ml_hit['process']} → "
+ f"{remote_ip} — {ml_hit['detail']}",
+ node_id=remote_ip,
+ details={**ml_hit, "ip": remote_ip, "pid": pkt.pid},
)
_flag_alert(a, nodes)
ad = a.to_dict()
@@ -1018,6 +1223,10 @@ def _process_batch(packets: list[Packet]) -> None:
out_alerts.append(ad)
asyncio.get_running_loop().create_task(_notify(ad))
+ # EN: Mining signals — cleartext stratum in the payload head and
+ # pool-port marking for later CPU corroboration (drain loop).
+ # FR: Signaux de minage — stratum en clair dans la tête du payload
+ # et marquage port-pool pour corroboration CPU (boucle drain).
for f in miner.analyze_packet(pkt):
a = Alert(
type=f["type"], severity=f["severity"],
@@ -1508,7 +1717,20 @@ def _load_settings() -> None:
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 "")
+ db.get_setting("telegram_chat_id", "") or "",
+ db.get_setting("syslog_addr", "") or "")
+ # EN: Opt-in IOC peer sync — explicit peer list only, packs leave only
+ # for operator-listed addresses (detection/gossip.py).
+ # FR: Sync IOC entre pairs opt-in — liste explicite seulement.
+ peer_sync.configure(db.get_setting("gossip_peers", []) or [])
+ # EN: Ask-on-first-connect (Linux NFQUEUE) — started only when the
+ # persisted opt-in is set AND the platform allows it.
+ # FR: Ask-on-first-connect (NFQUEUE Linux) — démarré seulement si
+ # l'opt-in persisté est posé ET la plateforme le permet.
+ if db.get_setting("ask_enabled", False):
+ ok, why = ask_mode.start()
+ if not ok:
+ logger.warning("ask mode unavailable: %s", why)
# EN: Local SLM enrichment — loopback-only by construction, opt-in.
# FR: Enrichissement SLM local — loopback par construction, opt-in.
slm.configure(bool(db.get_setting("slm_enabled", False)),
@@ -1686,10 +1908,25 @@ async def post_settings(body: SettingsBody) -> dict:
if key in ("ti_provider", "ti_api_key"):
ti.configure(db.get_setting("ti_provider", "none") or "none",
db.get_setting("ti_api_key", "") or "")
- if key in ("webhook_url", "webhook_enabled", "telegram_chat_id"):
+ if key in ("webhook_url", "webhook_enabled", "telegram_chat_id",
+ "syslog_addr"):
notifier.configure(db.get_setting("webhook_url", "") or "",
bool(db.get_setting("webhook_enabled", False)),
- db.get_setting("telegram_chat_id", "") or "")
+ db.get_setting("telegram_chat_id", "") or "",
+ db.get_setting("syslog_addr", "") or "")
+ if key == "ask_enabled":
+ # EN: Live toggle of NFQUEUE ask mode — stop is always safe;
+ # start reports platform availability honestly.
+ # FR: Bascule à chaud du mode ask NFQUEUE — stop toujours sûr ;
+ # start rapporte honnêtement la disponibilité plateforme.
+ if value:
+ ok, why = ask_mode.start()
+ if not ok:
+ logger.warning("ask mode unavailable: %s", why)
+ else:
+ ask_mode.stop()
+ if key == "gossip_peers":
+ peer_sync.configure(value if isinstance(value, list) else [])
if key == "integrity_watch":
integrity.configure(bool(value))
if key == "ebpf_probe":
@@ -2468,7 +2705,7 @@ async def alert_rules_add(body: CustomRuleBody) -> dict:
correspondants lèvent CUSTOM_RULE, rien n'est bloqué."""
try:
rule = custom_rules.add(body.name, body.field, body.op,
- body.value, body.severity)
+ body.value, body.severity, body.action)
except ValueError as exc:
raise HTTPException(400, str(exc))
db.set_setting("custom_rules", custom_rules.serialized())
@@ -2754,6 +2991,69 @@ def _collect_indicators() -> list[str]:
return list(dict.fromkeys(out))[:4096]
[email protected]("/remote/ioc_sync", dependencies=_AUTH)
+async def ioc_sync_status() -> dict:
+ """EN: Peer-sync status — configured peers + per-peer last results.
+ FR: État de la sync IOC — pairs configurés + derniers résultats."""
+ return peer_sync.status()
+
+
[email protected]("/remote/ioc_sync", dependencies=_AUTH)
+async def ioc_sync_push() -> dict:
+ """EN: Push this machine's salted-Merkle proof pack to every configured
+ peer — explicit opt-in fleet sharing (settings `gossip_peers`).
+ Only hash commitments leave the box, never raw indicators.
+ FR: Pousser le paquet Merkle salé local vers chaque pair configuré —
+ partage de flotte opt-in (settings `gossip_peers`). Seuls des
+ engagements de hash quittent la machine."""
+ if not peer_sync.peers:
+ raise HTTPException(400, "no peers configured "
+ "(set gossip_peers in settings)")
+ loop = asyncio.get_running_loop()
+ indicators = await loop.run_in_executor(None, _collect_indicators)
+ pack = iocshare.build_proof_pack(indicators)
+ return await loop.run_in_executor(None, peer_sync.push_pack, pack)
+
+
[email protected]("/security/ask", dependencies=_AUTH)
+async def ask_status() -> dict:
+ """EN: Ask-on-first-connect status — platform availability + queue
+ state. Linux/NFQUEUE only; other platforms report available=false.
+ FR: État ask-on-first-connect — disponibilité plateforme + file.
+ Linux/NFQUEUE seulement."""
+ ok, why = askmode.available()
+ return {"available": ok, "reason": why, **ask_mode.status()}
+
+
[email protected]("/security/ask/verdict", dependencies=_AUTH)
+async def ask_verdict(body: AskVerdictBody) -> dict:
+ """EN: Verdict for one pending NFQUEUE flow — the packet has been held
+ since the ASK_VERDICT alert; `allow` accepts or drops it now and
+ remembers the decision for the session.
+ FR: Verdict pour un flux NFQUEUE en attente — le paquet est gelé
+ depuis l'alerte ASK_VERDICT ; `allow` l'accepte ou le droppe et
+ mémorise la décision pour la session."""
+ loop = asyncio.get_running_loop()
+ decided = await loop.run_in_executor(
+ None, ask_mode.decide, body.remote_ip, body.remote_port,
+ body.proto, body.allow)
+ return {"ok": decided,
+ "note": "flow already timed out — OS policy applied"
+ if not decided else "verdict applied"}
+
+
[email protected]("/security/hollow", dependencies=_AUTH)
+async def hollow_check(body: PidBody) -> dict:
+ """EN: On-demand memory-vs-disk hollowing check — diffs the process's
+ executable .text pages in RAM against the file on disk (Linux
+ /proc only, bounded read). Honest capability reporting.
+ FR: Contrôle de hollowing mémoire/disque à la demande — diff les
+ pages .text en RAM contre le fichier disque (Linux /proc
+ seulement, lecture bornée)."""
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(None, hollowmod.hollow_check, body.pid)
+
+
@app.post("/security/explain", dependencies=_AUTH)
async def security_explain_post(body: ExplainBody) -> dict:
"""EN: Alert explanation — deterministic bilingual templates always;
diff --git a/backend/api/notify.py b/backend/api/notify.py
index f1c0483..cecee22 100644
--- a/backend/api/notify.py
+++ b/backend/api/notify.py
@@ -9,6 +9,9 @@ EN: External alert webhooks — OPT-IN. When the user configures a webhook URL
* Discord/Slack → {"content": "**[warning]** BEACON — …"}
* Telegram → {"chat_id": <from `telegram_chat_id` setting>, "text": "…"}
* generic → full alert JSON {"alert": {...}, "source": "snitch"}
+ * syslog → `syslog_addr` setting ("host:port" or
+ "tcp://host:port") sends RFC 3164 datagrams —
+ <PRI>TIME HOST TAG: MSG — the SIEM/Wazuh path.
FR: Webhooks d'alerte externes — OPT-IN. Quand l'utilisateur configure une
URL (webhook de canal Discord, incoming webhook Slack, URL de bot
@@ -21,8 +24,10 @@ from __future__ import annotations
import json
import logging
+import socket as _socket
import threading
import urllib.request
+from datetime import datetime
logger = logging.getLogger("snitch.notify")
@@ -31,6 +36,12 @@ logger = logging.getLogger("snitch.notify")
_FORWARD = {"warning", "critical"}
_TIMEOUT_S = 8
+# EN: RFC 3164 severity mapping — local4 facility (19) so Snitch alerts can
+# be routed/filtered inside a SIEM: warning→4, critical→2.
+# FR: Mapping de sévérité RFC 3164 — facilité local4 (19) pour router les
+# alertes Snitch dans un SIEM : warning→4, critical→2.
+_SEV_TO_SYSLOG = {"warning": 4, "critical": 2}
+
class WebhookNotifier:
"""EN: Holds webhook settings + dispatches alert payloads.
@@ -41,19 +52,23 @@ class WebhookNotifier:
self._url = ""
self._enabled = False
self._chat_id = ""
+ self._syslog = ""
- def configure(self, url: str, enabled: bool, chat_id: str = "") -> None:
+ def configure(self, url: str, enabled: bool, chat_id: str = "",
+ syslog_addr: str = "") -> None:
with self._lock:
self._url = (url or "").strip()
self._enabled = bool(enabled)
self._chat_id = (chat_id or "").strip()
+ self._syslog = (syslog_addr or "").strip()
def config(self) -> dict:
with self._lock:
return {"enabled": self._enabled,
"url_set": bool(self._url),
"url_masked": (self._url[:32] + "…") if len(self._url) > 32 else self._url,
- "chat_id_set": bool(self._chat_id)}
+ "chat_id_set": bool(self._chat_id),
+ "syslog_set": bool(self._syslog)}
def dispatch(self, alert: dict) -> None:
"""EN: Synchronous POST — must run in an executor, never on the event
@@ -61,10 +76,20 @@ class WebhookNotifier:
FR: POST synchrone — à lancer dans un executor, jamais sur la boucle.
Silencieux en échec : l'alerting ne doit jamais casser la détection."""
with self._lock:
- url, enabled, chat_id = self._url, self._enabled, self._chat_id
- if not enabled or not url or alert.get("severity") not in _FORWARD:
+ url, enabled, chat_id = \
+ self._url, self._enabled, self._chat_id
+ syslog_addr = self._syslog
+ if alert.get("severity") not in _FORWARD:
return
text = f"[{alert.get('severity','').upper()}] {alert.get('type')}: {alert.get('message')}"
+ # EN: Syslog path is independent of webhook_enabled — a SIEM user
+ # may want ONLY syslog. UDP by default, tcp:// for TCP.
+ # FR: Le chemin syslog est indépendant du webhook — UDP par
+ # défaut, tcp:// pour TCP.
+ if syslog_addr:
+ self._send_syslog(syslog_addr, alert, text)
+ if not enabled or not url:
+ return
if "discord.com" in url or "slack.com" in url:
payload = {"content": f"**{text}**"}
elif "api.telegram.org" in url:
@@ -82,5 +107,33 @@ class WebhookNotifier:
except Exception as e: # noqa: BLE001
logger.debug("webhook dispatch failed: %s", e)
+ @staticmethod
+ def _send_syslog(addr: str, alert: dict, text: str) -> None:
+ """EN: RFC 3164 datagram — <PRI>Mmm dd HH:MM:SS host tag: msg.
+ `addr` is "host:port" (UDP, default) or "tcp://host:port".
+ Never raises. / FR: Datagramme RFC 3164 — ne lève jamais."""
+ try:
+ tcp = addr.startswith("tcp://")
+ target = addr[6:] if tcp else addr
+ target = target.removeprefix("udp://")
+ host, _, port_s = target.rpartition(":")
+ port = int(port_s) if port_s.isdigit() else 514
+ sev = _SEV_TO_SYSLOG.get(alert.get("severity"), 5)
+ pri = 19 * 8 + sev # EN: local4.<sev>
+ ts = datetime.now().strftime("%b %d %H:%M:%S")
+ msg = f"<{pri}>{ts} {_socket.gethostname()} " \
+ f"snitch[{alert.get('type','?')}]: {text}".encode(
+ "utf-8", "replace")
+ if tcp:
+ with _socket.create_connection(
+ (host, port), timeout=_TIMEOUT_S) as s:
+ s.sendall(msg + b"\n")
+ else:
+ with _socket.socket(_socket.AF_INET,
+ _socket.SOCK_DGRAM) as s:
+ s.sendto(msg, (host, port))
+ except Exception as e: # noqa: BLE001
+ logger.debug("syslog dispatch failed: %s", e)
+
notifier = WebhookNotifier()
diff --git a/backend/capture/parser.py b/backend/capture/parser.py
index 5d5dc5b..01c6a62 100644
--- a/backend/capture/parser.py
+++ b/backend/capture/parser.py
@@ -83,14 +83,24 @@ class ParsedPacket:
# FR: (nom d'hôte, ip demandée|None, mac) d'un message DHCP client.
dhcp: Optional[tuple] = None
# EN: First ≤64 bytes of a PLAINTEXT TCP payload — used internally by
- # the stratum/mining detector only. NEVER stored or broadcast:
- # it exists to answer "does this flow speak a known-bad cleartext
- # protocol?" and is dropped with the packet. TLS is skipped.
+ # the stratum/mining detector and the entropy check. NEVER stored
+ # or broadcast: it exists to answer "does this flow speak a
+ # known-bad cleartext protocol?" and is dropped with the packet.
+ # TLS is skipped; ICMP echoes put their payload head here.
# FR: Premiers ≤64 octets d'un payload TCP EN CLAIR — utilisé
# uniquement en interne par le détecteur stratum/minage. JAMAIS
# stocké ni diffusé : sert à répondre « ce flux parle-t-il un
# protocole malveillant en clair ? », puis jeté. TLS ignoré.
app_head: bytes = b""
+ # EN: Leaf TLS certificate metadata from the passive handshake watcher
+ # (capture/tlscert.py) — None on TLS 1.3, incomplete handshakes or
+ # non-TLS flows. ICMP echoes carry their payload head in app_head
+ # and type/code in flags (type << 8 | code).
+ # FR: Métadonnées du certificat feuille via l'observateur passif —
+ # None en TLS 1.3, handshake incomplet ou flux non TLS. Les échos
+ # ICMP portent leur tête de payload dans app_head et type/code
+ # dans flags (type << 8 | code).
+ tls_cert: Optional[dict] = None
def parse_frame(linktype: int, buf: bytes) -> Optional[ParsedPacket]:
@@ -258,21 +268,34 @@ def _parse_transport(payload: bytes, proto: int, src: str, dst: str,
flags = payload[13]
tcp_payload = payload[data_off:] if data_off <= len(payload) else b""
- sni = None
# EN: Cheap gate: TLS record starts 0x16 0x03 xx on port 443 (or SNI on
# any port — be liberal, check both endpoints' payload anyway).
# FR: Filtre rapide : un enregistrement TLS commence par 0x16 0x03 xx
# sur le port 443 (ou SNI sur tout port — rester souple).
sni = None
app_head = b""
+ tls_cert = None
if tcp_payload[:2] == b"\x16\x03":
sni = parse_tls_sni(tcp_payload)
- elif tcp_payload:
+ if tcp_payload:
# EN: Cleartext protocol fingerprinting needs only the head —
# stratum/HTTP/IRC banners all declare themselves early.
+ # TLS stays opaque: ciphertext in app_head would be useless
+ # anyway, and the privacy contract is "cleartext only".
# FR: La signature de protocole en clair n'a besoin que de la
- # tête — stratum/HTTP/IRC se déclarent tôt.
- app_head = tcp_payload[:64]
+ # tête. TLS reste opaque : du chiffré dans app_head serait
+ # inutile et le contrat vie privée dit « clair seulement ».
+ if tcp_payload[:2] != b"\x16\x03":
+ app_head = tcp_payload[:64]
+ # EN: Passive server-cert watch — bounded flow reassembly,
+ # returns the leaf cert dict once the handshake completes.
+ # Feeds on the FULL segment, independent of app_head.
+ # FR: Veille passive du certificat serveur — réassemblage borné,
+ # renvoie le cert feuille une fois le handshake complet.
+ # Se nourrit du segment complet, indépendant d'app_head.
+ from capture import tlscert
+ tls_cert = tlscert.feed_tls_stream(src, sport, dst, dport,
+ tcp_payload)
dns = []
if sport == 53 or dport == 53:
@@ -280,7 +303,7 @@ def _parse_transport(payload: bytes, proto: int, src: str, dst: str,
dns = parse_dns(tcp_payload[2:]) if len(tcp_payload) > 2 else []
return ParsedPacket(src, dst, "TCP", wire_len, sport, dport, flags,
- dns, sni, None, app_head)
+ dns, sni, None, app_head, tls_cert)
if proto == IPPROTO_UDP:
if len(payload) < 8:
@@ -318,7 +341,19 @@ def _parse_transport(payload: bytes, proto: int, src: str, dst: str,
return ParsedPacket(src, dst, "UDP", wire_len, sport, dport, 0, dns, None, dhcp)
if proto in (IPPROTO_ICMP, IPPROTO_ICMPV6):
- return ParsedPacket(src, dst, "ICMP", wire_len)
+ # EN: ICMP type/code → flags (type << 8 | code); payload head into
+ # app_head for tunnel heuristics (echo should be near-empty or
+ # timestamp-sized — bulk data in ICMP is the tunnel signature).
+ # FR: type/code ICMP → flags (type << 8 | code) ; tête du payload
+ # dans app_head pour les heuristiques de tunnel (l'écho doit
+ # être quasi vide — des données massives = signature tunnel).
+ icmp_type, icmp_code, ihead = 0, 0, b""
+ if len(payload) >= 4:
+ icmp_type, icmp_code = payload[0], payload[1]
+ ihead = payload[8:72] if len(payload) > 8 else b""
+ return ParsedPacket(src, dst, "ICMP", wire_len, 0, 0,
+ (icmp_type << 8) | icmp_code, [], None, None,
+ ihead)
return ParsedPacket(src, dst, "OTHER", wire_len)
diff --git a/backend/capture/sniffer.py b/backend/capture/sniffer.py
index 4210470..090aebc 100644
--- a/backend/capture/sniffer.py
+++ b/backend/capture/sniffer.py
@@ -106,6 +106,11 @@ class Packet:
# FR: ≤64 o. de payload en clair pour la signature de protocole en
# interne (détection mineur stratum). Interne — jamais diffusé.
app_head: bytes = b""
+ # EN: Leaf TLS cert metadata (passive handshake watch) — internal use:
+ # anomaly checks, never persisted raw. None when not observed.
+ # FR: Métadonnées du cert feuille TLS (veille passive) — usage interne
+ # (contrôles d'anomalies), jamais persistées. None sinon.
+ tls_cert: Optional[dict] = None
def get_local_ips() -> set[str]:
@@ -386,6 +391,7 @@ class PacketSniffer:
dns=parsed.dns,
dhcp=parsed.dhcp,
app_head=parsed.app_head,
+ tls_cert=parsed.tls_cert,
))
# EN: Forensic ring entry — raw frame + wire ts + attribution, so
# /forensics/pcap can export exactly what was on the wire.
diff --git a/backend/capture/tlscert.py b/backend/capture/tlscert.py
new file mode 100644
index 0000000..f675726
--- /dev/null
+++ b/backend/capture/tlscert.py
@@ -0,0 +1,306 @@
+"""
+Snitch — passive TLS certificate inspection / inspection passive des
+certificats TLS.
+
+EN: Reads the SERVER's TLS Certificate handshake message straight off the
+ wire — no MITM, no decryption, no forged certificates. We only parse
+ what the server broadcasts in cleartext during the handshake:
+ * TLS 1.2 (and 1.3-without-encryption quirks): the Certificate
+ message carries the DER chain in the open. We extract the LEAF:
+ issuer CN/O, subject CN/O, self-signed flag (issuer==subject DER),
+ dNSName SANs and validity window.
+ * TLS 1.3: Certificate is encrypted after ServerHello — honestly
+ undecodable; we return None rather than pretend.
+ Handshakes span TCP segments, so a bounded per-flow reassembly buffer
+ (16 KiB/flow, 256 flows max, 30 s TTL — ~4 MiB worst case) stitches
+ records before parsing. Everything is drop-safe: malformed DER or an
+ incomplete handshake simply yields None.
+ The DER reader is deliberately minimal — enough to walk SEQUENCE /
+ SET / OID / [0]/[3] wrappers for the TBS certificate fields we need,
+ nothing more. Issuer/subject DNs are compared as raw DER bytes, which
+ is the strict RFC notion of self-issuance.
+
+FR: Lit le message TLS Certificate du SERVEUR directement sur le fil —
+ pas de MITM, pas de déchiffrement, jamais de certificat forgé. On ne
+ parse que ce que le serveur diffuse en clair : en TLS 1.2 le message
+ Certificate porte la chaîne DER en clair → extraction du certificat
+ feuille (issuer CN/O, subject CN/O, auto-signé si issuer==subject,
+ SANs dNSName, fenêtre de validité). TLS 1.3 chiffre ce message —
+ indécidable honnêtement → None. Les handshakes s'étalent sur plusieurs
+ segments TCP : un tampon de réassemblage borné par flux (16 Kio/flux,
+ 256 flux, TTL 30 s) reconstitue les enregistrements. Tout est tolérant
+ aux erreurs : DER malformé ou handshake incomplet → None. Le lecteur
+ DER est volontairement minimal.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Optional
+
+# EN: Server ports whose replies are worth reassembling — common TLS
+# services. The ClientHello SNI path stays single-segment elsewhere.
+# FR: Ports serveur dont les réponses méritent le réassemblage — services
+# TLS courants. Le chemin SNI ClientHello reste mono-segment ailleurs.
+_TLS_PORTS = {443, 853, 465, 587, 636, 993, 995, 989, 990, 8443, 9443}
+
+_MAX_FLOWS = 256
+_MAX_BUF = 16 * 1024
+_TTL_S = 30.0
+
+# EN: flow-key → [buffer_bytes, last_seen_ts]
+# FR: clé de flux → [octets tampon, dernier ts]
+_FLOWS: dict[tuple, list] = {}
+
+
+def feed_tls_stream(src: str, sport: int, dst: str, dport: int,
+ payload: bytes) -> Optional[dict]:
+ """EN: Feed one TCP segment of a possible TLS stream; returns the leaf
+ certificate dict when a complete Certificate handshake has been
+ reassembled and parsed, else None. Call for EVERY segment of the flow —
+ the buffer handles ordering loosely (record headers self-synchronize).
+ FR: Alimenter un segment TCP d'un flux TLS possible ; renvoie le
+ certificat feuille quand un handshake Certificate complet a été
+ réassemblé, sinon None."""
+ if sport not in _TLS_PORTS or not payload:
+ return None
+ now = time.monotonic()
+ # EN: Evict expired + over-cap entries lazily on access — no sweeper.
+ # FR: Expurger les entrées expirées à l'accès — pas de balayeur.
+ if len(_FLOWS) >= _MAX_FLOWS:
+ stale = [k for k, v in _FLOWS.items() if now - v[1] > _TTL_S]
+ for k in stale:
+ _FLOWS.pop(k, None)
+ if len(_FLOWS) >= _MAX_FLOWS:
+ _FLOWS.pop(next(iter(_FLOWS)), None)
+ key = (src, sport, dst, dport)
+ ent = _FLOWS.get(key)
+ if ent is None:
+ # EN: Only start buffering at a TLS record header — avoids holding
+ # mid-stream garbage on ports that merely share a number.
+ # FR: Ne commencer à tamponner qu'au début d'un enregistrement TLS
+ # — évite de garder du bruit de milieu de flux.
+ if payload[:2] != b"\x16\x03":
+ return None
+ ent = _FLOWS[key] = [bytearray(), now]
+ ent[1] = now
+ ent[0] += payload
+ if len(ent[0]) > _MAX_BUF:
+ _FLOWS.pop(key, None)
+ return None
+ cert = _extract_certificate(bytes(ent[0]))
+ if cert is not None:
+ _FLOWS.pop(key, None) # EN: done with this flow / FR: flux terminé
+ return cert
+
+
+def _extract_certificate(buf: bytes) -> Optional[dict]:
+ """EN: Walk TLS records; find handshake type 11 (Certificate), parse the
+ first DER cert → leaf metadata. Returns None while incomplete.
+ FR: Parcourt les enregistrements TLS ; trouve le handshake type 11
+ (Certificate), parse le premier certificat DER → métadonnées feuille."""
+ off = 0
+ hs = bytearray()
+ while off + 5 <= len(buf):
+ rtype, _ver, rlen = buf[off], buf[off + 1:off + 3], \
+ int.from_bytes(buf[off + 3:off + 5], "big")
+ if rtype != 22: # EN: handshake records only
+ off += 5 + max(rlen, 0) # FR: enregistrements handshake
+ continue
+ if off + 5 + rlen > len(buf):
+ return None # EN: record still partial
+ hs += buf[off + 5:off + 5 + rlen]
+ off += 5 + rlen
+ # EN: Walk handshake messages inside the reassembled handshake bytes.
+ # FR: Parcourt les messages handshake dans les octets réassemblés.
+ hoff = 0
+ while hoff + 4 <= len(hs):
+ htype = hs[hoff]
+ hlen = int.from_bytes(hs[hoff + 1:hoff + 4], "big")
+ if hoff + 4 + hlen > len(hs):
+ return None # EN: message still partial
+ if htype == 11: # EN: Certificate / FR: Certificate
+ body = bytes(hs[hoff + 4:hoff + 4 + hlen])
+ return _parse_certificate_msg(body)
+ hoff += 4 + hlen
+ return None
+
+
+def _parse_certificate_msg(body: bytes) -> Optional[dict]:
+ """EN: TLS Certificate message body = 3-byte total len + list of
+ 3-byte-len DER certs. Parse the FIRST (leaf).
+ FR: Corps du message Certificate = longueur totale 3 octets + liste de
+ certificats DER préfixés. On parse le PREMIER (feuille)."""
+ if len(body) < 6:
+ return None
+ first_len = int.from_bytes(body[3:6], "big")
+ der = body[6:6 + first_len]
+ if len(der) < first_len or first_len < 32:
+ return None
+ try:
+ return _parse_x509_leaf(der)
+ except Exception: # noqa: BLE001 — malformed DER
+ return None
+
+
+# ── Minimal DER reader / Lecteur DER minimal ─────────────────────────────────
+
+def _tlv(buf: bytes, off: int) -> tuple[int, bytes, int]:
+ """EN: Read one DER TLV → (tag, value, next_off). Short+long lengths.
+ Raises on truncation. / FR: Lit un TLV DER → (tag, valeur, off suivant)."""
+ if off + 2 > len(buf):
+ raise ValueError("truncated")
+ tag = buf[off]
+ ln = buf[off + 1]
+ pos = off + 2
+ if ln & 0x80:
+ n = ln & 0x7F
+ if n == 0 or n > 4 or pos + n > len(buf):
+ raise ValueError("bad length")
+ ln = int.from_bytes(buf[pos:pos + n], "big")
+ pos += n
+ if pos + ln > len(buf):
+ raise ValueError("truncated value")
+ return tag, buf[pos:pos + ln], pos + ln
+
+
+def _name_to_dict(name_der: bytes) -> dict:
+ """EN: X.501 Name → {cn, o, c, der} by walking RDNSequence →
+ RDN SET → AttributeTypeAndValue SEQ {OID, value}.
+ FR: X.501 Name → {cn, o, c, der} via RDNSequence → SET → SEQ {OID,valeur}."""
+ out = {"cn": "", "o": "", "c": "", "der": name_der}
+ _, seq, _ = _tlv(name_der, 0)
+ off = 0
+ while off < len(seq):
+ _, rdn_set, off = _tlv(seq, off)
+ soff = 0
+ while soff < len(rdn_set):
+ _, atv, soff = _tlv(rdn_set, soff)
+ aoff = 0
+ _, oid, aoff = _tlv(atv, aoff)
+ _, val, _ = _tlv(atv, aoff)
+ oid_s = ".".join(str(b) for b in _decode_oid(oid))
+ try:
+ text = val.decode("utf-8", "replace")
+ except Exception:
+ text = ""
+ if oid_s == "2.5.4.3":
+ out["cn"] = text
+ elif oid_s == "2.5.4.10":
+ out["o"] = text
+ elif oid_s == "2.5.4.6":
+ out["c"] = text
+ return out
+
+
+def _decode_oid(oid: bytes) -> list[int]:
+ """EN: DER OID bytes → arc list. / FR: Octets OID DER → liste d'arcs."""
+ if not oid:
+ return []
+ arcs = [oid[0] // 40, oid[0] % 40]
+ val = 0
+ for b in oid[1:]:
+ val = (val << 7) | (b & 0x7F)
+ if not b & 0x80:
+ arcs.append(val)
+ val = 0
+ return arcs
+
+
+def _parse_x509_leaf(der: bytes) -> dict:
+ """EN: Extract leaf fields from a DER certificate:
+ issuer/subject (CN/O/C + raw DER), self_signed (issuer==subject),
+ SAN dNSNames, not_before/not_after (UTCTime/GeneralizedTime raw).
+ FR: Extrait les champs feuille d'un certificat DER : issuer/subject,
+ auto-signé (issuer==subject), SANs dNSName, fenêtre de validité brute."""
+ tag, cert, _ = _tlv(der, 0)
+ if tag != 0x30:
+ raise ValueError("not a sequence")
+ _, tbs, _ = _tlv(cert, 0)
+ off = 0
+ tag, _, off = _tlv(tbs, off) # EN: [0] version or serial
+ if tag == 0xA0: # EN: explicit version / FR: version explicite
+ _, _, off = _tlv(tbs, off) # EN: then serial / FR: puis le serial
+ _, _, off = _tlv(tbs, off) # EN: signature alg / FR: algo signature
+ # EN: issuer Name — capture the RAW TLV slice for DER equality checks.
+ # FR: issuer Name — on capture la tranche TLV brute pour l'égalité DER.
+ iss_start = off
+ _, _, off = _tlv(tbs, off)
+ issuer_der = tbs[iss_start:off]
+ _, validity, off = _tlv(tbs, off) # EN: validity / FR: validité
+ sub_start = off
+ _, _, off = _tlv(tbs, off)
+ subject_der = tbs[sub_start:off]
+ _, _, off = _tlv(tbs, off) # EN: subject PKI / FR: PKI sujet
+
+ issuer = _name_to_dict(issuer_der)
+ subject = _name_to_dict(subject_der)
+
+ # EN: validity = SEQ { notBefore, notAfter } — UTCTime/GeneralizedTime.
+ # FR: validity = SEQ { notBefore, notAfter } — UTCTime/GeneralizedTime.
+ voff = 0
+ _, nb, voff = _tlv(validity, voff)
+ _, na, _ = _tlv(validity, voff)
+ not_before = nb.decode("ascii", "replace")
+ not_after = na.decode("ascii", "replace")
+
+ # EN: Optional [3] extensions → find SAN (OID 2.5.29.17) → dNSName list.
+ # FR: Extensions [3] optionnelles → SAN (OID 2.5.29.17) → liste dNSName.
+ sans: list[str] = []
+ while off < len(tbs):
+ tag, ext_wrap, off = _tlv(tbs, off)
+ if tag != 0xA3:
+ continue
+ _, exts, _ = _tlv(ext_wrap, 0)
+ eoff = 0
+ while eoff < len(exts):
+ _, ext, eoff = _tlv(exts, eoff)
+ xoff = 0
+ _, oid, xoff = _tlv(ext, xoff)
+ if ".".join(str(b) for b in _decode_oid(oid)) != "2.5.29.17":
+ continue
+ # EN: maybe a critical BOOLEAN then the OCTET STRING value.
+ # FR: éventuel BOOLEAN critical puis l'OCTET STRING valeur.
+ tag, val, xoff = _tlv(ext, xoff)
+ if tag == 0x01:
+ _, val, _ = _tlv(ext, xoff)
+ _, san_seq, _ = _tlv(val, 0)
+ goff = 0
+ while goff < len(san_seq):
+ gtag, gval, goff = _tlv(san_seq, goff)
+ if gtag == 0x82: # EN: dNSName IA5String / FR: dNSName IA5String
+ sans.append(gval.decode("ascii", "replace"))
+
+ return {
+ "issuer_cn": issuer["cn"], "issuer_o": issuer["o"],
+ "subject_cn": subject["cn"], "subject_o": subject["o"],
+ "self_signed": issuer_der == subject_der,
+ "sans": sans[:24],
+ "not_before": not_before, "not_after": not_after,
+ }
+
+
+def san_mismatch(sni: Optional[str], sans: list[str]) -> bool:
+ """EN: True when the ClientHello SNI is not covered by any SAN —
+ wildcard-aware (*.example.com covers a.example.com only).
+ FR: Vrai si le SNI du ClientHello n'est couvert par aucun SAN —
+ sensible aux wildcards."""
+ if not sni or not sans:
+ return False
+ sni = sni.lower().rstrip(".")
+ for pat in sans:
+ pat = pat.lower().rstrip(".")
+ if pat == sni:
+ return False
+ if pat.startswith("*."):
+ suffix = pat[1:] # EN: ".example.com"
+ if sni.endswith(suffix) and "." not in \
+ sni[:-len(suffix)]:
+ return False
+ return True
+
+
+def reset() -> None:
+ """EN: Drop all flow buffers (tests / shutdown).
+ FR: Vide les tampons de flux (tests / arrêt)."""
+ _FLOWS.clear()
diff --git a/backend/detection/anomaly.py b/backend/detection/anomaly.py
index 5de19f3..4dea020 100644
--- a/backend/detection/anomaly.py
+++ b/backend/detection/anomaly.py
@@ -519,6 +519,17 @@ class AnomalyDetector:
# FR: Écarter les alertes supprimées avant l'enregistrement —
# règles « ignorer cet hôte/ce type » persistées depuis l'UI.
alerts = [a for a in alerts if not self._suppressed(a.type, remote_ip)]
+ # EN: Make every packet alert actionable — the UI offers one-click
+ # Kill/Suspend (pid) and Block-IP (remote_ip is already in
+ # details.ip on every rule that has one).
+ # FR: Rendre chaque alerte actionnable — l'UI propose Tuer/
+ # Suspendre en un clic (pid) et Bloquer l'IP (remote_ip est
+ # déjà dans details.ip des règles concernées).
+ for a in alerts:
+ if pkt.pid and "pid" not in a.details:
+ a.details["pid"] = pkt.pid
+ if pkt.process_name and "process" not in a.details:
+ a.details["process"] = pkt.process_name
self._record(alerts)
return alerts
diff --git a/backend/detection/askmode.py b/backend/detection/askmode.py
new file mode 100644
index 0000000..639b751
--- /dev/null
+++ b/backend/detection/askmode.py
@@ -0,0 +1,267 @@
+"""
+Snitch — interactive ask-on-first-connect (Linux NFQUEUE) / demande
+interactive à la première connexion (NFQUEUE Linux).
+
+EN: The honest user-mode slice of "ask before letting a new outbound flow
+ out" — no kernel driver needed on Linux thanks to NFQUEUE: packets
+ matching an iptables rule are handed to a user-space verdict callback
+ that can ACCEPT or DROP them. We divert the FIRST outbound packet of
+ each unseen (remote_ip, remote_port, proto) flow into queue 7, hold it
+ pending the analyst's decision via the API, then apply the verdict.
+ Decisions persist per flow-key for the session, so only the first
+ packet of each flow ever waits.
+
+ * opt-in only: enable via settings ask_enabled=1 (needs root +
+ libnetfilter_queue — python package `NetfilterQueue`)
+ * iptables rule installed: `OUTPUT -j NFQUEUE --queue-num 7` minus
+ exemptions for loopback/LAN (the API itself must stay reachable)
+ * timeout policy `ask_timeout`: after N seconds with no verdict the
+ packet is dropped (secure default) or accepted (ask_failopen=1)
+ * flows the user already ruled on go straight through — this is
+ ask-on-first-connect, not ask-every-packet
+
+ This is REAL verdict power (Little-Snitch-style): the connection is
+ genuinely suspended until you answer. Platform scope: Linux only;
+ Windows/macOS need the kernel callout / NetworkExtension tracks
+ (contrib/) — reported honestly by available().
+
+FR: La tranche user-mode honnête du « demander avant de laisser sortir un
+ nouveau flux » — sans driver noyau sous Linux grâce à NFQUEUE : les
+ paquets matchés par iptables sont remis à un callback user-space qui
+ les ACCEPTe ou les DROPpe. On détourne le PREMIER paquet sortant de
+ chaque flux (ip, port, proto) inconnu vers la file 7, on le gèle en
+ attendant le verdict de l'analyste via l'API, puis on applique.
+ Opt-in uniquement (root + libnetfilter_queue requis). Politique de
+ timeout : drop par défaut (ask_failopen=1 pour accepter). Linux
+ seulement — Windows/macOS passent par les pistes noyau (contrib/).
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import platform
+import threading
+import time
+from typing import Callable, Optional
+
+logger = logging.getLogger(__name__)
+
+_QUEUE_NUM = 7
+_MAX_PENDING = 512
+_DEFAULT_TIMEOUT = 15.0
+
+
+def available() -> tuple[bool, str]:
+ """EN: Linux + root + NetfilterQueue importable + libnetfilter_queue.
+ FR: Linux + root + NetfilterQueue importable + libnetfilter_queue."""
+ if platform.system().lower() != "linux":
+ return False, "NFQUEUE is linux-only (windows/macOS need kernel " \
+ "callouts — see contrib/)"
+ try:
+ import netfilterqueue # noqa: F401
+ except ImportError:
+ return False, "python package `NetfilterQueue` + libnetfilter_queue " \
+ "required (pip install NetfilterQueue, apt install " \
+ "libnetfilter-queue1)"
+ if os.geteuid() != 0:
+ return False, "needs root (CAP_NET_ADMIN) for iptables + NFQUEUE"
+ return True, ""
+
+
+class AskMode:
+ """EN: Owns the NFQUEUE verdict loop + pending-flow table.
+ FR: Gère la boucle de verdict NFQUEUE + la table des flux en attente."""
+
+ def __init__(self, on_ask: Callable[[dict], None],
+ timeout: float = _DEFAULT_TIMEOUT,
+ failopen: bool = False):
+ self._on_ask = on_ask # EN: emit ASK_VERDICT alert / FR: émet l'alerte
+ self._timeout = max(3.0, min(float(timeout), 120.0))
+ self._failopen = failopen
+ self._nfq = None
+ self._thread: Optional[threading.Thread] = None
+ self._running = False
+ # EN: flow-key → (event, pkt, ts) pending verdict; decided → verdict
+ # FR: clé de flux → (event, pkt, ts) en attente ; décidé → verdict
+ self._pending: dict[tuple, list] = {}
+ self._decided: dict[tuple, bool] = {}
+ self._lock = threading.Lock()
+ self._rule_installed = False
+
+ # ── lifecycle / cycle de vie ──────────────────────────────────────────
+
+ def start(self) -> tuple[bool, str]:
+ ok, why = available()
+ if not ok:
+ return False, why
+ import subprocess
+ try:
+ from netfilterqueue import NetfilterQueue
+ except ImportError as e: # pragma: no cover
+ return False, str(e)
+ try:
+ self._nfq = NetfilterQueue()
+ self._nfq.bind(_QUEUE_NUM, self._verdict_cb)
+ except Exception as e: # noqa: BLE001
+ self._nfq = None
+ return False, f"nfqueue bind failed: {e}"
+ # EN: Divert outbound SYN/non-established flows into queue 7 —
+ # private ranges exempt so the LAN/UI never stalls.
+ # FR: Détourne les flux sortants non établis vers la file 7 —
+ # plages privées exemptées pour ne pas geler le LAN/l'UI.
+ cmds = [
+ ["iptables", "-w", "-I", "OUTPUT", "-o", "lo", "-j", "RETURN"],
+ ["iptables", "-w", "-I", "OUTPUT", "-m", "conntrack",
+ "--ctstate", "ESTABLISHED,RELATED", "-j", "RETURN"],
+ ["iptables", "-w", "-I", "OUTPUT", "-d", "127.0.0.0/8",
+ "-j", "RETURN"],
+ ["iptables", "-w", "-I", "OUTPUT", "-d", "10.0.0.0/8",
+ "-j", "RETURN"],
+ ["iptables", "-w", "-I", "OUTPUT", "-d", "172.16.0.0/12",
+ "-j", "RETURN"],
+ ["iptables", "-w", "-I", "OUTPUT", "-d", "192.168.0.0/16",
+ "-j", "RETURN"],
+ ["iptables", "-w", "-I", "OUTPUT", "-j", "NFQUEUE",
+ "--queue-num", str(_QUEUE_NUM)],
+ ]
+ for c in cmds:
+ try:
+ subprocess.run(c, timeout=10, check=False,
+ capture_output=True)
+ except OSError as e:
+ self.stop()
+ return False, f"iptables failed: {e}"
+ self._rule_installed = True
+ self._running = True
+ self._thread = threading.Thread(target=self._run, daemon=True,
+ name="snitch-askmode")
+ self._thread.start()
+ return True, ""
+
+ def _run(self) -> None:
+ try:
+ self._nfq.run()
+ except Exception as e: # noqa: BLE001
+ logger.warning("askmode nfqueue loop ended: %s", e)
+ finally:
+ self._running = False
+
+ def stop(self) -> None:
+ self._running = False
+ try:
+ if self._nfq is not None:
+ self._nfq.unbind()
+ except Exception: # noqa: BLE001
+ pass
+ if self._rule_installed:
+ import subprocess
+ subprocess.run(["iptables", "-w", "-D", "OUTPUT", "-j",
+ "NFQUEUE", "--queue-num", str(_QUEUE_NUM)],
+ timeout=10, check=False, capture_output=True)
+ self._rule_installed = False
+ with self._lock:
+ self._pending.clear()
+ self._decided.clear()
+
+ # ── verdict path / chemin du verdict ─────────────────────────────────
+
+ @staticmethod
+ def _flow_key(payload: bytes) -> Optional[tuple]:
+ """EN: Extract (remote_ip, remote_port, proto) from the raw IPv4/6
+ packet payload NFQUEUE hands us — only TCP/UDP outbound matters.
+ FR: Extrait (ip, port, proto) du paquet brut NFQUEUE — TCP/UDP
+ sortants seulement."""
+ try:
+ ver = payload[0] >> 4
+ if ver == 4:
+ ihl = (payload[0] & 0x0F) * 4
+ proto = payload[9]
+ dst = ".".join(str(b) for b in payload[16:20])
+ l4 = payload[ihl:]
+ elif ver == 6:
+ proto = payload[6]
+ dst = ":".join(f"{payload[24+i]:02x}{payload[25+i]:02x}"
+ for i in range(0, 16, 2))
+ l4 = payload[40:]
+ else:
+ return None
+ if proto == 6:
+ dport = int.from_bytes(l4[2:4], "big")
+ # EN: only SYN (first) packets get asked; the rest of the
+ # handshake rides the stored decision.
+ # FR: seuls les SYN (premiers paquets) interrogent ; le
+ # reste du handshake suit la décision stockée.
+ if len(l4) > 13 and not (l4[13] & 0x02):
+ return None
+ return (dst, dport, "TCP")
+ if proto == 17:
+ dport = int.from_bytes(l4[2:4], "big")
+ return (dst, dport, "UDP")
+ except (IndexError, ValueError):
+ return None
+ return None
+
+ def _verdict_cb(self, pkt) -> None:
+ try:
+ payload = pkt.get_payload()
+ key = self._flow_key(payload)
+ if key is None:
+ pkt.accept()
+ return
+ with self._lock:
+ verdict = self._decided.get(key)
+ if verdict is not None:
+ (pkt.accept if verdict else pkt.drop)()
+ return
+ # EN: Pending table bounded — overflow accepts (fail-open on
+ # capacity, documented; timeout policy is separate).
+ # FR: Table bornée — débordement accepte (fail-open capacitaire,
+ # documenté ; la politique de timeout est à part).
+ with self._lock:
+ if len(self._pending) >= _MAX_PENDING:
+ pkt.accept()
+ return
+ ev = threading.Event()
+ self._pending[key] = [ev, pkt, time.monotonic()]
+ self._on_ask({"type": "ASK_VERDICT", "remote_ip": key[0],
+ "remote_port": key[1], "proto": key[2],
+ "timeout_s": int(self._timeout)})
+ if not ev.wait(self._timeout):
+ with self._lock:
+ self._pending.pop(key, None)
+ self._decided[key] = self._failopen
+ (pkt.accept if self._failopen else pkt.drop)()
+ except Exception: # noqa: BLE001
+ try:
+ pkt.accept() # EN: never wedge the host
+ except Exception: # noqa: BLE001
+ pass
+
+ def decide(self, remote_ip: str, remote_port: int, proto: str,
+ allow: bool) -> bool:
+ """EN: API entry — verdict for a pending flow; returns False if the
+ flow already timed out. / FR: Entrée API — verdict pour un flux en
+ attente ; False si le flux a déjà expiré."""
+ key = (remote_ip, int(remote_port), (proto or "TCP").upper())
+ with self._lock:
+ ent = self._pending.pop(key, None)
+ self._decided[key] = bool(allow)
+ if ent is None:
+ return False
+ ev, pkt, _ = ent
+ try:
+ (pkt.accept if allow else pkt.drop)()
+ except Exception: # noqa: BLE001
+ pass
+ ev.set()
+ return True
+
+ def status(self) -> dict:
+ with self._lock:
+ return {"running": self._running,
+ "queue": _QUEUE_NUM if self._rule_installed else None,
+ "pending": len(self._pending),
+ "decided": len(self._decided),
+ "timeout_s": self._timeout,
+ "failopen": self._failopen}
diff --git a/backend/detection/contain.py b/backend/detection/contain.py
index dd561bc..cf80fc8 100644
--- a/backend/detection/contain.py
+++ b/backend/detection/contain.py
@@ -59,7 +59,13 @@ def available() -> tuple[bool, str]:
if _SYSTEM == "linux":
if shutil.which("unshare"):
return True, "linux user+net namespace (unshare -U -n)"
- return False, "no unshare binary"
+ # EN: firejail is a common pre-installed sandbox — `--net=none`
+ # gives the same zero-egress guarantee as our namespace path.
+ # FR: firejail est souvent pré-installé — `--net=none` donne la
+ # même garantie zéro-égress que le namespace.
+ if shutil.which("firejail"):
+ return True, "linux firejail (--net=none)"
+ return False, "no unshare or firejail binary"
if _SYSTEM == "darwin":
if shutil.which("sandbox-exec"):
return True, "macOS seatbelt (sandbox-exec deny network*)"
@@ -79,8 +85,14 @@ def sandbox_command(path: str, args: list[str]) -> list[str]:
préfère `unshare -U -n` ; si les userns non privilégiés sont
désactivés au boot, l'enfant renvoie EPERM — rapporté, pas simulé."""
if _SYSTEM == "linux":
- return ["unshare", "--user", "--net", "--map-root-user",
- "--fork", path, *args]
+ if shutil.which("unshare"):
+ return ["unshare", "--user", "--net", "--map-root-user",
+ "--fork", path, *args]
+ # EN: --net=none removes all interfaces except loopback; --quiet
+ # keeps firejail's own banner out of the captured output.
+ # FR: --net=none retire toutes les interfaces sauf loopback ;
+ # --quiet garde la bannière firejail hors de la sortie.
+ return ["firejail", "--net=none", "--quiet", "--", path, *args]
if _SYSTEM == "darwin":
return ["sandbox-exec", "-p", _MACOS_PROFILE, path, *args]
return [path, *args] # EN: never reached — caller checks available() first
diff --git a/backend/detection/customrules.py b/backend/detection/customrules.py
index 560e011..11359f3 100644
--- a/backend/detection/customrules.py
+++ b/backend/detection/customrules.py
@@ -6,13 +6,16 @@ EN: User-defined alert rules — a deliberately SMALL matcher, not a
own detections ("warn me when curl touches port 4444", "flag any
process talking to *.onion-ish hosts") without waiting for a Snitch
release. Rules are persisted in the settings table and matched
- in-line in the packet path — they only ALERT, they never block
- (blocking stays the firewall's job).
+ in-line in the packet path. The default action ALERTS only; a rule
+ may opt into action="block" which additionally installs a real
+ firewall rule on the matched remote host (deduped per rule+target).
Supported fields : remote_ip, host (SNI or DNS answer name),
process_name, remote_port, protocol, direction,
- size.
+ size, asn, country (from the local geo DB).
Supported ops : eq, ne, contains, regex, gt, lt, cidr.
+ Actions : alert (default) | block (firewall rule on the
+ matched remote_ip — the per-flow kill-switch).
Regex is bounded (pattern <= 200 chars, applied with a per-packet
compiled cache of <= 64 patterns) so a bad rule cannot DoS the
packet path; an invalid rule fails validation at creation.
@@ -23,9 +26,11 @@ FR: Règles d'alerte définies par l'utilisateur — un filtreur
active qui matche lève une alerte CUSTOM_RULE portant son nom, pour
construire ses propres détections sans attendre une release. Les
règles sont persistées dans la table settings et évaluées en ligne
- dans le chemin paquet — elles ALERTENT seulement, jamais de blocage
- (c'est le travail du pare-feu). Regex bornée pour qu'une mauvaise
- règle ne puisse pas DoS le pipeline.
+ dans le chemin paquet. L'action par défaut ALERTE seulement ; une
+ règle peut opter pour action="block" qui installe de plus une vraie
+ règle pare-feu sur l'hôte distant matché (dédupliquée par
+ règle+cible). Regex bornée pour qu'une mauvaise règle ne puisse pas
+ DoS le pipeline.
"""
from __future__ import annotations
@@ -37,9 +42,16 @@ import uuid
from typing import Optional
_FIELDS = ("remote_ip", "host", "process_name", "remote_port",
- "protocol", "direction", "size")
+ "protocol", "direction", "size", "asn", "country")
_OPS = ("eq", "ne", "contains", "regex", "gt", "lt", "cidr")
_SEVERITIES = ("info", "warning", "critical")
+# EN: "alert" (default) emits CUSTOM_RULE only; "block" additionally
+# creates a real firewall rule for the matched target — the per-app
+# kill-switch / auto-block path the UI asks for.
+# FR: « alert » (défaut) émet CUSTOM_RULE seulement ; « block » crée de
+# plus une vraie règle pare-feu sur la cible matchée — le kill-switch
+# par application demandé par l'UI.
+_ACTIONS = ("alert", "block")
_MAX_RULES = 256
_MAX_PATTERN = 200
_MAX_COMPILED = 64
@@ -82,6 +94,21 @@ class CustomRules:
raise ValueError(f"unknown op: {rule.get('op')}")
if rule.get("severity", "warning") not in _SEVERITIES:
raise ValueError(f"unknown severity: {rule.get('severity')}")
+ if rule.get("action", "alert") not in _ACTIONS:
+ raise ValueError(f"unknown action: {rule.get('action')}")
+ # EN: asn/country need the local geo DB — eq/ne/contains on the
+ # resolved value only; cidr/gt/lt would be meaningless.
+ # FR: asn/country exigent la base geo locale — eq/ne/contains sur
+ # la valeur résolue seulement.
+ if rule.get("field") in ("asn", "country") and \
+ rule.get("op") not in ("eq", "ne", "contains"):
+ raise ValueError(f"op {rule.get('op')} not meaningful for "
+ f"{rule.get('field')}")
+ if rule.get("action") == "block" and \
+ rule.get("field") not in ("remote_ip", "host",
+ "process_name", "asn", "country"):
+ raise ValueError("block action needs a blockable field "
+ "(remote_ip/host/process_name/asn/country)")
value = str(rule.get("value", ""))
if not value:
raise ValueError("empty value")
@@ -98,7 +125,7 @@ class CustomRules:
int(value) # EN: numeric ops need numbers / FR: ops numériques
def add(self, name: str, field: str, op: str, value: str,
- severity: str = "warning") -> dict:
+ severity: str = "warning", action: str = "alert") -> dict:
if len(self._rules) >= _MAX_RULES:
raise ValueError("rule limit reached")
rule = {
@@ -106,6 +133,7 @@ class CustomRules:
"name": (name or "").strip()[:120] or f"{field} {op} {value}",
"field": field, "op": op, "value": str(value).strip(),
"severity": severity, "enabled": True,
+ "action": action or "alert",
"hits": 0, "created": time.time(),
}
self._validate(rule)
@@ -130,7 +158,7 @@ class CustomRules:
# ── matching / correspondance ────────────────────────────────────────────
@staticmethod
- def _field_value(pkt, field: str):
+ def _field_value(pkt, field: str, geo: Optional[dict] = None):
"""EN: Extract the comparable value from a Packet.
FR: Extraire la valeur comparable d'un Packet."""
if field == "remote_ip":
@@ -151,6 +179,11 @@ class CustomRules:
return pkt.direction or ""
if field == "size":
return pkt.size
+ if field == "asn":
+ return str((geo or {}).get("asn") or "")
+ if field == "country":
+ g = geo or {}
+ return g.get("country") or g.get("country_code") or ""
return None
def _match_one(self, rule: dict, actual) -> bool:
@@ -192,7 +225,7 @@ class CustomRules:
continue
return False
- def check(self, pkt) -> list[dict]:
+ def check(self, pkt, geo: Optional[dict] = None) -> list[dict]:
"""EN: All enabled rules matching this packet (usually one per
packet is emitted — callers may cap). Hit counters updated.
FR: Toutes les règles actives qui matchent ce paquet (en pratique
@@ -201,7 +234,8 @@ class CustomRules:
for r in self._rules:
if not r.get("enabled"):
continue
- if self._match_one(r, self._field_value(pkt, r["field"])):
+ if self._match_one(
+ r, self._field_value(pkt, r["field"], geo)):
h = self._hits.setdefault(r["id"], {"count": 0, "last": 0.0})
h["count"] += 1
h["last"] = time.time()
diff --git a/backend/detection/ebpf_enforce.py b/backend/detection/ebpf_enforce.py
new file mode 100644
index 0000000..d051452
--- /dev/null
+++ b/backend/detection/ebpf_enforce.py
@@ -0,0 +1,190 @@
+"""
+Snitch — eBPF egress enforcement (Linux cgroup_skb) / enforcement eBPF en
+sortie (cgroup_skb Linux).
+
+EN: The kernel-enforcement complement to the *attribution* probe
+ (capture/ebpf_probe.py): a BPF_PROG_TYPE_CGROUP_SKB program attached
+ at cgroup2 egress that returns 0 (drop) for destinations present in a
+ BPF hash map — packets are killed inside the kernel before they leave,
+ which iptables rules achieve too, but with per-cgroup precision:
+ moving a PID into our dedicated cgroup sandboxes THAT process without
+ touching the rest of the host.
+
+ * drop by remote IPv4 — `block_ip(ip)` inserts into the map
+ * per-process scope — `isolate_pid(pid)` reparents it into
+ /sys/fs/cgroup/snitch (v2) so ONLY that process is filtered
+ * honest gates: needs root, bcc (`from bcc import BPF`), a mounted
+ cgroup2 tree and a kernel that allows cgroup_skb (≥4.10+)
+
+ Everything degrades to available()=False + applied=False — never a
+ fake success. The verdict is a real kernel drop, not a userspace race.
+
+FR: Complément d'enforcement noyau à la sonde d'attribution : un
+ programme BPF_PROG_TYPE_CGROUP_SKB attaché en egress cgroup2 qui
+ renvoie 0 (drop) pour les destinations présentes dans la map — les
+ paquets sont tués dans le noyau avant de sortir, avec une précision
+ par cgroup : déplacer un PID dans notre cgroup dédié isole CE
+ processus sans toucher le reste de l'hôte. Conditions honnêtes : root,
+ bcc, cgroup2 monté, noyau ≥4.10. Tout se dégrade en applied=False —
+ jamais de faux succès.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import ipaddress
+import os
+import platform
+from pathlib import Path
+from typing import Optional
+
+_CGROUP_DIR = Path("/sys/fs/cgroup/snitch")
+
+_PROG = r"""
+#include <uapi/linux/bpf.h>
+#include <uapi/linux/ip.h>
+#include <uapi/linux/in.h>
+#include <uapi/linux/if_ether.h>
+
+BPF_HASH(blocked, u32, u8, 4096);
+
+int egress_drop(struct __sk_buff *skb) {
+ /* EN: __sk_buff gives remote_ip4 directly for skb programs —
+ no header walking needed. */
+ u32 daddr = skb->remote_ip4;
+ u8 *hit = blocked.lookup(&daddr);
+ if (hit) {
+ return 0; /* EN: drop / FR: drop */
+ }
+ return 1; /* EN: pass / FR: passe */
+}
+"""
+
+
+def _cgroup2_root() -> Optional[Path]:
+ try:
+ for line in Path("/proc/mounts").read_text().splitlines():
+ parts = line.split()
+ if len(parts) >= 3 and parts[2] == "cgroup2":
+ return Path(parts[1])
+ except OSError:
+ return None
+ return None
+
+
+def available() -> tuple[bool, str]:
+ """EN: Linux + root + bcc + cgroup2 mounted. Honest capability probe.
+ FR: Linux + root + bcc + cgroup2 monté. Sonde de capacité honnête."""
+ if platform.system().lower() != "linux":
+ return False, "linux only"
+ if os.geteuid() != 0:
+ return False, "needs root"
+ try:
+ import bcc # noqa: F401
+ except ImportError:
+ return False, "bcc not installed"
+ if _cgroup2_root() is None:
+ return False, "no cgroup2 mount"
+ return True, ""
+
+
+class EbpfEnforcer:
+ """EN: One cgroup_skb egress program + blocked-IP map + our own
+ cgroup for per-process isolation. / FR: Un programme egress cgroup_skb
+ + map d'IP bloquées + cgroup dédié pour l'isolation par processus."""
+
+ def __init__(self) -> None:
+ self._b = None
+ self._fn = None
+ self._blocked: set[str] = set()
+ self._attached_to: Optional[str] = None
+ self._isolated: set[int] = set()
+
+ def start(self) -> tuple[bool, str]:
+ ok, why = available()
+ if not ok:
+ return False, why
+ try:
+ from bcc import BPF
+ self._b = BPF(text=_PROG)
+ self._fn = self._b.load_func("egress_drop", BPF.CGROUP_SKB)
+ # EN: Attach at the cgroup2 root — covers every process;
+ # per-process isolation narrows via our own cgroup below.
+ # FR: Attach à la racine cgroup2 — couvre tous les processus ;
+ # l'isolation par processus affine via notre cgroup.
+ root = str(_cgroup2_root())
+ self._b.attach_cgroup(self._fn, root,
+ self._b.BPFAttachType.CGROUP_INET_EGRESS)
+ self._attached_to = root
+ except Exception as e: # noqa: BLE001
+ self._b = None
+ return False, f"bpf attach failed: {e}"
+ try:
+ _CGROUP_DIR.mkdir(exist_ok=True)
+ except OSError:
+ pass
+ return True, ""
+
+ def stop(self) -> None:
+ try:
+ if self._b is not None and self._fn is not None \
+ and self._attached_to:
+ self._b.detach_cgroup(
+ self._fn, self._attached_to,
+ self._b.BPFAttachType.CGROUP_INET_EGRESS)
+ except Exception: # noqa: BLE001
+ pass
+ self._b = self._fn = None
+ self._attached_to = None
+
+ def block_ip(self, ip: str) -> tuple[bool, str]:
+ """EN: Add an IPv4/6 destination to the kernel drop map (v6
+ addresses are folded to their mapped v4 when possible — honest
+ limitation, cgroup_skb remote_ip4 is v4-only).
+ FR: Ajoute une destination à la map de drop noyau (v6 repliée en
+ v4 mappée quand possible — limite honnête, remote_ip4 est v4)."""
+ if self._b is None:
+ return False, "enforcer not started"
+ try:
+ addr = ipaddress.ip_address(ip)
+ if addr.version == 6:
+ if addr.ipv4_mapped is None:
+ return False, "cgroup_skb remote_ip4 is IPv4-only"
+ addr = addr.ipv4_mapped
+ key = ctypes.c_uint32(int.from_bytes(addr.packed, "big"))
+ self._b["blocked"][key] = ctypes.c_uint8(1)
+ self._blocked.add(str(addr))
+ return True, ""
+ except Exception as e: # noqa: BLE001
+ return False, str(e)[:200]
+
+ def unblock_ip(self, ip: str) -> None:
+ try:
+ addr = ipaddress.ip_address(ip)
+ if addr.version == 6 and addr.ipv4_mapped is not None:
+ addr = addr.ipv4_mapped
+ key = ctypes.c_uint32(int.from_bytes(addr.packed, "big"))
+ if self._b is not None:
+ del self._b["blocked"][key]
+ self._blocked.discard(str(addr))
+ except Exception: # noqa: BLE001
+ pass
+
+ def isolate_pid(self, pid: int) -> tuple[bool, str]:
+ """EN: Move a process into our cgroup so the attached program (and
+ any stricter future rules) applies to it specifically.
+ FR: Déplace un processus dans notre cgroup pour que le programme
+ s'applique spécifiquement à lui."""
+ procs = _CGROUP_DIR / "cgroup.procs"
+ try:
+ procs.write_text(str(int(pid)))
+ self._isolated.add(int(pid))
+ return True, ""
+ except OSError as e:
+ return False, str(e)[:200]
+
+ def status(self) -> dict:
+ return {"attached": self._attached_to is not None,
+ "cgroup": str(_CGROUP_DIR),
+ "blocked": sorted(self._blocked),
+ "isolated_pids": sorted(self._isolated)}
diff --git a/backend/detection/explain.py b/backend/detection/explain.py
index 4cbae8b..47519f0 100644
--- a/backend/detection/explain.py
+++ b/backend/detection/explain.py
@@ -529,14 +529,136 @@ EXPLANATIONS: dict[str, dict] = {
"Un paquet a correspondu à une condition que VOUS avez définie dans "
"le panneau de règles (champ + opérateur + valeur). C'est votre propre "
"détection qui se déclenche — pas une heuristique intégrée.",
- "The rule only alerts; it never blocks. Tune the field/op/value if it "
- "fires too often, or disable it from the rules list.",
- "La règle ne fait qu'alerter ; elle ne bloque jamais. Ajustez "
- "champ/op/valeur si elle se déclenche trop, ou désactivez-la.",
+ "Default rules only alert; rules with the block action additionally "
+ "install a firewall rule on the remote host. Tune field/op/value if "
+ "it fires too often, or disable it from the rules list.",
+ "Par défaut la règle ne fait qu'alerter ; une règle avec l'action "
+ "« block » installe de plus une règle pare-feu sur l'hôte distant. "
+ "Ajustez champ/op/valeur si elle se déclenche trop, ou désactivez-la.",
["Check which process triggered it",
- "Tighten the matcher if noisy"],
+ "Tighten the matcher if noisy",
+ "Review any firewall rule it auto-created"],
["Vérifier quel processus l'a déclenchée",
- "Resserrer le filtre si trop bavarde"]),
+ "Resserrer le filtre si trop bavarde",
+ "Revoir la règle pare-feu auto-créée le cas échéant"]),
+
+"TLS_CERT": _e(
+ "TLS certificate anomaly",
+ "Anomalie du certificat TLS",
+ "The server presented a leaf certificate that is self-signed or whose "
+ "SANs do not cover the requested SNI — observed passively from the "
+ "handshake, no interception involved.",
+ "Le serveur a présenté un certificat feuille auto-signé ou dont les "
+ "SANs ne couvrent pas le SNI demandé — observé passivement sur le "
+ "handshake, sans interception.",
+ "Self-signed certs are normal on internal tools and dev boxes; on a "
+ "public service they can mean MitM or a C2 with a throwaway cert. A "
+ "SAN/SNI mismatch means the endpoint answered with someone else's "
+ "certificate — suspicious on real services.",
+ "L'auto-signé est normal sur les outils internes et dev ; sur un "
+ "service public cela peut indiquer un MitM ou un C2 à cert jetable. "
+ "Un mismatch SAN/SNI signifie que l'endpoint a répondu avec le "
+ "certificat d'un autre — suspect sur un vrai service.",
+ ["Check the issuer shown in the alert",
+ "Verify the site loads correctly in a browser",
+ "Block the IP if the endpoint cannot be explained",
+ "Note: TLS 1.3 encrypts this message — absence of alert is not proof"],
+ ["Vérifier l'émetteur affiché dans l'alerte",
+ "Vérifier que le site se charge normalement dans un navigateur",
+ "Bloquer l'IP si l'endpoint est inexplicable",
+ "NB : TLS 1.3 chiffre ce message — l'absence d'alerte n'est pas une preuve"]),
+
+"HIGH_ENTROPY": _e(
+ "Encrypted-looking data on a cleartext channel",
+ "Données d'apparence chiffrée sur un canal en clair",
+ "The first payload bytes on a non-TLS socket are statistically "
+ "near-random — real plaintext protocols are structured and compress "
+ "well, so this suggests covert encryption, packed data or stego.",
+ "Les premiers octets du payload sur une socket non TLS sont "
+ "statistiquement quasi aléatoires — un vrai protocole clair est "
+ "structuré ; cela suggère du chiffrement couvert, des données packées "
+ "ou de la stéganographie.",
+ "Info-level by design: compressed uploads (zip, video, protobuf) "
+ "trigger it legitimately. It matters when an unexpected process "
+ "produces it.",
+ "Niveau info par conception : les envois compressés (zip, vidéo, "
+ "protobuf) la déclenchent légitimement. Elle compte quand un "
+ "processus inattendu la produit.",
+ ["Check which process is sending",
+ "Correlate with destination and other alerts",
+ "Ignore for known compression-heavy apps"],
+ ["Vérifier quel processus envoie",
+ "Corréler avec la destination et les autres alertes",
+ "Ignorer pour les apps connues très compressées"]),
+
+"ICMP_TUNNEL": _e(
+ "Possible ICMP tunnelling",
+ "Tunnel ICMP possible",
+ "Repeated ICMP echo packets carrying unusually large payloads — real "
+ "echo traffic is tiny; fat echoes are the classic signature of ICMP "
+ "exfiltration tools (ptunnel, icmpsh).",
+ "Paquets d'écho ICMP répétés avec des payloads anormalement gros — "
+ "l'écho réel est minuscule ; de gros échos sont la signature "
+ "classique des outils d'exfiltration ICMP (ptunnel, icmpsh).",
+ "ICMP passes where TCP/UDP are filtered, making it a favourite "
+ "covert channel. Requires several fat echoes to fire, so a single "
+ "odd ping stays quiet.",
+ "L'ICMP passe là où TCP/UDP sont filtrés — canal couvert favori. "
+ "Plusieurs gros échos requis pour déclencher, un ping isolé reste muet.",
+ ["Identify which host pair is talking",
+ "Check whether diagnostic tooling runs ICMP here",
+ "Block ICMP to that peer with a firewall rule if confirmed"],
+ ["Identifier la paire d'hôtes qui communique",
+ "Vérifier qu'un outil de diagnostic n'utilise pas ICMP ici",
+ "Bloquer l'ICMP vers ce pair si confirmé"]),
+
+"ML_ANOMALY": _e(
+ "Flow unlike this machine's baseline",
+ "Flux atypique vs la baseline de la machine",
+ "A pure-Python isolation forest scored this outbound flow as an "
+ "outlier against YOUR OWN recent traffic — unusual port, interval, "
+ "size pattern or fan-out. Unsupervised: it learned what YOUR machine "
+ "looks like, not what malware looks like.",
+ "Une forêt d'isolation pur Python a scoré ce flux sortant comme "
+ "outlier face à VOTRE propre trafic récent — port, intervalle, taille "
+ "ou fan-out inhabituels. Non supervisé : elle a appris à quoi "
+ "ressemble VOTRE machine, pas ce à quoi ressemble un malware.",
+ "Complements the heuristics — it can catch patterns no rule was "
+ "written for, but unusual-but-legit software (new apps, rare "
+ "backups) will also stand out early on. It needs a few hundred flows "
+ "before it scores anything.",
+ "Complète les heuristiques — elle peut attraper des motifs pour "
+ "lesquels aucune règle n'existe, mais le logiciel inhabituel-et-"
+ "légitime ressort aussi au début. Quelques centaines de flux sont "
+ "requis avant le premier score.",
+ ["Compare with what changed on the machine recently",
+ "Check the process against the integrity tools",
+ "Expect noise in the first days — it sharpens with uptime"],
+ ["Comparer avec ce qui a changé récemment sur la machine",
+ "Vérifier le processus avec les outils d'intégrité",
+ "Bruit attendu les premiers jours — se raffine avec le temps"]),
+
+"ASK_VERDICT": _e(
+ "New flow awaiting your verdict",
+ "Nouveau flux en attente de verdict",
+ "Ask-on-first-connect is enabled: the kernel handed this packet to "
+ "Snitch instead of letting it through. It is genuinely suspended "
+ "until you answer — this is real verdict power, not a notification.",
+ "Le mode ask-on-first-connect est actif : le noyau a remis ce paquet "
+ "à Snitch au lieu de le laisser passer. Il est réellement suspendu "
+ "jusqu'à votre réponse — vrai pouvoir de verdict, pas une notif.",
+ "Only the FIRST packet of each flow waits — decide once and the rest "
+ "of the connection rides your decision for the session. Unanswered "
+ "flows hit the timeout policy (drop by default).",
+ "Seul le PREMIER paquet de chaque flux attend — décidez une fois et "
+ "le reste de la connexion suit votre décision pour la session. Les "
+ "flux sans réponse subissent la politique de timeout (drop par défaut).",
+ ["Allow once or deny from the prompt",
+ "Create a firewall rule for permanent decisions",
+ "Linux/NFQUEUE only — see /security/ask for platform status"],
+ ["Autoriser ou refuser depuis le prompt",
+ "Créer une règle pare-feu pour les décisions permanentes",
+ "Linux/NFQUEUE seulement — voir /security/ask pour le statut"]),
}
diff --git a/backend/detection/firewall.py b/backend/detection/firewall.py
index 4d4c03f..e090091 100644
--- a/backend/detection/firewall.py
+++ b/backend/detection/firewall.py
@@ -51,6 +51,7 @@ from __future__ import annotations
import ipaddress
import os
import platform
+import shutil
import socket
import subprocess
import threading
@@ -101,6 +102,11 @@ class FirewallManager:
# EN: tc state for throttle rules — iface cached after first setup.
# FR: État tc pour les règles throttle — iface mise en cache.
self._tc_iface: str | None = None
+ # EN: Linux firewall tool — 'iptables' | 'nft' | False (none).
+ # nftables is the modern path; iptables-nft maps to it anyway.
+ # FR: Outil pare-feu Linux — 'iptables' | 'nft' | False (aucun).
+ # nftables est le chemin moderne ; iptables-nft y mappe déjà.
+ self._linux_fw: object | None = None
# ── Introspection / Introspection ────────────────────────────────────────
@@ -441,6 +447,11 @@ class FirewallManager:
# Names are resolved to PIDs lazily — best effort.
# FR: Le match owner fonctionne par PID sur paquets locaux.
return self._block_linux_process(target, rid)
+ tool = self._linux_tool()
+ if tool == "nft":
+ return self._nft_apply(kind, target, rid)
+ if tool is None:
+ return False, "no iptables or nft binary"
args = ["iptables", "-w", "-I", "OUTPUT"]
if kind in ("ip", "cidr", "domain"):
args += ["-d", target]
@@ -626,7 +637,11 @@ class FirewallManager:
# 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 False, "ip sinkhole needs iptables/nft (linux only)"
+ if self._linux_tool() == "nft":
+ return self._nft_dnat(value, rid)
+ if self._linux_tool() is None:
+ return False, "no iptables or nft binary"
return self._run(["iptables", "-w", "-t", "nat", "-I", "OUTPUT",
"-d", value, "-j", "DNAT",
"--to-destination", "127.0.0.1",
@@ -659,6 +674,9 @@ class FirewallManager:
except OSError:
pass
elif self._platform == "linux":
+ if self._linux_tool() == "nft":
+ self._nft_del_comment(f"snitch-sinkhole-{rid}")
+ return
self._run(["iptables", "-w", "-t", "nat", "-D", "OUTPUT",
"-d", value, "-j", "DNAT",
"--to-destination", "127.0.0.1",
@@ -707,14 +725,23 @@ class FirewallManager:
continue
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}"])
+ if self._linux_tool() == "nft":
+ # EN: Comment-tagged delete is the whole delta —
+ # one scan covers every stale IP at once.
+ # FR: La suppression par commentaire fait tout le
+ # delta en un scan.
+ self._nft_del_comment(f"snitch-{rid}")
+ for t in new:
+ self._nft_apply("domain", t, rid)
+ else:
+ 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":
if self._wfp() is not None:
# EN: True delta — per-IP keys mean stale addresses
@@ -766,6 +793,9 @@ class FirewallManager:
self._run(["netsh", "advfirewall", "firewall", "delete", "rule",
"name=all", "program=" + rule["value"]]) if kind == "process" else None
elif self._platform == "linux":
+ if self._linux_tool() == "nft":
+ self._nft_del_comment(f"snitch-{rid}")
+ return
targets = rule.get("resolved") if kind == "domain" else [rule["value"]]
for t in targets:
args = ["iptables", "-w", "-D", "OUTPUT"]
@@ -787,6 +817,14 @@ class FirewallManager:
PIDs via psutil. Only locally generated packets match; still useful
for an instant kill-switch on a known process.
FR: `owner` matche par PID — on résout le nom en PID via psutil."""
+ if self._linux_tool() == "nft":
+ # EN: nftables has no PID-owner match — meta skuid is per-USER.
+ # Honest refusal rather than a wrong-semantic rule.
+ # FR: nftables n'a pas de match par PID — meta skuid est par
+ # UTILISATEUR. Refus honnête plutôt qu'une règle biaisée.
+ return False, ("nftables cannot match per-process (owner "
+ "match is iptables-only); use a port/ip rule "
+ "instead")
try:
import psutil
pids = [p.pid for p in psutil.process_iter(["name"])
@@ -802,6 +840,94 @@ class FirewallManager:
ok_all = ok_all and ok
return ok_all, "" if ok_all else "owner match failed"
+ # ── Linux nftables backend / Backend nftables Linux ────────────────────
+ #
+ # EN: iptables-nft already maps onto nftables, but some minimal systems
+ # ship ONLY `nft`. When iptables is absent we drive nftables
+ # directly: a dedicated `inet snitch` table whose `output` chain
+ # hooks the output path, plus a `dnat` chain for IP sinkholes.
+ # Rules are removed by their `comment "snitch-<rid>"` tag — we
+ # scan `nft -a` handles and delete each match.
+ # FR: iptables-nft mappe déjà sur nftables, mais certains systèmes
+ # minimaux n'ont QUE `nft`. Sans iptables on pilote nftables
+ # directement : table `inet snitch` dédiée avec chaîne `output`
+ # accrochée au chemin sortant + chaîne `dnat` pour les sinkholes
+ # IP. Les règles se suppriment par leur tag `comment "snitch-<rid>"`
+ # via les handles de `nft -a`.
+
+ def _linux_tool(self) -> Optional[str]:
+ """EN: Cached Linux backend — 'iptables' preferred (widest compat),
+ 'nft' when only nftables exists, False when neither.
+ FR: Backend Linux en cache — 'iptables' de préférence, 'nft' quand
+ seul nftables existe, False sinon."""
+ if self._linux_fw is not None:
+ return self._linux_fw or None
+ if shutil.which("iptables"):
+ self._linux_fw = "iptables"
+ elif shutil.which("nft"):
+ self._linux_fw = "nft"
+ else:
+ self._linux_fw = False
+ return self._linux_fw or None
+
+ def _nft_setup(self) -> None:
+ """EN: Create the table + hooked chains once — idempotent, errors
+ ignored (existing objects make nft exit non-zero harmlessly).
+ FR: Crée la table + chaînes accrochées une fois — idempotent."""
+ self._run(["nft", "add", "table", "inet", "snitch"])
+ self._run(["nft", "add", "chain", "inet", "snitch", "output",
+ "{", "type", "filter", "hook", "output", "priority",
+ "0", ";", "policy", "accept", ";", "}"])
+ self._run(["nft", "add", "chain", "inet", "snitch", "dnat",
+ "{", "type", "nat", "hook", "output", "priority",
+ "-100", ";", "}"])
+
+ def _nft_apply(self, kind: str, target: str, rid: str) -> tuple[bool, str]:
+ """EN: Append one drop rule with our comment tag.
+ FR: Ajoute une règle drop avec notre tag de commentaire."""
+ self._nft_setup()
+ rule = ["nft", "add", "rule", "inet", "snitch", "output"]
+ if kind in ("ip", "cidr", "domain"):
+ fam = "ip6" if ":" in target else "ip"
+ rule += [fam, "daddr", target]
+ elif kind == "port":
+ rule += ["tcp", "dport", str(target)]
+ else:
+ return False, f"nft backend cannot match kind {kind}"
+ rule += ["counter", "drop", "comment", f'"snitch-{rid}"']
+ return self._run(rule)
+
+ def _nft_dnat(self, target: str, rid: str) -> tuple[bool, str]:
+ """EN: IP sinkhole under nftables — dnat to loopback in the nat
+ chain. / FR: Sinkhole IP sous nftables — dnat vers loopback."""
+ self._nft_setup()
+ fam = "ip6" if ":" in target else "ip"
+ loopback = "::1" if ":" in target else "127.0.0.1"
+ return self._run([
+ "nft", "add", "rule", "inet", "snitch", "dnat",
+ fam, "daddr", target, "counter", "dnat", "to", loopback,
+ "comment", f'"snitch-sinkhole-{rid}"'])
+
+ def _nft_del_comment(self, tag: str) -> None:
+ """EN: Delete every rule in our chains carrying `comment "tag"` —
+ handle-scan via `nft -a list chain`. Best-effort.
+ FR: Supprime chaque règle de nos chaînes portant `comment "tag"`
+ — scan des handles via `nft -a`. Au mieux."""
+ for chain in ("output", "dnat"):
+ ok, out = self._run(["nft", "-a", "list", "chain", "inet",
+ "snitch", chain])
+ if not ok:
+ continue
+ for line in out.splitlines():
+ if tag not in line or "handle" not in line:
+ continue
+ try:
+ handle = line.rsplit("handle", 1)[1].strip().split()[0]
+ self._run(["nft", "delete", "rule", "inet", "snitch",
+ chain, "handle", handle])
+ except (IndexError, ValueError):
+ continue
+
# ── macOS pf / pf macOS ──────────────────────────────────────────────────
def _pf_apply(self) -> tuple[bool, str]:
@@ -846,6 +972,25 @@ class FirewallManager:
return self._run(["netsh", "advfirewall", "set", "allprofiles",
"firewallpolicy", "blockinbound,allowoutbound"])
if self._platform == "linux":
+ if self._linux_tool() == "nft":
+ # EN: Lockdown under nftables — private/LAN returns, then a
+ # tagged blanket drop at the END of our output chain.
+ # FR: Lockdown sous nftables — return privé/LAN puis drop
+ # général taggé en FIN de notre chaîne output.
+ if on:
+ self._nft_setup()
+ nets = ", ".join(_PRIVATE_NETS[:5])
+ self._run(["nft", "add", "rule", "inet", "snitch",
+ "output", "ip", "daddr", "{", nets, "}",
+ "return", "comment", '"snitch-lock"'])
+ self._run(["nft", "add", "rule", "inet", "snitch",
+ "output", "oif", '"lo"', "return",
+ "comment", '"snitch-lock"'])
+ return self._run(["nft", "add", "rule", "inet",
+ "snitch", "output", "counter",
+ "drop", "comment", '"snitch-lock"'])
+ self._nft_del_comment("snitch-lock")
+ return True, ""
if on:
self._run(["iptables", "-w", "-N", "SNITCH_LOCK"])
self._run(["iptables", "-w", "-F", "SNITCH_LOCK"])
diff --git a/backend/detection/gossip.py b/backend/detection/gossip.py
new file mode 100644
index 0000000..4ba35b2
--- /dev/null
+++ b/backend/detection/gossip.py
@@ -0,0 +1,115 @@
+"""
+Snitch — peer IOC sharing (decentralized-lite) / partage d'IOC entre
+pairs (décentralisé allégé).
+
+EN: The honest, shippable version of "fleet gossip": instead of a real
+ epidemic protocol (libp2p, membership, NAT traversal — heavy and
+ attack-prone), Snitch instances EXPLICITLY paired by the operator
+ exchange their privacy-preserving IOC packs directly over HTTP:
+
+ * peers are opt-in and explicit — a list of `http(s)://host:port`
+ Snitch backends plus the shared bearer token; ZERO auto-discovery,
+ nothing ever leaves for an unlisted address
+ * transport = the peer's own authenticated API: our `format=proof`
+ pack is POSTed to its /security/iocpack/import — no new wire
+ protocol, the receiving side applies the same salted-Merkle
+ verification as a file import
+ * content = salted hash leaves + Merkle root ONLY (never raw IOCs,
+ never hostnames/paths/users — the pack format already guarantees
+ that)
+ * cadence = manual `POST /remote/ioc_sync` plus an optional periodic
+ push (~5 min) when `gossip_enabled` is set
+ * failures are recorded per-peer and surfaced honestly in status()
+
+ This IS decentralized sharing — no central server — scoped to the
+ operator's own fleet, which is the honest 90% of the feature. A real
+ anonymous gossip mesh stays a research item.
+
+FR: Version honnête et livrable du « gossip de flotte » : au lieu d'un
+ vrai protocole épidémique (lourd et exposé), les instances Snitch
+ explicitement appairées par l'opérateur échangent leurs packs IOC
+ préservant la vie privée en HTTP direct — pairs opt-in uniquement,
+ transport = l'API authentifiée du pair (notre pack `format=proof`
+ posté vers son /security/iocpack/import), contenu = feuilles salées +
+ racine Merkle seulement. Partage réellement décentralisé, borné à la
+ flotte de l'opérateur. Un mesh anonyme reste en recherche.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+import urllib.request
+import urllib.error
+
+_MAX_PEERS = 32
+_TIMEOUT = 8
+
+
+class PeerSync:
+ """EN: Owns the explicit peer list + per-peer sync state.
+ FR: Gère la liste de pairs explicite + l'état de sync par pair."""
+
+ def __init__(self, token_getter):
+ """EN: token_getter() → the bearer token peers expect (their own
+ API token — configured per deployment, never stored here).
+ FR: token_getter() → le jeton bearer attendu par les pairs."""
+ self._token_getter = token_getter
+ self._peers: list[str] = []
+ self._state: dict[str, dict] = {}
+
+ def configure(self, peers: list[str]) -> None:
+ """EN: Replace the peer list — host:port or http(s)://host:port,
+ deduped, bounded. http is allowed on purpose: peers are LAN/trust-
+ domain scoped and the payload is a hash pack, but https is
+ recommended across untrusted links (documented).
+ FR: Remplace la liste — host:port ou http(s)://, dédupliquée,
+ bornée. http autorisé volontairement (LAN) ; https recommandé sur
+ liens non fiables."""
+ clean = []
+ for p in peers[:_MAX_PEERS]:
+ p = str(p).strip().rstrip("/")
+ if not p:
+ continue
+ if not p.startswith(("http://", "https://")):
+ p = "http://" + p
+ if p not in clean:
+ clean.append(p)
+ self._peers = clean
+
+ @property
+ def peers(self) -> list[str]:
+ return list(self._peers)
+
+ def push_pack(self, pack: dict) -> dict:
+ """EN: POST one IOC pack (snitch-ioc-proof/1 dict) to every peer's
+ import endpoint. Returns per-peer results; never raises.
+ FR: POST un pack IOC vers l'endpoint import de chaque pair.
+ Renvoie les résultats par pair ; ne lève jamais."""
+ if not self._peers:
+ return {"ok": False, "error": "no peers configured"}
+ body = json.dumps(pack).encode()
+ results = {}
+ for peer in self._peers:
+ url = f"{peer}/security/iocpack/import"
+ req = urllib.request.Request(
+ url, data=body, method="POST",
+ headers={"Content-Type": "application/json",
+ "Authorization": f"Bearer {self._token_getter()}"})
+ try:
+ with urllib.request.urlopen(req, timeout=_TIMEOUT) as r:
+ st = {"ok": 200 <= r.status < 300, "code": r.status,
+ "ts": time.time()}
+ except urllib.error.HTTPError as e:
+ st = {"ok": False, "code": e.code, "ts": time.time()}
+ except (urllib.error.URLError, OSError) as e:
+ st = {"ok": False, "error": str(e)[:160],
+ "ts": time.time()}
+ results[peer] = st
+ self._state[peer] = st
+ return {"ok": all(s.get("ok") for s in results.values()),
+ "results": results}
+
+ def status(self) -> dict:
+ return {"peers": self._peers,
+ "last": dict(self._state)}
diff --git a/backend/detection/hollow.py b/backend/detection/hollow.py
new file mode 100644
index 0000000..ce73e16
--- /dev/null
+++ b/backend/detection/hollow.py
@@ -0,0 +1,164 @@
+"""
+Snitch — process-hollowing evidence check / vérification de hollowing.
+
+EN: The missing disk↔memory half of integrity.py: read the FILE-BACKED
+ executable pages straight out of /proc/<pid>/mem and compare their
+ SHA-256 to the same ranges on disk. Legit processes are byte-identical
+ there (.text is read-only file-mapped code — the kernel never rewrites
+ it); a mismatch means the image was patched after load — process
+ hollowing, hot-patch injection or manual code carving. Relocation
+ noise lives in writable mappings which we deliberately skip (only
+ r-xp/r--p file-backed regions of the exe itself are compared).
+
+ Honest bounds:
+ * Linux only — /proc/pid/mem requires ptrace-equivalent rights
+ (root, or CAP_SYS_PTRACE; yama scope can block same-uid reads —
+ reported honestly);
+ * on-demand scan, never continuous — reading megabytes of foreign
+ pages is expensive; the API endpoint triggers it per PID;
+ * bounded: ≤64 MiB of compared bytes, first 4096 differing pages
+ reported, always returns a dict, never raises.
+
+FR: La moitié disque↔mémoire manquante d'integrity.py : lit les pages
+ fichier-mappées de l'exécutable dans /proc/<pid>/mem et compare leur
+ SHA-256 aux mêmes zones sur disque. Un processus légitime y est
+ identique octet pour octet ; un écart = image patchée après chargement
+ (hollowing, injection, carving). Le bruit de relocation vit dans les
+ mappings accessibles en écriture — ignorés volontairement (on ne
+ compare que les régions r-xp/r--p fichier de l'exe). Linux seulement,
+ scan à la demande, borné, ne lève jamais.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import platform
+from pathlib import Path
+from typing import Optional
+
+_MAX_BYTES = 64 << 20
+_MAX_DIFFS = 4096
+
+
+def available() -> tuple[bool, str]:
+ if platform.system().lower() != "linux":
+ return False, "/proc/<pid>/mem is linux-only"
+ return True, ""
+
+
+def _exe_regions(pid: int, exe: str) -> list[tuple[int, int]]:
+ """EN: File-backed read/exec regions of the exe itself from maps —
+ returns [(start, end)] virtual ranges. Only the exe's own mappings:
+ library files are checked separately by the Merkle watcher.
+ FR: Régions fichier read/exec de l'exe lui-même — plages virtuelles
+ [(début, fin)]. Seules les mappings de l'exe : les bibliothèques sont
+ couvertes par la veille Merkle."""
+ regions = []
+ maps = Path(f"/proc/{pid}/maps")
+ try:
+ for line in maps.read_text(errors="replace").splitlines():
+ parts = line.split()
+ if len(parts) < 6 or parts[5] != exe:
+ continue
+ perms = parts[1]
+ if "w" in perms: # EN: writable → skip
+ continue # FR: writable → ignoré
+ if "r" not in perms:
+ continue
+ start, end = (int(x, 16) for x in parts[0].split("-"))
+ regions.append((start, end))
+ except OSError:
+ pass
+ return regions
+
+
+def _read_mem(pid: int, start: int, length: int) -> Optional[bytes]:
+ try:
+ with open(f"/proc/{pid}/mem", "rb", buffering=0) as m:
+ m.seek(start)
+ return m.read(length)
+ except OSError:
+ return None
+
+
+def _read_file_range(path: str, off: int, length: int) -> Optional[bytes]:
+ try:
+ with open(path, "rb") as f:
+ f.seek(off)
+ return f.read(length)
+ except OSError:
+ return None
+
+
+def hollow_check(pid: int) -> dict:
+ """EN: Compare the exe's file-backed memory pages with their disk
+ bytes. Returns {ok, matched_bytes, mismatches[], error?}. A mismatch
+ lists {vaddr, file_off, size} — where memory ≠ disk.
+ FR: Compare les pages mémoire fichier-mappées de l'exe aux octets
+ disque. Renvoie {ok, matched_bytes, mismatches[], error?}."""
+ ok, why = available()
+ if not ok:
+ return {"ok": False, "error": why}
+ try:
+ exe = os.readlink(f"/proc/{pid}/exe")
+ except OSError as e:
+ return {"ok": False, "error": f"cannot resolve exe: {e}"}
+ regions = _exe_regions(pid, exe)
+ if not regions:
+ return {"ok": False, "error": "no file-backed exe regions "
+ "(process gone or mem unreadable)",
+ "exe": exe}
+ # EN: Map file offsets — /proc/pid/maps column 3 is the file offset.
+ # FR: Offsets fichier — la colonne 3 de /proc/pid/maps est l'offset.
+ offsets: dict[tuple[int, int], int] = {}
+ try:
+ for line in Path(f"/proc/{pid}/maps").read_text(
+ errors="replace").splitlines():
+ parts = line.split()
+ if len(parts) < 6 or parts[5] != exe or "w" in parts[1]:
+ continue
+ s, e = (int(x, 16) for x in parts[0].split("-"))
+ offsets[(s, e)] = int(parts[2], 16)
+ except OSError:
+ pass
+
+ mismatches: list[dict] = []
+ compared = 0
+ for start, end in regions:
+ length = end - start
+ if length <= 0 or compared >= _MAX_BYTES:
+ continue
+ step = min(length, _MAX_BYTES - compared, 1 << 20)
+ mem = _read_mem(pid, start, step)
+ if mem is None:
+ return {"ok": False, "exe": exe,
+ "error": "cannot read process memory (yama/ptrace "
+ "restrictions or process exited)"}
+ disk = _read_file_range(exe, offsets.get((start, end), 0), step)
+ if disk is not None and len(mem) == len(disk):
+ compared += len(mem)
+ if hashlib.sha256(mem).digest() != \
+ hashlib.sha256(disk).digest():
+ # EN: Narrow to the first differing 4 KiB page.
+ # FR: Restreindre à la première page de 4 Kio différente.
+ for off in range(0, len(mem), 4096):
+ mseg, dseg = mem[off:off + 4096], disk[off:off + 4096]
+ if mseg != dseg:
+ mismatches.append({
+ "vaddr": hex(start + off),
+ "file_off": hex(
+ offsets.get((start, end), 0) + off),
+ "size": len(mseg)})
+ if len(mismatches) >= _MAX_DIFFS:
+ break
+ return {
+ "ok": True, "pid": pid, "exe": exe,
+ "regions": len(regions), "compared_bytes": compared,
+ "clean": not mismatches,
+ "mismatches": mismatches,
+ "verdict": ("executable memory differs from disk — hollowing or "
+ "in-memory patching suspected")
+ if mismatches else
+ "memory matches disk image",
+ }
diff --git a/backend/detection/iforest.py b/backend/detection/iforest.py
new file mode 100644
index 0000000..3016b62
--- /dev/null
+++ b/backend/detection/iforest.py
@@ -0,0 +1,120 @@
+"""
+Snitch — embedded isolation forest / forêt d'isolation embarquée.
+
+EN: A tiny pure-Python IsolationForest (Liu, Ting & Zhou 2008) — no numpy,
+ no ONNX runtime, ~150 lines. Random trees split the training window on
+ random feature/value pairs; anomalies isolate in few splits, so the
+ score is s = 2^(-E(h)/c(n)) where c(n) is the expected path length of
+ an unsuccessful BST search. Honest scope: this is UNSUPERVISED
+ statistical outlier scoring on Snitch's own flow summaries — it
+ complements the heuristic detectors, it does not replace them and it
+ carries no learned notion of "malware" (there are no labels). High
+ score = unusual vs this machine's own recent traffic.
+
+ Bounds: n_trees=64, sub-sample 256, training window 4096 summaries,
+ re-fit every 256 new samples — all constant-time/memory regardless of
+ uptime.
+
+FR: Petite IsolationForest en pur Python (Liu, Ting & Zhou 2008) — sans
+ numpy ni ONNX. Des arbres aléatoires découpent la fenêtre d'entraînement
+ sur des paires feature/valeur tirées au hasard ; les anomalies
+ s'isolent en peu de splits → score s = 2^(-E(h)/c(n)). Portée honnête :
+ score statistique non supervisé sur les flux de Snitch — complète les
+ détecteurs heuristiques, ne les remplace pas, aucune notion apprise de
+ « malware » (pas d'étiquettes). Score élevé = inhabituel vs le trafic
+ récent de CETTE machine. Bornes constantes : 64 arbres, échantillon
+ 256, fenêtre 4096, re-fit tous les 256.
+"""
+
+from __future__ import annotations
+
+import math
+import random
+from typing import Optional
+
+
+def _c(n: int) -> float:
+ """EN: Expected path length of an unsuccessful BST search on n points —
+ the normalizer c(n) = 2H(n-1) - 2(n-1)/n.
+ FR: Longueur de chemin attendue d'une recherche BST infructueuse sur n
+ points — le normaliseur c(n)."""
+ if n <= 1:
+ return 1.0
+ h = math.log(n - 1) + 0.5772156649 # EN: Euler–Mascheroni / FR: Euler–Mascheroni
+ return 2.0 * h - 2.0 * (n - 1) / n
+
+
+class _Node:
+ __slots__ = ("feat", "split", "left", "right", "size")
+
+ def __init__(self, size: int):
+ self.feat = -1
+ self.split = 0.0
+ self.left: Optional[_Node] = None
+ self.right: Optional[_Node] = None
+ self.size = size
+
+
+class IsolationForest:
+ """EN: Bounded isolation forest — fit() on a list of feature vectors,
+ score() a new vector to a 0..1 anomaly score (higher = more isolated).
+ FR: Forêt d'isolation bornée — fit() sur des vecteurs, score() un
+ nouveau vecteur vers un score 0..1 (plus haut = plus isolé)."""
+
+ def __init__(self, n_trees: int = 64, sample: int = 256,
+ max_depth: int = 8, seed: Optional[int] = None):
+ self.n_trees = n_trees
+ self.sample = sample
+ self.max_depth = max_depth
+ self._rng = random.Random(seed)
+ self._trees: list[_Node] = []
+
+ def fit(self, data: list[list[float]]) -> int:
+ """EN: Build the forest on `data`; returns number of trees fitted
+ (0 when data is too small to say anything honest).
+ FR: Construire la forêt ; nombre d'arbres (0 si données trop rares)."""
+ self._trees = []
+ if len(data) < 16:
+ return 0
+ sub = data if len(data) <= self.sample else \
+ self._rng.sample(data, self.sample)
+ for _ in range(self.n_trees):
+ self._trees.append(self._build(sub, 0))
+ return len(self._trees)
+
+ def _build(self, pts: list[list[float]], depth: int) -> _Node:
+ node = _Node(len(pts))
+ if len(pts) <= 1 or depth >= self.max_depth:
+ return node
+ nfeat = len(pts[0])
+ feat = self._rng.randrange(nfeat)
+ col = [p[feat] for p in pts]
+ lo, hi = min(col), max(col)
+ if lo == hi:
+ return node # EN: no split possible
+ node.feat = feat
+ node.split = self._rng.uniform(lo, hi)
+ left = [p for p in pts if p[feat] < node.split]
+ right = [p for p in pts if p[feat] >= node.split]
+ if not left or not right:
+ return node
+ node.left = self._build(left, depth + 1)
+ node.right = self._build(right, depth + 1)
+ return node
+
+ def _path(self, x: list[float], node: _Node, depth: float) -> float:
+ """EN: Path length of x in one tree + expected remainder c(size).
+ FR: Longueur de chemin de x dans un arbre + reste attendu c(size)."""
+ if node.feat < 0 or node.left is None or node.right is None:
+ return depth + _c(node.size)
+ branch = node.left if x[node.feat] < node.split else node.right
+ return self._path(x, branch, depth + 1.0)
+
+ def score(self, x: list[float]) -> float:
+ """EN: Anomaly score in [0,1] — s = 2^(-E(h)/c(n)). ~0.5 = average
+ point, →1 = isolated outlier, →0 = deeply normal.
+ FR: Score d'anomalie dans [0,1]. ~0,5 = point moyen, →1 = isolé."""
+ if not self._trees:
+ return 0.0
+ e_h = sum(self._path(x, t, 0.0) for t in self._trees) / len(self._trees)
+ return 2.0 ** (-e_h / _c(self.sample))
diff --git a/backend/detection/mlflow.py b/backend/detection/mlflow.py
new file mode 100644
index 0000000..1270fec
--- /dev/null
+++ b/backend/detection/mlflow.py
@@ -0,0 +1,122 @@
+"""
+Snitch — ML flow anomaly scoring / scoring ML des flux.
+
+EN: Feeds outbound flow summaries through a bounded pure-Python
+ IsolationForest (detection/iforest.py) and raises ML_ANOMALY when a
+ flow scores far above this machine's OWN traffic baseline. Features
+ are deliberately coarse and privacy-safe — no payloads, no hostnames:
+
+ [remote_port_norm, pkt_size_mean, interval_s, remote_fanout,
+ hour_of_day, bytes_per_pkt_out]
+
+ Honest framing: unsupervised outlier detection against THIS host's
+ learned normality — complements heuristics, emits few alerts
+ (per-(process,remote) cooldown), and disables itself until 384
+ summaries have been observed so early traffic isn't flagged en masse.
+
+FR: Alimente les résumés de flux sortants dans une IsolationForest pur
+ Python bornée et lève ML_ANOMALY quand un flux s'écarte fortement de
+ la propre baseline de la machine. Features volontairement grossières —
+ ni payloads ni noms d'hôte. Cadre honnête : détection d'outliers non
+ supervisée contre la normalité apprise — complément heuristique,
+ alertes parcimonieuses (cooldown par (processus,remote)), inerte tant
+ que 384 résumés n'ont pas été observés.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import math
+import time
+from collections import deque
+from typing import Optional
+
+from .iforest import IsolationForest
+
+_TRAIN_MIN = 384 # EN: summaries needed before scoring / FR: résumés requis avant scoring
+_WINDOW = 4096 # EN: rolling training window / FR: fenêtre glissante
+_REFIT_EVERY = 256 # EN: refit cadence in new samples / FR: cadence de re-fit
+# EN: Alert threshold — the iForest paper treats ≈0.5 as average and
+# s→1 as anomalous; ~0.6+ is the usual "top outliers" operating
+# point. 0.72 proved unreachable for points extreme on only a few
+# features (path-length compression), so we alert at 0.62.
+# FR: Seuil d'alerte — le papier iForest traite ≈0,5 comme moyen et
+# s→1 comme anomalie ; ~0,6+ est le point d'opération usuel. 0,72
+# s'est révélé inatteignable pour des points extrêmes sur peu de
+# features (compression des chemins) → alerte à 0,62.
+_THRESHOLD = 0.62 # EN: anomaly score alert threshold / FR: seuil d'alerte
+_COOLDOWN = 900 # EN: per (proc, remote) alert cooldown s / FR: cooldown d'alerte
+_MAX_KEYS = 4096
+
+
+class FlowAnomaly:
+ """EN: Rolling iForest over outbound flow summaries.
+ FR: iForest glissant sur les résumés de flux sortants."""
+
+ def __init__(self) -> None:
+ self._window: deque[list[float]] = deque(maxlen=_WINDOW)
+ self._forest = IsolationForest(n_trees=64, sample=256, max_depth=8,
+ seed=20261022)
+ self._since_fit = 0
+ self._fitted = False
+ self._cool: dict[tuple, float] = {}
+ self._first_seen: dict[tuple, float] = {}
+ self._fanout: dict[str, set[str]] = {}
+
+ def observe(self, proc: str, remote_ip: str, remote_port: int,
+ direction: str, size: int, ts: Optional[float] = None) \
+ -> Optional[dict]:
+ """EN: Record one packet's contribution to a flow and score when
+ warranted. Returns an alert context dict or None.
+ FR: Enregistre la contribution d'un paquet et score le cas échéant.
+ Renvoie un contexte d'alerte ou None."""
+ if direction != "out":
+ return None
+ now = ts or time.time()
+ try:
+ ipaddress.ip_address(remote_ip)
+ except ValueError:
+ return None
+ key = (proc or "?", remote_ip, int(remote_port or 0))
+ prev = self._first_seen.get(key)
+ interval = min(now - prev, 3600.0) if prev else 3600.0
+ if len(self._first_seen) < _MAX_KEYS:
+ self._first_seen[key] = now
+ fanset = self._fanout.setdefault(proc or "?", set())
+ if len(fanset) < 512:
+ fanset.add(remote_ip)
+
+ feats = [
+ min(int(remote_port or 0), 65535) / 65535.0,
+ min(size, 65535) / 65535.0,
+ math.log1p(interval) / math.log1p(3600.0),
+ min(len(fanset), 512) / 512.0,
+ (time.gmtime(now).tm_hour) / 23.0,
+ 1.0, # EN: placeholder weight / FR: poids
+ ]
+ self._window.append(feats)
+ self._since_fit += 1
+ if self._since_fit >= _REFIT_EVERY:
+ self._forest.fit(list(self._window))
+ self._fitted = True
+ self._since_fit = 0
+ if not self._fitted or len(self._window) < _TRAIN_MIN:
+ return None
+ score = self._forest.score(feats)
+ if score < _THRESHOLD:
+ return None
+ ck = (proc or "?", remote_ip)
+ last = self._cool.get(ck, 0.0)
+ if now - last < _COOLDOWN:
+ return None
+ if len(self._cool) < _MAX_KEYS:
+ self._cool[ck] = now
+ return {
+ "type": "ML_ANOMALY", "severity": "warning",
+ "remote_ip": remote_ip, "process": proc or "?",
+ "detail": f"isolation-forest score {score:.2f} ≥ {_THRESHOLD} — "
+ f"flow unlike this host's learned baseline "
+ f"(port {remote_port}, interval {interval:.0f}s, "
+ f"fan-out {len(fanset)})",
+ "score": round(score, 3),
+ }
diff --git a/backend/tests/test_v15_features.py b/backend/tests/test_v15_features.py
new file mode 100644
index 0000000..255a3dd
--- /dev/null
+++ b/backend/tests/test_v15_features.py
@@ -0,0 +1,583 @@
+"""
+Snitch — tests for the v1.5 hardening modules / tests des modules de
+durcissement v1.5.
+
+EN: Coverage: ICMP payload parsing (type/code→flags, head→app_head),
+ bounded TLS Certificate reassembly + minimal DER leaf parsing
+ (issuer/subject/self-signed/SANs), SAN-SNI wildcard matching, the
+ pure-Python isolation forest + flow scorer, geo-aware custom rules
+ and their block action validation, RFC 3164 syslog dispatch, the
+ NFQUEUE flow-key parser, IOC peer sync config, and the hollowing /
+ eBPF honest-capability probes. Everything runs without privileges —
+ platform-gated paths are probed through available() only.
+
+FR: Couverture : parsing de payload ICMP (type/code→flags, tête→app_head),
+ réassemblage borné du handshake Certificate + parsing DER minimal du
+ certificat feuille, matching wildcard SAN/SNI, forêt d'isolation pur
+ Python + scoreur de flux, règles géo (asn/country) et validation de
+ l'action block, dispatch syslog RFC 3164, extracteur de clé de flux
+ NFQUEUE, config de sync IOC entre pairs, et sondes de capacité
+ hollowing/eBPF. Aucun privilège requis.
+"""
+
+import socket
+import struct
+import time
+
+import pytest
+
+from capture.parser import DLT_EN10MB, parse_frame
+from capture import tlscert
+
+ETH = DLT_EN10MB
+
+
+# ── Frame builders (mirrors test_parser.py helpers) / Constructeurs ────────
+
+def eth(payload: bytes, ethertype: int = 0x0800) -> bytes:
+ return b"\xaa\xbb\xcc\xdd\xee\xff" + b"\x11\x22\x33\x44\x55\x66" \
+ + struct.pack("!H", ethertype) + payload
+
+
+def ipv4(src: bytes, dst: bytes, proto: int, payload: bytes) -> bytes:
+ total = 20 + len(payload)
+ hdr = struct.pack("!BBHHHBBH4s4s",
+ (4 << 4) | 5, 0, total, 0, 0, 64, proto, 0, src, dst)
+ return hdr + payload
+
+
+def tcp(sport: int, dport: int, flags: int = 0x18,
+ payload: bytes = b"") -> bytes:
+ hdr = struct.pack("!HHIIBBHHH", sport, dport, 0, 0, 5 << 4, flags,
+ 8192, 0, 0)
+ return hdr + payload
+
+
+# ── Minimal DER builder for a synthetic leaf cert / Constructeur DER ───────
+
+def _tlv(tag: int, val: bytes) -> bytes:
+ ln = len(val)
+ if ln < 128:
+ lb = bytes([ln])
+ elif ln < 256:
+ lb = b"\x81" + bytes([ln])
+ else:
+ lb = b"\x82" + struct.pack("!H", ln)
+ return bytes([tag]) + lb + val
+
+
+def _name(cn: str, org: str = "") -> bytes:
+ """EN: X.501 Name { cn, o? } — OID 2.5.4.3/10 as UTF8String.
+ FR: X.501 Name { cn, o? } — OID 2.5.4.3/10 en UTF8String."""
+ atv = _tlv(0x30, _tlv(0x06, b"\x55\x04\x03")
+ + _tlv(0x0C, cn.encode()))
+ rdns = _tlv(0x31, atv)
+ if org:
+ atv2 = _tlv(0x30, _tlv(0x06, b"\x55\x04\x0a")
+ + _tlv(0x0C, org.encode()))
+ rdns += _tlv(0x31, atv2)
+ return _tlv(0x30, rdns)
+
+
+def _san_ext(names: list[str]) -> bytes:
+ """EN: [3] extensions wrapper containing a SAN ext (OID 2.5.29.17)
+ with dNSName entries. / FR: Wrapper [3] avec ext SAN + dNSNames."""
+ gnames = b"".join(_tlv(0x82, n.encode("ascii")) for n in names)
+ ext_val = _tlv(0x04, _tlv(0x30, gnames)) # OCTET STRING { SEQ }
+ ext = _tlv(0x30, _tlv(0x06, b"\x55\x1d\x11") + ext_val)
+ return _tlv(0xA3, _tlv(0x30, ext))
+
+
+def make_cert(cn: str, issuer_cn: str, sans: list[str],
+ issuer_org: str = "Test CA",
+ days: tuple[bytes, bytes] = (b"250101000000Z",
+ b"300101000000Z")) -> bytes:
+ """EN: A structurally-valid-enough X.509 leaf for our bounded parser —
+ not cryptographically valid (fake signature), exactly what the
+ passive reader needs. `issuer_org=""` makes issuer DER == subject
+ DER (the strict self-issuance test).
+ FR: Certificat feuille structurellement valide pour le parseur —
+ signature factice. `issuer_org=""` rend issuer == subject en DER."""
+ tbs = (_tlv(0xA0, _tlv(0x02, b"\x02")) # version v3
+ + _tlv(0x02, b"\x01") # serial
+ + _tlv(0x30, _tlv(0x06, b"\x2a\x86\x48\x86\xf7\x0d\x01\x01\x0b")
+ + _tlv(0x05, b"")) # sha256WithRSA
+ + _name(issuer_cn, issuer_org) # issuer
+ + _tlv(0x30, _tlv(0x17, days[0]) + _tlv(0x17, days[1]))
+ + _name(cn) # subject
+ + _tlv(0x30, _tlv(0x30, _tlv(0x06, b"\x2a\x86\x48\x86\xf7\x0d"
+ b"\x01\x01\x01") + _tlv(0x05, b""))
+ + _tlv(0x03, b"\x00" + b"\xab" * 32)) # bogus PKI
+ + _san_ext(sans))
+ cert = (_tlv(0x30, tbs)
+ + _tlv(0x30, _tlv(0x06, b"\x2a\x86\x48\x86\xf7\x0d\x01\x01\x0b")
+ + _tlv(0x05, b""))
+ + _tlv(0x03, b"\x00" + b"\xcd" * 64))
+ return _tlv(0x30, cert)
+
+
+def tls_cert_record(der: bytes) -> bytes:
+ """EN: Wrap a DER cert into a TLS Certificate handshake record.
+ FR: Enveloppe un cert DER en enregistrement handshake Certificate."""
+ cert_entry = len(der).to_bytes(3, "big") + der
+ body = len(cert_entry).to_bytes(3, "big") + cert_entry
+ hs = b"\x0b" + len(body).to_bytes(3, "big") + body # type 11
+ return b"\x16\x03\x03" + struct.pack("!H", len(hs)) + hs
+
+
+# ── ICMP parsing / Parsing ICMP ─────────────────────────────────────────────
+
+def test_icmp_echo_payload_captured():
+ """EN: ICMP echo keeps type/code in flags and the payload head in
+ app_head — the tunnel heuristic's raw material.
+ FR: L'écho ICMP garde type/code dans flags et la tête dans app_head."""
+ tlscert.reset()
+ payload = b"\x08\x00\xf7\xff" + b"\x12\x34\x00\x01" + b"A" * 56
+ frame = eth(ipv4(b"\x0a\x00\x00\x01", b"\x08\x08\x08\x08", 1, payload))
+ p = parse_frame(ETH, frame)
+ assert p is not None and p.protocol == "ICMP"
+ assert p.tcp_flags >> 8 == 8 and p.tcp_flags & 0xFF == 0
+ assert p.app_head == b"A" * 56
+ assert p.tls_cert is None
+
+
+def test_icmpv6_echo_payload_captured():
+ """EN: ICMPv6 echo-request (type 128) gets the same treatment.
+ FR: L'écho ICMPv6 (type 128) reçoit le même traitement."""
+ tlscert.reset()
+ payload = b"\x80\x00\x00\x00" + b"\x00\x01\x00\x01" + b"B" * 40
+ src = bytes(range(16))
+ dst = bytes(range(16, 32))
+ plen = len(payload)
+ hdr = struct.pack("!IHBB16s16s", 6 << 28, plen, 58, 64, src, dst)
+ frame = eth(hdr + payload, ethertype=0x86DD)
+ p = parse_frame(ETH, frame)
+ assert p is not None and p.protocol == "ICMP"
+ assert p.tcp_flags >> 8 == 128
+ assert p.app_head == b"B" * 40
+
+
+def test_icmp_empty_payload_no_head():
+ """EN: A bare echo (no payload) produces an empty app_head — no
+ false tunnel signal. / FR: Un écho nu → app_head vide."""
+ tlscert.reset()
+ payload = b"\x08\x00\xf7\xff" + b"\x00\x01\x00\x01"
+ frame = eth(ipv4(b"\x0a\x00\x00\x01", b"\x08\x08\x08\x08", 1, payload))
+ p = parse_frame(ETH, frame)
+ assert p is not None and p.app_head == b""
+
+
+# ── TLS certificate / Certificat TLS ────────────────────────────────────────
+
+def test_tls_cert_parsed_single_segment():
+ """EN: A server Certificate record on :443 yields leaf metadata.
+ FR: Un enregistrement Certificate sur :443 donne les métadonnées."""
+ tlscert.reset()
+ der = make_cert("www.example.com", "Example CA",
+ ["www.example.com", "example.com"])
+ record = tls_cert_record(der)
+ cert = tlscert.feed_tls_stream("93.184.216.34", 443,
+ "10.0.0.5", 51000, record)
+ assert cert is not None
+ assert cert["subject_cn"] == "www.example.com"
+ assert cert["issuer_cn"] == "Example CA"
+ assert cert["self_signed"] is False
+ assert "example.com" in cert["sans"]
+ assert cert["not_before"] == "250101000000Z"
+
+
+def test_tls_cert_reassembled_two_segments():
+ """EN: The SAME record split mid-record still parses — the whole point
+ of the bounded reassembly buffer. / FR: Le même enregistrement coupé
+ en deux segments se parse quand même — c'est le but du tampon."""
+ tlscert.reset()
+ der = make_cert("a.example.org", "Self Root", ["a.example.org"])
+ record = tls_cert_record(der)
+ cut = len(record) // 2
+ assert tlscert.feed_tls_stream("1.2.3.4", 443, "10.0.0.1", 40000,
+ record[:cut]) is None
+ cert = tlscert.feed_tls_stream("1.2.3.4", 443, "10.0.0.1", 40000,
+ record[cut:])
+ assert cert is not None and cert["subject_cn"] == "a.example.org"
+
+
+def test_tls_self_signed_detected():
+ """EN: issuer == subject DER → self_signed=True.
+ FR: issuer == subject en DER → self_signed=True."""
+ tlscert.reset()
+ # EN: issuer DER must equal subject DER — same CN, no org either side.
+ # FR: issuer et subject identiques en DER — même CN, pas d'org.
+ der = make_cert("localhost", "localhost", ["localhost"],
+ issuer_org="")
+ cert = tlscert.feed_tls_stream("10.9.9.9", 443, "10.0.0.1", 40001,
+ tls_cert_record(der))
+ assert cert is not None and cert["self_signed"] is True
+
+
+def test_tls_wrong_port_ignored():
+ """EN: TLS bytes on a non-watched port are not buffered.
+ FR: Des octets TLS sur un port non surveillé ne sont pas tamponnés."""
+ tlscert.reset()
+ der = make_cert("x", "x", [])
+ assert tlscert.feed_tls_stream("1.2.3.4", 12345, "10.0.0.1", 999,
+ tls_cert_record(der)) is None
+ assert not tlscert._FLOWS
+
+
+def test_tls_garbage_dropped():
+ """EN: Mid-stream garbage never starts a buffer; over-cap buffers are
+ evicted. / FR: Du bruit ne démarre pas de tampon ; débordement expulsé."""
+ tlscert.reset()
+ assert tlscert.feed_tls_stream("1.2.3.4", 443, "10.0.0.1", 1,
+ b"GET / HTTP/1.1\r\n") is None
+ assert not tlscert._FLOWS
+ # EN: header then >16KiB → flow evicted / FR: en-tête puis >16 Kio → expulsé
+ tlscert.feed_tls_stream("1.2.3.4", 443, "10.0.0.1", 2, b"\x16\x03\x03")
+ tlscert.feed_tls_stream("1.2.3.4", 443, "10.0.0.1", 2, b"x" * 17000)
+ assert not tlscert._FLOWS
+
+
+def test_san_mismatch_wildcard():
+ """EN: Wildcard SANs cover exactly one label; bare SNI/mismatch flag.
+ FR: Les wildcards couvrent exactement un label."""
+ assert tlscert.san_mismatch("a.example.com", ["*.example.com"]) is False
+ assert tlscert.san_mismatch("a.b.example.com",
+ ["*.example.com"]) is True
+ assert tlscert.san_mismatch("example.com", ["*.example.com"]) is True
+ assert tlscert.san_mismatch("www.example.com",
+ ["www.example.com"]) is False
+ assert tlscert.san_mismatch(None, ["x"]) is False
+ assert tlscert.san_mismatch("x", []) is False
+
+
+def test_parser_tls_cert_end_to_end():
+ """EN: Full frame → tls_cert on the ParsedPacket.
+ FR: Trame complète → tls_cert sur le ParsedPacket."""
+ tlscert.reset()
+ der = make_cert("e2e.test", "E2E CA", ["e2e.test"])
+ seg = tcp(443, 51515, payload=tls_cert_record(der))
+ frame = eth(ipv4(b"\x5d\xb8\xd8\x22", b"\x0a\x00\x00\x05", 6, seg))
+ p = parse_frame(ETH, frame)
+ assert p is not None and p.tls_cert is not None
+ assert p.tls_cert["subject_cn"] == "e2e.test"
+
+
+# ── Isolation forest / Forêt d'isolation ────────────────────────────────────
+
+def test_iforest_scores_outlier_higher():
+ """EN: Trained on a tight cluster, an outlier must score clearly
+ above cluster members. / FR: Entraînée sur un cluster dense, un
+ outlier doit scorer nettement au-dessus."""
+ from detection.iforest import IsolationForest
+ # EN: Every feature must VARY in the training cloud — a constant
+ # column can never be split on, which would mask the outlier.
+ # FR: Chaque feature doit VARIER dans le nuage — une colonne
+ # constante ne peut jamais servir de split, ce qui masquerait
+ # l'outlier.
+ rng_pts = [[0.50 + (i % 10) * 0.002,
+ 0.50 + (i % 7) * 0.002,
+ 0.50 + (i % 5) * 0.002,
+ 0.50 + (i % 11) * 0.002,
+ 0.50 + (i % 3) * 0.002,
+ 0.50 + (i % 13) * 0.002]
+ for i in range(300)]
+ f = IsolationForest(seed=7)
+ assert f.fit(rng_pts) == 64
+ outlier = [0.99, 0.05, 0.99, 0.01, 0.99, 0.01]
+ normal = [0.51, 0.52, 0.50, 0.51, 0.50, 0.51]
+ # EN: Outlier must rank clearly above the cluster — the iForest's
+ # path-length compression keeps margins modest, so we assert a
+ # real gap AND the outlier sitting in the anomalous half.
+ # FR: L'outlier doit se classer nettement au-dessus — la compression
+ # des chemins garde les marges modestes → écart réel + zone
+ # anormale.
+ assert f.score(outlier) > f.score(normal) + 0.05
+ assert f.score(outlier) > 0.55
+ assert 0.0 <= f.score(normal) <= 1.0
+
+
+def test_iforest_too_small_is_honest():
+ """EN: Under 16 points the forest refuses to pretend — 0 trees, 0.0.
+ FR: Sous 16 points la forêt refuse de prétendre — 0 arbre, 0.0."""
+ from detection.iforest import IsolationForest
+ f = IsolationForest()
+ assert f.fit([[0.1] * 6 for _ in range(8)]) == 0
+ assert f.score([0.5] * 6) == 0.0
+
+
+def test_flow_ml_inert_then_scores():
+ """EN: The scorer stays inert below the training minimum, then emits
+ a dict for an extreme flow once fitted. / FR: Le scoreur reste inerte
+ sous le minimum d'entraînement, puis émet pour un flux extrême."""
+ from detection.mlflow import FlowAnomaly, _TRAIN_MIN
+ m = FlowAnomaly()
+ t = time.time()
+ # EN: Learn a boring baseline — same proc, same port, regular.
+ # FR: Une baseline monotone — même processus, même port, régulier.
+ for i in range(_TRAIN_MIN + 60):
+ m.observe("firefox", f"93.184.{i % 250}.{(i // 250)}",
+ 443, "out", 1200, t + i)
+ # EN: Score still available after training; an insane flow (weird
+ # port, giant packet, odd hour vs learned) should score higher.
+ # FR: Un flux aberrant doit scorer plus haut qu'un flux normal.
+ m._forest.fit(list(m._window))
+ m._fitted = True
+ normal_score = m._forest.score(
+ [443 / 65535.0, 1200 / 65535.0, 0.5, 0.5, 0.5, 1.0])
+ weird_score = m._forest.score(
+ [31337 / 65535.0, 65535 / 65535.0, 0.0, 1.0, 0.999, 1.0])
+ assert weird_score > normal_score
+
+
+def test_flow_ml_ignores_inbound_and_bad_ip():
+ """EN: Inbound packets and unparseable IPs produce nothing.
+ FR: Paquets entrants et IP imparsables ne produisent rien."""
+ from detection.mlflow import FlowAnomaly
+ m = FlowAnomaly()
+ assert m.observe("x", "1.2.3.4", 80, "in", 100) is None
+ assert m.observe("x", "not-an-ip", 80, "out", 100) is None
+
+
+# ── Custom rules geo + block / Règles géo + block ──────────────────────────
+
+def _pkt(remote="1.2.3.4", proc="curl", port=443, direction="out",
+ size=100, proto="TCP"):
+ """EN: Minimal Packet-shaped stub — only the fields the matcher reads.
+ FR: Stub minimal en forme de Packet — seulement les champs lus."""
+ class P:
+ dst_ip = remote if direction == "out" else "10.0.0.1"
+ src_ip = "10.0.0.1" if direction == "out" else remote
+ process_name = proc
+ remote_port = port
+ protocol = proto
+ direction_ = direction
+ size = 100
+ sni = None
+ dns: list = []
+ p = P()
+ p.direction = direction
+ p.size = size
+ return p
+
+
+def test_custom_rules_asn_country_via_geo():
+ """EN: asn/country fields resolve through the packet's geo record.
+ FR: Les champs asn/country se résolvent via l'enregistrement geo."""
+ from detection.customrules import CustomRules
+ cr = CustomRules()
+ cr.add("german", "country", "eq", "DE")
+ cr.add("asn", "asn", "eq", "12345")
+ geo = {"country": "DE", "asn": 12345}
+ hits = cr.check(_pkt(), geo)
+ assert {h["rule"]["name"] for h in hits} == {"german", "asn"}
+ # EN: no geo → fields are empty strings, no match / FR: sans geo → vide
+ assert cr.check(_pkt(), None) == []
+ assert cr.check(_pkt(), {"country": "FR", "asn": 1}) == []
+
+
+def test_custom_rules_block_action_validation():
+ """EN: action=block is accepted on blockable fields, rejected on
+ direction/size/protocol. / FR: action=block accepté sur champs
+ bloquables, refusé sur direction/size/protocol."""
+ from detection.customrules import CustomRules
+ cr = CustomRules()
+ for field in ("remote_ip", "host", "process_name", "asn", "country"):
+ r = cr.add(f"b-{field}", field, "eq", "x", action="block")
+ assert r["action"] == "block"
+ for field in ("direction", "size", "protocol", "remote_port"):
+ with pytest.raises(ValueError):
+ cr.add(f"bad-{field}", field, "eq", "x", action="block")
+ with pytest.raises(ValueError):
+ cr.add("bad-action", "remote_ip", "eq", "x", action="nuke")
+ # EN: bad ops for geo fields are rejected / FR: ops invalides refusées
+ with pytest.raises(ValueError):
+ cr.add("bad-op", "country", "gt", "x")
+ with pytest.raises(ValueError):
+ cr.add("bad-op2", "asn", "cidr", "1.0.0.0/8")
+
+
+# ── Syslog / Syslog ─────────────────────────────────────────────────────────
+
+def test_syslog_udp_rfc3164():
+ """EN: A UDP datagram in RFC 3164 shape — <PRI>TS HOST TAG: text with
+ local4.warning PRI = 156 for a warning alert.
+ FR: Datagramme UDP au format RFC 3164 — PRI local4.warning = 156."""
+ from api.notify import WebhookNotifier
+ n = WebhookNotifier()
+ srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ srv.bind(("127.0.0.1", 0))
+ srv.settimeout(3)
+ port = srv.getsockname()[1]
+ try:
+ n.configure("", enabled=False, syslog_addr=f"127.0.0.1:{port}")
+ n.dispatch({"severity": "warning", "type": "BEACON",
+ "message": "test beacon"})
+ data, _ = srv.recvfrom(2048)
+ text = data.decode()
+ assert text.startswith("<156>") # local4(19)*8 + warning(4)
+ assert "snitch[BEACON]" in text
+ assert "test beacon" in text
+ finally:
+ srv.close()
+
+
+def test_syslog_skips_info_severity():
+ """EN: info alerts are never forwarded — channel spam protection.
+ FR: Les alertes info ne sont jamais relayées — anti-spam."""
+ from api.notify import WebhookNotifier
+ n = WebhookNotifier()
+ srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ srv.bind(("127.0.0.1", 0))
+ srv.settimeout(0.4)
+ port = srv.getsockname()[1]
+ try:
+ n.configure("", enabled=False, syslog_addr=f"127.0.0.1:{port}")
+ n.dispatch({"severity": "info", "type": "NEW_HOST",
+ "message": "quiet"})
+ with pytest.raises(socket.timeout):
+ srv.recvfrom(512)
+ finally:
+ srv.close()
+
+
+def test_syslog_bad_addr_never_raises():
+ """EN: A bogus syslog address must not break the detection path.
+ FR: Une adresse syslog invalide ne doit pas casser la détection."""
+ from api.notify import WebhookNotifier
+ n = WebhookNotifier()
+ n.configure("", enabled=False, syslog_addr="nonexistent.invalid:514")
+ n.dispatch({"severity": "critical", "type": "X", "message": "m"})
+
+
+# ── NFQUEUE flow key / Clé de flux NFQUEUE ──────────────────────────────────
+
+def test_askmode_flow_key_tcp_syn():
+ """EN: IPv4 TCP SYN → (dst, dport, TCP); non-SYN → None; UDP → key.
+ FR: SYN TCP IPv4 → clé ; non-SYN → None ; UDP → clé."""
+ from detection.askmode import AskMode
+ # EN: SYN set, ACK clear → asked / FR: SYN posé, ACK effacé → demandé
+ syn = tcp(50000, 443, flags=0x02)
+ ip = ipv4(b"\x0a\x00\x00\x01", b"\x08\x08\x08\x08", 6, syn)
+ assert AskMode._flow_key(ip) == ("8.8.8.8", 443, "TCP")
+ # EN: ACK-only packet rides the stored decision → None
+ # FR: Paquet ACK seul → décision stockée → None
+ ack = tcp(50000, 443, flags=0x10)
+ ip2 = ipv4(b"\x0a\x00\x00\x01", b"\x08\x08\x08\x08", 6, ack)
+ assert AskMode._flow_key(ip2) is None
+ u = b"\x13\x88\x00\x35" + struct.pack("!HH", 8, 0)
+ ip3 = ipv4(b"\x0a\x00\x00\x01", b"\x08\x08\x08\x08", 17, u)
+ assert AskMode._flow_key(ip3) == ("8.8.8.8", 53, "UDP")
+
+
+def test_askmode_available_honest_on_nonlinux():
+ """EN: On this Mac the capability probe must honestly report Linux-
+ only (or missing deps) — never pretend. / FR: Sur ce Mac la sonde
+ doit honnêtement rapporter Linux-only — jamais prétendre."""
+ import platform
+ from detection.askmode import available
+ ok, why = available()
+ if platform.system().lower() != "linux":
+ assert ok is False and "linux" in why.lower()
+
+
+def test_askmode_decide_unknown_flow():
+ """EN: A verdict for a flow that never pended returns False — no
+ crash. / FR: Un verdict pour un flux inconnu renvoie False."""
+ from detection.askmode import AskMode
+ am = AskMode(lambda ctx: None)
+ assert am.decide("9.9.9.9", 443, "TCP", True) is False
+ st = am.status()
+ assert st["running"] is False and st["pending"] == 0
+
+
+# ── IOC peer sync / Sync IOC entre pairs ────────────────────────────────────
+
+def test_gossip_configure_dedup_and_prefix():
+ """EN: Peer list is deduped, scheme-prefixed, bounded.
+ FR: La liste de pairs est dédupliquée, préfixée, bornée."""
+ from detection.gossip import PeerSync
+ ps = PeerSync(lambda: "tok")
+ ps.configure(["10.0.0.2:8080", "http://10.0.0.2:8080",
+ " https://sec.example:9/", "", " "])
+ assert ps.peers == ["http://10.0.0.2:8080", "https://sec.example:9"]
+ ps.configure([f"h{i}" for i in range(40)])
+ assert len(ps.peers) == 32
+
+
+def test_gossip_push_no_peers():
+ """EN: Push with no peers is an honest error, never an exception.
+ FR: Push sans pairs = erreur honnête, jamais d'exception."""
+ from detection.gossip import PeerSync
+ assert PeerSync(lambda: "t").push_pack({"a": 1})["ok"] is False
+
+
+def test_gossip_push_calls_import_endpoint(monkeypatch):
+ """EN: The pack is POSTed as JSON to each peer's authenticated import
+ endpoint with the bearer token. / FR: Le pack est POSTé en JSON vers
+ l'endpoint import authentifié de chaque pair."""
+ from detection import gossip
+ calls = []
+
+ class R:
+ status = 200
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def fake_urlopen(req, timeout=0):
+ calls.append((req.full_url, req.headers.get("Authorization"),
+ req.data))
+ return R()
+
+ monkeypatch.setattr(gossip.urllib.request, "urlopen", fake_urlopen)
+ ps = gossip.PeerSync(lambda: "TOKEN")
+ ps.configure(["peer1:1"])
+ res = ps.push_pack({"format": "snitch-ioc-proof/1"})
+ assert res["ok"] is True
+ assert calls[0][0] == "http://peer1:1/security/iocpack/import"
+ assert calls[0][1] == "Bearer TOKEN"
+ assert b"snitch-ioc-proof" in calls[0][2]
+
+
+# ── Capability probes / Sondes de capacité ──────────────────────────────────
+
+def test_hollow_available_honest():
+ """EN: hollowing check reports its platform honestly — False off
+ Linux. / FR: le check hollowing rapporte honnêtement — False hors
+ Linux."""
+ import platform
+ from detection.hollow import available, hollow_check
+ ok, why = available()
+ if platform.system().lower() != "linux":
+ assert ok is False
+ res = hollow_check(1)
+ assert res["ok"] is False and "linux" in res["error"].lower()
+
+
+def test_ebpf_enforce_honest():
+ """EN: cgroup-skb enforcer reports unavailable cleanly off-Linux and
+ refuses to block before start. / FR: l'enforcer cgroup-skb rapporte
+ indisponible hors Linux et refuse de bloquer avant start."""
+ from detection.ebpf_enforce import EbpfEnforcer, available
+ ok, why = available()
+ e = EbpfEnforcer()
+ if not ok:
+ blk, reason = e.block_ip("1.2.3.4")
+ assert blk is False and reason
+ started, _why2 = e.start()
+ assert started is False
+
+
+def test_explain_covers_new_types():
+ """EN: Every new alert type has a bilingual explanation template.
+ FR: Chaque nouveau type d'alerte a un gabarit bilingue."""
+ from detection.explain import explain
+ for t in ("TLS_CERT", "HIGH_ENTROPY", "ICMP_TUNNEL", "ML_ANOMALY",
+ "ASK_VERDICT"):
+ rec = explain(t)
+ assert rec is not None, t
+ assert rec["what_en"] and rec["what_fr"]
+ assert rec["actions_en"] and rec["actions_fr"]
diff --git a/backend/version.py b/backend/version.py
index f016669..36d1611 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.4.0"
+__version__ = "1.5.0"
diff --git a/docs/FIREWALL.md b/docs/FIREWALL.md
index 855adb9..8c12a47 100644
--- a/docs/FIREWALL.md
+++ b/docs/FIREWALL.md
@@ -15,7 +15,7 @@ applied to the OS-native firewall, best-effort:
| OS | Mechanism |
|---|---|
| Windows | **WFP user-mode filters** via `fwpuclnt.dll` (ctypes, elevated) — `netsh advfirewall` remains the fallback |
-| Linux | `iptables -A OUTPUT -j DROP` (dedicated `SNITCH_LOCK` chain for lockdown); `tc` clsact/flower for throttling |
+| Linux | `nftables` when available (dedicated `inet snitch` table, rules removed by handle/comment), `iptables -A OUTPUT -j DROP` otherwise (`SNITCH_LOCK` chain for lockdown); `tc` clsact/flower for throttling |
| macOS | generated `pf` anchor loaded with `pfctl` |
On Windows, `detection/wfp.py` talks to the **Windows Filtering Platform**
@@ -182,10 +182,12 @@ never ship data off the machine:
uses — no hidden code path — and dedup against identical rules.
- **Custom alert rules** — `GET/POST/DELETE /alerts/rules` plus a
per-rule toggle. One field (`remote_ip`, `host`, `process_name`,
- `remote_port`, `protocol`, `direction`, `size`), one operator
- (`eq`, `ne`, `contains`, `regex`, `gt`, `lt`, `cidr`), one value →
- `CUSTOM_RULE` alerts with hit counters. Validated at creation,
- bounded regex cache, **alert-only** — blocking stays the firewall's.
+ `remote_port`, `protocol`, `direction`, `size`, `asn`, `country`),
+ one operator (`eq`, `ne`, `contains`, `regex`, `gt`, `lt`, `cidr`),
+ one value → `CUSTOM_RULE` alerts with hit counters. Validated at
+ creation, bounded regex cache. Default `action` is `alert`; setting
+ `action=block` also installs a real firewall rule on the matched
+ remote IP (deduped per rule+target) — the opt-in kill-switch.
- **Blocklist import** — `POST /firewall/blocklist` turns a local
hosts/domain file (a pure local read) or an opt-in URL (bounded
4 MiB HTTPS fetch — one of the few outbound requests Snitch can ever
@@ -215,6 +217,58 @@ never ship data off the machine:
- **ASN attribution** — when `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb`
is present, nodes carry `asn` (AS number) alongside `org`.
+### Passive inspection, kernel verdicts & fleet sync (v1.5)
+
+- **Passive TLS certificate inspection** — the parser reassembles
+ bounded TCP streams (≤16 KiB/flow, 30 s TTL) and reads the
+ `Certificate` handshake message: issuer/subject CN+O, self-signed
+ flag, DNS SANs, validity window, and `san_mismatch` against the
+ observed SNI → `TLS_CERT` alerts. **TLS 1.3 stays opaque** — its
+ certificates are encrypted, Snitch reports nothing rather than
+ guessing. No MITM, no decryption, no injected CA.
+- **High-entropy cleartext watch** — payloads ≥48 B on non-TLS
+ channels scoring ≥4.7 bits/byte raise `HIGH_ENTROPY` (covert
+ encryption/stego hint). Per-host 10-min cooldown.
+- **ICMP tunnel heuristic** — echo types carrying ≥24 B payloads,
+ repeated ≥3× in 5 min → `ICMP_TUNNEL` (ptunnel/icmpsh signature).
+- **ML flow anomaly** — pure-Python isolation forest (64 trees, zero
+ dependencies) over your own flow summaries — port, size, interval,
+ fan-out, hour. Inert below 384 learned flows, refits every 256,
+ score ≥0.62 → `ML_ANOMALY`. Baseline deviation, **not** a malware
+ classifier.
+- **Ask-on-connect (Linux, opt-in)** — `ask_enabled=1` + root +
+ `python-netfilterqueue`: new outbound flows are held on NFQUEUE 7
+ until you answer `POST /security/ask {flow_id, allow}` in the UI —
+ the Little Snitch-style prompt, for real. Default timeout 15 s,
+ fail-closed (`ask_failopen=1` to reverse). Windows/macOS need the
+ signed callout/NetworkExtension skeletons in `contrib/` — user-mode
+ cannot hold a connection.
+- **eBPF cgroup enforcement (Linux, opt-in)** — `ebpf_enforce.py`
+ moves a contained process into a dedicated cgroup and attaches a
+ `cgroup_skb/egress` program dropping its packets kernel-side.
+ Honest `available()` probe; firewall rules remain the fallback.
+- **Process-hollowing check (Linux)** — `GET /security/hollow/{pid}`
+ reads executable file-backed pages from `/proc/<pid>/mem` and diffs
+ them against the on-disk binary → bounded mismatch evidence.
+- **IOC peer sync (opt-in)** — `gossip_peers` lists up to 32 explicit
+ `host:port` Snitch instances; salted-Merkle proof packs are pushed
+ over authenticated HTTP(S), 8 s timeout. No discovery, no central
+ server — and it is **not** a zero-knowledge protocol: commitments
+ prove exact membership only.
+- **Syslog output (opt-in)** — `syslog_addr` (`host:port` UDP or
+ `tcp://host:port`) forwards warning/critical alerts as RFC 3164
+ `local4` — Wazuh/SIEM-ready. Independent of webhooks.
+- **Firejail containment** — `security/sandbox` prefers
+ `firejail --net=none` when present, falls back to `unshare`.
+- **nftables backend** — where `nft` exists, rules land in a dedicated
+ `inet snitch` table instead of iptables; `iptables-nft` hosts are
+ detected and keep the iptables path.
+- **Actionable alerts** — every alert carries structured `actions`
+ (block IP, kill/suspend process, ask verdict, inspect memory); the
+ UI renders them as one-click buttons.
+- **`asn`/`country` in custom rules** — matched against the local
+ geo DB, usable with `action=block` for a geo-fence kill-switch.
+
---
## Français
@@ -404,10 +458,12 @@ honnêtement et n'envoient jamais de données hors de la machine :
l'UI — aucun chemin caché — avec dédup des règles identiques.
- **Règles d'alerte personnalisées** — `GET/POST/DELETE /alerts/rules`
+ bascule par règle. Un champ (`remote_ip`, `host`, `process_name`,
- `remote_port`, `protocol`, `direction`, `size`), un opérateur
- (`eq`, `ne`, `contains`, `regex`, `gt`, `lt`, `cidr`), une valeur →
- alertes `CUSTOM_RULE` avec compteurs. Validées à la création, cache
- regex borné, **alerte seule** — le blocage reste au pare-feu.
+ `remote_port`, `protocol`, `direction`, `size`, `asn`, `country`),
+ un opérateur (`eq`, `ne`, `contains`, `regex`, `gt`, `lt`, `cidr`),
+ une valeur → alertes `CUSTOM_RULE` avec compteurs. Validées à la
+ création, cache regex borné. L'`action` par défaut est `alert` ;
+ `action=block` installe de plus une vraie règle pare-feu sur l'IP
+ distante matchée (dédup par règle+cible) — le kill-switch opt-in.
- **Import de blocklist** — `POST /firewall/blocklist` convertit un
fichier hosts/domaines local (lecture purement locale) ou une URL
opt-in (fetch HTTPS borné à 4 Mio — l'une des rares requêtes sortantes
@@ -437,3 +493,54 @@ honnêtement et n'envoient jamais de données hors de la machine :
non livrés, non chargés par Snitch.
- **Attribution ASN** — quand `GeoLite2-ASN.mmdb`/`dbip-asn-lite.mmdb`
est présente, les nœuds portent `asn` (numéro d'AS) en plus de `org`.
+
+### Inspection passive, verdicts noyau & sync de flotte (v1.5)
+
+- **Inspection TLS passive** — le parseur réassemble des flux TCP
+ bornés (≤16 Kio/flux, TTL 30 s) et lit le message `Certificate` :
+ CN+O émetteur/sujet, drapeau auto-signé, SANs DNS, fenêtre de
+ validité, `san_mismatch` vs le SNI observé → alertes `TLS_CERT`.
+ **TLS 1.3 reste opaque** — ses certificats sont chiffrés, Snitch ne
+ rapporte rien plutôt que deviner. Pas de MITM, pas de déchiffrement.
+- **Veille d'entropie en clair** — payloads ≥48 o hors TLS à ≥4,7
+ bits/octet → `HIGH_ENTROPY` (indice de chiffrement couvert/stégo).
+ Cooldown 10 min par hôte.
+- **Heuristique tunnel ICMP** — types echo portant ≥24 o, répétés
+ ≥3× en 5 min → `ICMP_TUNNEL` (signature ptunnel/icmpsh).
+- **Anomalie ML de flux** — forêt d'isolation pur Python (64 arbres,
+ zéro dépendance) sur vos propres résumés de flux — port, taille,
+ intervalle, fan-out, heure. Inerte sous 384 flux appris, réajustée
+ tous les 256, score ≥0,62 → `ML_ANOMALY`. Déviation de baseline,
+ **pas** un classifieur de malware.
+- **Ask-on-connect (Linux, opt-in)** — `ask_enabled=1` + root +
+ `python-netfilterqueue` : les nouveaux flux sortants sont retenus
+ sur NFQUEUE 7 jusqu'à votre `POST /security/ask {flow_id, allow}`
+ dans l'UI — la pop-up façon Little Snitch, pour de vrai. Timeout
+ 15 s, fail-closed (`ask_failopen=1` inverse). Windows/macOS exigent
+ les callout/NetworkExtension signés de `contrib/` — le user-mode ne
+ peut pas suspendre une connexion.
+- **Enforcement eBPF cgroup (Linux, opt-in)** — `ebpf_enforce.py`
+ déplace un processus contenu dans un cgroup dédié et attache un
+ programme `cgroup_skb/egress` qui droppe ses paquets côté noyau.
+ Sonde `available()` honnête ; les règles pare-feu restent le repli.
+- **Vérif process-hollowing (Linux)** — `GET /security/hollow/{pid}`
+ lit les pages exécutables fichier-mappées de `/proc/<pid>/mem` et
+ les compare au binaire disque → preuve de mismatch bornée.
+- **Sync IOC entre pairs (opt-in)** — `gossip_peers` liste jusqu'à
+ 32 instances Snitch `host:port` explicites ; les packs de preuves
+ Merkle salés sont poussés en HTTP(S) authentifié, timeout 8 s. Ni
+ découverte ni serveur central — et ce n'est **pas** du zero-knowledge :
+ les engagements prouvent seulement l'appartenance exacte.
+- **Sortie syslog (opt-in)** — `syslog_addr` (`host:port` UDP ou
+ `tcp://host:port`) relaie les alertes warning/critiques en RFC 3164
+ `local4` — prêt pour Wazuh/SIEM. Indépendant des webhooks.
+- **Containment Firejail** — `security/sandbox` préfère
+ `firejail --net=none` s'il est présent, repli `unshare`.
+- **Backend nftables** — là où `nft` existe, les règles vont dans une
+ table `inet snitch` dédiée plutôt que iptables ; les hôtes
+ `iptables-nft` sont détectés et gardent le chemin iptables.
+- **Alertes actionnables** — chaque alerte porte des `actions`
+ structurées (bloquer IP, tuer/suspendre, verdict ask, inspecter la
+ mémoire) rendues en boutons un clic dans l'UI.
+- **`asn`/`country` dans les règles custom** — matchés sur la base
+ geo locale, combinables avec `action=block` pour un geo-fence.
diff --git a/electron/package.json b/electron/package.json
index 7903c02..79ac01c 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch",
- "version": "1.4.0",
+ "version": "1.5.0",
"description": "Snitch \u2014 real-time network traffic visualizer / visualiseur de trafic r\u00e9seau en temps r\u00e9el",
"main": "main.js",
"license": "AGPL-3.0-or-later",
diff --git a/frontend/package.json b/frontend/package.json
index 342d55b..56be8a8 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch-frontend",
- "version": "1.4.0",
+ "version": "1.5.0",
"private": true,
"license": "AGPL-3.0-or-later",
"description": "Snitch UI \u2014 React + D3.js / Interface React + D3.js",
diff --git a/frontend/src/components/AlertPanel.jsx b/frontend/src/components/AlertPanel.jsx
index de65224..45b7975 100644
--- a/frontend/src/components/AlertPanel.jsx
+++ b/frontend/src/components/AlertPanel.jsx
@@ -21,6 +21,7 @@ import {
Activity, Unlock, TrendingUp, Camera, ShieldAlert,
FileWarning, Fingerprint, Cpu, HelpCircle,
Pickaxe, Magnet, Syringe, Package, ListFilter,
+ Ban, Skull, Pause, ShieldCheck, ShieldX, Brain, Waves,
} from 'lucide-react'
import { useT } from '../i18n'
import { apiBase, authHeaders } from '../api'
@@ -61,6 +62,85 @@ const TYPE_ICONS = {
SINKHOLE_HIT: Magnet,
INJECT_SUSPECT: Syringe,
CUSTOM_RULE: ListFilter,
+ TLS_CERT: Fingerprint,
+ HIGH_ENTROPY: Waves,
+ ICMP_TUNNEL: Activity,
+ ML_ANOMALY: Brain,
+ ASK_VERDICT: HelpCircle,
+}
+
+/**
+ * EN: One-click incident response on an alert — real API calls, tiny
+ * inline buttons under the alert body. `block` creates a real OS
+ * firewall rule on the remote IP; `kill`/`suspend` act on the
+ * reported pid; ASK_VERDICT alerts get allow/deny that resolves the
+ * held NFQUEUE packet. Errors stay silent — the action is best-effort
+ * remediation, the alert itself is the durable record.
+ * FR: Réponse à incident en un clic sur une alerte — vrais appels API.
+ * `block` crée une vraie règle pare-feu OS sur l'IP distante ;
+ * `kill`/`suspend` agissent sur le pid rapporté ; les alertes
+ * ASK_VERDICT ont autoriser/refuser qui résout le paquet NFQUEUE
+ * gelé. Échecs silencieux — remédiation au mieux.
+ */
+function AlertActions({ alert }) {
+ const { t } = useT()
+ const [done, setDone] = useState('')
+ const d = alert.details || {}
+ const post = async (path, body, tag) => {
+ try {
+ const base = await apiBase()
+ const headers = { ...(await authHeaders()), 'Content-Type': 'application/json' }
+ const r = await fetch(`${base}${path}`, {
+ method: 'POST', headers, body: JSON.stringify(body),
+ })
+ if (r.ok) setDone(tag)
+ } catch { /* best-effort remediation */ }
+ }
+ const btn = {
+ 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,
+ }
+ return (
+ <>
+ {alert.type === 'ASK_VERDICT' && d.remote_ip && (
+ <>
+ <button onClick={() => post('/security/ask/verdict',
+ { remote_ip: d.remote_ip, remote_port: d.remote_port,
+ proto: d.proto, allow: true }, 'allow')}
+ style={{ ...btn, color: '#4ade80', borderColor: '#4ade8044' }}>
+ <ShieldCheck size={10} /> {t('alert_act_allow')}
+ </button>
+ <button onClick={() => post('/security/ask/verdict',
+ { remote_ip: d.remote_ip, remote_port: d.remote_port,
+ proto: d.proto, allow: false }, 'deny')}
+ style={{ ...btn, color: '#ef4444', borderColor: '#ef444444' }}>
+ <ShieldX size={10} /> {t('alert_act_deny')}
+ </button>
+ </>
+ )}
+ {d.ip && !alert._grouped && done !== 'block' && (
+ <button onClick={() => post('/firewall/rules',
+ { kind: 'ip', value: d.ip, action: 'block' }, 'block')}
+ title={t('alert_act_block')} style={btn}>
+ <Ban size={10} /> {t('alert_act_block')}
+ </button>
+ )}
+ {d.pid && !alert._grouped && (
+ <>
+ <button onClick={() => post('/processes/kill', { pid: d.pid }, 'kill')}
+ title={t('alert_act_kill')} style={{ ...btn, color: '#ef4444' }}>
+ <Skull size={10} /> {t('alert_act_kill')}
+ </button>
+ <button onClick={() => post('/processes/suspend', { pid: d.pid }, 'suspend')}
+ title={t('alert_act_suspend')} style={btn}>
+ <Pause size={10} /> {t('alert_act_suspend')}
+ </button>
+ </>
+ )}
+ {done && <span style={{ fontSize: 9, color: '#4ade80' }}>✓ {done}</span>}
+ </>
+ )
}
/**
@@ -267,6 +347,7 @@ function AlertRow({ alert, onIgnore }) {
{t('ignore_alert')}
</button>
)}
+ <AlertActions alert={alert} />
</div>
</div>
</div>
diff --git a/frontend/src/components/Firewall.jsx b/frontend/src/components/Firewall.jsx
index dd46f93..dbc7ee6 100644
--- a/frontend/src/components/Firewall.jsx
+++ b/frontend/src/components/Firewall.jsx
@@ -62,6 +62,7 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
const [arOp, setArOp] = useState('contains')
const [arValue, setArValue] = useState('')
const [arSev, setArSev] = useState('warning')
+ const [arAction, setArAction] = useState('alert')
const refresh = useCallback(async () => {
const base = await apiBase()
@@ -233,7 +234,7 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
try {
await post('/alerts/rules', {
name: arName.trim(), field: arField, op: arOp,
- value: arValue.trim(), severity: arSev,
+ value: arValue.trim(), severity: arSev, action: arAction,
})
setArName(''); setArValue('')
refresh()
@@ -459,10 +460,12 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
</div>
{/* EN: Custom alert rules — user-defined matchers that raise
- CUSTOM_RULE alerts (alert-only, never block).
+ CUSTOM_RULE alerts; the "block" action additionally
+ installs a real firewall rule on the matched host.
FR: Règles d'alerte personnalisées — filtres définis par
- l'utilisateur qui lèvent des alertes CUSTOM_RULE (alerte
- seule, jamais de blocage). */}
+ l'utilisateur qui lèvent des alertes CUSTOM_RULE ;
+ l'action « block » installe en plus une vraie règle
+ pare-feu sur l'hôte matché. */}
<div style={{ borderTop: '1px solid var(--border)', marginTop: 10, paddingTop: 8 }}>
<div style={label}>{t('ar_title')}</div>
<div style={hint}>{t('ar_hint')}</div>
@@ -471,7 +474,7 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
placeholder={t('ar_name_ph')} aria-label={t('ar_name_ph')}
style={{ ...input, flex: '1 1 100%' }} />
<select value={arField} onChange={e => setArField(e.target.value)} aria-label={t('ar_field')} style={{ ...input }}>
- {['remote_ip', 'host', 'process_name', 'remote_port', 'protocol', 'direction', 'size'].map(f =>
+ {['remote_ip', 'host', 'process_name', 'remote_port', 'protocol', 'direction', 'size', 'asn', 'country'].map(f =>
<option key={f} value={f}>{f}</option>)}
</select>
<select value={arOp} onChange={e => setArOp(e.target.value)} aria-label={t('ar_op')} style={{ ...input }}>
@@ -486,6 +489,10 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
<option value="warning">{t('sev_warning')}</option>
<option value="critical">{t('sev_critical')}</option>
</select>
+ <select value={arAction} onChange={e => setArAction(e.target.value)} aria-label={t('ar_action')} style={{ ...input }}>
+ <option value="alert">{t('ar_action_alert')}</option>
+ <option value="block">{t('ar_action_block')}</option>
+ </select>
<button type="submit" style={{
background: '#3b82f6', border: 'none', borderRadius: 6,
color: '#fff', padding: '6px 10px', cursor: 'pointer',
@@ -496,6 +503,13 @@ export function FirewallPanel({ onClose, onLockdownChange }) {
<div key={r.id} style={{ ...row, padding: '5px 0' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<span style={{ fontSize: 10, color: 'var(--text)' }}>{r.name}</span>
+ {r.action === 'block' && (
+ <span style={{
+ fontSize: 8, fontWeight: 700, color: '#ef4444',
+ background: 'var(--bg)', borderRadius: 3,
+ padding: '0 4px', marginLeft: 5, textTransform: 'uppercase',
+ }}>{t('ar_action_block')}</span>
+ )}
<div style={hint}>
{r.field} {r.op} {r.value}
{r.hits > 0 && ` · ${t('ar_hits', r.hits)}`}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 7c28fdd..229d69f 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -395,7 +395,7 @@ export default {
bl_truncated: 'Liste am Limit gekürzt',
bl_remote: 'Remote-Abruf durchgeführt',
ar_title: 'Eigene Alarmregeln',
- ar_hint: 'CUSTOM_RULE-Alarme für eigene Muster auslösen — nur Alarm, nie Blockierung.',
+ ar_hint: 'CUSTOM_RULE-Alarme für eigene Muster — oder „Alarm + Block“ für automatische Firewall-Regeln.',
ar_name_ph: 'Regelname (optional)',
ar_field: 'Feld',
ar_op: 'Operator',
@@ -418,4 +418,22 @@ export default {
sb_done: code => `In Sandbox ausgeführt — Exit ${code}`,
sb_failed: 'Sandbox auf dieser Plattform nicht verfügbar',
alertmsg_CUSTOM_RULE: d => `Eigene Regel ausgelöst: ${d.rule?.name || 'unbenannte Regel'}`,
+ alert_TLS_CERT: 'TLS-Zertifikat',
+ alert_HIGH_ENTROPY: 'Hohe Entropie',
+ alert_ICMP_TUNNEL: 'ICMP-Tunnel',
+ alert_ML_ANOMALY: 'ML-Anomalie',
+ alert_ASK_VERDICT: 'Entscheid nötig',
+ alertmsg_TLS_CERT: d => `TLS-Zertifikatsanomalie für ${d.host || d.ip}: ${(d.reasons || []).join(', ')} (Aussteller ${d.issuer || '?'})`,
+ alertmsg_HIGH_ENTROPY: d => `Hoch-Entropie-Payload auf Klartextkanal ${d.process || '?'} → ${d.ip}:${d.port} (${d.entropy} Bits/Byte)`,
+ alertmsg_ICMP_TUNNEL: d => `Möglicher ICMP-Tunnel: wiederholte große Echo-Payloads mit ${d.ip}`,
+ alertmsg_ML_ANOMALY: d => `ML-Flussanomalie: ${d.process || '?'} → ${d.ip} (Score ${d.score})`,
+ alertmsg_ASK_VERDICT: d => `Entscheid nötig: ${d.process || 'ein Prozess'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (Auto-Entscheid in ${d.timeout_s}s)`,
+ alert_act_block: 'IP blockieren',
+ alert_act_kill: 'Beenden',
+ alert_act_suspend: 'Anhalten',
+ alert_act_allow: 'Erlauben',
+ alert_act_deny: 'Verweigern',
+ ar_action: 'Aktion',
+ ar_action_alert: 'Nur Alarm',
+ ar_action_block: 'Alarm + Block',
}
diff --git a/frontend/src/locales/en.js b/frontend/src/locales/en.js
index 22cdabe..274f152 100644
--- a/frontend/src/locales/en.js
+++ b/frontend/src/locales/en.js
@@ -399,7 +399,7 @@ export default { // Navigation
bl_truncated: 'list truncated at the cap',
bl_remote: 'remote fetch performed',
ar_title: 'Custom alert rules',
- ar_hint: 'Raise CUSTOM_RULE alerts on your own matches — alert-only, never blocks.',
+ ar_hint: 'Raise CUSTOM_RULE alerts on your own matches — or \'alert + block\' to auto-firewall matched hosts.',
ar_name_ph: 'Rule name (optional)',
ar_field: 'Field',
ar_op: 'Operator',
@@ -422,4 +422,22 @@ export default { // Navigation
sb_done: code => `Ran in sandbox — exit ${code}`,
sb_failed: 'Sandbox unavailable on this platform',
alertmsg_CUSTOM_RULE: d => `Custom rule matched: ${d.rule?.name || 'unnamed rule'}`,
+ alert_TLS_CERT: 'TLS certificate',
+ alert_HIGH_ENTROPY: 'High entropy',
+ alert_ICMP_TUNNEL: 'ICMP tunnel',
+ alert_ML_ANOMALY: 'ML anomaly',
+ alert_ASK_VERDICT: 'Verdict needed',
+ alertmsg_TLS_CERT: d => `TLS cert anomaly for ${d.host || d.ip}: ${(d.reasons || []).join(', ')} (issuer ${d.issuer || '?'})`,
+ alertmsg_HIGH_ENTROPY: d => `High-entropy payload on cleartext channel ${d.process || '?'} → ${d.ip}:${d.port} (${d.entropy} bits/byte)`,
+ alertmsg_ICMP_TUNNEL: d => `Possible ICMP tunnelling: repeated fat echo payloads with ${d.ip}`,
+ alertmsg_ML_ANOMALY: d => `ML flow anomaly: ${d.process || '?'} → ${d.ip} (score ${d.score})`,
+ alertmsg_ASK_VERDICT: d => `Verdict needed: ${d.process || 'a process'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (auto-decision in ${d.timeout_s}s)`,
+ alert_act_block: 'Block IP',
+ alert_act_kill: 'Kill',
+ alert_act_suspend: 'Suspend',
+ alert_act_allow: 'Allow',
+ alert_act_deny: 'Deny',
+ ar_action: 'Action',
+ ar_action_alert: 'Alert only',
+ ar_action_block: 'Alert + block',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 0066914..886e2c6 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -393,7 +393,7 @@ export default { // Navegación
bl_truncated: 'lista truncada al límite',
bl_remote: 'descarga remota realizada',
ar_title: 'Reglas de alerta personalizadas',
- ar_hint: 'Lanza alertas CUSTOM_RULE con tus propios patrones — solo alerta, nunca bloquea.',
+ ar_hint: 'Lanza alertas CUSTOM_RULE con tus propios patrones — o «alerta + bloqueo» para cortafuegos automático.',
ar_name_ph: 'Nombre de la regla (opcional)',
ar_field: 'Campo',
ar_op: 'Operador',
@@ -416,4 +416,22 @@ export default { // Navegación
sb_done: code => `Ejecutado en sandbox — salida ${code}`,
sb_failed: 'Sandbox no disponible en esta plataforma',
alertmsg_CUSTOM_RULE: d => `Regla personalizada activada: ${d.rule?.name || 'regla sin nombre'}`,
+ alert_TLS_CERT: 'Certificado TLS',
+ alert_HIGH_ENTROPY: 'Alta entropía',
+ alert_ICMP_TUNNEL: 'Túnel ICMP',
+ alert_ML_ANOMALY: 'Anomalía ML',
+ alert_ASK_VERDICT: 'Veredicto requerido',
+ alertmsg_TLS_CERT: d => `Anomalía del certificado TLS para ${d.host || d.ip}: ${(d.reasons || []).join(', ')} (emisor ${d.issuer || '?'})`,
+ alertmsg_HIGH_ENTROPY: d => `Payload de alta entropía en canal en claro ${d.process || '?'} → ${d.ip}:${d.port} (${d.entropy} bits/byte)`,
+ alertmsg_ICMP_TUNNEL: d => `Posible túnel ICMP: ecos repetidos con payloads grandes hacia ${d.ip}`,
+ alertmsg_ML_ANOMALY: d => `Anomalía ML de flujo: ${d.process || '?'} → ${d.ip} (puntuación ${d.score})`,
+ alertmsg_ASK_VERDICT: d => `Veredicto requerido: ${d.process || 'un proceso'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (decisión auto en ${d.timeout_s}s)`,
+ alert_act_block: 'Bloquear IP',
+ alert_act_kill: 'Matar',
+ alert_act_suspend: 'Suspender',
+ alert_act_allow: 'Permitir',
+ alert_act_deny: 'Denegar',
+ ar_action: 'Acción',
+ ar_action_alert: 'Solo alerta',
+ ar_action_block: 'Alerta + bloqueo',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index ea16779..7d994cf 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -395,7 +395,7 @@ export default { // Navigation
bl_truncated: 'liste tronquée au plafond',
bl_remote: 'fetch distant effectué',
ar_title: "Règles d'alerte personnalisées",
- ar_hint: 'Lever des alertes CUSTOM_RULE sur vos propres motifs — alerte seule, jamais de blocage.',
+ ar_hint: 'Lever des alertes CUSTOM_RULE sur vos propres motifs — ou « alerte + blocage » pour pare-feu automatique sur l\'hôte.',
ar_name_ph: 'Nom de la règle (optionnel)',
ar_field: 'Champ',
ar_op: 'Opérateur',
@@ -418,4 +418,22 @@ export default { // Navigation
sb_done: code => `Exécuté en sandbox — sortie ${code}`,
sb_failed: 'Sandbox indisponible sur cette plateforme',
alertmsg_CUSTOM_RULE: d => `Règle personnalisée déclenchée : ${d.rule?.name || 'règle sans nom'}`,
+ alert_TLS_CERT: 'Certificat TLS',
+ alert_HIGH_ENTROPY: 'Haute entropie',
+ alert_ICMP_TUNNEL: 'Tunnel ICMP',
+ alert_ML_ANOMALY: 'Anomalie ML',
+ alert_ASK_VERDICT: 'Verdict requis',
+ alertmsg_TLS_CERT: d => `Anomalie du certificat TLS pour ${d.host || d.ip} : ${(d.reasons || []).join(', ')} (émetteur ${d.issuer || '?'})`,
+ alertmsg_HIGH_ENTROPY: d => `Payload à haute entropie sur canal en clair ${d.process || '?'} → ${d.ip}:${d.port} (${d.entropy} bits/octet)`,
+ alertmsg_ICMP_TUNNEL: d => `Tunnel ICMP possible : échos répétés à gros payload avec ${d.ip}`,
+ alertmsg_ML_ANOMALY: d => `Anomalie ML de flux : ${d.process || '?'} → ${d.ip} (score ${d.score})`,
+ alertmsg_ASK_VERDICT: d => `Verdict requis : ${d.process || 'un processus'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (décision auto dans ${d.timeout_s}s)`,
+ alert_act_block: "Bloquer l'IP",
+ alert_act_kill: 'Tuer',
+ alert_act_suspend: 'Suspendre',
+ alert_act_allow: 'Autoriser',
+ alert_act_deny: 'Refuser',
+ ar_action: 'Action',
+ ar_action_alert: 'Alerte seule',
+ ar_action_block: 'Alerte + blocage',
}
diff --git a/frontend/src/locales/ja.js b/frontend/src/locales/ja.js
index 7a7a3c8..e874eff 100644
--- a/frontend/src/locales/ja.js
+++ b/frontend/src/locales/ja.js
@@ -395,7 +395,7 @@ export default {
bl_truncated: '上限で切り詰められました',
bl_remote: 'リモート取得を実行しました',
ar_title: 'カスタムアラートルール',
- ar_hint: '独自の条件で CUSTOM_RULE アラートを発火 — 通知のみ、ブロックはしません。',
+ ar_hint: '独自の条件で CUSTOM_RULE アラート — 「アラート+ブロック」で自動ファイアウォールも可能。',
ar_name_ph: 'ルール名 (任意)',
ar_field: 'フィールド',
ar_op: '演算子',
@@ -418,4 +418,22 @@ export default {
sb_done: code => `サンドボックスで実行 — 終了コード ${code}`,
sb_failed: 'このプラットフォームではサンドボックスを利用できません',
alertmsg_CUSTOM_RULE: d => `カスタムルールに一致: ${d.rule?.name || '無名のルール'}`,
+ alert_TLS_CERT: 'TLS証明書',
+ alert_HIGH_ENTROPY: '高エントロピー',
+ alert_ICMP_TUNNEL: 'ICMPトンネル',
+ alert_ML_ANOMALY: 'ML異常',
+ alert_ASK_VERDICT: '判定が必要',
+ alertmsg_TLS_CERT: d => `${d.host || d.ip} のTLS証明書異常: ${(d.reasons || []).join(', ')} (発行者 ${d.issuer || '?'})`,
+ alertmsg_HIGH_ENTROPY: d => `平文チャネル上の高エントロピーペイロード ${d.process || '?'} → ${d.ip}:${d.port} (${d.entropy} bits/byte)`,
+ alertmsg_ICMP_TUNNEL: d => `ICMPトンネルの可能性: ${d.ip} との大きなエコーペイロードの繰り返し`,
+ alertmsg_ML_ANOMALY: d => `MLフロー異常: ${d.process || '?'} → ${d.ip} (スコア ${d.score})`,
+ alertmsg_ASK_VERDICT: d => `判定が必要: ${d.process || 'プロセス'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (${d.timeout_s}秒で自動判定)`,
+ alert_act_block: 'IPをブロック',
+ alert_act_kill: '強制終了',
+ alert_act_suspend: '一時停止',
+ alert_act_allow: '許可',
+ alert_act_deny: '拒否',
+ ar_action: 'アクション',
+ ar_action_alert: 'アラートのみ',
+ ar_action_block: 'アラート+ブロック',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 2205c67..c57a980 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -395,7 +395,7 @@ export default {
bl_truncated: 'lista truncada no limite',
bl_remote: 'busca remota realizada',
ar_title: 'Regras de alerta personalizadas',
- ar_hint: 'Dispare alertas CUSTOM_RULE com seus próprios padrões — só alerta, nunca bloqueia.',
+ ar_hint: 'Dispare alertas CUSTOM_RULE com seus padrões — ou «alerta + bloqueio» para firewall automático.',
ar_name_ph: 'Nome da regra (opcional)',
ar_field: 'Campo',
ar_op: 'Operador',
@@ -418,4 +418,22 @@ export default {
sb_done: code => `Executado no sandbox — saída ${code}`,
sb_failed: 'Sandbox indisponível nesta plataforma',
alertmsg_CUSTOM_RULE: d => `Regra personalizada acionada: ${d.rule?.name || 'regra sem nome'}`,
+ alert_TLS_CERT: 'Certificado TLS',
+ alert_HIGH_ENTROPY: 'Alta entropia',
+ alert_ICMP_TUNNEL: 'Túnel ICMP',
+ alert_ML_ANOMALY: 'Anomalia ML',
+ alert_ASK_VERDICT: 'Veredito necessário',
+ alertmsg_TLS_CERT: d => `Anomalia do certificado TLS para ${d.host || d.ip}: ${(d.reasons || []).join(', ')} (emissor ${d.issuer || '?'})`,
+ alertmsg_HIGH_ENTROPY: d => `Payload de alta entropia em canal aberto ${d.process || '?'} → ${d.ip}:${d.port} (${d.entropy} bits/byte)`,
+ alertmsg_ICMP_TUNNEL: d => `Possível túnel ICMP: ecos repetidos com payloads grandes com ${d.ip}`,
+ alertmsg_ML_ANOMALY: d => `Anomalia ML de fluxo: ${d.process || '?'} → ${d.ip} (score ${d.score})`,
+ alertmsg_ASK_VERDICT: d => `Veredito necessário: ${d.process || 'um processo'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (decisão automática em ${d.timeout_s}s)`,
+ alert_act_block: 'Bloquear IP',
+ alert_act_kill: 'Matar',
+ alert_act_suspend: 'Suspender',
+ alert_act_allow: 'Permitir',
+ alert_act_deny: 'Negar',
+ ar_action: 'Ação',
+ ar_action_alert: 'Só alerta',
+ ar_action_block: 'Alerta + bloqueio',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 4a7b92d..54b69ea 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -395,7 +395,7 @@ export default {
bl_truncated: 'список обрезан до лимита',
bl_remote: 'выполнена удалённая загрузка',
ar_title: 'Пользовательские правила алертов',
- ar_hint: 'Поднимает алерты CUSTOM_RULE по вашим шаблонам — только алерт, никогда не блокирует.',
+ ar_hint: 'Алерты CUSTOM_RULE по вашим шаблонам — или «алерт + блок» для автоправила фаервола.',
ar_name_ph: 'Имя правила (необязательно)',
ar_field: 'Поле',
ar_op: 'Оператор',
@@ -418,4 +418,22 @@ export default {
sb_done: code => `Выполнено в песочнице — код ${code}`,
sb_failed: 'Песочница недоступна на этой платформе',
alertmsg_CUSTOM_RULE: d => `Сработало своё правило: ${d.rule?.name || 'безымянное правило'}`,
+ alert_TLS_CERT: 'TLS-сертификат',
+ alert_HIGH_ENTROPY: 'Высокая энтропия',
+ alert_ICMP_TUNNEL: 'ICMP-туннель',
+ alert_ML_ANOMALY: 'ML-аномалия',
+ alert_ASK_VERDICT: 'Нужен вердикт',
+ alertmsg_TLS_CERT: d => `Аномалия TLS-сертификата для ${d.host || d.ip}: ${(d.reasons || []).join(', ')} (издатель ${d.issuer || '?'})`,
+ alertmsg_HIGH_ENTROPY: d => `Высокоэнтропийная полезная нагрузка в открытом канале ${d.process || '?'} → ${d.ip}:${d.port} (${d.entropy} бит/байт)`,
+ alertmsg_ICMP_TUNNEL: d => `Возможный ICMP-туннель: повторные объёмные эхо-пакеты с ${d.ip}`,
+ alertmsg_ML_ANOMALY: d => `ML-аномалия потока: ${d.process || '?'} → ${d.ip} (оценка ${d.score})`,
+ alertmsg_ASK_VERDICT: d => `Нужен вердикт: ${d.process || 'процесс'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (авторешение через ${d.timeout_s}с)`,
+ alert_act_block: 'Блокировать IP',
+ alert_act_kill: 'Убить',
+ alert_act_suspend: 'Приостановить',
+ alert_act_allow: 'Разрешить',
+ alert_act_deny: 'Запретить',
+ ar_action: 'Действие',
+ ar_action_alert: 'Только алерт',
+ ar_action_block: 'Алерт + блок',
}
diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.js
index 3ee547e..3ff13be 100644
--- a/frontend/src/locales/zh-CN.js
+++ b/frontend/src/locales/zh-CN.js
@@ -395,7 +395,7 @@ export default {
bl_truncated: '列表已按上限截断',
bl_remote: '已执行远程获取',
ar_title: '自定义告警规则',
- ar_hint: '按您自己的条件触发 CUSTOM_RULE 告警 — 仅告警,绝不阻断。',
+ ar_hint: '按您自己的条件触发 CUSTOM_RULE 告警 — 或选「告警+封锁」自动添加防火墙规则。',
ar_name_ph: '规则名称(可选)',
ar_field: '字段',
ar_op: '运算符',
@@ -418,4 +418,22 @@ export default {
sb_done: code => `已在沙箱中运行 — 退出码 ${code}`,
sb_failed: '此平台不支持沙箱',
alertmsg_CUSTOM_RULE: d => `自定义规则命中:${d.rule?.name || '未命名规则'}`,
+ alert_TLS_CERT: 'TLS证书',
+ alert_HIGH_ENTROPY: '高熵值',
+ alert_ICMP_TUNNEL: 'ICMP隧道',
+ alert_ML_ANOMALY: 'ML异常',
+ alert_ASK_VERDICT: '需要判定',
+ alertmsg_TLS_CERT: d => `${d.host || d.ip} 的TLS证书异常: ${(d.reasons || []).join(', ')} (签发者 ${d.issuer || '?'})`,
+ alertmsg_HIGH_ENTROPY: d => `明文信道上的高熵载荷 ${d.process || '?'} → ${d.ip}:${d.port} (${d.entropy} 比特/字节)`,
+ alertmsg_ICMP_TUNNEL: d => `疑似ICMP隧道: 与 ${d.ip} 之间反复出现大载荷回显`,
+ alertmsg_ML_ANOMALY: d => `ML流量异常: ${d.process || '?'} → ${d.ip} (得分 ${d.score})`,
+ alertmsg_ASK_VERDICT: d => `需要判定: ${d.process || '某进程'} → ${d.remote_ip}:${d.remote_port}/${d.proto} (${d.timeout_s}秒后自动判定)`,
+ alert_act_block: '封锁IP',
+ alert_act_kill: '终止',
+ alert_act_suspend: '挂起',
+ alert_act_allow: '允许',
+ alert_act_deny: '拒绝',
+ ar_action: '动作',
+ ar_action_alert: '仅告警',
+ ar_action_block: '告警+封锁',
}