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
feat: privilege split, tray icon, /shutdown, desktop notifications
MoneyLisa254c4257ba26
diff --git a/SECURITY.md b/SECURITY.mdindex 5ae9006..e05bc94 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -35,22 +35,24 @@ conception :## Privileges / Privilèges-**EN:** Packet capture requires elevated privileges. Current limitation: under-Electron the **whole app** (Chromium UI included) runs elevated on Windows-(`requireAdministrator`). A privileged-daemon split (unprivileged UI +-elevated capture backend) is a known roadmap item — see issues.+**EN:** Packet capture requires elevated privileges — but only the backend+holds them. The Electron UI runs unprivileged (`asInvoker`); on Windows the+backend alone is spawned elevated (`Start-Process -Verb RunAs`, one UAC+prompt per launch) and is stopped through the authenticated `/shutdown`+endpoint since an unprivileged process cannot signal it.-- Windows: Administrator + Npcap (installed by you from npcap.com)+- Windows: UI unprivileged + backend elevated via UAC + Npcap (installed by you from npcap.com)- Linux: `setcap cap_net_raw,cap_net_admin` on the binary, or root- macOS: read access to `/dev/bpf*` (experimental support)-**FR :** La capture de paquets exige des privilèges élevés. Limite actuelle :-sous Electron, **toute l'app** (interface Chromium incluse) tourne en mode-élevé sous Windows (`requireAdministrator`). Une séparation daemon privilégié-(UI non élevée + backend de capture élevé) est un point de feuille de route-connu — voir les issues.+**FR :** La capture de paquets exige des privilèges élevés — mais seul le+backend les détient. L'UI Electron tourne sans privilèges (`asInvoker`) ;+sous Windows, seul le backend est lancé en mode élevé (`Start-Process -Verb+RunAs`, une invite UAC par lancement) et il est arrêté via l'endpoint+authentifié `/shutdown` puisqu'un processus non privilégié ne peut pas le+signaler.-- Windows : Administrateur + Npcap (installé par vos soins depuis npcap.com)+- Windows : UI non privilégiée + backend élevé via UAC + Npcap (installé par vos soins depuis npcap.com)- Linux : `setcap cap_net_raw,cap_net_admin` sur le binaire, ou root- macOS : accès en lecture à `/dev/bpf*` (support expérimental)diff --git a/backend/api/main.py b/backend/api/main.pyindex caa23d2..ccca63a 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -61,6 +61,7 @@ import asyncioimport ipaddressimport jsonimport logging+import osimport queueimport threadingimport time@@ -961,6 +962,36 @@ async def unignore_alert(body: IgnoreBody) -> dict:return {"suppressions": suppressions}[email protected]("/shutdown", dependencies=_AUTH)+async def shutdown() -> dict:+ """+ EN: Graceful process exit — flushes the DB, stops capture, then exits.+ Needed because an elevated backend (Windows RunAs) CANNOT be killed+ by our unprivileged UI process; the token-gated endpoint is the only+ clean shutdown path. Exit happens 0.5 s later so the HTTP 200 reply+ reaches the caller first.+ FR: Sortie propre du processus — flush la BDD, stoppe la capture, puis+ quitte. Nécessaire car un backend élevé (RunAs Windows) ne PEUT PAS+ être tué par notre UI non privilégiée ; l'endpoint authentifié est le+ seul chemin d'arrêt propre. La sortie survient 0,5 s plus tard pour+ que la réponse HTTP 200 atteigne l'appelant.+ """+ def _exit_soon() -> None:+ try:+ # EN: Synchronous cleanup (uvicorn is already unwinding by the+ # time the lifespan finally runs — do it ourselves here).+ # FR: Nettoyage synchrone (uvicorn se déroule déjà quand le+ # finally du lifespan tourne — on le fait nous-même ici).+ _stop_capture()+ db.flush()+ except Exception:+ pass+ os._exit(0)++ asyncio.get_running_loop().call_later(0.5, _exit_soon)+ return {"ok": True}++# ── History / Historique ─────────────────────────────────────────────────────@app.get("/history/host/{ip}", dependencies=_AUTH)diff --git a/backend/run_backend.py b/backend/run_backend.pyindex ea28345..81db7d5 100644--- a/backend/run_backend.py+++ b/backend/run_backend.py@@ -47,13 +47,28 @@ from api.main import app # noqa: E402import uvicorn # noqa: E402if __name__ == '__main__':+ # EN: Optional --port/--bind argv flags — needed by the Windows elevated+ # spawn path, where environment variables cannot cross the UAC+ # boundary. Env vars still take precedence when both are present.+ # FR: Drapeaux argv optionnels --port/--bind — nécessaires pour le+ # lancement élevé Windows, où les variables d'environnement ne+ # traversent pas la frontière UAC. Les variables d'env gardent la+ # priorité quand les deux sont présentes.+ argv_port = argv_bind = None+ args = sys.argv[1:]+ for i, a in enumerate(args):+ if a == '--port' and i + 1 < len(args):+ argv_port = args[i + 1]+ elif a == '--bind' and i + 1 < len(args):+ argv_bind = args[i + 1]+# EN: Loopback-only by default everywhere — Electron AND Docker/dev.# Set SNITCH_BIND=0.0.0.0 to expose (token auth still applies).# FR: Loopback uniquement par défaut partout — Electron ET Docker/dev.# Poser SNITCH_BIND=0.0.0.0 pour exposer (le jeton reste exigé).uvicorn.run(app,- host=os.environ.get('SNITCH_BIND', '127.0.0.1'),- port=int(os.environ.get('SNITCH_PORT', '8000')),+ host=os.environ.get('SNITCH_BIND') or argv_bind or '127.0.0.1',+ port=int(os.environ.get('SNITCH_PORT') or argv_port or '8000'),log_level='warning',)diff --git a/docs/threat-model.md b/docs/threat-model.mdindex 82c3058..5d09ec8 100644--- a/docs/threat-model.md+++ b/docs/threat-model.md@@ -31,9 +31,10 @@ same process. There is **no cloud component** and **no telemetry**.### Known limitations-- **Root/Admin required for capture.** In Electron v1 the whole app runs- elevated on Windows (`requireAdministrator`) — a privileged split is on the- roadmap, see `docs/architecture.md`.+- **Admin/elevation is still required for capture** — but scoped to the+ backend only: the Electron UI runs asInvoker while the backend is spawned+ elevated (`Start-Process -Verb RunAs`) and stopped via the authenticated+ `/shutdown` endpoint.- The API token protects HTTP/WS but **not** against another local processrunning as you that can read `data/api_token.txt` or the Electron IPC.- SQLite data at rest is unencrypted.@@ -76,9 +77,10 @@ le même processus. **Aucun composant cloud, aucune télémétrie.**### Limites connues-- **Capture = privilèges admin/root.** Sous Electron v1, toute l'app tourne- élevée sur Windows (`requireAdministrator`) — séparation privilégiée en- feuille de route, voir `docs/architecture.md`.+- **Capture = privilèges admin/root**, mais limités au backend : l'UI+ Electron tourne en asInvoker tandis que le backend est lancé élevé+ (`Start-Process -Verb RunAs`) et arrêté via l'endpoint authentifié+ `/shutdown`.- Le jeton protège HTTP/WS mais **pas** contre un autre processus localtournant sous votre compte qui lit `data/api_token.txt` ou l'IPC Electron.- Les données SQLite au repos ne sont pas chiffrées.diff --git a/electron/generate-icon.js b/electron/generate-icon.jsindex b9ccf9f..8d5d7c7 100644--- a/electron/generate-icon.js+++ b/electron/generate-icon.js@@ -18,7 +18,7 @@ const zlib = require('zlib')const fs = require('fs')const path = require('path')-const S = 256+const S = 512// EN: RGBA pixel buffer, fully transparent. / FR: buffer de pixels RGBA, entièrement transparent.const buf = Buffer.alloc(S * S * 4, 0)@@ -78,10 +78,10 @@ function drawEllipse(cx, cy, rx, ry, r, g, b, a) {}const cx = S / 2, cy = S / 2-const R = 92 // EN: sphere radius / FR: rayon de la sphère+const R = 184 // EN: sphere radius / FR: rayon de la sphère// ── Rounded-square black background / Fond noir à coins arrondis ─────────────-const cornerR = 50+const cornerR = 100for (let y = 0; y < S; y++)for (let x = 0; x < S; x++) {const dx = Math.abs(x - cx) - (cx - cornerR)@@ -99,7 +99,7 @@ for (const rx_f of [0.32, 0.74])drawEllipse(cx, cy, R * rx_f, R, 255, 255, 255, 38)// ── Sphere ring / Anneau de la sphère ────────────────────────────────────────-strokeCircle(cx, cy, R, 2.8, 255, 255, 255, 190)+strokeCircle(cx, cy, R, 5.6, 255, 255, 255, 190)// ── Peripheral nodes / Nœuds périphériques ───────────────────────────────────const scale = R / 118@@ -118,16 +118,16 @@ for (let i = 0; i < nodes.length; i++) {for (const [nx,ny] of nodes) drawLine(cx, cy, nx, ny, 255, 255, 255, 38)for (const [nx,ny] of nodes) {- fillCircle(nx, ny, 5.5, 0, 0, 0, 255)- strokeCircle(nx, ny, 5.5, 1.8, 255, 255, 255, 210)- fillCircle(nx, ny, 2.8, 247, 176, 22, 255)+ fillCircle(nx, ny, 11, 0, 0, 0, 255)+ strokeCircle(nx, ny, 11, 3.6, 255, 255, 255, 210)+ fillCircle(nx, ny, 5.6, 247, 176, 22, 255)}// ── Center node / Nœud central ───────────────────────────────────────────────-fillCircle(cx, cy, 18, 247, 176, 22, 45)-fillCircle(cx, cy, 11, 247, 176, 22, 155)-fillCircle(cx, cy, 7, 247, 176, 22, 255)-fillCircle(cx, cy, 3, 255, 255, 255, 255)+fillCircle(cx, cy, 36, 247, 176, 22, 45)+fillCircle(cx, cy, 22, 247, 176, 22, 155)+fillCircle(cx, cy, 14, 247, 176, 22, 255)+fillCircle(cx, cy, 6, 255, 255, 255, 255)// ── PNG encoding / Encodage PNG ──────────────────────────────────────────────// EN: Minimal hand-rolled PNG writer: signature + IHDR + IDAT + IEND withdiff --git a/electron/main.js b/electron/main.jsindex db1dfc9..8f29078 100644--- a/electron/main.js+++ b/electron/main.js@@ -45,7 +45,7 @@*/const _electron = require('electron')-const { app, BrowserWindow, dialog, ipcMain, shell } = _electron.default || _electron+const { app, BrowserWindow, dialog, ipcMain, shell, Tray, Menu } = _electron.default || _electronconst { spawn, execSync } = require('child_process')const crypto = require('crypto')const path = require('path')@@ -77,19 +77,32 @@ const iconPath = isDev? path.join(__dirname, 'icon.png'): path.join(resourcesDir, 'icon.png')-// EN: Backend stdout/stderr go to a real log file — never stdio:'ignore',-// so crashes leave a trace the diagnostics export can pick up.-// FR: stdout/stderr du backend vont dans un vrai fichier de log — jamais-// stdio:'ignore', pour qu'un crash laisse une trace récupérable par-// l'export de diagnostic.-const logDir = path.join(app.getPath('userData'), 'logs')+// EN: Log dir = the backend's own data dir (LOCALAPPDATA\Snitch on Windows,+// etc.) so "Open logs" and the /diagnostics log_tail read the SAME file+// the backend writes to — even when the backend runs elevated and gets+// no SNITCH_USER_DATA env (frozen builds resolve the platform dir).+// FR: Dossier de logs = le dossier de données du backend lui-même+// (LOCALAPPDATA\Snitch sous Windows, etc.) pour que « Ouvrir les logs »+// et le log_tail de /diagnostics lisent le MÊME fichier que celui écrit+// par le backend — même quand il tourne élevé et ne reçoit pas+// SNITCH_USER_DATA (les builds figés résolvent le dossier plateforme).+// EN: backendDataDir() is hoisted (function declaration below) — safe to+// call here at module level.+// FR: backendDataDir() est hissée (déclaration de fonction plus bas) —+// appelable ici au niveau module.+const logDir = path.join(backendDataDir(), 'logs')const logFile = path.join(logDir, 'backend.log')let mainWindow = nulllet splashWindow = nulllet backendProc = null+let tray = nulllet backendPort = 0 // EN: chosen at launch / FR: choisi au lancementlet isQuitting = false+let backendElevated = false // EN: Windows RunAs spawn — we can't kill it,+ // /shutdown is the exit path.+ // FR: spawn élevé Windows — on ne peut pas+ // le tuer, /shutdown est le chemin d'arrêt.// ── API token + port / Jeton API + port ─────────────────────────────────────// EN: 48-hex-char secret generated once per app launch. Passed to the backend@@ -229,9 +242,52 @@ function createMain() {mainWindow.show()mainWindow.focus()})++ // EN: Minimize to tray instead of quitting — a network monitor is meant+ // to keep watching. Real exit happens via the tray menu's Quit item.+ // FR: Réduire dans la zone de notification au lieu de quitter — un+ // moniteur réseau est fait pour continuer à observer. La vraie sortie+ // passe par l'entrée Quitter du menu de la zone de notification.+ mainWindow.on('close', (e) => {+ if (!isQuitting && tray) {+ e.preventDefault()+ mainWindow.hide()+ }+ })mainWindow.on('closed', () => { mainWindow = null })}+/**+ * EN: System tray — bilingual menu with Show / Open logs / Quit. The icon+ * is the generated 512px PNG; Electron scales it per platform.+ * FR: Zone de notification — menu bilingue Afficher / Ouvrir les logs /+ * Quitter. L'icône est le PNG 512 px généré ; Electron l'adapte selon+ * la plateforme.+ */+function createTray() {+ tray = new Tray(iconPath)+ tray.setToolTip('Snitch')+ const menu = Menu.buildFromTemplate([+ {+ label: 'Show Snitch / Afficher Snitch',+ click: () => { if (mainWindow) { mainWindow.show(); mainWindow.focus() } },+ },+ {+ label: 'Open logs / Ouvrir les logs',+ click: () => shell.openPath(logDir),+ },+ { type: 'separator' },+ {+ label: 'Quit / Quitter',+ click: () => { isQuitting = true; app.quit() },+ },+ ])+ tray.setContextMenu(menu)+ // EN: A plain click (Windows/Linux) or double-click restores the window.+ // FR: Un simple clic (Windows/Linux) ou double-clic restaure la fenêtre.+ tray.on('click', () => { if (mainWindow) { mainWindow.show(); mainWindow.focus() } })+}+// ── Backend process / Processus backend ──────────────────────────────────────/*** EN: Poll the REST API until it answers or we run out of attempts. The@@ -286,6 +342,60 @@ function killBackend() {}}+/**+ * EN: The writable dir the FROZEN backend resolves on each platform —+ * mirrors paths.py so the token file we drop lands where it looks.+ * Windows: %LOCALAPPDATA%\Snitch. macOS: ~/Library/Application Support/Snitch.+ * Linux: $XDG_DATA_HOME/snitch or ~/.local/share/snitch.+ * FR: Le dossier inscriptible que le backend FIGÉ résout sur chaque+ * plateforme — reflète paths.py pour que le fichier de jeton qu'on+ * dépose atterrisse là où il le cherche.+ */+function backendDataDir() {+ if (isWindows) return path.join(process.env.LOCALAPPDATA || path.join(app.getPath('home'), 'AppData', 'Local'), 'Snitch')+ if (process.platform === 'darwin') return path.join(app.getPath('home'), 'Library', 'Application Support', 'Snitch')+ return path.join(process.env.XDG_DATA_HOME || path.join(app.getPath('home'), '.local', 'share'), 'snitch')+}++/**+ * EN: Windows privilege split — the UI runs UNPRIVILEGED (asInvoker); only+ * the backend asks for admin via `Start-Process -Verb RunAs` (one UAC+ * prompt per launch). Env vars can't cross UAC, so we pass the port as+ * an argv flag and pre-write the token to api_token.txt — the backend's+ * own resolution order picks it up. In dev we spawn normally: capture+ * will fail without rights but the UI stays usable.+ * FR: Séparation de privilèges Windows — l'UI tourne SANS privilèges+ * (asInvoker) ; seul le backend demande l'admin via `Start-Process -Verb+ * RunAs` (une invite UAC par lancement). Les variables d'env ne+ * traversent pas l'UAC, donc on passe le port en argument argv et on+ * pré-écrit le jeton dans api_token.txt — l'ordre de résolution du+ * backend le récupère. En dev on lance normalement : la capture échouera+ * sans droits mais l'UI reste utilisable.+ */+function launchBackendElevated() {+ const dataDir = backendDataDir()+ fs.mkdirSync(dataDir, { recursive: true })+ fs.writeFileSync(path.join(dataDir, 'api_token.txt'), API_TOKEN, { mode: 0o600 })++ // EN: -FilePath/-ArgumentList carefully quoted (paths may contain spaces).+ // FR: -FilePath/-ArgumentList soigneusement entre guillemets (chemins avec espaces).+ const ps = `Start-Process -FilePath "${backendExe}" -ArgumentList '--port ${backendPort}' -Verb RunAs -WindowStyle Hidden`+ backendProc = spawn('powershell.exe', [+ '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', ps,+ ], { windowsHide: true, stdio: 'ignore' })+ backendElevated = true++ backendProc.on('error', err => {+ if (isQuitting) return+ dialog.showErrorBox('Snitch', `Failed to start backend / Échec du démarrage du backend :\n${err.message}`)+ app.quit()+ })+ // EN: No 'exit' crash-watch here — the powershell wrapper exits as soon as+ // the elevated child is up; waitForBackend() is the liveness check.+ // FR: Pas de surveillance 'exit' ici — le wrapper powershell sort dès que+ // l'enfant élevé est lancé ; waitForBackend() est le test de vie.+}+function launchBackend() {/** EN: Spawn the compiled backend with SNITCH_TOKEN + SNITCH_PORT in its* environment; windowsHide keeps a console window from flashing;@@ -298,6 +408,15 @@ function launchBackend() {app.quit(); return}+ // EN: Windows packaged build → elevated child, unprivileged UI.+ // Everything else → normal spawn, same privilege as the UI.+ // FR: Build packagé Windows → enfant élevé, UI non privilégiée.+ // Le reste → spawn normal, même privilège que l'UI.+ if (isWindows && !isDev) {+ launchBackendElevated()+ return+ }+fs.mkdirSync(logDir, { recursive: true })const logFd = fs.openSync(logFile, 'a')@@ -330,6 +449,30 @@ function launchBackend() {})}+/**+ * EN: Ask the backend to exit through its authenticated /shutdown endpoint —+ * the ONLY way to stop an elevated child we can't signal. Falls back to+ * killing our own child tree for the unprivileged path.+ * FR: Demander au backend de quitter via son endpoint authentifié /shutdown+ * — le SEUL moyen d'arrêter un enfant élevé qu'on ne peut pas signaler.+ * Repli : tuer notre propre arbre de processus pour le chemin non élevé.+ */+function shutdownBackend() {+ if (backendElevated) {+ try {+ const req = http.request(+ `http://127.0.0.1:${backendPort}/shutdown`,+ { method: 'POST', headers: { 'X-Snitch-Token': API_TOKEN }, timeout: 3000 },+ res => res.resume())+ req.on('error', () => {}) // EN: best-effort — app is exiting anyway+ req.on('timeout', () => req.destroy())+ req.end()+ } catch { /* EN: nothing more we can do / FR: rien de plus à faire */ }+ return+ }+ killBackend()+}+// ── App lifecycle / Cycle de vie de l'application ────────────────────────────app.whenReady().then(async () => {// EN: On Windows, Npcap is a hard requirement — guide the user to npcap.com@@ -348,11 +491,19 @@ app.whenReady().then(async () => {try {await waitForBackend()} catch (e) {- dialog.showErrorBox('Snitch', `Backend unavailable / Backend indisponible :\n${e.message}`)+ // EN: On Windows an elevated backend that never answers usually means+ // the UAC prompt was declined — say so explicitly.+ // FR: Sous Windows un backend élevé qui ne répond jamais signifie+ // généralement une invite UAC refusée — le dire explicitement.+ const extra = backendElevated+ ? '\n\nDid you decline the admin (UAC) prompt? Capture requires it.\nAvez-vous refusé l\'invite administrateur (UAC) ? La capture l\'exige.'+ : ''+ dialog.showErrorBox('Snitch', `Backend unavailable / Backend indisponible :\n${e.message}${extra}`)app.quit(); return}createMain()+ createTray()})app.on('window-all-closed', () => {@@ -366,5 +517,7 @@ app.on('window-all-closed', () => {app.on('before-quit', () => {isQuitting = true- killBackend()+ // EN: /shutdown API call for the elevated backend; direct kill otherwise.+ // FR: Appel API /shutdown pour le backend élevé ; kill direct sinon.+ shutdownBackend()})diff --git a/electron/package.json b/electron/package.jsonindex 7326760..94da409 100644--- a/electron/package.json+++ b/electron/package.json@@ -41,7 +41,7 @@],"win": {"target": "nsis",- "requestedExecutionLevel": "requireAdministrator"+ "requestedExecutionLevel": "asInvoker"},"nsis": {"oneClick": false,diff --git a/frontend/src/hooks/useWebSocket.js b/frontend/src/hooks/useWebSocket.jsindex 6fda3e4..299baf6 100644--- a/frontend/src/hooks/useWebSocket.js+++ b/frontend/src/hooks/useWebSocket.js@@ -23,6 +23,26 @@import { useEffect, useRef, useState } from 'react'import { apiBase, authHeaders, wsUrlWithToken, wsBase } from '../api'+// EN: Desktop notifications for warning/critical alerts — only when the+// window is NOT focused (no double-notification while you watch). Uses+// the Web Notification API, which Electron grants without prompting;+// browsers get a one-time permission request on first alert.+// FR: Notifications bureau pour les alertes warning/critiques — seulement+// quand la fenêtre n'a PAS le focus (pas de doublon quand on regarde).+// API Web Notification, qu'Electron accorde sans invite ; les+// navigateurs demandent la permission une fois à la première alerte.+function notifyAlert(alert) {+ if (alert.severity === 'info' || !document.hidden) return+ if (typeof Notification === 'undefined') return+ const fire = () => new Notification(`Snitch — ${alert.type}`, {+ body: alert.message || '', tag: alert.id, silent: false,+ })+ if (Notification.permission === 'granted') fire()+ else if (Notification.permission === 'default') {+ Notification.requestPermission().then(p => { if (p === 'granted') fire() })+ }+}+export function useWebSocket(url) {const ws = useRef(null)const [nodes, setNodes] = useState({})@@ -173,6 +193,7 @@ export function useWebSocket(url) {const incoming = msg.alertssetAlerts(prev => [...incoming.slice().reverse(), ...prev].slice(0, 200))setUnread(prev => prev + incoming.length)+ incoming.forEach(notifyAlert)}}@@ -194,6 +215,7 @@ export function useWebSocket(url) {if (msg.type === 'alert') {setAlerts(prev => [msg.alert, ...prev].slice(0, 200))setUnread(prev => prev + 1)+ notifyAlert(msg.alert)}// EN: Capture/filter status changed (local or remote action).