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 enterprise layer: SaC config, Sigma, IP feeds, fleet view, deploy assets

MoneyLisaf2c9e3e5120e
diff --git a/.github/labels.yml b/.github/labels.yml
new file mode 100644
index 0000000..281be42
--- /dev/null
+++ b/.github/labels.yml
@@ -0,0 +1,54 @@
+# Snitch — canonical issue labels / labels canoniques des issues.
+# EN: Sync with `github-label-sync` or apply manually — keeping the list
+# in the repo makes triage conventions reviewable like code.
+# FR: Sync via `github-label-sync` ou à la main — garder la liste dans
+# le dépôt rend les conventions de triage révisables comme du code.
+
+- name: "good first issue"
+ color: "7057ff"
+ description: "Good for newcomers — bounded scope, mentoring available"
+- name: "help wanted"
+ color: "008672"
+ description: "Extra attention needed from the community"
+- name: "bug"
+ color: "d73a4a"
+ description: "Something is not working"
+- name: "enhancement"
+ color: "a2eeef"
+ description: "New feature or improvement"
+- name: "detection"
+ color: "b60205"
+ description: "Detection engine: rules, Sigma, heuristics"
+- name: "firewall"
+ color: "e99695"
+ description: "Blocking, rules, NFQUEUE/eBPF/WFP/pf"
+- name: "capture"
+ color: "f9d0c4"
+ description: "libpcap, parsers, protocol decoding"
+- name: "siem"
+ color: "c5def5"
+ description: "Syslog, CEF, ECS, Wazuh/Splunk/Graylog integrations"
+- name: "fleet"
+ color: "bfd4f2"
+ description: "Multi-agent: gossip, /remote/fleet, Helm, Ansible"
+- name: "docs"
+ color: "0075ca"
+ description: "Documentation improvements and translations"
+- name: "i18n"
+ color: "0e8a16"
+ description: "UI/localization work"
+- name: "security"
+ color: "b60205"
+ description: "Vulnerability or hardening report — use advisories for real CVEs"
+- name: "windows"
+ color: "5319e7"
+ description: "Windows-specific (Npcap, WFP, netsh)"
+- name: "macos"
+ color: "5319e7"
+ description: "macOS-specific (NetworkExtension, pf)"
+- name: "linux"
+ color: "5319e7"
+ description: "Linux-specific (NFQUEUE, eBPF, nftables)"
+- name: "wontfix"
+ color: "ffffff"
+ description: "Not planned — reason explained in the thread"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 47c1d52..5824457 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,19 @@ All notable changes to Snitch. / Toutes les modifications notables de Snitch.
The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.
+## [1.6.0] — 2026-10-22 — enterprise layer / couche entreprise
+
+### Added / Ajouté
+
+- **Security-as-Code config file / Fichier de config Security-as-Code** — `backend/configfile.py` applies `$SNITCH_CONFIG`, else `snitch.toml`/`snitch.json` in the data dir at startup; every declared key overrides the DB so Ansible/Puppet/GPO provision Snitch with one file (`packaging/snitch.toml.example`). / `configfile.py` applique `$SNITCH_CONFIG` ou `snitch.toml`/`.json` du data dir ; chaque clé déclarée écrase la DB — un fichier suffit pour provisionner.
+- **Sigma rule import / Import de règles Sigma** — `POST /alerts/rules/sigma` + `detection/sigma.py`: a bounded, documented subset (field selections, `|contains`/`|startswith`/`|endswith`/`|re`/`|cidr`/`|gt`/`|lt`/`|all`, `1 of`/`all of` conditions) compiled into multi-clause AND custom rules (`conds:`); unmappable selections are reported in `skipped`, never mistranslated. / Sous-ensemble borné et documenté compilé en règles AND multi-clauses ; les sélections non mappables sont rapportées dans `skipped`.
+- **IP threat feeds / Flux TI IP** — `POST /firewall/blocklist` accepts `kind: "ip"` (Blocklist.de, URLhaus/Feodo exports, plain IP-per-line or CSV) imported as `ip` rules; private/reserved/loopback never imported, CIDRs over 4096 addresses rejected. `kind: "domain"` unchanged. / `kind: "ip"` importe les flux IP en règles `ip` ; privées/réservées jamais importées.
+- **Fleet console view / Vue console de flotte** — `GET /remote/fleet` merges every `gossip_peers` node's `/security/audit` (agent count, worst/mean hardening score, per-peer findings) — any Snitch instance can act as the collector; per-peer failures degrade gracefully. / `GET /remote/fleet` fusionne les `/security/audit` des pairs — n'importe quelle instance fait collecteur.
+- **CEF syslog output / Sortie syslog CEF** — `syslog_format: "cef"` wraps forwarded alerts in `CEF:0|Cognition|Snitch|…` (ArcSight/Wazuh/Splunk-ready) over the same UDP/TCP syslog path; `rfc3164` remains the default. / `syslog_format: "cef"` enveloppe les alertes en CEF; `rfc3164` reste le défaut.
+- **ECS export / Export ECS** — `GET /forensics/export?format=ecs` emits NDJSON Elastic Common Schema 8.11 (alerts → `event.kind=alert`, process entries carry `file.hash.sha256`), ingestible by Elastic Agent/Logstash/OpenSearch. / NDJSON ECS 8.11 ingérable par Elastic/Logstash/OpenSearch.
+- **Deployment assets / Assets de déploiement** — hardened systemd unit (`deploy/systemd/`), Ansible role + playbook (`deploy/ansible/`), Helm chart for collector/agent modes (`deploy/helm/snitch/`), nfpm config for .deb/.rpm (`packaging/nfpm.yaml`), MkDocs site (`mkdocs.yml`), integration guide `docs/INTEGRATIONS.md` (Wazuh, Splunk, Graylog/Loki, Ansible, Docker/K8s), canonical GitHub labels (`.github/labels.yml`). / Unité systemd durcie, rôle Ansible, chart Helm (collecteur/agent), nfpm .deb/.rpm, site MkDocs, guide d'intégrations, labels GitHub.
+- **Multi-clause custom rules / Règles multi-clauses** — `customrules` rules may now carry `conds:` (Sigma-style AND over any field set); the single `field/op/value` form is unchanged. / Les règles acceptent `conds:` (AND multi-champs façon Sigma) ; la forme simple est inchangée.
+
## [1.5.3] — 2026-10-22
### Added / Ajouté
diff --git a/CITATION.cff b/CITATION.cff
index 83a425f..93effca 100644
--- a/CITATION.cff
+++ b/CITATION.cff
@@ -17,5 +17,5 @@ keywords:
- privacy
- traffic visualization
- cybersecurity
-version: "1.5.3"
+version: "1.6.0"
date-released: "2026-10-01"
diff --git a/README.md b/README.md
index c944c7e..b2a5eb0 100644
--- a/README.md
+++ b/README.md
@@ -241,6 +241,31 @@ snitch/
└── dist/ Compiled output (backend exe, installer)
```
+### Enterprise & fleet
+
+Snitch also ships as a headless agent for SOC/SOC-adjacent deployments —
+everything is file-driven and free:
+
+- **Security-as-Code** — one `snitch.toml` (or `$SNITCH_CONFIG`) overrides
+ every setting at startup; provision a whole fleet with Ansible
+ (`deploy/ansible/`), Puppet, Salt or GPO.
+- **SIEM-native** — CEF or RFC 3164 syslog, generic webhooks, and
+ `GET /forensics/export?format=ecs` (Elastic Common Schema NDJSON) feed
+ Wazuh, Splunk, Graylog, Loki and Elastic out of the box.
+- **Sigma import** — `POST /alerts/rules/sigma` compiles a documented
+ Sigma subset into Snitch rules (`skipped` reasons for anything
+ unmappable, never silent).
+- **Fleet view** — `GET /remote/fleet` merges every configured peer's
+ hardening audit into one dashboard; a Helm chart
+ (`deploy/helm/snitch`) runs the collector in-cluster.
+- **Headless** — hardened systemd unit (`deploy/systemd/`), nfpm
+ `.deb`/`.rpm` packaging (`packaging/`), Docker image — no GUI needed.
+- **Free threat feeds** — `POST /firewall/blocklist` imports domain
+ (StevenBlack) and IP (Blocklist.de, URLhaus/Feodo) lists, locally or
+ via explicit opt-in fetch.
+
+Step-by-step recipes live in [docs/INTEGRATIONS.md](docs/INTEGRATIONS.md).
+
### Contribute
Bug reports and PRs are welcome — see [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -411,6 +436,30 @@ snitch/
└── dist/ Sortie compilée (exe backend, installateur)
```
+### Entreprise & flotte
+
+Snitch fonctionne aussi en agent headless pour déploiements SOC — tout
+est piloté par fichiers et gratuit :
+
+- **Security-as-Code** — un `snitch.toml` (ou `$SNITCH_CONFIG`) écrase
+ chaque réglage au démarrage ; provisionnez toute une flotte via Ansible
+ (`deploy/ansible/`), Puppet, Salt ou GPO.
+- **Natif SIEM** — syslog CEF ou RFC 3164, webhooks génériques et
+ `GET /forensics/export?format=ecs` (NDJSON Elastic Common Schema)
+ alimentent Wazuh, Splunk, Graylog, Loki et Elastic.
+- **Import Sigma** — `POST /alerts/rules/sigma` compile un sous-ensemble
+ Sigma documenté en règles Snitch (motifs `skipped` pour l'inmappable).
+- **Vue de flotte** — `GET /remote/fleet` fusionne l'audit de durcissement
+ de chaque pair ; un chart Helm (`deploy/helm/snitch`) fait tourner le
+ collecteur en cluster.
+- **Headless** — unité systemd durcie (`deploy/systemd/`), packaging
+ `.deb`/`.rpm` via nfpm (`packaging/`), image Docker — sans GUI.
+- **Flux TI gratuits** — `POST /firewall/blocklist` importe les listes
+ de domaines (StevenBlack) et d'IP (Blocklist.de, URLhaus/Feodo),
+ localement ou via fetch opt-in explicite.
+
+Recettes pas-à-pas dans [docs/INTEGRATIONS.md](docs/INTEGRATIONS.md).
+
### Contribuer
Rapports de bugs et PR bienvenus — voir [CONTRIBUTING.md](CONTRIBUTING.md).
diff --git a/backend/api/main.py b/backend/api/main.py
index 453e7a7..4f1c843 100644
--- a/backend/api/main.py
+++ b/backend/api/main.py
@@ -382,6 +382,13 @@ class BlocklistBody(BaseModel):
url: str = ""
action: str = "block"
max_entries: int = 500
+ # EN: "domain" (hosts/domain lists — StevenBlack…) or "ip"
+ # (IP feeds — Blocklist.de, URLhaus/Feodo exports). Default
+ # keeps the historic domain behaviour.
+ # FR: « domain » (listes hosts/domaines — StevenBlack…) ou « ip »
+ # (flux IP — Blocklist.de, exports URLhaus/Feodo). Le défaut
+ # conserve le comportement historique.
+ kind: str = "domain"
class CustomRuleBody(BaseModel):
@@ -1156,10 +1163,19 @@ def _process_batch(packets: list[Packet]) -> None:
# vraie règle pare-feu sur l'IP distante (dédupliquée).
for m in custom_rules.check(pkt, geo)[:1]:
r = m["rule"]
+ # EN: Single-condition rules show their clause; multi-clause
+ # (Sigma) rules show the clause count — the full conds are
+ # in details.rule either way. / FR: Les règles simples
+ # affichent leur clause ; les règles multi-clauses
+ # (Sigma) affichent le nombre — les conds complètes sont
+ # dans details.rule.
+ cond = (f"{r['field']} {r['op']} {r['value']}"
+ if r.get("field")
+ else f"{len(r.get('conds', []))} clauses")
a = Alert(
type="CUSTOM_RULE", severity=r["severity"],
message=f"Custom rule matched: {r['name']} "
- f"({r['field']} {r['op']} {r['value']}) — hit #{m['count']}"
+ f"({cond}) — hit #{m['count']}"
+ (" by " + pkt.process_name if pkt.process_name else ""),
node_id=remote_ip,
details={"rule": r, "process": pkt.process_name,
@@ -1838,6 +1854,17 @@ def _load_settings() -> None:
whitelist et exclusions de processus survivent aux redémarrages.
"""
global _port_filter, _excluded_processes, _whitelisted_ips, _watchlist
+ # EN: Security-as-Code — a snitch.toml/snitch.json in the data dir (or
+ # $SNITCH_CONFIG) is applied FIRST, so fleet provisioning works
+ # without touching the UI. Declared keys override the DB.
+ # FR: Security-as-Code — un snitch.toml/snitch.json dans le data dir
+ # (ou $SNITCH_CONFIG) s'applique EN PREMIER : le provisionnement de
+ # flotte marche sans toucher l'UI. Les clés déclarées priment.
+ try:
+ import configfile
+ configfile.apply(data_dir(), db.set_setting)
+ except Exception as e: # noqa: BLE001
+ logger.warning("config file apply failed: %s", e)
_port_filter = db.get_setting("ports", []) or []
_excluded_processes = set(db.get_setting("excluded_processes", []) or [])
_whitelisted_ips = set(db.get_setting("whitelisted_ips", []) or [])
@@ -1870,7 +1897,9 @@ def _load_settings() -> None:
notifier.configure(db.get_setting("webhook_url", "") or "",
bool(db.get_setting("webhook_enabled", False)),
db.get_setting("telegram_chat_id", "") or "",
- db.get_setting("syslog_addr", "") or "")
+ db.get_setting("syslog_addr", "") or "",
+ db.get_setting("syslog_format", "rfc3164") or "rfc3164",
+ __version__)
# 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.
@@ -2067,11 +2096,13 @@ async def post_settings(body: SettingsBody) -> dict:
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",
- "syslog_addr"):
+ "syslog_addr", "syslog_format"):
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("syslog_addr", "") or "")
+ db.get_setting("syslog_addr", "") or "",
+ db.get_setting("syslog_format", "rfc3164")
+ or "rfc3164", __version__)
if key == "ask_enabled":
# EN: Live toggle of NFQUEUE ask mode — stop is always safe;
# start reports platform availability honestly.
@@ -2813,6 +2844,8 @@ async def firewall_blocklist(body: BlocklistBody) -> dict:
raise HTTPException(400, "provide exactly one of path or url")
if body.action not in ("block", "sinkhole"):
raise HTTPException(400, "action must be block or sinkhole")
+ if body.kind not in ("domain", "ip"):
+ raise HTTPException(400, "kind must be domain or ip")
remote = bool(body.url)
def _load_text() -> str:
@@ -2830,18 +2863,24 @@ async def firewall_blocklist(body: BlocklistBody) -> dict:
text = await loop.run_in_executor(None, _load_text)
except (ValueError, OSError) as exc:
raise HTTPException(400, str(exc))
- domains = blocklist.parse_domains(text)
+ # EN: `kind` picks the extractor — domains for hosts-style lists,
+ # IPs for feed-style lists (private/reserved never imported).
+ # FR: `kind` choisit l'extracteur — domaines pour les listes façon
+ # hosts, IP pour les flux (privées/réservées jamais importées).
+ parse = blocklist.parse_ips if body.kind == "ip" \
+ else blocklist.parse_domains
+ entries = parse(text)
cap = blocklist.clamp_max(body.max_entries)
- truncated = len(domains) > cap
- domains = domains[:cap]
+ truncated = len(entries) > cap
+ entries = entries[:cap]
def _apply() -> tuple[int, int]:
added = skipped = 0
- for d in domains:
- if fw._find_rule("domain", d, body.action):
+ for d in entries:
+ if fw._find_rule(body.kind, d, body.action):
skipped += 1
continue
- fw.add_rule("domain", d, body.action)
+ fw.add_rule(body.kind, d, body.action)
added += 1
return added, skipped
@@ -2849,7 +2888,8 @@ async def firewall_blocklist(body: BlocklistBody) -> dict:
rules, lockdown = fw.serialized()
db.set_setting("firewall_rules", rules)
await broadcast({"type": "firewall", "rules": rules, "lockdown": lockdown})
- return {"ok": True, "remote_fetch": remote, "parsed": len(domains),
+ return {"ok": True, "remote_fetch": remote, "kind": body.kind,
+ "parsed": len(entries),
"added": added, "skipped": skipped, "truncated": truncated}
@@ -2891,6 +2931,42 @@ async def alert_rules_delete(rule_id: str) -> dict:
return {"ok": True}
[email protected]("/alerts/rules/sigma", dependencies=_AUTH)
+async def alert_rules_sigma(body: dict) -> dict:
+ """EN: Import a Sigma detection YAML — converted into custom rules
+ through detection/sigma.py's BOUNDED subset (detection field→value
+ maps, |modifiers, list OR/|all AND, selection/1-of/all-of
+ conditions). Unmappable selections are reported in `skipped`,
+ never silently mistranslated. Imported rules are alert-only
+ (Sigma has no block semantics).
+ FR: Importer un YAML Sigma — converti en règles custom via le
+ sous-ensemble BORNÉ de detection/sigma.py. Les sélections non
+ mappables sont rapportées dans `skipped`. Les règles importées
+ sont alert-only (Sigma n'a pas de sémantique de blocage)."""
+ import detection.sigma as sig
+ text = str((body or {}).get("yaml", ""))
+ if not text.strip() or len(text) > 200_000:
+ raise HTTPException(400, "empty or oversized sigma yaml")
+ try:
+ out = sig.convert(text)
+ except ValueError as exc:
+ raise HTTPException(400, str(exc))
+ imported = []
+ for r in out["rules"]:
+ try:
+ rule = custom_rules.add(r["name"], None, None, None,
+ r["severity"], "alert",
+ conds=r["conds"])
+ except ValueError as exc:
+ out["skipped"].append(f"{r['name']}: {exc}")
+ continue
+ rule["sigma_id"] = r["sigma_id"]
+ imported.append(rule)
+ db.set_setting("custom_rules", custom_rules.serialized())
+ return {"ok": True, "imported": len(imported),
+ "rules": imported, "skipped": out["skipped"]}
+
+
@app.post("/alerts/rules/{rule_id}/toggle", dependencies=_AUTH)
async def alert_rules_toggle(rule_id: str, body: FirewallToggleBody) -> dict:
"""EN: Enable/disable a rule without deleting it.
@@ -3168,6 +3244,21 @@ async def ioc_sync_status() -> dict:
return peer_sync.status()
[email protected]("/remote/fleet", dependencies=_AUTH)
+async def fleet_view() -> dict:
+ """EN: Lightweight fleet console — merges every configured peer's
+ /security/audit into one dashboard view (agent count, worst and
+ mean hardening score, per-agent findings). The "regroup N agents"
+ feature in its honest minimal form: any Snitch instance can act
+ as the collector; peers come from `gossip_peers`.
+ FR: Console de flotte légère — fusion des /security/audit de chaque
+ pair configuré (nombre d'agents, pire et moyenne des scores,
+ constats par agent). La version honnête minimale du « regrouper
+ N agents » : n'importe quelle instance peut jouer le collecteur."""
+ loop = asyncio.get_running_loop()
+ return await loop.run_in_executor(None, peer_sync.fleet_audit)
+
+
@app.post("/remote/ioc_sync", dependencies=_AUTH)
async def ioc_sync_push() -> dict:
"""EN: Push this machine's salted-Merkle proof pack to every configured
@@ -3534,9 +3625,72 @@ async def forensics_export(process: Optional[str] = None,
return _forensics_csv(bundle)
if format == "stix":
return _forensics_stix(bundle, ip=ip)
+ if format == "ecs":
+ return _forensics_ecs(bundle)
return bundle
+def _forensics_ecs(bundle: dict) -> PlainTextResponse:
+ """EN: Elastic Common Schema NDJSON — one line per event so Elastic
+ Agent / Logstash / OpenSearch ingest it without a parser plugin.
+ Alerts map to event.kind=alert + destination/process slots;
+ process entries carry file.hash.sha256 for hash-based hunting.
+ FR: NDJSON Elastic Common Schema — une ligne par événement, ingérable
+ par Elastic Agent / Logstash / OpenSearch sans plugin. Les alertes
+ mappent event.kind=alert + destination/process ; les processus
+ portent file.hash.sha256 pour la chasse par hash."""
+ base = {
+ "ecs": {"version": "8.11"},
+ "observer": {"vendor": "Cognition", "product": "Snitch",
+ "version": bundle["version"], "type": "firewall"},
+ "host": {"name": bundle["host"]},
+ }
+ lines: list[str] = []
+ for a in bundle.get("alerts", []):
+ det = a.get("details") or {}
+ ev = dict(base)
+ ev["@timestamp"] = a.get("timestamp") or bundle["generated_at"]
+ ev["event"] = {
+ "kind": "alert", "category": ["network"],
+ "type": ["indicator"], "dataset": "snitch.alerts",
+ "action": a.get("type", "ALERT"),
+ "severity": {"critical": 80, "warning": 50}.get(
+ a.get("severity"), 21),
+ }
+ if det.get("ip") or a.get("node_id"):
+ ev["destination"] = {"ip": det.get("ip") or a.get("node_id")}
+ if det.get("port"):
+ ev["destination"]["port"] = det["port"]
+ if det.get("process"):
+ ev["process"] = {"name": det["process"]}
+ if det.get("pid"):
+ ev["process"]["pid"] = det["pid"]
+ ev["message"] = a.get("message", "")
+ ev["rule"] = {"name": a.get("type", "?")}
+ lines.append(json.dumps(ev, ensure_ascii=False))
+ for p in bundle.get("processes", []):
+ ev = dict(base)
+ ev["@timestamp"] = bundle["generated_at"]
+ ev["event"] = {"kind": "event", "category": ["process"],
+ "type": ["info"], "dataset": "snitch.forensics"}
+ proc = {"name": p.get("name"), "pid": p.get("pid"),
+ "executable": p.get("exe"),
+ "command_line": " ".join(p.get("cmdline") or [])}
+ if p.get("sha256"):
+ ev["file"] = {"hash": {"sha256": p["sha256"]},
+ "path": p.get("exe")}
+ if p.get("parents"):
+ par = p["parents"][0]
+ proc["parent"] = {"name": par.get("name"),
+ "pid": par.get("pid")}
+ ev["process"] = proc
+ lines.append(json.dumps(ev, ensure_ascii=False))
+ return PlainTextResponse(
+ "\n".join(lines) + "\n", media_type="application/x-ndjson",
+ headers={"Content-Disposition":
+ 'attachment; filename="snitch-forensics.ndjson"'})
+
+
def _forensics_csv(bundle: dict) -> PlainTextResponse:
"""EN: Flatten the bundle into one CSV (section, key/value rows) —
spreadsheet- and grep-friendly.
diff --git a/backend/api/notify.py b/backend/api/notify.py
index cecee22..6faaf1e 100644
--- a/backend/api/notify.py
+++ b/backend/api/notify.py
@@ -42,6 +42,41 @@ _TIMEOUT_S = 8
# alertes Snitch dans un SIEM : warning→4, critical→2.
_SEV_TO_SYSLOG = {"warning": 4, "critical": 2}
+# EN: CEF (ArcSight Common Event Format) 0–10 scale — SIEM connectors
+# (Wazuh, Graylog, Splunk UF, Elastic Agent) parse it natively.
+# FR: Échelle CEF 0–10 — les connecteurs SIEM le parsent nativement.
+_SEV_TO_CEF = {"warning": 5, "critical": 8}
+
+
+def _cef_escape(s: str, header: bool = False) -> str:
+ """EN: CEF escaping — `\\` everywhere, `|` in header fields,
+ `=`+newlines in extension values. / FR: Échappement CEF."""
+ s = str(s).replace("\\", "\\\\")
+ if header:
+ return s.replace("|", "\\|")
+ return s.replace("=", "\\=").replace("\n", "\\n").replace("\r", "")
+
+
+def to_cef(alert: dict, version: str) -> str:
+ """EN: One alert as a CEF:0 line — vendor/product/version/signature/
+ name/severity then the extension. `details.ip/process` map to the
+ standard dst/sproc slots so SIEM correlation works out of the box.
+ FR: Une alerte en ligne CEF:0 — `details.ip/process` mappent les
+ champs standard dst/sproc pour la corrélation SIEM directe."""
+ sev = _SEV_TO_CEF.get(alert.get("severity"), 3)
+ det = alert.get("details") or {}
+ ext = {
+ "rt": alert.get("timestamp") or "",
+ "dst": det.get("ip") or alert.get("node_id") or "",
+ "sproc": det.get("process") or "",
+ "cs1Label": "alertType", "cs1": alert.get("type") or "",
+ "cs2Label": "reasons", "cs2": ",".join(det.get("reasons") or []),
+ }
+ ext_s = " ".join(f"{k}={_cef_escape(v)}" for k, v in ext.items() if v)
+ return "CEF:0|Cognition|Snitch|{}|{}|{}|{}|{}".format(
+ _cef_escape(version, True), _cef_escape(alert.get("type"), True),
+ _cef_escape(alert.get("message"), True), sev, ext_s)
+
class WebhookNotifier:
"""EN: Holds webhook settings + dispatches alert payloads.
@@ -53,14 +88,23 @@ class WebhookNotifier:
self._enabled = False
self._chat_id = ""
self._syslog = ""
+ self._syslog_format = "rfc3164"
+ self._version = "?"
def configure(self, url: str, enabled: bool, chat_id: str = "",
- syslog_addr: str = "") -> None:
+ syslog_addr: str = "", syslog_format: str = "rfc3164",
+ version: 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()
+ # EN: "cef" wraps the message in ArcSight CEF inside the
+ # syslog envelope — anything else keeps plain RFC 3164.
+ # FR: « cef » enveloppe le message en CEF ArcSight dans
+ # l'enveloppe syslog — sinon RFC 3164 brut.
+ self._syslog_format = "cef" if syslog_format == "cef" else "rfc3164"
+ self._version = version
def config(self) -> dict:
with self._lock:
@@ -68,7 +112,8 @@ class WebhookNotifier:
"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),
- "syslog_set": bool(self._syslog)}
+ "syslog_set": bool(self._syslog),
+ "syslog_format": self._syslog_format}
def dispatch(self, alert: dict) -> None:
"""EN: Synchronous POST — must run in an executor, never on the event
@@ -79,15 +124,20 @@ class WebhookNotifier:
url, enabled, chat_id = \
self._url, self._enabled, self._chat_id
syslog_addr = self._syslog
+ syslog_format = self._syslog_format
+ version = self._version
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.
+ # may want ONLY syslog. UDP by default, tcp:// for TCP. The
+ # body is RFC 3164 text or a CEF:0 payload per syslog_format.
# FR: Le chemin syslog est indépendant du webhook — UDP par
- # défaut, tcp:// pour TCP.
+ # défaut. Le corps est du texte RFC 3164 ou un payload CEF:0
+ # selon syslog_format.
if syslog_addr:
- self._send_syslog(syslog_addr, alert, text)
+ body = to_cef(alert, version) if syslog_format == "cef" else text
+ self._send_syslog(syslog_addr, alert, body)
if not enabled or not url:
return
if "discord.com" in url or "slack.com" in url:
diff --git a/backend/configfile.py b/backend/configfile.py
new file mode 100644
index 0000000..e35675d
--- /dev/null
+++ b/backend/configfile.py
@@ -0,0 +1,101 @@
+"""
+Snitch — declarative config file (Security-as-Code) / fichier de
+configuration déclaratif (Security-as-Code).
+
+EN: Lets admins provision Snitch entirely by file — Ansible, Puppet,
+ SaltStack, GPO or a docker-compose bind-mount drop ONE file and the
+ backend applies it at startup, no clicks:
+
+ * path resolution — `$SNITCH_CONFIG` first, then
+ `data_dir()/snitch.toml`, then `data_dir()/snitch.json`
+ * format — TOML (stdlib tomllib, Python ≥3.11) or JSON; the file
+ is a FLAT map of the same keys `/settings` accepts
+ (`syslog_addr`, `kill_switch_enabled`, `firewall_rules`, …)
+ * precedence — the FILE wins for every key it declares (that is
+ the point of Security-as-Code: the repo is the source of truth);
+ undeclared keys keep whatever the DB/UI last persisted
+ * failure honesty — an unreadable or invalid file logs a warning
+ and yields {}; Snitch never refuses to start on a typo
+
+ Example::
+
+ # snitch.toml — dropped by Ansible onto every host
+ syslog_addr = "siem.corp:514"
+ syslog_format = "cef"
+ kill_switch_enabled = true
+ ask_enabled = false
+ ports = [443]
+ gossip_peers = ["sec-01.corp:8080"]
+
+FR: Permet de provisionner Snitch entièrement par fichier — Ansible,
+ Puppet, GPO ou un bind-mount Docker déposent UN fichier et le backend
+ l'applique au démarrage, sans clic. Résolution : `$SNITCH_CONFIG`,
+ puis `data_dir()/snitch.toml`, puis `snitch.json`. TOML (stdlib) ou
+ JSON, map plate des mêmes clés que `/settings`. Le FICHIER gagne pour
+ les clés déclarées — le dépôt est la source de vérité. Un fichier
+ invalide log un warning et n'empêche jamais le démarrage.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import tomllib
+from pathlib import Path
+
+logger = logging.getLogger("snitch.configfile")
+
+
+def _candidate_paths(data_dir: Path) -> list[Path]:
+ """EN: $SNITCH_CONFIG wins, then the conventional names inside the
+ data dir. / FR: $SNITCH_CONFIG d'abord, puis les noms usuels."""
+ env = os.environ.get("SNITCH_CONFIG", "").strip()
+ out = []
+ if env:
+ out.append(Path(env))
+ out += [data_dir / "snitch.toml", data_dir / "snitch.json"]
+ return out
+
+
+def load(data_dir: Path) -> dict:
+ """EN: Flat settings dict from the first config file found — {} when
+ none exists or the file cannot be parsed. Values pass through
+ unchanged (the settings layer already handles arbitrary JSON types).
+ FR: Réglages plats du premier fichier trouvé — {} s'il n'y en a pas
+ ou si le parsing échoue."""
+ for path in _candidate_paths(data_dir):
+ if not path.is_file():
+ continue
+ try:
+ raw = path.read_bytes()
+ cfg = (tomllib.loads(raw.decode("utf-8"))
+ if path.suffix.lower() == ".toml"
+ else json.loads(raw.decode("utf-8")))
+ except (OSError, tomllib.TOMLDecodeError, json.JSONDecodeError,
+ UnicodeDecodeError) as e:
+ logger.warning("config file %s unreadable: %s", path, e)
+ return {}
+ if not isinstance(cfg, dict):
+ logger.warning("config file %s is not a mapping — ignored",
+ path)
+ return {}
+ logger.info("config file loaded: %s (%d keys)", path, len(cfg))
+ return cfg
+ return {}
+
+
+def apply(data_dir: Path, set_setting) -> int:
+ """EN: Persist each declared key via the normal settings path — the
+ file is authoritative for what it names. Returns the applied count.
+ FR: Persiste chaque clé déclarée par le chemin normal — le fichier
+ fait foi pour ce qu'il nomme. Renvoie le nombre appliqué."""
+ cfg = load(data_dir)
+ applied = 0
+ for key, value in cfg.items():
+ try:
+ set_setting(str(key), value)
+ applied += 1
+ except Exception as e: # noqa: BLE001
+ logger.warning("config key %s rejected: %s", key, e)
+ return applied
diff --git a/backend/detection/blocklist.py b/backend/detection/blocklist.py
index f0a00ef..1212165 100644
--- a/backend/detection/blocklist.py
+++ b/backend/detection/blocklist.py
@@ -79,6 +79,56 @@ def parse_domains(text: str) -> list[str]:
return out
+def parse_ips(text: str) -> list[str]:
+ """EN: Extract unique PUBLIC IPs from IP-feed text — one-per-line
+ lists (Blocklist.de, Feodo CSV `ip,port,...`), CIDR lines expanded
+ only for /32-/64 hosts, hosts-format lines use their first token.
+ Private/reserved/loopback addresses are skipped — an IP feed never
+ rewrites your LAN into the firewall. Order-preserving dedupe.
+ FR: Extraire les IP PUBLIQUES uniques d'un flux IP — listes une-par-
+ ligne (Blocklist.de, CSV Feodo `ip,port,…`), CIDR limité aux hôtes
+ /32-/64, format hosts = premier token. Les IP privées/réservées/
+ loopback sont ignorées — un flux IP ne réécrit jamais le LAN dans
+ le pare-feu. Dédup en conservant l'ordre."""
+ seen: set[str] = set()
+ out: list[str] = []
+ for raw in text.splitlines():
+ line = raw.split("#", 1)[0].strip()
+ if not line:
+ continue
+ # EN: CSV feeds ("ip,port,...") or plain "ip" / "ip port"-style.
+ # FR: Flux CSV (« ip,port,… ») ou « ip » / « ip port » simple.
+ token = re.split(r"[,\s;]", line, maxsplit=1)[0].strip()
+ if "/" in token:
+ try:
+ net = ipaddress.ip_network(token, strict=False)
+ except ValueError:
+ continue
+ if net.num_addresses > 4096:
+ continue # EN: refuse giant CIDRs / FR: refuser les gros CIDR
+ for ip in net.hosts() if net.num_addresses > 2 else net:
+ s = str(ip)
+ if s not in seen and not ip.is_private \
+ and not ip.is_reserved and not ip.is_loopback \
+ and not ip.is_link_local and not ip.is_multicast:
+ seen.add(s)
+ out.append(s)
+ continue
+ try:
+ ip = ipaddress.ip_address(token)
+ except ValueError:
+ continue
+ if ip.is_private or ip.is_reserved or ip.is_loopback \
+ or ip.is_link_local or ip.is_multicast \
+ or ip.is_unspecified:
+ continue
+ s = str(ip)
+ if s not in seen:
+ seen.add(s)
+ out.append(s)
+ return out
+
+
def _looks_like_ip(token: str) -> bool:
try:
ipaddress.ip_address(token)
diff --git a/backend/detection/customrules.py b/backend/detection/customrules.py
index 11359f3..747420b 100644
--- a/backend/detection/customrules.py
+++ b/backend/detection/customrules.py
@@ -87,55 +87,79 @@ class CustomRules:
# ── CRUD ─────────────────────────────────────────────────────────────────
+ @staticmethod
+ def _clauses(rule: dict) -> list[dict]:
+ """EN: The rule's AND-clauses — `conds` (Sigma-style multi-field
+ AND) when present, else the single top-level condition.
+ FR: Les clauses AND de la règle — `conds` (multi-champ façon
+ Sigma) si présentes, sinon la condition simple."""
+ return rule.get("conds") or [rule]
+
def _validate(self, rule: dict) -> None:
- if rule.get("field") not in _FIELDS:
- raise ValueError(f"unknown field: {rule.get('field')}")
- if rule.get("op") not in _OPS:
- raise ValueError(f"unknown op: {rule.get('op')}")
+ clauses = self._clauses(rule)
+ if not clauses or len(clauses) > 16:
+ raise ValueError("a rule needs 1..16 clauses")
+ first_field = clauses[0].get("field")
+ for c in clauses:
+ if c.get("field") not in _FIELDS:
+ raise ValueError(f"unknown field: {c.get('field')}")
+ if c.get("op") not in _OPS:
+ raise ValueError(f"unknown op: {c.get('op')}")
+ # EN: asn/country need the local geo DB — eq/ne/contains on
+ # the resolved value only.
+ # FR: asn/country exigent la base geo — eq/ne/contains
+ # seulement sur la valeur résolue.
+ if c.get("field") in ("asn", "country") and \
+ c.get("op") not in ("eq", "ne", "contains"):
+ raise ValueError(f"op {c.get('op')} not meaningful for "
+ f"{c.get('field')}")
+ value = str(c.get("value", ""))
+ if not value:
+ raise ValueError("empty value")
+ if c["op"] == "regex":
+ if len(value) > _MAX_PATTERN:
+ raise ValueError("pattern too long")
+ try:
+ re.compile(value)
+ except re.error as exc:
+ raise ValueError(f"bad regex: {exc}") from exc
+ if c["op"] == "cidr":
+ ipaddress.ip_network(value, strict=False)
+ if c["op"] in ("gt", "lt") and \
+ c["field"] in ("remote_port", "size"):
+ int(value) # EN: numeric ops need numbers / FR: ops numériques
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"):
+ first_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")
- if rule["op"] == "regex":
- if len(value) > _MAX_PATTERN:
- raise ValueError("pattern too long")
- try:
- re.compile(value)
- except re.error as exc:
- raise ValueError(f"bad regex: {exc}") from exc
- if rule["op"] == "cidr":
- ipaddress.ip_network(value, strict=False)
- if rule["op"] in ("gt", "lt") and rule["field"] in ("remote_port", "size"):
- int(value) # EN: numeric ops need numbers / FR: ops numériques
def add(self, name: str, field: str, op: str, value: str,
- severity: str = "warning", action: str = "alert") -> dict:
+ severity: str = "warning", action: str = "alert",
+ conds: Optional[list] = None) -> dict:
if len(self._rules) >= _MAX_RULES:
raise ValueError("rule limit reached")
rule = {
"id": uuid.uuid4().hex[:10],
"name": (name or "").strip()[:120] or f"{field} {op} {value}",
- "field": field, "op": op, "value": str(value).strip(),
"severity": severity, "enabled": True,
"action": action or "alert",
"hits": 0, "created": time.time(),
}
+ if conds:
+ # EN: Multi-clause AND rule (Sigma-style selection) — no
+ # top-level field/op/value. / FR: Règle AND multi-clauses
+ # (selection façon Sigma) — pas de field/op/value simple.
+ rule["conds"] = [{"field": str(c.get("field", "")),
+ "op": str(c.get("op", "")),
+ "value": str(c.get("value", "")).strip()}
+ for c in conds]
+ else:
+ rule.update(field=field, op=op, value=str(value).strip())
self._validate(rule)
self._rules.append(rule)
return rule
@@ -234,8 +258,11 @@ class CustomRules:
for r in self._rules:
if not r.get("enabled"):
continue
- if self._match_one(
- r, self._field_value(pkt, r["field"], geo)):
+ # EN: every clause of the rule must match (Sigma-style AND).
+ # FR: chaque clause de la règle doit matcher (AND façon Sigma).
+ if all(self._match_one(
+ c, self._field_value(pkt, c["field"], geo))
+ for c in self._clauses(r)):
h = self._hits.setdefault(r["id"], {"count": 0, "last": 0.0})
h["count"] += 1
h["last"] = time.time()
diff --git a/backend/detection/dga.py b/backend/detection/dga.py
index dc71cfc..d71a26a 100644
--- a/backend/detection/dga.py
+++ b/backend/detection/dga.py
@@ -90,7 +90,7 @@ def score(name: str) -> Optional[dict]:
name = name.rstrip(".").lower()
if name.replace(".", "").isdigit() or ":" in name:
return None # EN: IP literal / FR: IP
- labels = [l for l in name.split(".") if l]
+ labels = [lbl for lbl in name.split(".") if lbl]
if len(labels) < 2:
return None
diff --git a/backend/detection/gossip.py b/backend/detection/gossip.py
index 4ba35b2..9ded877 100644
--- a/backend/detection/gossip.py
+++ b/backend/detection/gossip.py
@@ -113,3 +113,41 @@ class PeerSync:
def status(self) -> dict:
return {"peers": self._peers,
"last": dict(self._state)}
+
+ def fleet_audit(self) -> dict:
+ """EN: Lightweight fleet console — GET /security/audit from every
+ configured peer (authenticated, bounded timeout, failures are
+ per-peer errors not crashes) and merge into one view: agent
+ count, worst score, per-peer findings. This is the honest
+ minimal version of "regroup N agents in one dashboard" — peers
+ are still the operator-listed gossip_peers, so trust domain is
+ unchanged. / FR: Console de flotte légère — GET /security/audit
+ de chaque pair configuré et fusion en une vue. Version honnête
+ minimale du « regrouper N agents » — les pairs sont les
+ gossip_peers de l'opérateur, domaine de confiance inchangé."""
+ agents: list[dict] = []
+ for peer in self._peers:
+ req = urllib.request.Request(
+ f"{peer}/security/audit",
+ headers={"Authorization":
+ f"Bearer {self._token_getter()}"})
+ try:
+ with urllib.request.urlopen(req, timeout=_TIMEOUT) as r:
+ data = json.loads(r.read().decode("utf-8", "replace"))
+ data["peer"] = peer
+ data["reachable"] = True
+ agents.append(data)
+ except urllib.error.HTTPError as e:
+ agents.append({"peer": peer, "reachable": False,
+ "error": f"http {e.code}"})
+ except (urllib.error.URLError, OSError, ValueError) as e:
+ agents.append({"peer": peer, "reachable": False,
+ "error": str(e)[:160]})
+ scores = [a["score"] for a in agents
+ if a.get("reachable") and isinstance(a.get("score"), int)]
+ return {"agent_count": len(agents),
+ "reachable": sum(1 for a in agents if a.get("reachable")),
+ "worst_score": min(scores) if scores else None,
+ "mean_score": round(sum(scores) / len(scores), 1)
+ if scores else None,
+ "agents": agents}
diff --git a/backend/detection/sigma.py b/backend/detection/sigma.py
new file mode 100644
index 0000000..58812a1
--- /dev/null
+++ b/backend/detection/sigma.py
@@ -0,0 +1,218 @@
+"""
+Snitch — Sigma rule import (bounded subset) / import de règles Sigma
+(sous-ensemble borné).
+
+EN: Converts a Sigma detection YAML into Snitch custom rules with an
+ honest, documented subset of the spec:
+
+ supported — `detection` selections that are field→value maps
+ (implicit AND), `field|modifier` operators
+ (contains, startswith, endswith, re, cidr, gt, lt,
+ all), list values (OR inside a field → regex
+ alternation; `|all` → one clause per value), list
+ selections (OR → one rule per selection) and the
+ conditions `selection`, `1 of them`, `all of them`
+ mapped — level: critical→critical, high/medium→warning,
+ low/informational→info; title→name, id kept for
+ traceability
+ NOT handled — count/near/aggregation conditions, timeframe,
+ Sigma backend pipelines, taxonomies outside the
+ mapped field list — skipped selections are reported
+ in `skipped`, never silently half-imported
+
+ Sigma is an SIEM log language, so the field vocabulary is mapped to
+ what a PACKET sensor can actually see (dst ip/port, process name,
+ SNI/DNS host, protocol, ASN, country) — a Sigma rule referencing
+ e.g. `CommandLine` is skipped rather than mistranslated.
+
+FR: Convertit un YAML de détection Sigma en règles custom Snitch avec
+ un sous-ensemble honnête et documenté de la spec : sélections
+ champ→valeur (AND implicite), modificateurs contains/startswith/
+ endswith/re/cidr/gt/lt/all, listes (OR intra-champ → regex,
+ `|all` → une clause par valeur), sélections listées (OR → une
+ règle par sélection), conditions `selection`, `1 of them`,
+ `all of them`. Les aggrégations count/near, timeframe, pipelines
+ backend et taxonomies hors champ mappé sont IGNORÉES et rapportées
+ dans `skipped` — jamais de traduction à moitié silencieuse. Les
+ champs sont mappés vers ce qu'un capteur de PAQUETS voit réellement.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Optional
+
+_MAX_RULES = 64 # EN: per import / FR: par import
+_MAX_VALUE = 200 # EN: chars per clause value / FR: caractères par valeur
+
+# EN: Sigma (log) field names → Snitch packet fields, lowercased and
+# normalised (underscores/dots removed). / FR: Champs Sigma (logs) →
+# champs paquet Snitch, en minuscules et normalisés.
+_FIELD_MAP = {
+ "destinationip": "remote_ip", "dst_ip": "remote_ip",
+ "dstip": "remote_ip", "destination_ip": "remote_ip",
+ "destinationport": "remote_port", "dst_port": "remote_port",
+ "dstport": "remote_port", "destination_port": "remote_port",
+ "image": "process_name", "processname": "process_name",
+ "process_name": "process_name", "originalfilename": "process_name",
+ "destinationhostname": "host", "destination_host": "host",
+ "destinationhost": "host", "domain": "host", "hostname": "host",
+ "host": "host", "queryname": "host", "sni": "host",
+ "tlsservername": "host", "dnsquery": "host",
+ "protocol": "protocol", "ipprotocol": "protocol",
+ "destinationasn": "asn", "asn": "asn",
+ "destinationcountry": "country", "country": "country",
+}
+
+# EN: |modifier → (op, transform). startswith/endswith become anchored
+# regexes; plain field or |all use per-value ops below.
+# FR: |modificateur → (op, transform). startswith/endswith deviennent
+# des regex ancrées ; champ nu ou |all utilisent les ops ci-dessous.
+_MODS = {
+ "contains": ("contains", str),
+ "startswith": ("regex", lambda v: "^" + re.escape(str(v))),
+ "endswith": ("regex", lambda v: re.escape(str(v)) + "$"),
+ "re": ("regex", str),
+ "cidr": ("cidr", str),
+ "gt": ("gt", str),
+ "lt": ("lt", str),
+}
+
+_LEVELS = {"critical": "critical", "high": "warning", "medium": "warning",
+ "low": "info", "informational": "info"}
+
+
+def _norm(name: str) -> str:
+ return re.sub(r"[_.\- ]", "", name.lower())
+
+
+def _clause(key: str, value) -> Optional[dict]:
+ """EN: One `field|mod: value` pair → {field, op, value} or None when
+ the field/modifier is outside the supported subset.
+ FR: Une paire `champ|mod: valeur` → clause ou None si hors périmètre."""
+ field_raw, _, mod = key.partition("|")
+ field = _FIELD_MAP.get(_norm(field_raw))
+ if not field:
+ return None
+ if not mod:
+ op, xf = "eq", str
+ elif mod.lower() == "all":
+ op, xf = "eq", str # EN: handled by caller (AND) / FR: géré par l'appelant (AND)
+ else:
+ found = _MODS.get(mod.lower())
+ if not found:
+ return None
+ op, xf = found
+ return {"field": field, "op": op, "xf": xf}
+
+
+def _selection_to_conds(sel: dict) -> Optional[list[dict]]:
+ """EN: One selection map → AND clause list, or None when any entry
+ is unmapped (honest skip — a half-translated selection would widen
+ the match). / FR: Une sélection → clauses AND, ou None si une entrée
+ n'est pas mappée (skip honnête)."""
+ conds: list[dict] = []
+ for key, value in sel.items():
+ key, _, all_mod = key.partition("|")
+ is_all = all_mod.lower() == "all"
+ values = value if isinstance(value, list) else [value]
+ if not values:
+ return None
+ if is_all:
+ # EN: field|all: [a,b] — every value must match → AND
+ # clauses, one per value. / FR: field|all: [a,b] —
+ # chaque valeur doit matcher → clauses AND.
+ for v in values:
+ c = _clause(key, v)
+ if c is None:
+ return None
+ conds.append({"field": c["field"], "op": c["op"],
+ "value": str(c["xf"](v))[:_MAX_VALUE]})
+ continue
+ built = []
+ for v in values:
+ c = _clause(f"{key}|{all_mod}" if all_mod else key, v)
+ if c is None:
+ return None
+ built.append((c, v))
+ if len(built) == 1:
+ c, v = built[0]
+ conds.append({"field": c["field"], "op": c["op"],
+ "value": str(c["xf"](v))[:_MAX_VALUE]})
+ else:
+ # EN: OR inside one field → regex alternation (escaped for
+ # eq/contains, verbatim for re). / FR: OR intra-champ →
+ # alternation regex (échappée pour eq/contains, verbatim
+ # pour re).
+ c0 = built[0][0]
+ if any(c["field"] != c0["field"] for c, _ in built):
+ return None
+ if all_mod.lower() in ("re",):
+ alt = "|".join(f"(?:{v})" for _, v in built)
+ else:
+ alt = "|".join(re.escape(str(v)) for _, v in built)
+ if all_mod.lower() == "startswith":
+ alt = "^(?:" + alt + ")"
+ elif all_mod.lower() == "endswith":
+ alt = "(?:" + alt + ")$"
+ elif not all_mod:
+ alt = f"^(?:{alt})$"
+ conds.append({"field": c0["field"], "op": "regex",
+ "value": alt[:_MAX_VALUE]})
+ return conds or None
+
+
+def convert(yaml_text: str) -> dict:
+ """EN: Sigma YAML → {"rules": [{name, conds, severity, sigma_id}],
+ "skipped": [reasons]}. Raises ValueError on malformed input.
+ FR: YAML Sigma → règles + motifs de skip. ValueError si invalide."""
+ import yaml
+ doc = yaml.safe_load(yaml_text)
+ if not isinstance(doc, dict):
+ raise ValueError("not a Sigma rule (expected a mapping)")
+ # EN: Multi-document files — callers split with '---' themselves;
+ # safe_load only reads the first doc. / FR: Fichiers multi-doc —
+ # l'appelant sépare avec '---' ; safe_load ne lit que le premier.
+ det = doc.get("detection") or {}
+ if not isinstance(det, dict) or "condition" not in det:
+ raise ValueError("no detection.condition")
+ title = str(doc.get("title") or "Sigma rule")[:120]
+ sid = str(doc.get("id") or "")
+ severity = _LEVELS.get(str(doc.get("level") or "").lower(), "warning")
+ cond_raw = str(det.get("condition") or "").strip()
+ combine_all = cond_raw.lower().startswith("all of")
+ sel_names = re.findall(r"[A-Za-z_][\w]*", cond_raw)
+ sel_names = [n for n in sel_names
+ if n.lower() not in ("of", "them", "all", "and",
+ "or", "not", "selection")]
+ if not sel_names:
+ sel_names = [k for k in det if k != "condition"]
+ rules: list[dict] = []
+ skipped: list[str] = []
+ merged_conds: list[dict] = []
+ for name in sel_names:
+ sel = det.get(name)
+ if sel is None:
+ continue
+ selections = sel if isinstance(sel, list) else [sel]
+ for i, s in enumerate(selections):
+ if not isinstance(s, dict):
+ skipped.append(f"{name}[{i}]: not a map")
+ continue
+ conds = _selection_to_conds(s)
+ if conds is None:
+ skipped.append(f"{name}[{i}]: unmapped field/modifier")
+ continue
+ if combine_all:
+ merged_conds += conds
+ else:
+ rules.append({"name": title, "conds": conds,
+ "severity": severity, "sigma_id": sid})
+ if len(rules) >= _MAX_RULES:
+ break
+ if combine_all and merged_conds:
+ rules = [{"name": title, "conds": merged_conds,
+ "severity": severity, "sigma_id": sid}]
+ if not rules and not skipped:
+ skipped.append("no selection matched the condition")
+ return {"rules": rules[:_MAX_RULES], "skipped": skipped}
diff --git a/backend/requirements.txt b/backend/requirements.txt
index d72e4a7..5833d7d 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -17,3 +17,4 @@ websockets==17.2 # EN: WebSocket support / FR: support WebSocket
maxminddb==3.2.0 # EN: raw .mmdb reader — GeoLite2 AND DB-IP Lite / FR: lecteur .mmdb brut — GeoLite2 ET DB-IP Lite
psutil==7.2.2 # EN: process + network interface info / FR: infos processus + interfaces réseau
aiofiles==25.1.0 # EN: async file I/O / FR: E/S fichiers asynchrones
+pyyaml==6.0.3 # EN: Sigma rule YAML import (detection/sigma.py) / FR: import de règles Sigma YAML
diff --git a/backend/tests/test_enterprise.py b/backend/tests/test_enterprise.py
new file mode 100644
index 0000000..c0d3b95
--- /dev/null
+++ b/backend/tests/test_enterprise.py
@@ -0,0 +1,213 @@
+"""
+EN: Tests for the enterprise layer — declarative config file, Sigma
+ import, IP-feed blocklists, fleet merge, CEF/ECS output.
+FR: Tests de la couche entreprise — fichier de config déclaratif,
+ import Sigma, blocklists IP, fusion de flotte, sorties CEF/ECS.
+"""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+
+# ── configfile / fichier de config ─────────────────────────────────────────────
+
+def test_configfile_toml(tmp_path, monkeypatch):
+ import configfile
+ monkeypatch.delenv("SNITCH_CONFIG", raising=False)
+ (tmp_path / "snitch.toml").write_text(
+ 'syslog_addr = "siem:514"\nkill_switch_enabled = true\nports = [80, 443]\n')
+ cfg = configfile.load(tmp_path)
+ assert cfg["syslog_addr"] == "siem:514" and cfg["ports"] == [80, 443]
+
+
+def test_configfile_env_wins(tmp_path, monkeypatch):
+ import configfile
+ env_file = tmp_path / "elsewhere.toml"
+ env_file.write_text('ask_enabled = true\n')
+ monkeypatch.setenv("SNITCH_CONFIG", str(env_file))
+ cfg = configfile.load(tmp_path) # no local file → env only
+ assert cfg == {"ask_enabled": True}
+
+
+def test_configfile_invalid_is_empty(tmp_path, monkeypatch):
+ import configfile
+ monkeypatch.delenv("SNITCH_CONFIG", raising=False)
+ (tmp_path / "snitch.toml").write_text('this is = = broken [[[\n')
+ assert configfile.load(tmp_path) == {} # EN: never crashes / FR: ne plante jamais
+
+
+def test_configfile_apply_overrides(tmp_path, monkeypatch):
+ import configfile
+ monkeypatch.delenv("SNITCH_CONFIG", raising=False)
+ (tmp_path / "snitch.toml").write_text('kill_switch_enabled = true\n')
+ store = {"kill_switch_enabled": False}
+ n = configfile.apply(tmp_path, lambda k, v: store.__setitem__(k, v))
+ assert n == 1 and store["kill_switch_enabled"] is True
+
+
+# ── blocklist IP feeds / flux IP ──────────────────────────────────────────────
+
+def test_parse_ips_basic():
+ from detection import blocklist
+ text = "# comment\n1.2.3.4\n5.6.7.8,443,2024-01-01\n1.2.3.4\n"
+ assert blocklist.parse_ips(text) == ["1.2.3.4", "5.6.7.8"]
+
+
+def test_parse_ips_skips_private():
+ from detection import blocklist
+ ips = blocklist.parse_ips("10.0.0.1\n192.168.1.1\n127.0.0.1\n8.8.8.8\n")
+ assert ips == ["8.8.8.8"]
+
+
+def test_parse_ips_cidr_bounded():
+ from detection import blocklist
+ # EN: 91.198.174.x is RIPE NCC — genuinely public, unlike 203.0.113.x
+ # (TEST-NET-3, correctly filtered as reserved).
+ # FR: 91.198.174.x est RIPE NCC — vraiment public, contrairement à
+ # 203.0.113.x (TEST-NET-3, filtré à juste titre comme réservé).
+ ips = blocklist.parse_ips("91.198.174.0/29\n10.0.0.0/8\nnot-an-ip\n")
+ assert len(ips) == 6 and all(x.startswith("91.198.174.") for x in ips)
+
+
+def test_parse_ips_rejects_doc_ranges():
+ from detection import blocklist
+ assert blocklist.parse_ips("203.0.113.5\n198.51.100.9\n192.0.2.1\n") == []
+
+
+# ── sigma ────────────────────────────────────────────────────────────────────
+
+_SIGMA = """
+title: Suspicious outbound to C2
+id: abc-123
+level: high
+detection:
+ selection:
+ DestinationIp|cidr: 198.51.100.0/24
+ DestinationPort: 4444
+ condition: selection
+"""
+
+
+def test_sigma_convert_simple():
+ import pytest
+ pytest.importorskip("yaml")
+ from detection import sigma
+ out = sigma.convert(_SIGMA)
+ assert len(out["rules"]) == 1 and not out["skipped"]
+ conds = out["rules"][0]["conds"]
+ assert {"field": "remote_ip", "op": "cidr",
+ "value": "198.51.100.0/24"} in conds
+ assert {"field": "remote_port", "op": "eq",
+ "value": "4444"} in conds
+ assert out["rules"][0]["severity"] == "warning" # EN: level=high / FR: level=high
+
+
+def test_sigma_or_list_becomes_regex():
+ import pytest
+ pytest.importorskip("yaml")
+ from detection import sigma
+ out = sigma.convert("""
+title: multi
+detection:
+ selection:
+ Domain: [evil.com, bad.org]
+ condition: selection
+""")
+ c = out["rules"][0]["conds"][0]
+ assert c["op"] == "regex" and "evil\\.com" in c["value"]
+
+
+def test_sigma_unmapped_skipped_honestly():
+ import pytest
+ pytest.importorskip("yaml")
+ from detection import sigma
+ out = sigma.convert("""
+title: has commandline
+detection:
+ selection:
+ CommandLine|contains: powershell
+ condition: selection
+""")
+ assert not out["rules"] and out["skipped"] # EN: honest skip / FR: skip honnête
+
+
+def test_sigma_conds_rule_matches_all_clauses():
+ from detection.customrules import CustomRules
+ cr = CustomRules()
+ cr.add("multi", None, None, None, conds=[
+ {"field": "remote_port", "op": "eq", "value": "4444"},
+ {"field": "protocol", "op": "eq", "value": "tcp"},
+ ])
+
+ class P:
+ dst_ip, src_ip = "1.2.3.4", "10.0.0.5"
+ direction, remote_port, protocol = "out", 4444, "tcp"
+ sni, dns, process_name, size, pid = "", [], "", 100, 1
+ assert len(cr.check(P())) == 1
+ P.protocol = "udp" # EN: one clause fails → no match
+ assert cr.check(P()) == [] # FR: une clause rate → pas de match
+
+
+def test_sigma_conds_reject_bad_field():
+ import pytest
+ from detection.customrules import CustomRules
+ with pytest.raises(ValueError):
+ CustomRules().add("bad", None, None, None, conds=[
+ {"field": "nope", "op": "eq", "value": "x"}])
+
+
+# ── fleet merge / fusion de flotte ───────────────────────────────────────────
+
+def test_fleet_audit_merge(monkeypatch):
+ from detection.gossip import PeerSync
+ import urllib.request
+ import json
+
+ ps = PeerSync(lambda: "tok")
+ ps.configure(["peer-a:8000", "peer-b:8000"])
+
+ class FakeResp:
+ def __init__(self, payload):
+ self._b = json.dumps(payload).encode()
+ def read(self):
+ return self._b
+ def __enter__(self):
+ return self
+ def __exit__(self, *a):
+ return False
+
+ calls = []
+
+ def fake_open(req, timeout=None):
+ calls.append(req.full_url)
+ if "peer-a" in req.full_url:
+ return FakeResp({"score": 42, "findings": []})
+ raise urllib.error.URLError("down")
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_open)
+ out = ps.fleet_audit()
+ assert out["agent_count"] == 2 and out["reachable"] == 1
+ assert out["worst_score"] == 42 and out["mean_score"] == 42.0
+ assert out["agents"][1]["reachable"] is False
+
+
+# ── CEF / ECS ────────────────────────────────────────────────────────────────
+
+def test_to_cef_escapes_and_maps():
+ from api.notify import to_cef
+ line = to_cef({"type": "CUSTOM_RULE", "severity": "critical",
+ "message": "a|b=c\\d", "timestamp": "2024-01-01T00:00:00Z",
+ "details": {"ip": "1.2.3.4", "process": "evil",
+ "pid": 42}}, "1.5.3")
+ assert line.startswith("CEF:0|Cognition|Snitch|1.5.3|CUSTOM_RULE|")
+ assert "|8|" in line # EN: critical→cef 8 / FR: critical→cef 8
+ assert "dst=1.2.3.4" in line and "sproc=evil" in line
+ assert "\\\\" in line or "\\|" in line or "\\=" in line # EN: escaped / FR: échappé
+
+
+def test_to_cef_header_pipes_escaped():
+ from api.notify import _cef_escape
+ assert _cef_escape("a|b", header=True) == "a\\|b"
+ assert _cef_escape("a=b") == "a\\=b"
diff --git a/backend/version.py b/backend/version.py
index 0ccef3c..bcd38a8 100644
--- a/backend/version.py
+++ b/backend/version.py
@@ -5,4 +5,4 @@ FR: Source unique de la version du backend (affichée dans /diagnostics).
À garder alignée avec electron/package.json et frontend/package.json.
"""
-__version__ = "1.5.3"
+__version__ = "1.6.0"
diff --git a/deploy/ansible/roles/snitch/tasks/main.yml b/deploy/ansible/roles/snitch/tasks/main.yml
new file mode 100644
index 0000000..7d91284
--- /dev/null
+++ b/deploy/ansible/roles/snitch/tasks/main.yml
@@ -0,0 +1,62 @@
+---
+# Snitch — minimal Ansible role (headless Linux deploy)
+# EN: Installs the backend into /opt/snitch, drops the declarative
+# config (/etc/snitch/snitch.toml — the Security-as-Code file the
+# backend applies at startup) and enables the systemd unit.
+# Usage: ansible-playbook -i hosts deploy/ansible/site.yml
+# FR: Installe le backend dans /opt/snitch, dépose la config
+# déclarative (/etc/snitch/snitch.toml — le fichier Security-as-Code
+# appliqué au démarrage) et active l'unité systemd.
+
+- name: Create the snitch system user / Créer l'utilisateur système snitch
+ ansible.builtin.user:
+ name: snitch
+ system: true
+ create_home: false
+ shell: /usr/sbin/nologin
+
+- name: Install runtime dependencies / Installer les dépendances
+ ansible.builtin.package:
+ name: "{{ item }}"
+ state: present
+ loop:
+ - python3
+ - python3-venv
+ - libpcap0.8 # EN: Debian name — override for dnf distros / FR: nom Debian — surcharger pour dnf
+ ignore_errors: true # EN: package names differ across distros / FR: noms différents selon la distro
+
+- name: Deploy the backend tree / Déployer l'arborescence backend
+ ansible.builtin.copy:
+ src: backend/
+ dest: /opt/snitch/backend/
+ owner: root
+ group: snitch
+ mode: "0644"
+
+- name: Create the virtualenv + pinned deps / Créer le venv + deps épinglées
+ ansible.builtin.pip:
+ requirements: /opt/snitch/backend/requirements.txt
+ virtualenv: /opt/snitch/backend/env
+ virtualenv_python: python3
+
+- name: Deploy the declarative config / Déployer la config déclarative
+ ansible.builtin.template:
+ src: snitch.toml.j2
+ dest: /etc/snitch/snitch.toml
+ owner: root
+ group: snitch
+ mode: "0640"
+
+- name: Deploy + enable the systemd unit / Déployer + activer l'unité
+ ansible.builtin.copy:
+ src: systemd/snitch.service
+ dest: /etc/systemd/system/snitch.service
+ mode: "0644"
+ notify: reload systemd
+
+- name: Start snitch / Démarrer snitch
+ ansible.builtin.systemd:
+ name: snitch
+ state: started
+ enabled: true
+ daemon_reload: true
diff --git a/deploy/ansible/roles/snitch/templates/snitch.toml.j2 b/deploy/ansible/roles/snitch/templates/snitch.toml.j2
new file mode 100644
index 0000000..c1256ef
--- /dev/null
+++ b/deploy/ansible/roles/snitch/templates/snitch.toml.j2
@@ -0,0 +1,29 @@
+# Snitch — declarative config (Security-as-Code), rendered by Ansible.
+# EN: Every key here OVERRIDES the UI/DB value at startup — this file is
+# the fleet source of truth. Keys are the /settings names.
+# FR: Chaque clé ÉCRASE la valeur UI/DB au démarrage — ce fichier est la
+# source de vérité de la flotte. Les clés sont les noms de /settings.
+
+# EN: SIEM output — CEF over syslog (Wazuh/Splunk/ArcSight-ready).
+# FR: Sortie SIEM — CEF via syslog (compatible Wazuh/Splunk/ArcSight).
+{% if snitch_syslog_addr is defined %}
+syslog_addr = "{{ snitch_syslog_addr }}"
+syslog_format = "{{ snitch_syslog_format | default('cef') }}"
+{% endif %}
+
+# EN: Ask-on-first-connect (Linux NFQUEUE) — false on headless servers.
+# FR: Ask-on-first-connect (NFQUEUE Linux) — false sur serveurs headless.
+ask_enabled = {{ snitch_ask_enabled | default(false) | lower }}
+
+# EN: Volume kill-switch. / FR: Kill-switch de volume.
+kill_switch_enabled = {{ snitch_kill_switch | default(true) | lower }}
+upload_threshold_mb = {{ snitch_upload_threshold | default(500) }}
+
+# EN: Fleet peers — this node's gossip_peers, also used by /remote/fleet.
+# FR: Pairs de flotte — gossip_peers du nœud, utilisés par /remote/fleet.
+{% if snitch_peers is defined %}
+gossip_peers = {{ snitch_peers | to_json }}
+{% endif %}
+
+# EN: Monitored ports / FR: Ports surveillés
+ports = {{ snitch_ports | default([80, 443]) | to_json }}
diff --git a/deploy/ansible/site.yml b/deploy/ansible/site.yml
new file mode 100644
index 0000000..f6857ad
--- /dev/null
+++ b/deploy/ansible/site.yml
@@ -0,0 +1,11 @@
+---
+# Snitch — example site playbook / playbook d'exemple
+# ansible-playbook -i inventory deploy/ansible/site.yml
+- hosts: snitch_agents
+ become: true
+ vars:
+ snitch_syslog_addr: "siem.example.com:514"
+ snitch_syslog_format: "cef"
+ snitch_peers: ["sec-01:8000", "sec-02:8000"]
+ roles:
+ - snitch
diff --git a/deploy/helm/snitch/Chart.yaml b/deploy/helm/snitch/Chart.yaml
new file mode 100644
index 0000000..8d4db88
--- /dev/null
+++ b/deploy/helm/snitch/Chart.yaml
@@ -0,0 +1,15 @@
+apiVersion: v2
+name: snitch
+description: |
+ Snitch — local-first network observability & outbound firewall.
+ Deploys a backend instance that can act as a fleet collector
+ (/remote/fleet over gossip_peers) or a per-node agent.
+type: application
+version: 0.1.0
+appVersion: "1.6.0"
+home: https://github.com/aixisstudio/Snitch
+keywords:
+ - security
+ - network-monitoring
+ - edr
+ - firewall
diff --git a/deploy/helm/snitch/templates/_helpers.tpl b/deploy/helm/snitch/templates/_helpers.tpl
new file mode 100644
index 0000000..1d9defc
--- /dev/null
+++ b/deploy/helm/snitch/templates/_helpers.tpl
@@ -0,0 +1,2 @@
+{{- define "snitch.name" -}}snitch{{- end -}}
+{{- define "snitch.fullname" -}}snitch{{- end -}}
diff --git a/deploy/helm/snitch/templates/configmap.yaml b/deploy/helm/snitch/templates/configmap.yaml
new file mode 100644
index 0000000..9a83429
--- /dev/null
+++ b/deploy/helm/snitch/templates/configmap.yaml
@@ -0,0 +1,17 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: {{ include "snitch.fullname" . }}-config
+ labels:
+ app: {{ include "snitch.name" . }}
+data:
+ snitch.toml: |
+ # EN: Declarative config rendered from .Values.config
+ # FR: Config déclarative rendue depuis .Values.config
+ {{- if .Values.config.syslog_addr }}
+ syslog_addr = {{ .Values.config.syslog_addr | quote }}
+ syslog_format = {{ .Values.config.syslog_format | quote }}
+ {{- end }}
+ ask_enabled = {{ .Values.config.ask_enabled }}
+ kill_switch_enabled = {{ .Values.config.kill_switch_enabled }}
+ gossip_peers = {{ .Values.config.gossip_peers | toJson }}
diff --git a/deploy/helm/snitch/templates/deployment.yaml b/deploy/helm/snitch/templates/deployment.yaml
new file mode 100644
index 0000000..b5cbbb3
--- /dev/null
+++ b/deploy/helm/snitch/templates/deployment.yaml
@@ -0,0 +1,72 @@
+apiVersion: apps/v1
+kind: {{ if eq .Values.mode "agent" }}DaemonSet{{ else }}Deployment{{ end }}
+metadata:
+ name: {{ include "snitch.fullname" . }}
+ labels:
+ app: {{ include "snitch.name" . }}
+spec:
+ {{- if ne .Values.mode "agent" }}
+ replicas: {{ .Values.replicas }}
+ {{- end }}
+ selector:
+ matchLabels:
+ app: {{ include "snitch.name" . }}
+ template:
+ metadata:
+ labels:
+ app: {{ include "snitch.name" . }}
+ spec:
+ hostNetwork: {{ eq .Values.mode "agent" }}
+ containers:
+ - name: snitch
+ image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
+ imagePullPolicy: {{ .Values.image.pullPolicy }}
+ ports:
+ - containerPort: 8000
+ env:
+ - name: SNITCH_BIND
+ value: "0.0.0.0"
+ - name: SNITCH_PORT
+ value: "8000"
+ - name: SNITCH_CONFIG
+ value: /etc/snitch/snitch.toml
+ - name: SNITCH_DATA_DIR
+ value: /var/lib/snitch
+ {{- if .Values.token }}
+ - name: SNITCH_TOKEN
+ valueFrom:
+ secretKeyRef:
+ name: {{ include "snitch.fullname" . }}-token
+ key: token
+ {{- end }}
+ securityContext:
+ allowPrivilegeEscalation: false
+ {{- if and (eq .Values.mode "agent") .Values.agentCapabilities }}
+ capabilities:
+ add: ["NET_RAW", "NET_ADMIN"]
+ {{- else }}
+ capabilities:
+ drop: ["ALL"]
+ {{- end }}
+ volumeMounts:
+ - name: config
+ mountPath: /etc/snitch
+ readOnly: true
+ - name: data
+ mountPath: /var/lib/snitch
+ readinessProbe:
+ tcpSocket:
+ port: 8000
+ initialDelaySeconds: 5
+ periodSeconds: 15
+ volumes:
+ - name: config
+ configMap:
+ name: {{ include "snitch.fullname" . }}-config
+ - name: data
+ {{- if .Values.persistence.enabled }}
+ persistentVolumeClaim:
+ claimName: {{ include "snitch.fullname" . }}-data
+ {{- else }}
+ emptyDir: {}
+ {{- end }}
diff --git a/deploy/helm/snitch/templates/service.yaml b/deploy/helm/snitch/templates/service.yaml
new file mode 100644
index 0000000..7d2cf63
--- /dev/null
+++ b/deploy/helm/snitch/templates/service.yaml
@@ -0,0 +1,38 @@
+{{- if ne .Values.mode "agent" }}
+apiVersion: v1
+kind: Service
+metadata:
+ name: {{ include "snitch.fullname" . }}
+spec:
+ type: {{ .Values.service.type }}
+ ports:
+ - port: {{ .Values.service.port }}
+ targetPort: 8000
+ selector:
+ app: {{ include "snitch.name" . }}
+{{- end }}
+{{- if .Values.token }}
+---
+apiVersion: v1
+kind: Secret
+metadata:
+ name: {{ include "snitch.fullname" . }}-token
+type: Opaque
+stringData:
+ token: {{ .Values.token }}
+{{- end }}
+{{- if .Values.persistence.enabled }}
+---
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+ name: {{ include "snitch.fullname" . }}-data
+spec:
+ accessModes: ["ReadWriteOnce"]
+ resources:
+ requests:
+ storage: {{ .Values.persistence.size }}
+ {{- if .Values.persistence.storageClass }}
+ storageClassName: {{ .Values.persistence.storageClass }}
+ {{- end }}
+{{- end }}
diff --git a/deploy/helm/snitch/values.yaml b/deploy/helm/snitch/values.yaml
new file mode 100644
index 0000000..118cfc4
--- /dev/null
+++ b/deploy/helm/snitch/values.yaml
@@ -0,0 +1,43 @@
+# Snitch Helm values / valeurs Helm Snitch
+image:
+ repository: ghcr.io/aixisstudio/snitch
+ tag: "latest"
+ pullPolicy: IfNotPresent
+
+# EN: "collector" exposes the API in-cluster and polls peers via
+# /remote/fleet; "agent" runs as a DaemonSet on each node.
+# FR: « collector » expose l'API dans le cluster et sonde les pairs via
+# /remote/fleet ; « agent » tourne en DaemonSet sur chaque nœud.
+mode: collector
+replicas: 1
+
+service:
+ type: ClusterIP
+ port: 8000
+
+# EN: A fixed API token — REQUIRED for anything reachable off-loopback.
+# Generate once: openssl rand -hex 32
+# FR: Jeton API fixe — REQUIS pour tout accès hors loopback.
+token: ""
+
+# EN: Declarative settings — rendered into snitch.toml (Security-as-Code).
+# FR: Réglages déclaratifs — rendus dans snitch.toml.
+config:
+ syslog_addr: ""
+ syslog_format: "cef"
+ ask_enabled: false
+ kill_switch_enabled: true
+ # EN: Agent-mode: list each OTHER node here so /remote/fleet can merge.
+ # FR: Mode agent : lister les AUTRES nœuds pour /remote/fleet.
+ gossip_peers: []
+
+persistence:
+ enabled: true
+ size: 1Gi
+ storageClass: ""
+
+# EN: Agent capture needs NET_RAW/NET_ADMIN on the node — granted only
+# in agent mode. Collector stays unprivileged.
+# FR: La capture agent exige NET_RAW/NET_ADMIN sur le nœud — accordés
+# seulement en mode agent. Le collecteur reste non privilégié.
+agentCapabilities: true
diff --git a/deploy/systemd/snitch.service b/deploy/systemd/snitch.service
new file mode 100644
index 0000000..1e7f0e9
--- /dev/null
+++ b/deploy/systemd/snitch.service
@@ -0,0 +1,55 @@
+# Snitch backend — systemd unit (headless/daemon mode)
+# EN: Runs the FastAPI backend as a hardened system service. Packet
+# capture needs CAP_NET_RAW (libpcap); firewall management needs
+# CAP_NET_ADMIN — both granted via AmbientCapabilities, no full
+# root required for the process identity.
+# Install: sudo install -m644 deploy/systemd/snitch.service /etc/systemd/system/
+# sudo systemctl daemon-reload && sudo systemctl enable --now snitch
+# FR: Lance le backend FastAPI en service système durci. La capture
+# exige CAP_NET_RAW (libpcap) ; le pare-feu CAP_NET_ADMIN — via
+# AmbientCapabilities, sans root complet pour l'identité du processus.
+
+[Unit]
+Description=Snitch — local-first network observability & outbound firewall
+Documentation=https://github.com/aixisstudio/Snitch
+After=network.target
+Wants=network.target
+
+[Service]
+Type=simple
+# EN: Dedicated unprivileged user; create with:
+# useradd --system --no-create-home --shell /usr/sbin/nologin snitch
+# FR: Utilisateur dédié non privilégié :
+# useradd --system --no-create-home --shell /usr/sbin/nologin snitch
+User=snitch
+Group=snitch
+WorkingDirectory=/opt/snitch/backend
+ExecStart=/opt/snitch/backend/env/bin/python -m uvicorn api.main:app \
+ --host 127.0.0.1 --port 8000
+Restart=on-failure
+RestartSec=5s
+
+# EN: Exactly the two capabilities capture+firewall need — nothing more.
+# FR: Exactement les deux capacités capture+pare-feu — rien de plus.
+AmbientCapabilities=CAP_NET_RAW CAP_NET_ADMIN
+CapabilityBoundingSet=CAP_NET_RAW CAP_NET_ADMIN
+
+# EN: Headless mode — set SNITCH_DEMO=1 here for a synthetic-traffic
+# demo box; SNITCH_CONFIG points at the declarative settings file.
+# FR: Mode headless — SNITCH_DEMO=1 pour une démo synthétique ;
+# SNITCH_CONFIG pointe le fichier de settings déclaratif.
+Environment=SNITCH_CONFIG=/etc/snitch/snitch.toml
+Environment=SNITCH_DATA_DIR=/var/lib/snitch
+
+# EN: Hardening — the backend only needs its data dir writable.
+# FR: Durcissement — le backend n'a besoin d'écrire que dans son data dir.
+NoNewPrivileges=true
+ProtectSystem=strict
+ProtectHome=true
+PrivateTmp=true
+ReadWritePaths=/var/lib/snitch
+StateDirectory=snitch
+ConfigurationDirectory=snitch
+
+[Install]
+WantedBy=multi-user.target
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
new file mode 100644
index 0000000..278934d
--- /dev/null
+++ b/docs/INTEGRATIONS.md
@@ -0,0 +1,158 @@
+# Snitch — Enterprise integrations / Intégrations entreprise
+
+**EN:** Step-by-step recipes for wiring Snitch into a SOC stack —
+Wazuh, Splunk, Graylog/Loki, Ansible, Docker/Kubernetes — all free and
+self-hosted, matching Snitch's local-first posture. Snitch emits no
+telemetry of its own; the only outbound connections are the ones you
+configure below.
+
+**FR :** Recettes pas-à-pas pour brancher Snitch dans une stack SOC —
+Wazuh, Splunk, Graylog/Loki, Ansible, Docker/Kubernetes — gratuites et
+auto-hébergées, dans l'esprit local-first de Snitch. Snitch n'émet
+aucune télémétrie propre ; les seules connexions sortantes sont celles
+configurées ci-dessous.
+
+---
+
+## 1. SIEM output / Sortie SIEM
+
+Snitch ships three native formats for alert forwarding:
+
+| Setting / Réglage | Values / Valeurs | Effect / Effet |
+|---|---|---|
+| `syslog_addr` | `host:514` or `tcp://host:514` | Enables syslog forwarding (UDP default, TCP with the `tcp://` prefix) |
+| `syslog_format` | `rfc3164` *(default)* | Classic BSD syslog — readable by every collector |
+| | `cef` | `CEF:0|Snitch|…` — ArcSight/Wazuh/Splunk auto-parse `src`, `dst`, `dpt`, `cs1` (process)… |
+| `webhook_url` + `webhook_enabled` | URL | Generic JSON `POST` (or Discord/Slack/Telegram auto-detected payloads) |
+| `GET /forensics/export?format=…` | `json`, `csv`, `stix`, `ecs` | One-shot forensic bundles — `ecs` emits newline-delimited Elastic Common Schema |
+
+Set them in the UI (Settings → Security) or in `snitch.toml`:
+
+```toml
+syslog_addr = "siem.example.com:514"
+syslog_format = "cef"
+```
+
+## 2. Wazuh
+
+1. Enable a syslog listener on the Wazuh manager (`/var/ossec/etc/ossec.conf`):
+
+ ```xml
+ <remote>
+ <connection>syslog</connection>
+ <port>514</port>
+ <protocol>udp</protocol>
+ <allowed-ips>your-agent-subnet</allowed-ips>
+ </remote>
+ ```
+
+2. Point each Snitch agent at it — Ansible:
+
+ ```yaml
+ snitch_syslog_addr: "wazuh.example.com:514"
+ snitch_syslog_format: "cef"
+ ```
+
+3. Wazuh's CEF decoder picks the `CEF:0|Snitch|…` messages up; alert
+ `severity` maps to syslog PRI (critical→2, warning→4, info→6).
+
+## 3. Splunk
+
+1. Settings → Data Inputs → UDP → new input on 514, sourcetype `syslog`
+ (or a TCP input for `tcp://…` senders).
+2. `syslog_format = "cef"` gives you `src`, `dst`, `dpt`, `cs1Label`
+ fields for free; for dashboards, poll `GET /forensics/export?format=ecs`
+ on a schedule through a scripted input and let the JSON auto-extract.
+
+## 4. Graylog / Loki
+
+- **Graylog**: System → Inputs → Syslog UDP, bind 514. CEF extension
+ fields land as message fields.
+- **Loki/Grafana**: point `syslog_addr` at a `promtail` syslog target or
+ scrape `/forensics/export?format=ecs` with a cron → `loki` push job.
+
+## 5. Declarative configuration (Security-as-Code)
+
+The backend applies **one file** at startup — `$SNITCH_CONFIG`, else
+`snitch.toml`/`snitch.json` in the data dir. Every key it declares
+overrides the UI/DB value, so the file is the fleet source of truth:
+
+```toml
+syslog_addr = "siem.example.com:514"
+syslog_format = "cef"
+kill_switch_enabled = true
+ask_enabled = false # headless servers
+gossip_peers = ["sec-01:8000"]
+ports = [80, 443]
+```
+
+See `packaging/snitch.toml.example` for the full vocabulary.
+
+## 6. Ansible / Puppet / Salt / GPO
+
+- **Ansible** — ready-made role in `deploy/ansible/`:
+
+ ```bash
+ ansible-playbook -i inventory deploy/ansible/site.yml
+ ```
+
+ It installs `/opt/snitch`, the venv, `/etc/snitch/snitch.toml` and the
+ hardened systemd unit, then enables `snitch.service`.
+
+- **Puppet / SaltStack** — same three primitives: copy the backend tree,
+ render `snitch.toml`, manage the `snitch.service` unit. The unit file
+ in `deploy/systemd/` is your contract.
+
+- **Windows GPO** — deploy a scheduled task running
+ `pythonw -m uvicorn api.main:app --host 127.0.0.1` from a network share,
+ or package the checkout with NSSM (`nssm install Snitch …`) for a real
+ service. Ask-on-connect on Windows additionally needs the signed WFP
+ callout — see `docs/SIGNING.md`.
+
+## 7. Docker & Kubernetes
+
+- **Single host**: `docker compose up` — `network_mode: host` +
+ `cap_add: NET_RAW/NET_ADMIN` already configured in `docker-compose.yml`.
+- **Fleet console**: `deploy/helm/snitch` — `mode: collector` runs a
+ ClusterIP Deployment that merges every configured agent's audit into
+ `GET /remote/fleet`; `mode: agent` renders a host-network DaemonSet
+ with `NET_RAW`/`NET_ADMIN`.
+
+ ```bash
+ helm install snitch ./deploy/helm/snitch \
+ --set token=$(openssl rand -hex 32) \
+ --set config.gossip_peers='["agent-1:8000","agent-2:8000"]'
+ ```
+
+## 8. Sigma rules
+
+`POST /alerts/rules/sigma` accepts a Sigma detection YAML and compiles the
+supported subset (field→value selections, `|contains`/`|startswith`/
+`|endswith`/`|re`/`|cidr`/`|gt`/`|lt`/`|all`, `1 of`/`all of` conditions)
+into Snitch custom rules — alert-only, `skipped` reasons returned for
+anything outside the subset. Fields map to what a *packet* sensor sees
+(`DestinationIp→remote_ip`, `Image→process_name`, `Domain→host`, …).
+
+## 9. Threat-intel feeds (free)
+
+`POST /firewall/blocklist` imports both shapes:
+
+- `kind: "domain"` — hosts/domain lists (StevenBlack, EasyList…) →
+ `domain` firewall rules;
+- `kind: "ip"` — IP feeds (Blocklist.de, URLhaus/Feodo exports) → `ip`
+ rules; private/reserved/loopback addresses are never imported.
+
+`path:` reads a local file (fully offline); `url:` is an explicit,
+audited opt-in fetch (`remote_fetch: true` in the response). Cap at
+`max_entries ≤ 5000` — giant feeds belong in a resolver.
+
+Opt-in API providers (AbuseIPDB / OTX / VirusTotal) stay available via
+`ti_provider` + `ti_api_key` — nothing calls out until you set a key.
+
+## 10. Headless / daemon mode
+
+The GUI is optional: the backend is the whole product. Run it bare
+(`uvicorn api.main:app`), under the shipped systemd unit, or in the
+container — every feature above works without the frontend.
+`SNITCH_DEMO=1` still gives a no-root synthetic feed for training rooms
+and CTFs.
diff --git a/electron/package.json b/electron/package.json
index 30dbf31..d27f104 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch",
- "version": "1.5.3",
+ "version": "1.6.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 6ba77e9..4e9e9ea 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -1,6 +1,6 @@
{
"name": "snitch-frontend",
- "version": "1.5.3",
+ "version": "1.6.0",
"private": true,
"license": "AGPL-3.0-or-later",
"description": "Snitch UI \u2014 React + D3.js / Interface React + D3.js",
diff --git a/mkdocs.yml b/mkdocs.yml
new file mode 100644
index 0000000..5a8c5b2
--- /dev/null
+++ b/mkdocs.yml
@@ -0,0 +1,25 @@
+# Snitch — Docs-as-Code (MkDocs)
+# EN: Serve locally with `pip install mkdocs-material && mkdocs serve`.
+# English files only in the nav — every doc ships 6 translations next
+# to it (*.de.md, *.fr.md inside the same tree).
+# FR: Servir localement : `pip install mkdocs-material && mkdocs serve`.
+# Nav anglaise — chaque doc a 6 traductions à côté.
+site_name: Snitch
+site_description: Local-first network observability & outbound firewall
+repo_url: https://github.com/aixisstudio/Snitch
+docs_dir: docs
+theme:
+ name: readthedocs
+nav:
+ - Home: ../README.md
+ - Architecture: architecture.md
+ - Firewall & blocking: FIREWALL.md
+ - Integrations (SIEM/deploy): INTEGRATIONS.md
+ - Packaging & signing: PACKAGING.md
+ - Signing deep-dive: SIGNING.md
+ - Threat model: threat-model.md
+ - Privacy score: privacy-score.md
+markdown_extensions:
+ - admonition
+ - toc:
+ permalink: true
diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml
new file mode 100644
index 0000000..8010795
--- /dev/null
+++ b/packaging/nfpm.yaml
@@ -0,0 +1,55 @@
+# Snitch — nfpm packaging (one file → .deb AND .rpm AND .apk)
+# EN: Build: nfpm package -f packaging/nfpm.yaml -p deb
+# nfpm package -f packaging/nfpm.yaml -p rpm
+# Requires a prepared staging tree: backend/ + venv under /opt/snitch.
+# Chocolatey/winget/brew formulas live in their own upstream repos —
+# see docs/INTEGRATIONS.md for the submission steps.
+# FR: Build : nfpm package -f packaging/nfpm.yaml -p deb|rpm.
+# Exige un arbre staging : backend/ + venv sous /opt/snitch. Les
+# formulas choco/winget/brew vivent dans leurs dépôts upstream.
+name: snitch
+arch: amd64
+platform: linux
+version: "1.6.0"
+release: 1
+section: net
+priority: optional
+maintainer: "Snitch contributors <[email protected]>"
+description: |
+ Local-first network observability and outbound firewall —
+ packet capture via libpcap, per-process traffic graph, alerting,
+ custom rules, Sigma import, CEF/ECS/syslog SIEM output.
+ Observabilité réseau local-first et pare-feu sortant.
+vendor: Snitch
+homepage: https://github.com/aixisstudio/Snitch
+license: AGPL-3.0-or-later
+contents:
+ - src: staging/opt/snitch/backend
+ dst: /opt/snitch/backend
+ - src: deploy/systemd/snitch.service
+ dst: /usr/lib/systemd/system/snitch.service
+ type: config|noreplace
+ - src: packaging/snitch.toml.example
+ dst: /etc/snitch/snitch.toml
+ type: config|noreplace
+overrides:
+ rpm:
+ contents:
+ - src: deploy/systemd/snitch.service
+ dst: /usr/lib/systemd/system/snitch.service
+ deb:
+ dependencies:
+ - python3
+ - python3-venv
+ - libpcap0.8
+ rpm:
+ dependencies:
+ - python3
+ - libpcap
+scripts:
+ postinstall: |
+ #!/bin/sh
+ id snitch >/dev/null 2>&1 || \
+ useradd --system --no-create-home --shell /usr/sbin/nologin snitch
+ systemctl daemon-reload >/dev/null 2>&1 || true
+ echo "Enable with: systemctl enable --now snitch"
diff --git a/packaging/snitch.toml.example b/packaging/snitch.toml.example
new file mode 100644
index 0000000..e75856b
--- /dev/null
+++ b/packaging/snitch.toml.example
@@ -0,0 +1,25 @@
+# Snitch — declarative config example / exemple de config déclarative.
+# Copy to /etc/snitch/snitch.toml (or $SNITCH_CONFIG, or the data dir).
+# Copier vers /etc/snitch/snitch.toml (ou $SNITCH_CONFIG, ou le data dir).
+
+# EN: SIEM forwarding — syslog_format: "cef" | "rfc3164"
+# FR: Relais SIEM — syslog_format : « cef » | « rfc3164 »
+# syslog_addr = "siem.example.com:514" # udp — tcp://host:514 for TCP
+# syslog_format = "cef"
+
+# EN: Ask-on-first-connect (Linux NFQUEUE) — needs root, off on headless.
+# FR: Ask-on-first-connect (NFQUEUE Linux) — root requis, off en headless.
+ask_enabled = false
+ask_timeout = 20
+ask_failopen = false
+
+# EN: Automatic volume kill-switch. / FR: Kill-switch de volume auto.
+kill_switch_enabled = true
+upload_threshold_mb = 500
+
+# EN: Fleet peers for IOC gossip + /remote/fleet merge.
+# FR: Pairs de flotte pour le gossip IOC + fusion /remote/fleet.
+# gossip_peers = ["sec-01.corp:8000"]
+
+# EN: Monitored ports (empty = all). / FR: Ports surveillés (vide = tous).
+# ports = [80, 443]