Real-time network monitor + outbound firewall — see & block every connection. Privacy-first, local-first, Rust fleet agent, SIEM exports, 8 languages. / Moniteur réseau temps réel + pare-feu sortant, agent de flotte Rust, exports SIEM. 100 % local.
Python cybersecurityd3jsebpfedrelectronfastapifirewallfleet-managementlinuxlittle-snitch-alternativemacosnetwork-monitornetwork-securitypacket-captureprivacyreactrustself-hostedsiemwindows
Add remote agent contract, YARA-L export, deploy skeletons, release CI
MoneyLisa50bd514dee52
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..e6206e8--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,91 @@+# Snitch — release packaging & submission automation+# EN: On a v* tag: build the nfpm packages, update the Homebrew tap+# formula, and submit winget/choco manifests. Everything is a no-op+# until you create the listed secrets — the workflow fails loudly+# and explains what's missing instead of silently skipping.+# FR: Sur tag v* : paquets nfpm, formule Homebrew tap, manifests+# winget/choco. Tout est no-op tant que les secrets listés n'existent+# pas — le workflow échoue en expliquant ce qui manque plutôt que de+# sauter en silence.+#+# Required secrets / Secrets requis:+# HOMEBREW_TAP_TOKEN — PAT with repo write on aixisstudio/homebrew-tap+# WINGET_TOKEN — PAT for microsoft/winget-pkgs submission+# CHOCO_API_KEY — chocolatey.org push key+# (GITHUB_TOKEN is automatic for artifact uploads)++name: release++on:+ push:+ tags: ["v*"]++permissions:+ contents: write++jobs:+ nfpm:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - name: Stage backend + venv-free tree / Arbre staging+ run: |+ mkdir -p staging/opt/snitch+ cp -r backend staging/opt/snitch/+ rm -rf staging/opt/snitch/backend/env staging/opt/snitch/backend/tests+ - uses: goreleaser/nfpm-action@v2+ with:+ version: latest+ - name: Build .deb/.rpm+ run: |+ V=${GITHUB_REF_NAME#v}+ sed -i "s/^version:.*/version: \"$V\"/" packaging/nfpm.yaml+ nfpm package -f packaging/nfpm.yaml -p deb -t dist/+ nfpm package -f packaging/nfpm.yaml -p rpm -t dist/+ - uses: actions/upload-artifact@v4+ with:+ name: linux-packages+ path: dist/++ homebrew-tap:+ needs: nfpm+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - name: Render + push formula / Rendre + pousser la formule+ env:+ HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}+ run: |+ V=${GITHUB_REF_NAME#v}+ SHA=$(curl -sL "https://github.com/aixisstudio/Snitch/archive/refs/tags/${GITHUB_REF_NAME}.tar.gz" | sha256sum | cut -d' ' -f1)+ sed -e "s|@VERSION@|$V|" -e "s|@SHA256@|$SHA|" \+ packaging/homebrew/snitch.rb > snitch.rb+ git clone "https://x-access-token:${HOMEBREW_TAP_TOKEN}@github.com/aixisstudio/homebrew-tap.git" tap+ mkdir -p tap/Formula+ cp snitch.rb tap/Formula/snitch.rb+ cd tap && git add Formula/snitch.rb+ git -c user.name=snitch-bot -c [email protected] \+ commit -m "snitch $V" && git push++ winget:+ if: startsWith(github.ref, 'refs/tags/v')+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - name: Submit winget manifest / Soumettre le manifeste winget+ uses: vedantmgoyal9/winget-releaser@v2+ with:+ identifier: aixisstudio.Snitch+ installers-regex: 'Snitch-Setup-.*\.exe$'+ token: ${{ secrets.WINGET_TOKEN }}++ chocolatey:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - name: Pack + push choco / Pack + push choco+ env:+ CHOCO_API_KEY: ${{ secrets.CHOCO_API_KEY }}+ run: |+ choco pack packaging/choco/snitch.nuspec --version ${env:GITHUB_REF_NAME.TrimStart('v')}+ choco push snitch.*.nupkg --source https://push.chocolatey.org/ --api-key $env:CHOCO_API_KEYdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5824457..a8c9400 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,17 @@ All notable changes to Snitch. / Toutes les modifications notables de Snitch.The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.+## [1.6.1] — 2026-10-22 — enterprise follow-through / suite entreprise++### Added / Ajouté++- **Rust agent + ingest API / Agent Rust + API d'ingestion** — `agent/` ships a zero-dependency Rust daemon (~1 MB single binary) that diffs the host socket table (`/proc/net/*`, Linux) and pushes new outbound flows to the new authenticated `POST /ingest/events` (contract `snitch-agent/1`, ≤1000 events/request, per-item validation). Events feed the SAME custom-rule detection surface as local packets and accumulate under `agent-host:…` history keys. Honest scope: sockets only — no payloads/SNI, process attribution is a marked TODO, HTTP transport for LAN trust domains. `deploy/systemd/snitch-agent.service` included. / Daemon Rust zéro-dépendance qui diff la table de sockets et pousse les nouveaux flux vers `POST /ingest/events` (contrat `snitch-agent/1`, borné et validé). Mêmes règles custom que les paquets locaux. Périmètre honnête : sockets seulement.+- **YARA-L export / Export YARA-L** — `GET /alerts/rules/yaral` + `detection/yaral.py`: all custom rules (including Sigma-imported `conds` rules) exported as a YARA-L 2.0 file for Google SecOps/Chronicle, with packet-sensor→UDM field mapping documented inline; untranslatable clauses become `// SKIPPED` comments. Gives a Sigma→YARA-L path for free. / Export unidirectionnel des règles custom en YARA-L 2.0 (mapping UDM documenté, clauses intraduisibles en `// SKIPPED`) — chemin Sigma→YARA-L inclus.+- **Puppet / Salt / GPO skeletons / Squelettes Puppet / Salt / GPO** — `deploy/puppet/` module + ERB template, `deploy/salt/` state, `deploy/gpo/Install-Snitch.ps1` silent installer (ProgramData config, venv, SYSTEM scheduled task on 127.0.0.1) — all `help wanted` community-maintained. / Module Puppet + template ERB, state Salt, installeur silencieux PowerShell pour GPO/Intune — tous marqués `help wanted`.+- **Release automation / Automatisation de release** — `.github/workflows/release.yml`: on `v*` tags, builds nfpm `.deb`/`.rpm`, renders + pushes the Homebrew formula to `aixisstudio/homebrew-tap`, submits the winget manifest (winget-releaser) and packs/pushes Chocolatey — all gated on documented secrets (`HOMEBREW_TAP_TOKEN`, `WINGET_TOKEN`, `CHOCO_API_KEY`). Formula/nuspec templates in `packaging/homebrew/` + `packaging/choco/`. / Sur tags `v*` : paquets nfpm, formule Homebrew vers le tap, manifeste winget, push Chocolatey — tout conditionné aux secrets documentés.+- **Translated INTEGRATIONS docs / Doc INTEGRATIONS traduite** — `docs/INTEGRATIONS.{de,es,ja,pt-BR,ru,zh-CN}.md` generated with a "community translated — PRs welcome" banner. / Variantes traduites avec bandeau « traduction communautaire — PR bienvenues ».+- **Community badge block / Bloc badges communauté** — README carries a commented Discord/Matrix badge snippet ready to activate once the server invite exists. / Bloc badge Discord/Matrix commenté dans le README, prêt à activer dès que l'invitation existe.+## [1.6.0] — 2026-10-22 — enterprise layer / couche entreprise### Added / Ajoutédiff --git a/CITATION.cff b/CITATION.cffindex 93effca..da6fba7 100644--- a/CITATION.cff+++ b/CITATION.cff@@ -17,5 +17,5 @@ keywords:- privacy- traffic visualization- cybersecurity-version: "1.6.0"+version: "1.6.1"date-released: "2026-10-01"diff --git a/README.md b/README.mdindex b2a5eb0..93e96e7 100644--- a/README.md+++ b/README.md@@ -17,6 +17,10 @@[](https://github.com/aixisstudio/Snitch/releases/latest)[](https://github.com/aixisstudio/Snitch/stargazers)[](https://star-history.com/#aixisstudio/Snitch&Date)+<!-- Community badges — UNCOMMENT once the server exists and paste the+ real invite URL (channels: #announcements #general #dev #help).+ [](https://discord.gg/INVITE_CODE)+ [](https://matrix.to/#/#snitch:matrix.org) --><!-- EN: Live capture of the demo mode (SNITCH_DEMO=1) — synthetic traffic only.FR: Capture du mode démo (SNITCH_DEMO=1) — trafic synthétique uniquement. -->diff --git a/agent/Cargo.toml b/agent/Cargo.tomlnew file mode 100644index 0000000..9ed9235--- /dev/null+++ b/agent/Cargo.toml@@ -0,0 +1,21 @@+# Snitch agent — zero-dependency mini-daemon / mini-daemon sans dépendances.+# EN: `cargo build --release` produces ONE static-ish binary. No crates:+# /proc parsing is plain fs, the ingest POST is a raw TcpStream.+# FR: `cargo build --release` produit UN seul binaire. Zéro crate :+# /proc en fs brut, le POST ingest en TcpStream manuel.+[package]+name = "snitch-agent"+version = "1.6.1"+edition = "2021"+license = "AGPL-3.0-only"+description = "Lightweight socket-observation agent for the Snitch collector"++[[bin]]+name = "snitch-agent"+path = "src/main.rs"++[profile.release]+opt-level = "z" # EN: smallest binary / FR: binaire minimal+lto = true+strip = true+panic = "abort"diff --git a/agent/README.md b/agent/README.mdnew file mode 100644index 0000000..8124a8c--- /dev/null+++ b/agent/README.md@@ -0,0 +1,54 @@+# snitch-agent — lightweight remote sensor / capteur distant léger++**EN:** A zero-dependency Rust daemon that watches the host's socket+table (`/proc/net/*`, Linux) and pushes newly-observed outbound flows to+a Snitch collector's `POST /ingest/events` — contract `snitch-agent/1`.+One `cargo build --release` produces a single ~1 MB binary with no+runtime deps, so it deploys via a plain file copy or `nfpm`.++Scope, honestly:++- it observes **sockets**, it does not sniff packets — no payloads, no+ SNI/DNS; the collector's own capture keeps those duties;+- process attribution (`/proc/*/fd` walk) is a marked TODO in+ `src/main.rs`, not half-implemented;+- transport is plain HTTP + bearer — same trust-domain model as+ `gossip_peers`; tunnel over WireGuard/TLS on hostile links.++**FR :** Un daemon Rust sans dépendance qui surveille la table de+sockets de l'hôte (`/proc/net/*`, Linux) et pousse les nouveaux flux+sortants vers `POST /ingest/events` du collecteur — contrat+`snitch-agent/1`. Un seul `cargo build --release` → binaire ~1 Mo sans+dépendance runtime, déployable par simple copie ou `nfpm`.++Périmètre honnête : SOCKETS seulement (pas de payloads/SNI/DNS),+attribution de processus en TODO explicite dans `src/main.rs`, transport+HTTP + bearer (même modèle de confiance que `gossip_peers`).++## Build & run / Compiler & lancer++```bash+cargo build --release+SNITCH_SERVER="collector:8000" \+SNITCH_TOKEN="<collector api token>" \+SNITCH_HOST="agent-01" \+./target/release/snitch-agent+```++## systemd / service++`deploy/systemd/snitch-agent.service` runs it unprivileged — the agent+only needs to read `/proc/net`, no capabilities at all.++## Wire format / format fil++```json+POST /ingest/events Authorization: Bearer <token>+{"agent":"snitch-agent/1","host":"agent-01","events":[+ {"ts":1718000000,"src_ip":"10.0.0.5","dst_ip":"93.184.216.34",+ "src_port":51822,"dst_port":443,"proto":"tcp","direction":"out",+ "bytes":0,"process":"","pid":0,"sni":""}]}+```++`bytes`, `process`, `pid` are `0`/empty until the TODOs land — the+collector still applies the full custom-rules surface to every event.diff --git a/agent/src/main.rs b/agent/src/main.rsnew file mode 100644index 0000000..9a0fc94--- /dev/null+++ b/agent/src/main.rs@@ -0,0 +1,220 @@+//! Snitch agent — lightweight remote sensor for a Snitch collector.+//! Agent Snitch — capteur léger pour un collecteur Snitch.+//!+//! EN: Watches the host's live socket table (Linux: /proc/net/{tcp,tcp6,+//! udp,udp6}; falls back to a periodic scan) and pushes the DIFF —+//! new outbound/established endpoints only — to the collector's+//! `POST /ingest/events` endpoint, contract `snitch-agent/1`.+//!+//! Deliberately zero-dependency and honest about scope:+//! * it observes SOCKETS, it does not sniff packets — no payloads,+//! no SNI, no DNS answers (the collector's own pcap path keeps+//! those duties on the host it runs on);+//! * pid↔process attribution needs /proc/*/fd walking — marked+//! TODO below rather than half-done;+//! * HTTP only for the same reason gossip allows http: LAN/trust+//! domain; run behind a WireGuard/TLS tunnel on hostile links.+//!+//! Config: SNITCH_SERVER="collector:8000" SNITCH_TOKEN="<bearer>"+//! SNITCH_HOST="agent-name" SNITCH_INTERVAL_SECS=5+//!+//! FR: Surveille la table de sockets de l'hôte (/proc/net/*) et pousse+//! le DIFF — nouvelles extrémités sortantes/établies — vers le+//! collecteur `POST /ingest/events`, contrat `snitch-agent/1`.+//! Zéro dépendance volontaire, périmètre honnête : SOCKETS seulement+//! (pas de payloads/SNI/DNS), attribution pid↔process en TODO, HTTP+//! uniquement (domaine de confiance LAN).++use std::collections::HashSet;+use std::env;+use std::fs;+use std::io::{Read, Write};+use std::net::TcpStream;+use std::process;+use std::time::{Duration, SystemTime, UNIX_EPOCH};++const AGENT_ID: &str = "snitch-agent/1";+const MAX_EVENTS_PER_POST: usize = 1000; // EN: matches backend cap / FR: cap backend++#[derive(Clone, PartialEq, Eq, Hash)]+struct Sock {+ proto: String, // "tcp" | "udp"+ local: String, // "ip:port"+ remote: String, // "ip:port" — empty when LISTEN/unconnected+ state: u8,+}++fn hex_ip(h: &str, v6: bool) -> String {+ // EN: /proc stores addresses little-endian hex. IPv4: 8 chars.+ // IPv6: 32 chars in 4 little-endian u32 groups.+ // FR: /proc stocke les adresses en hexa little-endian.+ if !v6 {+ let b: Vec<u8> = (0..4)+ .filter_map(|i| u8::from_str_radix(&h[i * 2..i * 2 + 2], 16).ok())+ .collect();+ if b.len() == 4 {+ return format!("{}.{}.{}.{}", b[3], b[2], b[1], b[0]);+ }+ return String::new();+ }+ if h.len() != 32 {+ return String::new();+ }+ let mut b = [0u8; 16];+ for i in 0..16 {+ b[i] = u8::from_str_radix(&h[i * 2..i * 2 + 2], 16).unwrap_or(0);+ }+ // EN: each 4-byte group is little-endian — swap inside each group.+ // FR: chaque groupe de 4 octets est little-endian — swap par groupe.+ for g in 0..4 {+ b.swap(g * 4, g * 4 + 3);+ b.swap(g * 4 + 1, g * 4 + 2);+ }+ let a = std::net::Ipv6Addr::from(b);+ a.to_string()+}++fn parse_table(path: &str, proto: &str, v6: bool, out: &mut HashSet<Sock>) {+ // EN: One line: sl local rem st … — rem "00000000:0000" = unconnected.+ // FR: Une ligne : sl local rem st … — rem « 00000000:0000 » = non connecté.+ let Ok(text) = fs::read_to_string(path) else { return };+ for line in text.lines().skip(1) {+ let f: Vec<&str> = line.split_whitespace().collect();+ if f.len() < 4 {+ continue;+ }+ let (lip, lport) = f[1].split_once(':').unwrap_or(("", "0"));+ let (rip, rport) = f[2].split_once(':').unwrap_or(("", "0"));+ let port = u16::from_str_radix(rport, 16).unwrap_or(0);+ let state = u8::from_str_radix(f[3], 16).unwrap_or(0);+ if port == 0 {+ continue; // EN: LISTEN/unnamed — not an outbound flow / FR: pas un flux sortant+ }+ let local = format!("{}:{}", hex_ip(lip, v6),+ u16::from_str_radix(lport, 16).unwrap_or(0));+ let remote = format!("{}:{}", hex_ip(rip, v6), port);+ out.insert(Sock { proto: proto.into(), local, remote, state });+ }+}++fn socket_table() -> HashSet<Sock> {+ let mut s = HashSet::with_capacity(4096);+ for (path, proto, v6) in [+ ("/proc/net/tcp", "tcp", false),+ ("/proc/net/tcp6", "tcp", true),+ ("/proc/net/udp", "udp", false),+ ("/proc/net/udp6", "udp", true),+ ] {+ parse_table(path, proto, v6, &mut s);+ }+ s+}++fn json_escape(s: &str) -> String {+ s.chars().flat_map(|c| match c {+ '"' => vec!['\\', '"'],+ '\\' => vec!['\\', '\\'],+ c if (c as u32) < 0x20 => {+ format!("\\u{:04x}", c as u32).chars().collect()+ }+ c => vec![c],+ }).collect()+}++fn post_batch(server: &str, token: &str, host: &str,+ events: &[String]) -> Result<(), String> {+ // EN: Minimal HTTP/1.1 POST, no TLS stack — see module doc for the+ // trust-domain reasoning. Bearer auth on every request.+ // FR: POST HTTP/1.1 minimal, pas de TLS — voir le doc module pour le+ // domaine de confiance. Bearer sur chaque requête.+ let body = format!(+ "{{\"agent\":\"{}\",\"host\":\"{}\",\"events\":[{}]}}",+ json_escape(AGENT_ID), json_escape(host), events.join(","));+ let req = format!(+ "POST /ingest/events HTTP/1.1\r\nHost: {server}\r\n\+ Authorization: Bearer {token}\r\nContent-Type: application/json\r\n\+ Content-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len());+ let mut stream = TcpStream::connect(server)+ .map_err(|e| format!("connect {server}: {e}"))?;+ stream.set_read_timeout(Some(Duration::from_secs(10))).ok();+ stream.set_write_timeout(Some(Duration::from_secs(10))).ok();+ stream.write_all(req.as_bytes()).map_err(|e| e.to_string())?;+ let mut resp = String::new();+ stream.read_to_string(&mut resp).map_err(|e| e.to_string())?;+ match resp.split(' ').nth(1) {+ Some(code) if code.starts_with('2') => Ok(()),+ _ => Err(format!("ingest rejected: {}",+ resp.lines().next().unwrap_or("?"))),+ }+}++fn sock_to_event(s: &Sock) -> Option<String> {+ // EN: only flow-like rows — a REMOTE endpoint with a real port.+ // Direction is "out": the agent reports what the box reaches,+ // which is the threat surface Snitch models.+ // FR: seulement les lignes flux — une extrémité distante avec un vrai+ // port. Direction « out » : l'agent rapporte ce que la machine+ // joint, surface de menace modélisée par Snitch.+ let (rip, rport) = s.remote.rsplit_once(':')?;+ let (lip, lport) = s.local.rsplit_once(':')?;+ if rip.is_empty() || rip == "0.0.0.0" || rip == "::" || rport == "0" {+ return None;+ }+ let ts = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();+ Some(format!(+ "{{\"ts\":{ts},\"src_ip\":\"{}\",\"dst_ip\":\"{}\",\+ \"src_port\":{},\"dst_port\":{},\"proto\":\"{}\",\+ \"direction\":\"out\",\"bytes\":0}}",+ json_escape(lip), json_escape(rip),+ lport, rport, json_escape(&s.proto)))+}++fn main() {+ let server = env::var("SNITCH_SERVER").unwrap_or_else(|_| "127.0.0.1:8000".into());+ let token = env::var("SNITCH_TOKEN").unwrap_or_default();+ if token.is_empty() {+ eprintln!("snitch-agent: SNITCH_TOKEN is required (collector bearer)");+ process::exit(2);+ }+ let host = env::var("SNITCH_HOST")+ .unwrap_or_else(|_| env::var("HOSTNAME").unwrap_or_else(|_| "agent".into()));+ let interval: u64 = env::var("SNITCH_INTERVAL_SECS")+ .ok().and_then(|v| v.parse().ok()).unwrap_or(5).max(1);++ // TODO(pid-attr): walk /proc/<pid>/fd symlinks to map socket inodes+ // → process name/pid, then fill the `process`/`pid` event fields.+ // Kept out on purpose until it is exact, not approximate.+ let mut seen: HashSet<Sock> = HashSet::new();+ let mut pending: Vec<String> = Vec::new();+ eprintln!("snitch-agent {AGENT_ID} → {server} as '{host}' every {interval}s");++ loop {+ let now = socket_table();+ for s in now.difference(&seen) {+ if let Some(ev) = sock_to_event(s) {+ pending.push(ev);+ }+ }+ // EN: forget departed sockets so reconnecting flaps re-report —+ // the collector's own dedup decides what is noise.+ // FR: oublier les sockets partis pour re-signaler les flaps —+ // la dédup du collecteur tranche ce qui est du bruit.+ seen = now;+ if !pending.is_empty() {+ let chunk: Vec<String> = pending+ .drain(..pending.len().min(MAX_EVENTS_PER_POST)).collect();+ match post_batch(&server, &token, &host, &chunk) {+ Ok(()) => {}+ Err(e) => {+ eprintln!("snitch-agent: {e}");+ // EN: bounded retry — requeue but never grow past the cap.+ // FR: retry borné — remise en file sans jamais dépasser le cap.+ pending.splice(0..0, chunk.into_iter());+ pending.truncate(MAX_EVENTS_PER_POST);+ }+ }+ }+ std::thread::sleep(Duration::from_secs(interval));+ }+}diff --git a/backend/api/main.py b/backend/api/main.pyindex 4f1c843..0b084bc 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -2967,6 +2967,24 @@ async def alert_rules_sigma(body: dict) -> dict:"rules": imported, "skipped": out["skipped"]}[email protected]("/alerts/rules/yaral", dependencies=_AUTH,+ response_class=PlainTextResponse)+async def alert_rules_yaral() -> PlainTextResponse:+ """EN: Export every custom rule as a YARA-L 2.0 file for Google+ SecOps/Chronicle. One-way export — packet-sensor fields map to+ honest UDM approximations (see detection/yaral.py); rules with+ no translatable clause come out commented // SKIPPED. Combined+ with /alerts/rules/sigma this gives a Sigma→YARA-L path.+ FR: Exporter toutes les règles custom en fichier YARA-L 2.0 pour+ Google SecOps/Chronicle. Export unidirectionnel — mapping honnête+ capteur-paquet → UDM ; les règles sans clause traduisible+ sortent en // SKIPPED. Avec l'import Sigma, chemin Sigma→YARA-L.+ """+ import detection.yaral as yaral+ return PlainTextResponse(yaral.export(custom_rules.serialized()),+ media_type="text/plain")++@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.@@ -3237,6 +3255,114 @@ def _collect_indicators() -> list[str]:return list(dict.fromkeys(out))[:4096]+# ── Agent ingestion (snitch-agent/1) / Ingestion d'agents ─────────────────────++_MAX_AGENT_EVENTS = 1000 # EN: per request / FR: par requête+_MAX_AGENT_FIELD = 253 # EN: chars per string field / FR: caractères+++class AgentBatchBody(BaseModel):+ """EN: POST /ingest/events envelope — the documented contract a+ lightweight agent (Rust daemon, scripted /proc reader, forwarder)+ speaks. `events` are SOCKET/flow observations, not packets: the+ backend treats them as detection input (custom rules + history),+ never as parsed traffic.+ FR: Enveloppe POST /ingest/events — le contrat documenté qu'un agent+ léger parle. `events` = observations de sockets/flux, pas des+ paquets : le backend les traite en entrée de détection (règles+ custom + historique), jamais comme du trafic parsé."""+ agent: str = "" # EN: e.g. "snitch-agent/1" / FR: ex.+ host: str = "" # EN: reporting host / FR: hôte émetteur+ # EN: untyped on purpose — malformed items are skipped per-item,+ # not rejected with a 422 that drops the whole batch.+ # FR: non typé volontairement — les items malformés sont ignorés+ # unitairement, pas rejetés en 422 qui perd tout le lot.+ events: list = []++[email protected]("/ingest/events", dependencies=_AUTH)+async def ingest_events(body: AgentBatchBody) -> dict:+ """EN: Ingest normalized flow events from remote agents.++ Contract `snitch-agent/1` — each event: {src_ip, dst_ip,+ src_port?, dst_port?, proto?, direction?, bytes?, process?,+ pid?, sni?, ts?}. Events are validated, bounded (≤1000/request,+ ≤253 chars/string, numbers coerced), then fed to the SAME+ detection machinery as local packets: custom rules can raise+ CUSTOM_RULE alerts (message prefixed with the agent host) and+ bytes accumulate into host/process history under+ `agent:<host>:<ip>`/`agent:<host>:<process>`. Unknown fields are+ ignored; nothing here trusts the agent beyond the bearer token.+ FR: Ingérer des événements de flux normalisés d'agents distants.+ Contrat `snitch-agent/1`. Événements validés et bornés puis+ injectés dans la MÊME machinerie de détection que les paquets+ locaux : règles custom → CUSTOM_RULE (préfixé par l'hôte agent)+ et historique sous `agent:<hôte>:…`. Champs inconnus ignorés.+ """+ events = body.events[:_MAX_AGENT_EVENTS]+ host = str(body.host or "agent")[:_MAX_AGENT_FIELD] or "agent"+ accepted = alerts = 0+ minute = db._utcnow_minute()++ class _Ev: # EN: Packet-shaped adapter / FR: adaptateur+ def __init__(self, e: dict):+ self.direction = "out" if e.get("direction") != "in" else "in"+ self.src_ip = str(e.get("src_ip") or "")[:64]+ self.dst_ip = str(e.get("dst_ip") or "")[:64]+ try:+ self.remote_port = int(e.get("dst_port") or 0)+ except (TypeError, ValueError):+ self.remote_port = 0+ self.protocol = str(e.get("proto") or "tcp")[:8].lower()+ try:+ self.size = max(0, int(e.get("bytes") or 0))+ except (TypeError, ValueError):+ self.size = 0+ self.process_name = str(e.get("process") or "")[:_MAX_AGENT_FIELD]+ try:+ self.pid = int(e.get("pid") or 0)+ except (TypeError, ValueError):+ self.pid = 0+ self.sni = str(e.get("sni") or "")[:_MAX_AGENT_FIELD]+ self.dns = []++ for raw in events:+ if not isinstance(raw, dict):+ continue+ ev = _Ev(raw)+ if not ev.dst_ip:+ continue+ accepted += 1+ db.accumulate_history(minute, "host",+ f"{host}:{ev.dst_ip}", ev.size)+ if ev.process_name:+ db.accumulate_history(minute, "process",+ f"{host}:{ev.process_name}", ev.size)+ # EN: Same rules, same alert type — the agent's flows get the+ # identical detection surface a local packet would.+ # FR: Mêmes règles, même type d'alerte — les flux de l'agent ont+ # la même surface de détection qu'un paquet local.+ for m in custom_rules.check(ev, None)[:1]:+ r = m["rule"]+ a = Alert(+ type="CUSTOM_RULE", severity=r["severity"],+ message=f"[{host}] Custom rule matched: {r['name']} "+ f"— hit #{m['count']}",+ node_id=ev.dst_ip,+ details={"rule": r, "process": ev.process_name,+ "agent": host, "direction": ev.direction,+ "ip": ev.dst_ip},+ )+ ad = a.to_dict()+ db.log_alert(ad)+ asyncio.get_running_loop().create_task(_notify(ad))+ alerts += 1+ return {"ok": True, "agent": body.agent or "unknown",+ "received": len(body.events), "accepted": accepted,+ "alerts": alerts,+ "truncated": len(body.events) > _MAX_AGENT_EVENTS}++@app.get("/remote/ioc_sync", dependencies=_AUTH)async def ioc_sync_status() -> dict:"""EN: Peer-sync status — configured peers + per-peer last results.diff --git a/backend/detection/yaral.py b/backend/detection/yaral.pynew file mode 100644index 0000000..e9a1f92--- /dev/null+++ b/backend/detection/yaral.py@@ -0,0 +1,147 @@+"""+Snitch — YARA-L 2.0 export / export YARA-L 2.0.++EN: Translates Snitch custom rules (single-condition or `conds:` AND+ rules, including Sigma-imported ones) into a YARA-L 2.0 file for+ Google SecOps/Chronicle UDM pipelines. Snitch stays the runtime —+ this is a one-way EXPORT, giving a Sigma→YARA-L path for free+ (Sigma YAML → snitch rules → YARA-L text).++ Field mapping (packet-sensor → UDM, honest approximations):++ remote_ip → target.ip (eq/ne =/!=, cidr → net.ip_in_range_cidr)+ remote_port → target.port (eq/ne/gt/lt)+ host → network.tls.client.server_name OR'd with+ network.dns.questions.name — SNI and DNS are both+ "host" in Snitch; emitted as a ( … or … ) clause+ process_name → principal.process.file.full_path (contains → regex)+ protocol → network.ip_protocol (tcp/udp uppercased)+ direction → network.direction (OUTBOUND/INBOUND)+ asn → network.asn (eq/ne only)+ country → target.location.country_or_region+ size → network.sent_bytes (gt/lt only — UDM byte fields+ are numeric; eq stays numeric too)+ regex → =~ /pattern/ (forwarded verbatim)++ Ops outside a field's row are dropped with a `// SKIPPED` comment —+ never mistranslated, same honesty contract as the Sigma importer.++FR: Traduit les règles custom Snitch (simples ou `conds:` AND, y+ compris les règles importées Sigma) en fichier YARA-L 2.0 pour+ pipelines UDM Google SecOps/Chronicle. Export unidirectionnel —+ donne un chemin Sigma→YARA-L gratuitement. Les ops hors ligne sont+ ignorées avec un commentaire `// SKIPPED`, jamais mal traduites.+"""++from __future__ import annotations++import re++_HEADER = """// Snitch — auto-generated YARA-L 2.0 rules+// Source: Snitch custom rules (single + Sigma-imported conds rules)+// Regenerate: GET /alerts/rules/yaral — do NOT edit by hand.+// Field mapping is packet-sensor → UDM; see detection/yaral.py.++"""++_SEV = {"critical": "CRITICAL", "warning": "HIGH", "info": "INFORMATIONAL"}++# EN: ops usable per field — None means "skip with a comment".+# FR: ops utilisables par champ — None = « skip avec commentaire ».+_FIELD: dict[str, dict] = {+ "remote_ip": {"lhs": "$e.target.ip",+ "ops": ("eq", "ne", "cidr")},+ "remote_port": {"lhs": "$e.target.port",+ "ops": ("eq", "ne", "gt", "lt")},+ "host": {"lhs": None, # EN: dual-field clause / FR: clause double+ "ops": ("eq", "ne", "contains", "regex")},+ "process_name": {"lhs": "$e.principal.process.file.full_path",+ "ops": ("eq", "ne", "contains", "regex")},+ "protocol": {"lhs": "$e.network.ip_protocol",+ "ops": ("eq", "ne"),+ "xf": str.upper},+ "direction": {"lhs": "$e.network.direction",+ "ops": ("eq", "ne"),+ "xf": lambda v: "OUTBOUND" if v == "out" else "INBOUND"},+ "asn": {"lhs": "$e.network.asn", "ops": ("eq", "ne")},+ "country": {"lhs": "$e.target.location.country_or_region",+ "ops": ("eq", "ne", "contains")},+ "size": {"lhs": "$e.network.sent_bytes",+ "ops": ("eq", "ne", "gt", "lt")},+}+++def _esc(s: str) -> str:+ return s.replace("\\", "\\\\").replace('"', '\\"')+++def _clause(field: str, op: str, value: str) -> str | None:+ spec = _FIELD.get(field)+ if spec is None or op not in spec["ops"]:+ return None+ v = spec.get("xf", lambda x: x)(value)+ if field == "host":+ # EN: "host" covers SNI + DNS answers — emit the honest OR.+ # FR: « host » couvre SNI + réponses DNS — OR honnête émis.+ if op == "regex":+ pat = f"/{value}/"+ return (f"($e.network.tls.client.server_name =~ {pat} or "+ f"$e.network.dns.questions.name =~ {pat})")+ cmp = "=" if op == "eq" else ("!=" if op == "ne" else None)+ if op == "contains":+ pat = f"/.*{re.escape(value)}.*/"+ return (f"($e.network.tls.client.server_name =~ {pat} or "+ f"$e.network.dns.questions.name =~ {pat})")+ return (f"($e.network.tls.client.server_name {cmp} \"{_esc(v)}\" or "+ f"$e.network.dns.questions.name {cmp} \"{_esc(v)}\")")+ lhs = spec["lhs"]+ if op == "cidr":+ return f'net.ip_in_range_cidr({lhs}, "{_esc(v)}")'+ if op == "regex":+ return f"{lhs} =~ /{v}/"+ if op == "contains":+ return f"{lhs} =~ /.*{re.escape(v)}.*/"+ sym = {"eq": "=", "ne": "!=", "gt": ">", "lt": "<"}[op]+ # EN: numeric UDM fields stay unquoted. / FR: champs UDM numériques sans guillemets.+ val = v if field in ("remote_port", "size", "asn") else f'"{_esc(v)}"'+ return f"{lhs} {sym} {val}"+++def export(rules: list[dict]) -> str:+ """EN: Serialized rules → a complete .yar file. Each rule's clauses+ are ANDed (same semantics as the packet matcher); rules with zero+ translatable clauses are emitted commented-out with a // SKIPPED+ note. / FR: Règles sérialisées → fichier .yar complet. Clauses ANDées+ ; les règles sans clause traduisible sont émises en commentaire."""+ out = [_HEADER]+ for r in rules:+ rid = re.sub(r"[^A-Za-z0-9_]", "_", str(r.get("id", "x")))+ name = str(r.get("name", "rule")).replace('"', "'")[:120]+ sev = _SEV.get(r.get("severity", "warning"), "MEDIUM")+ clauses = []+ skipped = []+ for c in (r.get("conds") or+ [{"field": r.get("field"), "op": r.get("op"),+ "value": r.get("value")}]):+ cl = _clause(str(c.get("field")), str(c.get("op")),+ str(c.get("value", "")))+ (clauses if cl else skipped).append(+ cl or f"{c.get('field')} {c.get('op')} {c.get('value')}")+ if not clauses:+ out.append(f"// SKIPPED rule {name!r}: no translatable clause "+ f"({', '.join(skipped)})")+ continue+ body = " and\n ".join(clauses)+ note = ("\n // skipped: " + "; ".join(skipped)) if skipped else ""+ out.append(+ f'rule snitch_{rid} {{\n'+ f' meta:\n'+ f' author = "Snitch"\n'+ f' description = "{_esc(name)}"\n'+ f' severity = "{sev}"\n'+ f' events:\n'+ f' {body}{note}\n'+ f' condition:\n'+ f' $e\n'+ f'}}\n')+ return "\n".join(out)diff --git a/backend/tests/test_enterprise.py b/backend/tests/test_enterprise.pyindex c0d3b95..f664a38 100644--- a/backend/tests/test_enterprise.py+++ b/backend/tests/test_enterprise.py@@ -211,3 +211,92 @@ def test_to_cef_header_pipes_escaped():from api.notify import _cef_escapeassert _cef_escape("a|b", header=True) == "a\\|b"assert _cef_escape("a=b") == "a\\=b"+++# ── YARA-L export / export YARA-L ────────────────────────────────────────────++def test_yaral_single_rule():+ from detection import yaral+ out = yaral.export([{"id": "r1", "name": "bad c2", "severity": "critical",+ "field": "remote_ip", "op": "cidr",+ "value": "10.0.0.0/8"}])+ assert "rule snitch_r1" in out+ assert 'net.ip_in_range_cidr($e.target.ip, "10.0.0.0/8")' in out+ assert 'severity = "CRITICAL"' in out+++def test_yaral_conds_and():+ from detection import yaral+ out = yaral.export([{"id": "s1", "name": "multi", "severity": "warning",+ "conds": [+ {"field": "remote_port", "op": "eq",+ "value": "4444"},+ {"field": "host", "op": "contains",+ "value": "evil.com"}]}])+ assert "$e.target.port = 4444" in out and " and\n" in out+ assert "network.tls.client.server_name" in out+ assert "network.dns.questions.name" in out+++def test_yaral_unmappable_skipped_honestly():+ from detection import yaral+ out = yaral.export([{"id": "x", "name": "nope", "severity": "info",+ "field": "direction", "op": "contains",+ "value": "y"}])+ assert "// SKIPPED rule 'nope'" in out+ assert "rule snitch_x {" not in out+++def test_yaral_numeric_fields_unquoted():+ from detection import yaral+ out = yaral.export([{"id": "n", "name": "p", "severity": "info",+ "field": "remote_port", "op": "gt",+ "value": "1024"}])+ assert "$e.target.port > 1024" in out+++# ── Agent ingest / ingestion d'agent ─────────────────────────────────────────++def test_ingest_events_endpoint():+ import pytest+ pytest.importorskip("httpx")+ from fastapi.testclient import TestClient+ from api.main import app+ from api.security import API_TOKEN+ c = TestClient(app)+ r = c.post("/ingest/events",+ headers={"X-Snitch-Token": API_TOKEN},+ json={"agent": "snitch-agent/1", "host": "a1",+ "events": [{"src_ip": "10.0.0.5", "dst_ip": "93.184.216.34",+ "src_port": 51000, "dst_port": 443,+ "proto": "tcp", "direction": "out"}]})+ assert r.status_code == 200+ assert r.json()["accepted"] == 1+++def test_ingest_events_auth_required():+ import pytest+ pytest.importorskip("httpx")+ from fastapi.testclient import TestClient+ from api.main import app+ c = TestClient(app)+ r = c.post("/ingest/events", json={"events": []})+ assert r.status_code in (401, 403)+++def test_ingest_events_bounded_and_validated():+ import pytest+ pytest.importorskip("httpx")+ from fastapi.testclient import TestClient+ from api.main import app+ from api.security import API_TOKEN+ c = TestClient(app)+ r = c.post("/ingest/events",+ headers={"X-Snitch-Token": API_TOKEN},+ json={"agent": "x", "host": "h",+ "events": [{"dst_ip": ""}, # EN: dropped / FR: rejeté+ "not-a-dict", # EN: dropped / FR: rejeté+ {"dst_ip": "8.8.8.8", "dst_port": "junk"}]})+ body = r.json()+ assert body["accepted"] == 1 # EN: only the valid one / FR: seul le valide+ assert body["received"] == 3diff --git a/backend/version.py b/backend/version.pyindex bcd38a8..70d36ba 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.6.0"+__version__ = "1.6.1"diff --git a/deploy/gpo/Install-Snitch.ps1 b/deploy/gpo/Install-Snitch.ps1new file mode 100644index 0000000..ac5ad1f--- /dev/null+++ b/deploy/gpo/Install-Snitch.ps1@@ -0,0 +1,80 @@+<#+.SYNOPSIS+ Snitch — silent install for GPO/SCCM deployment / installation+ silencieuse pour déploiement GPO/SCCM.++.DESCRIPTION+ EN: Drops the backend into %ProgramFiles%\Snitch, writes the+ declarative config to %ProgramData%\Snitch\snitch.toml (the+ backend applies it at startup — same Security-as-Code contract+ as Linux), creates the venv + pinned deps, and registers a+ SYSTEM scheduled task running headless on 127.0.0.1.+ Designed for a GPO startup script or Intune/MDM win32 app:+ powershell -ExecutionPolicy Bypass -File Install-Snitch.ps1 `+ -Source \\share\snitch -Token <api-token>+ FR: Dépose le backend dans %ProgramFiles%\Snitch, écrit la config+ déclarative dans %ProgramData%\Snitch\snitch.toml (appliquée au+ démarrage — même contrat Security-as-Code que Linux), crée le+ venv + deps épinglées, et enregistre une tâche planifiée SYSTEM+ headless sur 127.0.0.1. Pour script de démarrage GPO ou app+ win32 Intune/MDM.+#>+param(+ [Parameter(Mandatory=$true)]+ [string]$Source, # EN: repo checkout or share path / FR: checkout ou partage+ [string]$InstallDir = "$env:ProgramFiles\Snitch",+ [string]$DataDir = "$env:ProgramData\Snitch",+ [string]$Token = "", # EN: fixed API token (recommended) / FR: jeton fixe (recommandé)+ [int]$Port = 8000+)+$ErrorActionPreference = 'Stop'++# EN: 1) Files / FR: 1) Fichiers+New-Item -ItemType Directory -Force -Path $InstallDir, $DataDir | Out-Null+Copy-Item -Recurse -Force -Path (Join-Path $Source 'backend') `+ -Destination $InstallDir++# EN: 2) Declarative config — file wins over DB, same as Linux.+# FR: 2) Config déclarative — le fichier prime sur la DB, comme Linux.+@"+ask_enabled = false+kill_switch_enabled = true+"@ | Set-Content -Encoding UTF8 -Path (Join-Path $DataDir 'snitch.toml')++# EN: 3) venv + pinned deps / FR: 3) venv + deps épinglées+$py = (Get-Command python -ErrorAction Stop).Source+& $py -m venv (Join-Path $InstallDir 'env')+& (Join-Path $InstallDir 'env\Scripts\python.exe') -m pip install -r `+ (Join-Path $InstallDir 'backend\requirements.txt') --quiet++# EN: 4) Headless scheduled task at startup (SYSTEM, loopback only).+# FR: 4) Tâche planifiée headless au démarrage (SYSTEM, loopback).+$uvicorn = Join-Path $InstallDir 'env\Scripts\pythonw.exe'+$action = New-ScheduledTaskAction -Execute $uvicorn `+ -Argument "-m uvicorn api.main:app --host 127.0.0.1 --port $Port" `+ -WorkingDirectory (Join-Path $InstallDir 'backend')+$trigger = New-ScheduledTaskTrigger -AtStartup+$principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' `+ -LogonType ServiceAccount -RunLevel Highest+$env = "SNITCH_DATA_DIR=$DataDir;SNITCH_CONFIG=" ++ (Join-Path $DataDir 'snitch.toml')+if ($Token) { $env += ";SNITCH_TOKEN=$Token" }+Register-ScheduledTask -TaskName 'Snitch' -Action $action `+ -Trigger $trigger -Principal $principal -Force `+ -Description 'Snitch network observability backend (headless)'+Set-ScheduledTask -TaskName 'Snitch' -Settings `+ (New-ScheduledTaskSettingsSet -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1))+# EN: env vars for the task — via a launcher cmd file (task env is limited).+# FR: vars d'env de la tâche — via un cmd lanceur (env de tâche limité).+@"+@echo off+set $env.Split(';')[0]+set $env.Split(';')[1]+$(if ($Token) { 'set ' + $env.Split(';')[2] })+"$uvicorn" -m uvicorn api.main:app --host 127.0.0.1 --port $Port+"@ | Set-Content -Encoding ASCII -Path (Join-Path $InstallDir 'run.cmd')+$action = New-ScheduledTaskAction -Execute (Join-Path $InstallDir 'run.cmd') `+ -WorkingDirectory (Join-Path $InstallDir 'backend')+Set-ScheduledTask -TaskName 'Snitch' -Action $action | Out-Null+Start-ScheduledTask -TaskName 'Snitch'+Write-Host "Snitch installed — API on http://127.0.0.1:$Port (token auth)"diff --git a/deploy/helm/snitch/Chart.yaml b/deploy/helm/snitch/Chart.yamlindex 8d4db88..b635fa2 100644--- a/deploy/helm/snitch/Chart.yaml+++ b/deploy/helm/snitch/Chart.yaml@@ -6,7 +6,7 @@ description: |(/remote/fleet over gossip_peers) or a per-node agent.type: applicationversion: 0.1.0-appVersion: "1.6.0"+appVersion: "1.6.1"home: https://github.com/aixisstudio/Snitchkeywords:- securitydiff --git a/deploy/puppet/modules/snitch/manifests/init.pp b/deploy/puppet/modules/snitch/manifests/init.ppnew file mode 100644index 0000000..b3cfd53--- /dev/null+++ b/deploy/puppet/modules/snitch/manifests/init.pp@@ -0,0 +1,68 @@+# Snitch — Puppet module skeleton (community maintained, help wanted)+# EN: Same three primitives as the Ansible role — deploy the backend+# tree, render /etc/snitch/snitch.toml, manage snitch.service.+# Extend with Hiera keys (snitch::syslog_addr, snitch::peers…) as+# your fleet needs; PRs welcome.+# FR: Mêmes trois primitives que le rôle Ansible — déployer le backend,+# rendre /etc/snitch/snitch.toml, gérer snitch.service. Étendre avec+# des clés Hiera selon la flotte ; PR bienvenues.+class snitch (+ String $install_dir = '/opt/snitch',+ String $config_dir = '/etc/snitch',+ String $user = 'snitch',+ Boolean $manage_service = true,+) {+ user { $user:+ ensure => present,+ system => true,+ managehome => false,+ shell => '/usr/sbin/nologin',+ }++ file { [$install_dir, "${install_dir}/backend", $config_dir,+ '/var/lib/snitch']:+ ensure => directory,+ }++ # EN: Push the checked-out backend/ tree (or swap for a release tarball+ # via the `source` param of your file resource / an archive module).+ # FR: Pousser l'arbre backend/ (ou un tarball de release via `source`).+ file { "${install_dir}/backend":+ ensure => directory,+ source => 'puppet:///modules/snitch/backend',+ recurse => true,+ owner => 'root',+ group => $user,+ mode => '0644',+ }++ file { "${config_dir}/snitch.toml":+ ensure => file,+ content => template('snitch/snitch.toml.erb'),+ owner => 'root',+ group => $user,+ mode => '0640',+ notify => Service['snitch'],+ }++ file { '/etc/systemd/system/snitch.service':+ ensure => file,+ source => 'puppet:///modules/snitch/snitch.service',+ mode => '0644',+ notify => Exec['systemd-reload'],+ }++ exec { 'systemd-reload':+ command => '/bin/systemctl daemon-reload',+ refreshonly => true,+ }++ if $manage_service {+ service { 'snitch':+ ensure => running,+ enable => true,+ subscribe => [File['/etc/systemd/system/snitch.service'],+ File["${config_dir}/snitch.toml"]],+ }+ }+}diff --git a/deploy/puppet/modules/snitch/templates/snitch.toml.erb b/deploy/puppet/modules/snitch/templates/snitch.toml.erbnew file mode 100644index 0000000..f9237d5--- /dev/null+++ b/deploy/puppet/modules/snitch/templates/snitch.toml.erb@@ -0,0 +1,10 @@+# Snitch — declarative config (rendered by Puppet / rendu par Puppet)+<% if @syslog_addr -%>+syslog_addr = "<%= @syslog_addr %>"+syslog_format = "<%= @syslog_format || 'cef' %>"+<% end -%>+ask_enabled = <%= @ask_enabled.nil? ? 'false' : @ask_enabled %>+kill_switch_enabled = <%= @kill_switch.nil? ? 'true' : @kill_switch %>+<% if @peers -%>+gossip_peers = <%= @peers.to_s.gsub("'", '"') %>+<% end -%>diff --git a/deploy/salt/snitch/init.sls b/deploy/salt/snitch/init.slsnew file mode 100644index 0000000..18b5950--- /dev/null+++ b/deploy/salt/snitch/init.sls@@ -0,0 +1,69 @@+# Snitch — SaltStack state skeleton (community maintained, help wanted)+# EN: Same three primitives — user, tree + venv, snitch.toml, unit.+# Pillar keys: snitch:syslog_addr, snitch:peers, …+# FR: Mêmes trois primitives — utilisateur, arbre + venv, snitch.toml,+# unité. Clés pillar : snitch:syslog_addr, snitch:peers, …++snitch-user:+ user.present:+ - name: snitch+ - system: True+ - createhome: False+ - shell: /usr/sbin/nologin++snitch-dirs:+ file.directory:+ - names:+ - /opt/snitch+ - /etc/snitch+ - /var/lib/snitch+ - require:+ - user: snitch-user++snitch-backend:+ file.recurse:+ - name: /opt/snitch/backend+ - source: salt://snitch/backend+ - dir_mode: "0755"+ - file_mode: "0644"+ - require:+ - file: snitch-dirs++snitch-venv:+ virtualenv.managed:+ - name: /opt/snitch/backend/env+ - requirements: /opt/snitch/backend/requirements.txt+ - require:+ - file: snitch-backend++snitch-config:+ file.managed:+ - name: /etc/snitch/snitch.toml+ - source: salt://snitch/files/snitch.toml.jinja+ - template: jinja+ - mode: "0640"+ - user: root+ - group: snitch+ - watch_in:+ - service: snitch-service++snitch-unit:+ file.managed:+ - name: /etc/systemd/system/snitch.service+ - source: salt://snitch/files/snitch.service+ - mode: "0644"+ - require:+ - file: snitch-dirs+ module.run:+ - name: service.systemctl_reload+ - onchanges:+ - file: snitch-unit++snitch-service:+ service.running:+ - name: snitch+ - enable: True+ - require:+ - virtualenv: snitch-venv+ - file: snitch-config+ - module: snitch-unitdiff --git a/deploy/systemd/snitch-agent.service b/deploy/systemd/snitch-agent.servicenew file mode 100644index 0000000..5278214--- /dev/null+++ b/deploy/systemd/snitch-agent.service@@ -0,0 +1,39 @@+# snitch-agent — systemd unit (remote sensor / capteur distant)+# EN: The agent only READS /proc/net — it needs zero capabilities and+# runs fully unprivileged. Install next to the binary:+# install -m755 target/release/snitch-agent /usr/local/bin/+# install -m644 deploy/systemd/snitch-agent.service /etc/systemd/system/+# systemctl enable --now snitch-agent+# FR: L'agent ne fait que LIRE /proc/net — zéro capacité, totalement+# non privilégié.++[Unit]+Description=Snitch agent — lightweight socket sensor for a Snitch collector+After=network-online.target+Wants=network-online.target++[Service]+Type=simple+DynamicUser=yes+ExecStart=/usr/local/bin/snitch-agent+Restart=on-failure+RestartSec=5s++# EN: collector endpoint + bearer — put real values in a drop-in:+# /etc/systemd/system/snitch-agent.service.d/env.conf+# [Service] Environment=SNITCH_SERVER=… SNITCH_TOKEN=…+# FR: endpoint collecteur + bearer — vraies valeurs dans un drop-in.+Environment=SNITCH_SERVER=127.0.0.1:8000+Environment=SNITCH_INTERVAL_SECS=5++NoNewPrivileges=true+ProtectSystem=strict+ProtectHome=true+PrivateTmp=true+# EN: needs /proc/net — that lives inside /proc, keep it visible.+# FR: a besoin de /proc/net — laisser /proc visible.+ProtectProc=default+RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6++[Install]+WantedBy=multi-user.targetdiff --git a/docs/INTEGRATIONS.de.md b/docs/INTEGRATIONS.de.mdnew file mode 100644index 0000000..86b2ad7--- /dev/null+++ b/docs/INTEGRATIONS.de.md@@ -0,0 +1,169 @@+# Snitch — Enterprise-Integrationen++*Community translated — PRs welcome for refinement / Von der Community übersetzt — PRs zur Verbesserung willkommen.*++**DE:** Schritt-für-Schritt-Anleitungen, um Snitch in einen SOC-Stack+einzubinden — Wazuh, Splunk, Graylog/Loki, Ansible, Docker/Kubernetes —+alles kostenlos und selbst gehostet, passend zu Snitches Local-first-Ansatz.+Snitch sendet keine eigene Telemetrie; die einzigen ausgehenden+Verbindungen sind die hier konfigurierten.++---++## 1. SIEM-Ausgabe++Snitch bietet drei native Formate für die Alarm-Weiterleitung:++| Einstellung | Werte | Wirkung |+|---|---|---|+| `syslog_addr` | `host:514` oder `tcp://host:514` | Aktiviert Syslog-Weiterleitung (UDP Standard, TCP mit `tcp://`-Präfix) |+| `syslog_format` | `rfc3164` *(Standard)* | Klassisches BSD-Syslog — von jedem Kollektor lesbar |+| | `cef` | `CEF:0|Snitch|…` — ArcSight/Wazuh/Splunk parsen `src`, `dst`, `dpt`, `cs1` (Prozess) automatisch |+| `webhook_url` + `webhook_enabled` | URL | Generischer JSON-`POST` (oder automatisch erkannte Discord/Slack/Telegram-Payloads) |+| `GET /forensics/export?format=…` | `json`, `csv`, `stix`, `ecs` | Einmalige Forensik-Bundles — `ecs` erzeugt zeilenweise Elastic Common Schema |++In der UI setzen (Einstellungen → Sicherheit) oder in `snitch.toml`:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+```++## 2. Wazuh++1. Syslog-Listener auf dem Wazuh-Manager aktivieren (`/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. Jeden Snitch-Agenten darauf zeigen lassen — Ansible:++ ```yaml+ snitch_syslog_addr: "wazuh.example.com:514"+ snitch_syslog_format: "cef"+ ```++3. Der CEF-Decoder von Wazuh übernimmt die `CEF:0|Snitch|…`-Meldungen;+ `severity` wird auf syslog-PRI abgebildet (critical→2, warning→4, info→6).++## 3. Splunk++1. Einstellungen → Daten-Inputs → UDP → neuer Input auf 514, Sourcetype+ `syslog` (oder TCP-Input für `tcp://…`-Sender).+2. `syslog_format = "cef"` liefert `src`, `dst`, `dpt`, `cs1Label` gratis;+ für Dashboards `GET /forensics/export?format=ecs` per Scripted Input+ abfragen — JSON wird automatisch extrahiert.++## 4. Graylog / Loki++- **Graylog**: System → Inputs → Syslog UDP, Port 514. CEF-Erweiterungsfelder+ landen als Nachrichtenfelder.+- **Loki/Grafana**: `syslog_addr` auf ein `promtail`-Syslog-Target richten+ oder `/forensics/export?format=ecs` per Cronjob → Loki-Push-Job scrapen.++## 5. Deklarative Konfiguration (Security-as-Code)++Das Backend wendet **eine Datei** beim Start an — `$SNITCH_CONFIG`, sonst+`snitch.toml`/`snitch.json` im Datenverzeichnis. Jede deklarierte+Einstellung überschreibt den UI/DB-Wert — die Datei ist die+Wahrheitsquelle der Flotte:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+kill_switch_enabled = true+ask_enabled = false # headless Server+gossip_peers = ["sec-01:8000"]+ports = [80, 443]+```++Vollständiges Vokabular: `packaging/snitch.toml.example`.++## 6. Ansible / Puppet / Salt / GPO++- **Ansible** — fertige Rolle in `deploy/ansible/`:++ ```bash+ ansible-playbook -i inventory deploy/ansible/site.yml+ ```++ Installiert `/opt/snitch`, das venv, `/etc/snitch/snitch.toml` und die+ gehärtete systemd-Unit, aktiviert dann `snitch.service`.++- **Puppet / SaltStack** — Community-Skelette in `deploy/puppet/` und+ `deploy/salt/` (Label `help wanted`): dieselben drei Primitive —+ Backend-Baum kopieren, `snitch.toml` rendern, `snitch.service` verwalten.++- **Windows GPO** — `deploy/gpo/Install-Snitch.ps1` führt die+ Silent-Installation aus (ProgramData-Config, venv, SYSTEM-Aufgabe auf+ 127.0.0.1). Ask-on-connect unter Windows braucht zusätzlich den+ signierten WFP-Callout — siehe `docs/SIGNING.md`.++## 7. Docker & Kubernetes++- **Einzelhost**: `docker compose up` — `network_mode: host` ++ `cap_add: NET_RAW/NET_ADMIN` bereits in `docker-compose.yml`.+- **Flotten-Konsole**: `deploy/helm/snitch` — `mode: collector` startet+ ein ClusterIP-Deployment, das die Audits aller konfigurierten Agenten+ in `GET /remote/fleet` zusammenführt; `mode: agent` rendert ein+ Host-Network-DaemonSet mit `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-Regeln++`POST /alerts/rules/sigma` akzeptiert ein Sigma-YAML und kompiliert die+unterstützte Teilmenge (Feld→Wert-Selektionen, `|contains`/`|startswith`/+`|endswith`/`|re`/`|cidr`/`|gt`/`|lt`/`|all`, `1 of`/`all of`-Bedingungen)+in Snitch-Custom-Rules — nur Alarme, `skipped`-Gründe für alles+außerhalb der Teilmenge. Felder werden auf das gemappt, was ein+*Paket*-Sensor sieht (`DestinationIp→remote_ip`, `Image→process_name`,+`Domain→host`, …).++YARA-L für Google SecOps/Chronicle: `GET /alerts/rules/yaral` exportiert+alle Regeln (inkl. importierter Sigma-Regeln) als `.yar`-Datei — der+Weg Sigma→YARA-L ist damit abgedeckt.++## 9. Remote-Agenten (snitch-agent/1)++`agent/` enthält einen leichten Rust-Daemon (null Abhängigkeiten, ein+~1-MB-Binary), der die Socket-Tabelle des Hosts (`/proc/net/*`)+beobachtet und neue ausgehende Flows an `POST /ingest/events` pusht.+Er beobachtet Sockets — keine Payloads/SNI (das bleibt beim lokalen+Capture); Prozess-Attribution ist als TODO markiert. Transport: HTTP ++Bearer-Token (Trust-Domain wie `gossip_peers`).++## 10. Kostenlose Threat-Intel-Feeds++`POST /firewall/blocklist` importiert beide Formen:++- `kind: "domain"` — Hosts-/Domain-Listen (StevenBlack, EasyList…) →+ `domain`-Firewall-Regeln;+- `kind: "ip"` — IP-Feeds (Blocklist.de, URLhaus/Feodo-Exports) →+ `ip`-Regeln; private/reservierte/Loopback-Adressen werden nie importiert.++`path:` liest eine lokale Datei (vollständig offline); `url:` ist ein+expliziter, auditierter Opt-in-Fetch (`remote_fetch: true` in der+Antwort). Limit `max_entries ≤ 5000` — riesige Feeds gehören in einen+Resolver.++Opt-in-API-Anbieter (AbuseIPDB / OTX / VirusTotal) bleiben über+`ti_provider` + `ti_api_key` verfügbar — ohne Schlüssel geht nichts raus.++## 11. Headless- / Daemon-Modus++Die GUI ist optional: das Backend ist das gesamte Produkt. Direkt+(`uvicorn api.main:app`), unter der mitgelieferten systemd-Unit oder im+Container — alle Funktionen oben laufen ohne Frontend.+`SNITCH_DEMO=1` liefert weiterhin einen root-freien synthetischen Feed+für Schulungen und CTFs.diff --git a/docs/INTEGRATIONS.es.md b/docs/INTEGRATIONS.es.mdnew file mode 100644index 0000000..5e7b925--- /dev/null+++ b/docs/INTEGRATIONS.es.md@@ -0,0 +1,168 @@+# Snitch — Integraciones empresariales++*Community translated — PRs welcome for refinement / Traducido por la comunidad — se aceptan PRs de mejora.*++**ES:** Recetas paso a paso para integrar Snitch en un stack SOC —+Wazuh, Splunk, Graylog/Loki, Ansible, Docker/Kubernetes — todo gratis y+auto-alojado, coherente con la postura local-first de Snitch. Snitch no+emite telemetría propia; las únicas conexiones salientes son las que+configuras aquí.++---++## 1. Salida SIEM++Snitch ofrece tres formatos nativos para reenviar alertas:++| Ajuste | Valores | Efecto |+|---|---|---|+| `syslog_addr` | `host:514` o `tcp://host:514` | Activa el reenvío syslog (UDP por defecto, TCP con prefijo `tcp://`) |+| `syslog_format` | `rfc3164` *(por defecto)* | Syslog BSD clásico — legible por cualquier colector |+| | `cef` | `CEF:0|Snitch|…` — ArcSight/Wazuh/Splunk parsean `src`, `dst`, `dpt`, `cs1` (proceso) automáticamente |+| `webhook_url` + `webhook_enabled` | URL | `POST` JSON genérico (o payloads Discord/Slack/Telegram autodetectados) |+| `GET /forensics/export?format=…` | `json`, `csv`, `stix`, `ecs` | Bundles forenses de una vez — `ecs` emite Elastic Common Schema en NDJSON |++Configúralos en la UI (Ajustes → Seguridad) o en `snitch.toml`:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+```++## 2. Wazuh++1. Activa un listener syslog en el manager Wazuh (`/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. Apunta cada agente Snitch — Ansible:++ ```yaml+ snitch_syslog_addr: "wazuh.example.com:514"+ snitch_syslog_format: "cef"+ ```++3. El decodificador CEF de Wazuh recoge los `CEF:0|Snitch|…`; la+ `severity` se mapea a PRI syslog (critical→2, warning→4, info→6).++## 3. Splunk++1. Configuración → Entradas de datos → UDP → nueva entrada en 514,+ sourcetype `syslog` (o entrada TCP para emisores `tcp://…`).+2. `syslog_format = "cef"` te da `src`, `dst`, `dpt`, `cs1Label` gratis;+ para dashboards consulta `GET /forensics/export?format=ecs` con un+ scripted input — el JSON se extrae automáticamente.++## 4. Graylog / Loki++- **Graylog**: System → Inputs → Syslog UDP, puerto 514. Los campos de+ extensión CEF llegan como campos del mensaje.+- **Loki/Grafana**: apunta `syslog_addr` a un target syslog de `promtail`+ o scrapea `/forensics/export?format=ecs` con cron → job push a Loki.++## 5. Configuración declarativa (Security-as-Code)++El backend aplica **un archivo** al arrancar — `$SNITCH_CONFIG`, o+`snitch.toml`/`snitch.json` en el directorio de datos. Cada clave+declarada sobrescribe el valor UI/DB: el archivo es la fuente de verdad+de la flota:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+kill_switch_enabled = true+ask_enabled = false # servidores headless+gossip_peers = ["sec-01:8000"]+ports = [80, 443]+```++Vocabulario completo: `packaging/snitch.toml.example`.++## 6. Ansible / Puppet / Salt / GPO++- **Ansible** — rol listo en `deploy/ansible/`:++ ```bash+ ansible-playbook -i inventory deploy/ansible/site.yml+ ```++ Instala `/opt/snitch`, el venv, `/etc/snitch/snitch.toml` y la unidad+ systemd endurecida, y habilita `snitch.service`.++- **Puppet / SaltStack** — esqueletos comunitarios en `deploy/puppet/` y+ `deploy/salt/` (label `help wanted`): las mismas tres primitivas —+ copiar el árbol backend, renderizar `snitch.toml`, gestionar+ `snitch.service`.++- **Windows GPO** — `deploy/gpo/Install-Snitch.ps1` hace la instalación+ silenciosa (config en ProgramData, venv, tarea SYSTEM en 127.0.0.1).+ Ask-on-connect en Windows requiere además el callout WFP firmado —+ ver `docs/SIGNING.md`.++## 7. Docker & Kubernetes++- **Host único**: `docker compose up` — `network_mode: host` ++ `cap_add: NET_RAW/NET_ADMIN` ya en `docker-compose.yml`.+- **Consola de flota**: `deploy/helm/snitch` — `mode: collector` lanza+ un Deployment ClusterIP que fusiona las auditorías de todos los+ agentes configurados en `GET /remote/fleet`; `mode: agent` renderiza+ un DaemonSet host-network con `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. Reglas Sigma++`POST /alerts/rules/sigma` acepta un YAML Sigma y compila el subconjunto+soportado (selecciones campo→valor, `|contains`/`|startswith`/`|endswith`/+`|re`/`|cidr`/`|gt`/`|lt`/`|all`, condiciones `1 of`/`all of`) en reglas+custom de Snitch — solo alertas, con motivos `skipped` para lo no+soportado. Los campos se mapean a lo que un sensor de *paquetes* ve+(`DestinationIp→remote_ip`, `Image→process_name`, `Domain→host`, …).++YARA-L para Google SecOps/Chronicle: `GET /alerts/rules/yaral` exporta+todas las reglas (incluidas las Sigma importadas) como archivo `.yar` —+el camino Sigma→YARA-L queda cubierto.++## 9. Agentes remotos (snitch-agent/1)++`agent/` contiene un daemon Rust ligero (cero dependencias, un solo+binario ~1 MB) que observa la tabla de sockets del host (`/proc/net/*`)+y envía los nuevos flujos salientes a `POST /ingest/events`. Observa+sockets — sin payloads/SNI (eso queda en el capture local); la+atribución de proceso está marcada como TODO. Transporte: HTTP + bearer+(dominio de confianza como `gossip_peers`).++## 10. Feeds de threat-intel gratuitos++`POST /firewall/blocklist` importa ambas formas:++- `kind: "domain"` — listas hosts/dominios (StevenBlack, EasyList…) →+ reglas `domain`;+- `kind: "ip"` — feeds IP (Blocklist.de, exports URLhaus/Feodo) → reglas+ `ip`; nunca se importan direcciones privadas/reservadas/loopback.++`path:` lee un archivo local (totalmente offline); `url:` es un fetch+opt-in explícito y auditado (`remote_fetch: true` en la respuesta).+Límite `max_entries ≤ 5000` — los feeds gigantes pertenecen a un resolver.++Los proveedores opt-in (AbuseIPDB / OTX / VirusTotal) siguen disponibles+vía `ti_provider` + `ti_api_key` — nada sale sin tu clave.++## 11. Modo headless / daemon++La GUI es opcional: el backend es todo el producto. Ejecútalo directo+(`uvicorn api.main:app`), bajo la unidad systemd incluida o en el+contenedor — todas las funciones anteriores funcionan sin frontend.+`SNITCH_DEMO=1` sigue ofreciendo un feed sintético sin root para+formaciones y CTFs.diff --git a/docs/INTEGRATIONS.ja.md b/docs/INTEGRATIONS.ja.mdnew file mode 100644index 0000000..8abc2a7--- /dev/null+++ b/docs/INTEGRATIONS.ja.md@@ -0,0 +1,170 @@+# Snitch — エンタープライズ統合++*Community translated — PRs welcome for refinement / コミュニティ翻訳 — 改善PR歓迎。*++**日本語:** Snitch を SOC スタックに組み込むためのステップバイステップ+ガイド — Wazuh、Splunk、Graylog/Loki、Ansible、Docker/Kubernetes。+すべて無料・セルフホストで、Snitch のローカルファースト方針と一致します。+Snitch 自身はテレメトリを一切送信しません。外部への接続は、ここで+設定するものだけです。++---++## 1. SIEM 出力++アラート転送用に3つのネイティブ形式を提供:++| 設定 | 値 | 効果 |+|---|---|---|+| `syslog_addr` | `host:514` または `tcp://host:514` | syslog 転送を有効化(UDP がデフォルト、`tcp://` プレフィックスで TCP) |+| `syslog_format` | `rfc3164` *(デフォルト)* | 古典的 BSD syslog — あらゆるコレクターで読める |+| | `cef` | `CEF:0|Snitch|…` — ArcSight/Wazuh/Splunk が `src`、`dst`、`dpt`、`cs1`(プロセス)を自動パース |+| `webhook_url` + `webhook_enabled` | URL | 汎用 JSON `POST`(Discord/Slack/Telegram のペイロードは自動検出) |+| `GET /forensics/export?format=…` | `json`、`csv`、`stix`、`ecs` | ワンショットのフォレンジックバンドル — `ecs` は Elastic Common Schema NDJSON を出力 |++UI(設定 → セキュリティ)または `snitch.toml` で設定:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+```++## 2. Wazuh++1. Wazuh マネージャーで syslog リスナーを有効化(`/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. 各 Snitch エージェントを向ける — Ansible:++ ```yaml+ snitch_syslog_addr: "wazuh.example.com:514"+ snitch_syslog_format: "cef"+ ```++3. Wazuh の CEF デコーダーが `CEF:0|Snitch|…` を拾い、`severity` は+ syslog PRI にマップされます(critical→2、warning→4、info→6)。++## 3. Splunk++1. 設定 → データ入力 → UDP → 514 の新規入力、sourcetype `syslog`+ (`tcp://…` 送信側には TCP 入力)。+2. `syslog_format = "cef"` で `src`、`dst`、`dpt`、`cs1Label` が無料で+ 使えます。ダッシュボードには scripted input で+ `GET /forensics/export?format=ecs` をポーリング — JSON は自動抽出。++## 4. Graylog / Loki++- **Graylog**: System → Inputs → Syslog UDP、514 にバインド。CEF 拡張+ フィールドはメッセージフィールドとして届きます。+- **Loki/Grafana**: `syslog_addr` を `promtail` の syslog ターゲットに+ 向けるか、cron → Loki push ジョブで+ `/forensics/export?format=ecs` をスクレイプ。++## 5. 宣言的設定(Security-as-Code)++バックエンドは起動時に**1つのファイル**を適用します — `$SNITCH_CONFIG`、+なければデータディレクトリの `snitch.toml`/`snitch.json`。宣言された+キーは UI/DB の値を上書き — このファイルがフリートの真実の源です:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+kill_switch_enabled = true+ask_enabled = false # headless サーバー+gossip_peers = ["sec-01:8000"]+ports = [80, 443]+```++完全な語彙は `packaging/snitch.toml.example` を参照。++## 6. Ansible / Puppet / Salt / GPO++- **Ansible** — `deploy/ansible/` に完成済みロール:++ ```bash+ ansible-playbook -i inventory deploy/ansible/site.yml+ ```++ `/opt/snitch`、venv、`/etc/snitch/snitch.toml`、強化 systemd ユニットを+ インストールし、`snitch.service` を有効化します。++- **Puppet / SaltStack** — `deploy/puppet/` と `deploy/salt/` に+ コミュニティ製スケルトン(`help wanted` ラベル):同じ3つの+ プリミティブ — バックエンドツリー配置、`snitch.toml` レンダリング、+ `snitch.service` 管理。++- **Windows GPO** — `deploy/gpo/Install-Snitch.ps1` がサイレント+ インストールを実行(ProgramData 設定、venv、127.0.0.1 の SYSTEM+ タスク)。Windows の ask-on-connect には署名済み WFP コールアウトが+ さらに必要 — `docs/SIGNING.md` 参照。++## 7. Docker & Kubernetes++- **単一ホスト**: `docker compose up` — `network_mode: host` ++ `cap_add: NET_RAW/NET_ADMIN` は `docker-compose.yml` 設定済み。+- **フリートコンソール**: `deploy/helm/snitch` — `mode: collector` は+ 設定済みエージェントの監査を `GET /remote/fleet` に集約する+ ClusterIP Deployment を起動;`mode: agent` は `NET_RAW`/`NET_ADMIN`+ 付きのホストネットワーク DaemonSet をレンダリング。++ ```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 ルール++`POST /alerts/rules/sigma` は Sigma 検出 YAML を受け取り、サポート済み+サブセット(フィールド→値セレクション、`|contains`/`|startswith`/+`|endswith`/`|re`/`|cidr`/`|gt`/`|lt`/`|all`、`1 of`/`all of` 条件)を+Snitch カスタムルールにコンパイル — アラートのみ、非対応部分は+`skipped` に理由を返します。フィールドは*パケット*センサーが見えるものに+マッピング(`DestinationIp→remote_ip`、`Image→process_name`、+`Domain→host` など)。++Google SecOps/Chronicle 向け YARA-L:`GET /alerts/rules/yaral` が全+ルール(Sigma 由来を含む)を `.yar` ファイルとしてエクスポート —+Sigma→YARA-L パスはこれでカバー済み。++## 9. リモートエージェント(snitch-agent/1)++`agent/` には軽量 Rust デーモン(依存ゼロ、単一 ~1MB バイナリ)があり、+ホストのソケットテーブル(`/proc/net/*`)を監視し、新しいアウトバウンド+フローを `POST /ingest/events` にプッシュします。ソケットを観測する+だけ — ペイロード/SNI なし(それはローカルキャプチャの仕事);+プロセス帰属は TODO マーク済み。トランスポートは HTTP + Bearer+(`gossip_peers` と同じトラストドメイン)。++## 10. 無料脅威インテリジェンスフィード++`POST /firewall/blocklist` は両方の形式をインポート:++- `kind: "domain"` — hosts/ドメインリスト(StevenBlack、EasyList…)→+ `domain` ファイアウォールルール;+- `kind: "ip"` — IP フィード(Blocklist.de、URLhaus/Feodo エクスポート)+ → `ip` ルール;プライベート/予約/ループバックは絶対にインポートしない。++`path:` はローカルファイルを読む(完全オフライン);`url:` は明示的で+監査可能なオプトインフェッチ(レスポンスに `remote_fetch: true`)。+上限 `max_entries ≤ 5000` — 巨大フィードはリゾルバーの仕事。++オプトイン API プロバイダー(AbuseIPDB / OTX / VirusTotal)は+`ti_provider` + `ti_api_key` で利用可能 — キーを設定しない限り+何も送信しません。++## 11. ヘッドレス/デーモンモード++GUI はオプション:バックエンドが製品のすべて。直接起動+(`uvicorn api.main:app`)、同梱 systemd ユニット、またはコンテナ —+上記すべての機能がフロントエンドなしで動作します。+`SNITCH_DEMO=1` は研修や CTF 向けに root 不要の合成フィードを+提供し続けます。diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.mdindex 278934d..7a18c8b 100644--- a/docs/INTEGRATIONS.md+++ b/docs/INTEGRATIONS.md@@ -99,15 +99,15 @@ See `packaging/snitch.toml.example` for the full vocabulary.It installs `/opt/snitch`, the venv, `/etc/snitch/snitch.toml` and thehardened 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.+- **Puppet / SaltStack** — community skeletons in `deploy/puppet/` and+ `deploy/salt/` (label `help wanted`): the same three primitives —+ copy the backend tree, render `snitch.toml`, manage `snitch.service`.-- **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`.+- **Windows GPO** — `deploy/gpo/Install-Snitch.ps1` performs the silent+ install (ProgramData config, venv, SYSTEM scheduled task on 127.0.0.1)+ for GPO startup scripts or Intune win32 packaging. Ask-on-connect on+ Windows additionally needs the signed WFP callout — see+ `docs/SIGNING.md`.## 7. Docker & Kubernetes@@ -124,7 +124,7 @@ See `packaging/snitch.toml.example` for the full vocabulary.--set config.gossip_peers='["agent-1:8000","agent-2:8000"]'```-## 8. Sigma rules+## 8. Sigma rules & YARA-L`POST /alerts/rules/sigma` accepts a Sigma detection YAML and compiles thesupported subset (field→value selections, `|contains`/`|startswith`/@@ -133,7 +133,21 @@ into Snitch custom rules — alert-only, `skipped` reasons returned foranything outside the subset. Fields map to what a *packet* sensor sees(`DestinationIp→remote_ip`, `Image→process_name`, `Domain→host`, …).-## 9. Threat-intel feeds (free)+YARA-L for Google SecOps/Chronicle: `GET /alerts/rules/yaral` exports all+custom rules (including Sigma-imported ones) as a `.yar` file — the+Sigma→YARA-L path is covered transitively.++## 9. Remote agents (snitch-agent/1)++`agent/` ships a zero-dependency Rust daemon (~1 MB single binary) that+watches the host socket table (`/proc/net/*`, Linux) and pushes newly+observed outbound flows to `POST /ingest/events`. It observes sockets —+no payloads/SNI (that's the local capture's job); process attribution is+a marked TODO. Transport: HTTP + bearer token, same trust-domain model+as `gossip_peers`. A `snitch-agent.service` unit lives in+`deploy/systemd/`.++## 10. Threat-intel feeds (free)`POST /firewall/blocklist` imports both shapes:@@ -149,7 +163,7 @@ audited opt-in fetch (`remote_fetch: true` in the response). Cap atOpt-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+## 11. Headless / daemon modeThe GUI is optional: the backend is the whole product. Run it bare(`uvicorn api.main:app`), under the shipped systemd unit, or in thediff --git a/docs/INTEGRATIONS.pt-BR.md b/docs/INTEGRATIONS.pt-BR.mdnew file mode 100644index 0000000..0f6ed69--- /dev/null+++ b/docs/INTEGRATIONS.pt-BR.md@@ -0,0 +1,167 @@+# Snitch — Integrações empresariais++*Community translated — PRs welcome for refinement / Traduzido pela comunidade — PRs de melhoria são bem-vindos.*++**PT-BR:** Receitas passo a passo para ligar o Snitch a um stack SOC —+Wazuh, Splunk, Graylog/Loki, Ansible, Docker/Kubernetes — tudo grátis e+auto-hospedado, coerente com a postura local-first do Snitch. O Snitch+não emite telemetria própria; as únicas conexões de saída são as que+você configura aqui.++---++## 1. Saída SIEM++O Snitch oferece três formatos nativos para encaminhar alertas:++| Ajuste | Valores | Efeito |+|---|---|---|+| `syslog_addr` | `host:514` ou `tcp://host:514` | Ativa o encaminhamento syslog (UDP por padrão, TCP com prefixo `tcp://`) |+| `syslog_format` | `rfc3164` *(padrão)* | Syslog BSD clássico — legível por qualquer coletor |+| | `cef` | `CEF:0|Snitch|…` — ArcSight/Wazuh/Splunk fazem parse de `src`, `dst`, `dpt`, `cs1` (processo) automaticamente |+| `webhook_url` + `webhook_enabled` | URL | `POST` JSON genérico (ou payloads Discord/Slack/Telegram autodetectados) |+| `GET /forensics/export?format=…` | `json`, `csv`, `stix`, `ecs` | Bundles forenses únicos — `ecs` emite Elastic Common Schema em NDJSON |++Configure na UI (Configurações → Segurança) ou no `snitch.toml`:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+```++## 2. Wazuh++1. Ative um listener syslog no manager Wazuh (`/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. Aponte cada agente Snitch — Ansible:++ ```yaml+ snitch_syslog_addr: "wazuh.example.com:514"+ snitch_syslog_format: "cef"+ ```++3. O decodificador CEF do Wazuh captura os `CEF:0|Snitch|…`; a+ `severity` mapeia para PRI syslog (critical→2, warning→4, info→6).++## 3. Splunk++1. Configurações → Entradas de dados → UDP → nova entrada na 514,+ sourcetype `syslog` (ou entrada TCP para remetentes `tcp://…`).+2. `syslog_format = "cef"` dá `src`, `dst`, `dpt`, `cs1Label` de graça;+ para dashboards, consulte `GET /forensics/export?format=ecs` via+ scripted input — o JSON é extraído automaticamente.++## 4. Graylog / Loki++- **Graylog**: System → Inputs → Syslog UDP, porta 514. Os campos de+ extensão CEF chegam como campos da mensagem.+- **Loki/Grafana**: aponte `syslog_addr` para um target syslog do+ `promtail` ou faça scrape de `/forensics/export?format=ecs` via cron+ → job push para o Loki.++## 5. Configuração declarativa (Security-as-Code)++O backend aplica **um arquivo** na inicialização — `$SNITCH_CONFIG`, ou+`snitch.toml`/`snitch.json` no diretório de dados. Cada chave declarada+sobrescreve o valor UI/DB: o arquivo é a fonte de verdade da frota:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+kill_switch_enabled = true+ask_enabled = false # servidores headless+gossip_peers = ["sec-01:8000"]+ports = [80, 443]+```++Vocabulário completo: `packaging/snitch.toml.example`.++## 6. Ansible / Puppet / Salt / GPO++- **Ansible** — role pronta em `deploy/ansible/`:++ ```bash+ ansible-playbook -i inventory deploy/ansible/site.yml+ ```++ Instala `/opt/snitch`, o venv, `/etc/snitch/snitch.toml` e a unit+ systemd endurecida, e habilita `snitch.service`.++- **Puppet / SaltStack** — esqueletos comunitários em `deploy/puppet/` e+ `deploy/salt/` (label `help wanted`): as mesmas três primitivas —+ copiar a árvore backend, renderizar `snitch.toml`, gerenciar+ `snitch.service`.++- **Windows GPO** — `deploy/gpo/Install-Snitch.ps1` faz a instalação+ silenciosa (config no ProgramData, venv, tarefa SYSTEM em 127.0.0.1).+ Ask-on-connect no Windows requer adicionalmente o callout WFP+ assinado — ver `docs/SIGNING.md`.++## 7. Docker & Kubernetes++- **Host único**: `docker compose up` — `network_mode: host` ++ `cap_add: NET_RAW/NET_ADMIN` já no `docker-compose.yml`.+- **Console de frota**: `deploy/helm/snitch` — `mode: collector` sobe um+ Deployment ClusterIP que funde as auditorias de todos os agentes+ configurados em `GET /remote/fleet`; `mode: agent` renderiza um+ DaemonSet host-network com `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. Regras Sigma++`POST /alerts/rules/sigma` aceita um YAML Sigma e compila o subconjunto+suportado (seleções campo→valor, `|contains`/`|startswith`/`|endswith`/+`|re`/`|cidr`/`|gt`/`|lt`/`|all`, condições `1 of`/`all of`) em regras+custom do Snitch — apenas alertas, com motivos `skipped` para o que não+é suportado. Os campos mapeiam para o que um sensor de *pacotes* vê+(`DestinationIp→remote_ip`, `Image→process_name`, `Domain→host`, …).++YARA-L para Google SecOps/Chronicle: `GET /alerts/rules/yaral` exporta+todas as regras (incluindo as importadas de Sigma) como arquivo `.yar` —+o caminho Sigma→YARA-L fica coberto.++## 9. Agentes remotos (snitch-agent/1)++`agent/` contém um daemon Rust leve (zero dependências, um binário ~1 MB)+que observa a tabela de sockets do host (`/proc/net/*`) e envia novos+fluxos de saída para `POST /ingest/events`. Observa sockets — sem+payloads/SNI (isso fica com o capture local); atribuição de processo é+TODO marcado. Transporte: HTTP + bearer (mesmo domínio de confiança de+`gossip_peers`).++## 10. Feeds de threat-intel gratuitos++`POST /firewall/blocklist` importa ambas as formas:++- `kind: "domain"` — listas hosts/domínios (StevenBlack, EasyList…) →+ regras `domain`;+- `kind: "ip"` — feeds IP (Blocklist.de, exports URLhaus/Feodo) → regras+ `ip`; endereços privados/reservados/loopback nunca são importados.++`path:` lê arquivo local (totalmente offline); `url:` é um fetch opt-in+explícito e auditado (`remote_fetch: true` na resposta). Limite+`max_entries ≤ 5000` — feeds gigantes pertencem a um resolver.++Provedores opt-in (AbuseIPDB / OTX / VirusTotal) seguem disponíveis via+`ti_provider` + `ti_api_key` — nada sai sem a sua chave.++## 11. Modo headless / daemon++A GUI é opcional: o backend é o produto inteiro. Rode direto+(`uvicorn api.main:app`), sob a unit systemd incluída ou no container —+todas as funções acima funcionam sem frontend. `SNITCH_DEMO=1` segue+oferecendo um feed sintético sem root para treinamentos e CTFs.diff --git a/docs/INTEGRATIONS.ru.md b/docs/INTEGRATIONS.ru.mdnew file mode 100644index 0000000..450f86c--- /dev/null+++ b/docs/INTEGRATIONS.ru.md@@ -0,0 +1,168 @@+# Snitch — корпоративные интеграции++*Community translated — PRs welcome for refinement / Перевод сообщества — PR с правками приветствуются.*++**RU:** Пошаговые рецепты подключения Snitch к SOC-стеку —+Wazuh, Splunk, Graylog/Loki, Ansible, Docker/Kubernetes — всё бесплатно+и self-hosted, в духе local-first Snitch. Snitch сам не отправляет+телеметрию; единственные исходящие соединения — те, что настроены здесь.++---++## 1. Вывод в SIEM++Три нативных формата пересылки алертов:++| Настройка | Значения | Эффект |+|---|---|---|+| `syslog_addr` | `host:514` или `tcp://host:514` | Включает syslog-пересылку (UDP по умолчанию, TCP через префикс `tcp://`) |+| `syslog_format` | `rfc3164` *(по умолчанию)* | Классический BSD syslog — читается любым коллектором |+| | `cef` | `CEF:0|Snitch|…` — ArcSight/Wazuh/Splunk автоматически парсят `src`, `dst`, `dpt`, `cs1` (процесс) |+| `webhook_url` + `webhook_enabled` | URL | Универсальный JSON `POST` (или автоопределяемые payload-ы Discord/Slack/Telegram) |+| `GET /forensics/export?format=…` | `json`, `csv`, `stix`, `ecs` | Разовые форензик-бандлы — `ecs` выдаёт Elastic Common Schema в NDJSON |++Настраивается в UI (Настройки → Безопасность) или в `snitch.toml`:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+```++## 2. Wazuh++1. Включите syslog-слушатель на менеджере Wazuh (`/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. Направьте каждого агента Snitch — Ansible:++ ```yaml+ snitch_syslog_addr: "wazuh.example.com:514"+ snitch_syslog_format: "cef"+ ```++3. CEF-декодер Wazuh подхватит `CEF:0|Snitch|…`; `severity` маппируется+ в syslog PRI (critical→2, warning→4, info→6).++## 3. Splunk++1. Settings → Data Inputs → UDP → новый ввод на 514, sourcetype+ `syslog` (или TCP-ввод для отправителей `tcp://…`).+2. `syslog_format = "cef"` даёт поля `src`, `dst`, `dpt`, `cs1Label`;+ для дашбордов опрашивайте `GET /forensics/export?format=ecs` через+ scripted input — JSON извлекается автоматически.++## 4. Graylog / Loki++- **Graylog**: System → Inputs → Syslog UDP, порт 514. Расширенные+ поля CEF прилетают полями сообщения.+- **Loki/Grafana**: направьте `syslog_addr` на syslog-target `promtail`+ или забирайте `/forensics/export?format=ecs` через cron → push-джоб+ в Loki.++## 5. Декларативная конфигурация (Security-as-Code)++Бэкенд применяет **один файл** при старте — `$SNITCH_CONFIG`, либо+`snitch.toml`/`snitch.json` в каталоге данных. Каждый объявленный ключ+переопределяет значение UI/DB — файл является источником истины флота:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+kill_switch_enabled = true+ask_enabled = false # headless-серверы+gossip_peers = ["sec-01:8000"]+ports = [80, 443]+```++Полный словарь: `packaging/snitch.toml.example`.++## 6. Ansible / Puppet / Salt / GPO++- **Ansible** — готовая роль в `deploy/ansible/`:++ ```bash+ ansible-playbook -i inventory deploy/ansible/site.yml+ ```++ Ставит `/opt/snitch`, venv, `/etc/snitch/snitch.toml` и усиленный+ systemd-юнит, затем включает `snitch.service`.++- **Puppet / SaltStack** — комьюнити-скелеты в `deploy/puppet/` и+ `deploy/salt/` (label `help wanted`): те же три примитива —+ развернуть дерево backend, отрендерить `snitch.toml`, управлять+ `snitch.service`.++- **Windows GPO** — `deploy/gpo/Install-Snitch.ps1` выполняет тихую+ установку (конфиг в ProgramData, venv, SYSTEM-задача на 127.0.0.1).+ Ask-on-connect в Windows дополнительно требует подписанный+ WFP-коллаут — см. `docs/SIGNING.md`.++## 7. Docker & Kubernetes++- **Один хост**: `docker compose up` — `network_mode: host` ++ `cap_add: NET_RAW/NET_ADMIN` уже в `docker-compose.yml`.+- **Флит-консоль**: `deploy/helm/snitch` — `mode: collector` запускает+ ClusterIP-Deployment, сливающий аудиты всех настроенных агентов в+ `GET /remote/fleet`; `mode: agent` рендерит host-network DaemonSet+ с `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++`POST /alerts/rules/sigma` принимает Sigma YAML и компилирует+поддерживаемое подмножество (селекции поле→значение, `|contains`/+`|startswith`/`|endswith`/`|re`/`|cidr`/`|gt`/`|lt`/`|all`, условия+`1 of`/`all of`) в кастомные правила Snitch — только алерты, причины+`skipped` возвращаются для всего вне подмножества. Поля маппируются на+то, что видит *пакетный* сенсор (`DestinationIp→remote_ip`,+`Image→process_name`, `Domain→host`, …).++YARA-L для Google SecOps/Chronicle: `GET /alerts/rules/yaral`+экспортирует все правила (включая импортированные из Sigma) в файл+`.yar` — путь Sigma→YARA-L закрыт.++## 9. Удалённые агенты (snitch-agent/1)++`agent/` содержит лёгкий Rust-демон (ноль зависимостей, один бинарник+~1 МБ), наблюдающий таблицу сокетов хоста (`/proc/net/*`) и пушащий+новые исходящие потоки в `POST /ingest/events`. Он наблюдает сокеты —+без payload/SNI (это дело локальной capture-ветки); атрибуция процессов+помечена TODO. Транспорт: HTTP + bearer (та же trust-domain-модель,+что `gossip_peers`).++## 10. Бесплатные threat-intel фиды++`POST /firewall/blocklist` импортирует обе формы:++- `kind: "domain"` — hosts/доменные списки (StevenBlack, EasyList…) →+ правила `domain`;+- `kind: "ip"` — IP-фиды (Blocklist.de, экспорты URLhaus/Feodo) →+ правила `ip`; приватные/зарезервированные/loopback-адреса никогда+ не импортируются.++`path:` читает локальный файл (полностью офлайн); `url:` — явный+аудируемый opt-in fetch (`remote_fetch: true` в ответе). Лимит+`max_entries ≤ 5000` — гигантские фиды относятся к резолверу.++Opt-in провайдеры (AbuseIPDB / OTX / VirusTotal) доступны через+`ti_provider` + `ti_api_key` — без ключа ничего наружу не уходит.++## 11. Headless-режим / демон++GUI опционален: бэкенд — это весь продукт. Запускайте напрямую+(`uvicorn api.main:app`), под прилагаемым systemd-юнитом или в+контейнере — все функции выше работают без фронтенда. `SNITCH_DEMO=1`+по-прежнему даёт синтетический фид без root для обучения и CTF.diff --git a/docs/INTEGRATIONS.zh-CN.md b/docs/INTEGRATIONS.zh-CN.mdnew file mode 100644index 0000000..a438d7e--- /dev/null+++ b/docs/INTEGRATIONS.zh-CN.md@@ -0,0 +1,162 @@+# Snitch — 企业集成++*Community translated — PRs welcome for refinement / 社区翻译 — 欢迎提交改进 PR。*++**中文:** 将 Snitch 接入 SOC 技术栈的分步指南 — Wazuh、Splunk、+Graylog/Loki、Ansible、Docker/Kubernetes — 全部免费且自托管,+符合 Snitch 的本地优先原则。Snitch 自身不发送任何遥测数据;+唯一的出站连接就是您在此处配置的连接。++---++## 1. SIEM 输出++Snitch 为告警转发提供三种原生格式:++| 设置 | 取值 | 效果 |+|---|---|---|+| `syslog_addr` | `host:514` 或 `tcp://host:514` | 启用 syslog 转发(默认 UDP,`tcp://` 前缀使用 TCP) |+| `syslog_format` | `rfc3164` *(默认)* | 经典 BSD syslog — 任何采集器均可读取 |+| | `cef` | `CEF:0|Snitch|…` — ArcSight/Wazuh/Splunk 自动解析 `src`、`dst`、`dpt`、`cs1`(进程) |+| `webhook_url` + `webhook_enabled` | URL | 通用 JSON `POST`(自动识别 Discord/Slack/Telegram 负载) |+| `GET /forensics/export?format=…` | `json`、`csv`、`stix`、`ecs` | 一次性取证包 — `ecs` 输出 Elastic Common Schema NDJSON |++在 UI(设置 → 安全)或 `snitch.toml` 中配置:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+```++## 2. Wazuh++1. 在 Wazuh 管理器上启用 syslog 监听器(`/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. 将每个 Snitch 代理指向它 — Ansible:++ ```yaml+ snitch_syslog_addr: "wazuh.example.com:514"+ snitch_syslog_format: "cef"+ ```++3. Wazuh 的 CEF 解码器会接收 `CEF:0|Snitch|…` 消息;`severity`+ 映射到 syslog PRI(critical→2、warning→4、info→6)。++## 3. Splunk++1. 设置 → 数据输入 → UDP → 在 514 上新建输入,sourcetype 为+ `syslog`(`tcp://…` 发送方用 TCP 输入)。+2. `syslog_format = "cef"` 免费提供 `src`、`dst`、`dpt`、`cs1Label`+ 字段;仪表盘可通过 scripted input 定时拉取+ `GET /forensics/export?format=ecs` — JSON 自动提取。++## 4. Graylog / Loki++- **Graylog**:System → Inputs → Syslog UDP,绑定 514。CEF 扩展字段+ 会作为消息字段到达。+- **Loki/Grafana**:将 `syslog_addr` 指向 `promtail` 的 syslog target,+ 或用 cron → Loki push 任务抓取 `/forensics/export?format=ecs`。++## 5. 声明式配置(Security-as-Code)++后端启动时应用**一个文件** — `$SNITCH_CONFIG`,否则为数据目录中的+`snitch.toml`/`snitch.json`。声明的每个键都会覆盖 UI/DB 值 ——+该文件是整个集群的单一事实来源:++```toml+syslog_addr = "siem.example.com:514"+syslog_format = "cef"+kill_switch_enabled = true+ask_enabled = false # 无头服务器+gossip_peers = ["sec-01:8000"]+ports = [80, 443]+```++完整词汇见 `packaging/snitch.toml.example`。++## 6. Ansible / Puppet / Salt / GPO++- **Ansible** — `deploy/ansible/` 中现成的 role:++ ```bash+ ansible-playbook -i inventory deploy/ansible/site.yml+ ```++ 安装 `/opt/snitch`、venv、`/etc/snitch/snitch.toml` 和加固的+ systemd 单元,然后启用 `snitch.service`。++- **Puppet / SaltStack** — `deploy/puppet/` 与 `deploy/salt/` 中的+ 社区骨架(`help wanted` 标签):同样三个原语 —— 部署 backend+ 目录树、渲染 `snitch.toml`、管理 `snitch.service`。++- **Windows GPO** — `deploy/gpo/Install-Snitch.ps1` 执行静默安装+ (ProgramData 配置、venv、127.0.0.1 上的 SYSTEM 计划任务)。+ Windows 上的 ask-on-connect 还需要已签名的 WFP callout —+ 见 `docs/SIGNING.md`。++## 7. Docker 与 Kubernetes++- **单主机**:`docker compose up` — `network_mode: host` ++ `cap_add: NET_RAW/NET_ADMIN` 已在 `docker-compose.yml` 中配置。+- **集群控制台**:`deploy/helm/snitch` — `mode: collector` 运行+ ClusterIP Deployment,将所有已配置代理的审计合并到+ `GET /remote/fleet`;`mode: agent` 渲染带 `NET_RAW`/`NET_ADMIN`+ 的 host-network DaemonSet。++ ```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 规则++`POST /alerts/rules/sigma` 接受 Sigma 检测 YAML,将支持的子集+(字段→值选择、`|contains`/`|startswith`/`|endswith`/`|re`/`|cidr`/+`|gt`/`|lt`/`|all`、`1 of`/`all of` 条件)编译为 Snitch 自定义规则 ——+仅告警,超出子集的内容会在 `skipped` 中返回原因。字段映射到+*数据包*传感器实际可见的内容(`DestinationIp→remote_ip`、+`Image→process_name`、`Domain→host` 等)。++面向 Google SecOps/Chronicle 的 YARA-L:`GET /alerts/rules/yaral`+将所有规则(包括导入的 Sigma 规则)导出为 `.yar` 文件 ——+Sigma→YARA-L 路径就此打通。++## 9. 远程代理(snitch-agent/1)++`agent/` 包含一个轻量 Rust 守护进程(零依赖,单个 ~1MB 二进制),+监视主机 socket 表(`/proc/net/*`)并将新的出站流推送到+`POST /ingest/events`。它只观测 socket —— 无 payload/SNI+(那是本地抓包的职责);进程归属标记为 TODO。传输:HTTP + Bearer+(与 `gossip_peers` 相同的信任域)。++## 10. 免费威胁情报源++`POST /firewall/blocklist` 支持两种导入形式:++- `kind: "domain"` — hosts/域名列表(StevenBlack、EasyList…)→+ `domain` 防火墙规则;+- `kind: "ip"` — IP 源(Blocklist.de、URLhaus/Feodo 导出)→ `ip`+ 规则;私有/保留/回环地址永远不会被导入。++`path:` 读取本地文件(完全离线);`url:` 是显式、可审计的 opt-in+抓取(响应中带 `remote_fetch: true`)。上限 `max_entries ≤ 5000` ——+巨型源应交给解析器。++Opt-in API 提供商(AbuseIPDB / OTX / VirusTotal)仍可通过+`ti_provider` + `ti_api_key` 使用 —— 不设密钥就不会有任何外呼。++## 11. 无头/守护进程模式++GUI 是可选的:后端即全部产品。直接运行(`uvicorn api.main:app`)、+用附带的 systemd 单元或在容器中 —— 以上所有功能无需前端即可工作。+`SNITCH_DEMO=1` 继续为培训和 CTF 提供免 root 的合成流量。diff --git a/electron/package.json b/electron/package.jsonindex d27f104..1d342aa 100644--- a/electron/package.json+++ b/electron/package.json@@ -1,6 +1,6 @@{"name": "snitch",- "version": "1.6.0",+ "version": "1.6.1","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.jsonindex 4e9e9ea..5ac6a0f 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -1,6 +1,6 @@{"name": "snitch-frontend",- "version": "1.6.0",+ "version": "1.6.1","private": true,"license": "AGPL-3.0-or-later","description": "Snitch UI \u2014 React + D3.js / Interface React + D3.js",diff --git a/packaging/choco/snitch.nuspec b/packaging/choco/snitch.nuspecnew file mode 100644index 0000000..8524138--- /dev/null+++ b/packaging/choco/snitch.nuspec@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Snitch — Chocolatey package spec (packed by release.yml).+ The nupkg wraps the checkout + deploy/gpo/Install-Snitch.ps1. -->+<package xmlns="http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd">+ <metadata>+ <id>snitch</id>+ <version>0.0.0</version><!-- replaced at pack time -->+ <title>Snitch</title>+ <authors>Snitch contributors</authors>+ <owners>aixisstudio</owners>+ <licenseUrl>https://github.com/aixisstudio/Snitch/blob/main/LICENSE</licenseUrl>+ <projectUrl>https://github.com/aixisstudio/Snitch</projectUrl>+ <requireLicenseAcceptance>false</requireLicenseAcceptance>+ <description>Local-first network observability and outbound firewall — headless backend with REST/WebSocket API, Sigma rules, CEF/ECS SIEM output.</description>+ <summary>Network traffic visualizer + outbound firewall (headless agent)</summary>+ <tags>network security firewall monitoring edr siem</tags>+ <packageSourceUrl>https://github.com/aixisstudio/Snitch/tree/main/packaging/choco</packageSourceUrl>+ </metadata>+ <files>+ <file src="tools\**" target="tools" />+ <file src="..\..\backend\**" target="backend" />+ <file src="..\..\deploy\gpo\**" target="deploy\gpo" />+ </files>+</package>diff --git a/packaging/choco/tools/chocolateyinstall.ps1 b/packaging/choco/tools/chocolateyinstall.ps1new file mode 100644index 0000000..57a8250--- /dev/null+++ b/packaging/choco/tools/chocolateyinstall.ps1@@ -0,0 +1,10 @@+# Snitch — chocolatey install script+# EN: The package payload is the repo snapshot; the install delegates to+# the same GPO silent-installer so behaviour is identical everywhere.+# FR: Le payload est le snapshot du dépôt ; l'install délègue au même+# installeur silencieux GPO — comportement identique partout.+$ErrorActionPreference = 'Stop'+$tools = Split-Path -Parent $MyInvocation.MyCommand.Definition+$src = Split-Path -Parent $tools # EN: package root / FR: racine du paquet+& powershell -ExecutionPolicy Bypass -File `+ (Join-Path $src 'deploy\gpo\Install-Snitch.ps1') -Source $srcdiff --git a/packaging/homebrew/snitch.rb b/packaging/homebrew/snitch.rbnew file mode 100644index 0000000..d4876bf--- /dev/null+++ b/packaging/homebrew/snitch.rb@@ -0,0 +1,35 @@+# Snitch — Homebrew formula template (rendered by release.yml →+# aixisstudio/homebrew-tap). @VERSION@/@SHA256@ are CI placeholders.+# FR: Modèle de formule Homebrew (rendu par release.yml vers le tap).+class Snitch < Formula+ desc "Local-first network observability and outbound firewall"+ homepage "https://github.com/aixisstudio/Snitch"+ url "https://github.com/aixisstudio/Snitch/archive/refs/tags/v@[email protected]"+ sha256 "@SHA256@"+ license "AGPL-3.0-or-later"+ head "https://github.com/aixisstudio/Snitch.git", branch: "main"++ depends_on "[email protected]"++ def install+ venv = virtualenv_create(libexec, "python3.13")+ venv.pip_install resources+ # EN: the backend is the product — install the tree, link a launcher.+ # FR: le backend est le produit — installer l'arbre, lier un lanceur.+ libexec.install "backend"+ (bin/"snitch").write_env_script libexec/"bin/python",+ "-m uvicorn api.main:app --host 127.0.0.1 --port 8000",+ PYTHONPATH: libexec/"backend", SNITCH_DATA_DIR: var/"snitch"+ end++ service do+ run [opt_bin/"snitch"]+ keep_alive true+ log_path var/"log/snitch.log"+ error_log_path var/"log/snitch.log"+ end++ test do+ system bin/"snitch", "--help"+ end+enddiff --git a/packaging/nfpm.yaml b/packaging/nfpm.yamlindex 8010795..a385db9 100644--- a/packaging/nfpm.yaml+++ b/packaging/nfpm.yaml@@ -10,7 +10,7 @@name: snitcharch: amd64platform: linux-version: "1.6.0"+version: "1.6.1"release: 1section: netpriority: optional