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
Fix audit round-3 findings: GPO token leak, quoting, bounds
MoneyLisa9252fc5130d4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 454fcb9..c217e2f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -99,6 +99,31 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) — EN/FR.FR: le moniteur média sonde toutes les 10 s par défaut (3 s avant —chaque tick Linux parcourt les fichiers ouverts de tous lesprocessus) ; `SNITCH_MEDIA_INTERVAL` (3–300 s) ajuste.+- EN: **GPO installer no longer writes the master token in cleartext**+ — `-Token` now lands in `%ProgramData%\Snitch\api_token.txt` ACL'd to+ SYSTEM+Administrators instead of a world-readable `SNITCH_TOKEN=…`+ line inside `%ProgramFiles%\Snitch\run.cmd`. The launcher also quotes+ `set "VAR=value"` so `&`/spaces in paths cannot inject.+ FR: **L'installeur GPO n'écrit plus le jeton maître en clair** —+ `-Token` atterrit dans `api_token.txt` restreint à+ SYSTEM+Administrateurs au lieu d'une ligne lisible par tous dans+ `run.cmd`. Le lanceur quote aussi `set "VAR=valeur"`.+- EN: **Electron elevated launches hardened** — the macOS osascript+ command now shell-quotes paths BEFORE AppleScript-quoting (a `"`/`$`+ in the data dir or binary path could no longer survive into+ `/bin/sh`), and the Windows UAC command uses PowerShell single-quoted+ strings (`'` → `''`).+ FR: **Lancements élevés Electron durcis** — quoting shell puis+ AppleScript sous macOS, et chaînes PowerShell en apostrophes sous+ Windows.+- EN: `/security/ask/verdict` normalizes `remote_ip` through+ `ipaddress` at the boundary (it feeds the whitelist, a firewall rule+ and the flow-key match); `/settings` rejects >256 keys per batch;+ kill/suspend report fixed labels instead of exception text; WFP+ keep-alive pins and the gossip fleet-audit body read are bounded.+ FR: `/security/ask/verdict` normalise `remote_ip` via `ipaddress` ;+ `/settings` refuse >256 clés ; kill/suspend renvoient des libellés+ fixes ; les pins WFP et la lecture fleet-audit sont bornés.- EN: **All project surfaces synced to v1.6.3** — README (Rust agent,enrollment, `ti_feeds`, `.rpm`, `snitchd` formula), ROADMAP (v1.5.x/diff --git a/backend/api/main.py b/backend/api/main.pyindex a78b1ce..34959e3 100644--- a/backend/api/main.py+++ b/backend/api/main.py@@ -2200,6 +2200,12 @@ async def post_settings(body: SettingsBody) -> dict:"""EN: Persist arbitrary settings keys (language, thresholds…).FR: Persister des clés de réglage arbitraires (langue, seuils…)."""loop = asyncio.get_running_loop()+ # EN: Bound the batch — every key costs a DB write, so an unbounded+ # settings dict would be a disk-write flood vector.+ # FR: Borner le lot — chaque clé coûte une écriture DB, donc un dict+ # non borné serait un vecteur d'inondation disque.+ if len(body.settings) > 256:+ raise HTTPException(400, "too many settings keys (max 256)")for key, value in body.settings.items():await loop.run_in_executor(None, db.set_setting, key, value)# EN: Live-apply settings the detector reads dynamically — no restart@@ -3172,7 +3178,11 @@ async def kill_process(body: PidBody) -> dict:try:name = await loop.run_in_executor(None, _do)except Exception as exc:- raise HTTPException(400, f"kill failed: {exc}")+ # EN: fixed label — exception text stays in logs (CodeQL:+ # stack-trace exposure). / FR: libellé fixe — le texte+ # d'exception reste dans les logs.+ logger.warning("kill pid %s failed: %s", body.pid, exc)+ raise HTTPException(400, "kill failed") from excreturn {"ok": True, "pid": body.pid, "name": name}@@ -3196,7 +3206,8 @@ async def suspend_process(body: PidBody) -> dict:try:res = await loop.run_in_executor(None, _do)except Exception as exc:- raise HTTPException(400, f"suspend failed: {exc}")+ logger.warning("suspend pid %s failed: %s", body.pid, exc)+ raise HTTPException(400, "suspend failed") from excreturn {"ok": True, "pid": body.pid, **res}@@ -3665,15 +3676,26 @@ async def ask_verdict(body: AskVerdictBody) -> dict:mémorise la décision pour la session. `permanent` écrit en plusune politique durable (whitelist ou règle pare-feu)."""loop = asyncio.get_running_loop()+ # EN: Normalize at the boundary — the value lands in the whitelist,+ # a firewall rule AND the decide() key match; the parser-+ # produced form is what NFQUEUE flow keys look like anyway.+ # FR: Normaliser à la frontière — la valeur atterrit dans la+ # whitelist, une règle pare-feu ET la clé de decide() ; la forme+ # produite par le parseur est de toute façon celle des clés de+ # flux NFQUEUE.+ try:+ remote_ip = str(ipaddress.ip_address(body.remote_ip))+ except ValueError:+ raise HTTPException(400, "invalid remote_ip") from Nonedecided = await loop.run_in_executor(- None, ask_mode.decide, body.remote_ip, body.remote_port,+ None, ask_mode.decide, remote_ip, body.remote_port,body.proto, body.allow)persisted = Noneif body.permanent:if body.allow:# EN: "Allow always" → durable whitelist entry for the IP.# FR: « Autoriser toujours » → entrée whitelist durable.- _whitelisted_ips.add(body.remote_ip)+ _whitelisted_ips.add(remote_ip)db.set_setting("whitelisted_ips",sorted(_whitelisted_ips))persisted = "whitelisted"@@ -3682,7 +3704,7 @@ async def ask_verdict(body: AskVerdictBody) -> dict:# FR: « Bloquer définitivement » → vraie règle pare-feu.try:await loop.run_in_executor(- None, fw.add_rule, "ip", body.remote_ip, "block", 0)+ None, fw.add_rule, "ip", remote_ip, "block", 0)rules, _lock = fw.serialized()db.set_setting("firewall_rules", rules)await broadcast({"type": "firewall", "rules": rules})diff --git a/backend/detection/gossip.py b/backend/detection/gossip.pyindex 9ded877..eb547b7 100644--- a/backend/detection/gossip.py+++ b/backend/detection/gossip.py@@ -133,7 +133,12 @@ class PeerSync:f"Bearer {self._token_getter()}"})try:with urllib.request.urlopen(req, timeout=_TIMEOUT) as r:- data = json.loads(r.read().decode("utf-8", "replace"))+ # EN: bounded read — a misbehaving/malicious peer+ # must not hand us an unbounded body.+ # FR: lecture bornée — un pair défaillant/hostile ne+ # doit pas nous servir un corps illimité.+ data = json.loads(+ r.read(1 << 20).decode("utf-8", "replace"))data["peer"] = peerdata["reachable"] = Trueagents.append(data)diff --git a/backend/detection/wfp.py b/backend/detection/wfp.pyindex 0570b04..0f33c8f 100644--- a/backend/detection/wfp.py+++ b/backend/detection/wfp.py@@ -170,7 +170,14 @@ class WfpBackend:def __init__(self):self._dll = Noneself._engine = ctypes.c_void_p()- self._keepalive: list = [] # EN: pinned ctypes objects / FR: objets ctypes épinglés+ # EN: pinned ctypes objects — bounded: app blobs accumulate per+ # add_block, so cap the list (dropping a pin only risks GC of+ # blobs WFP already copied during FwpmFilterAdd0).+ # FR: objets ctypes épinglés — bornés : les blobs s'accumulent à+ # chaque add_block, donc caper la liste (retirer un pin ne+ # risque que le GC de blobs que WFP a déjà copiés).+ self._keepalive: list = []+ self._keepalive_max = 2048# ── lifecycle / cycle de vie ─────────────────────────────────────────────@@ -369,6 +376,8 @@ class WfpBackend:rc = self._dll.FwpmGetAppIdFromFileName0(path, ctypes.byref(blob))if rc != 0 or not blob:return None+ if len(self._keepalive) >= self._keepalive_max:+ del self._keepalive[:self._keepalive_max // 4]self._keepalive.append(blob) # EN: keep alive; freed w/ engine / FR: gardé vivantreturn blobdiff --git a/backend/tests/test_enterprise.py b/backend/tests/test_enterprise.pyindex cd7e21e..9443083 100644--- a/backend/tests/test_enterprise.py+++ b/backend/tests/test_enterprise.py@@ -247,8 +247,8 @@ def test_fleet_audit_merge(monkeypatch):class FakeResp:def __init__(self, payload):self._b = json.dumps(payload).encode()- def read(self):- return self._b+ def read(self, size=-1):+ return self._b if size < 0 else self._b[:size]def __enter__(self):return selfdef __exit__(self, *a):diff --git a/deploy/gpo/Install-Snitch.ps1 b/deploy/gpo/Install-Snitch.ps1index ac5ad1f..fcbb06a 100644--- a/deploy/gpo/Install-Snitch.ps1+++ b/deploy/gpo/Install-Snitch.ps1@@ -58,19 +58,42 @@ $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" }+# EN: The token goes to %ProgramData%\Snitch\api_token.txt ACL'd to+# SYSTEM+Administrators — NOT into run.cmd: Program Files is+# world-readable, so a plaintext SNITCH_TOKEN=… line would hand the+# master API key to any local user. The backend auto-reads the file.+# FR: Le jeton va dans %ProgramData%\Snitch\api_token.txt restreint à+# SYSTEM+Administrateurs — PAS dans run.cmd : Program Files est+# lisible par tous, donc une ligne SNITCH_TOKEN=… donnerait la clé+# API maître à tout utilisateur local. Le backend lit le fichier+# automatiquement.+if ($Token) {+ $tokPath = Join-Path $DataDir 'api_token.txt'+ Set-Content -Encoding ASCII -NoNewline -Path $tokPath -Value $Token+ $acl = Get-Acl $tokPath+ $acl.SetAccessRuleProtection($true, $false) # EN: cut inheritance / FR: couper l'héritage+ foreach ($rule in @($acl.Access)) { $acl.RemoveAccessRule($rule) | Out-Null }+ foreach ($id in 'SYSTEM', 'Administrators') {+ $acl.AddAccessRule((New-Object `+ System.Security.AccessControl.FileSystemAccessRule(+ $id, 'FullControl', 'Allow')))+ }+ Set-Acl -Path $tokPath -AclObject $acl+}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).+# EN: env vars for the task — via a launcher cmd file (task env is+# limited). `set "VAR=value"` quoting keeps & and spaces in paths+# from being interpreted.# FR: vars d'env de la tâche — via un cmd lanceur (env de tâche limité).+# `set "VAR=valeur"` empêche & et espaces d'être interprétés.@"@echo off-set $env.Split(';')[0]-set $env.Split(';')[1]-$(if ($Token) { 'set ' + $env.Split(';')[2] })+set "SNITCH_DATA_DIR=$DataDir"+set "SNITCH_CONFIG=$(Join-Path $DataDir 'snitch.toml')""$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') `diff --git a/electron/main.js b/electron/main.jsindex 4d3093b..aefc9e9 100644--- a/electron/main.js+++ b/electron/main.js@@ -559,9 +559,14 @@ function launchBackendElevated() {} catch { /* EN: token still reaches the backend via env / FR: le jeton arrive quand même via l'env */ }if (isWindows) {- // 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`+ // EN: PowerShell SINGLE-quoted strings — a " in the exe path would+ // break out of a double-quoted -FilePath and inject commands;+ // single quotes only need ' → '' escaping.+ // FR: Chaînes PowerShell en APOSTROPHES — un " dans le chemin de+ // l'exe sortirait d'un -FilePath entre guillemets et injecterait+ // des commandes ; les apostrophes n'exigent que ' → ''.+ const psq = s => `'${String(s).replace(/'/g, "''")}'`+ const ps = `Start-Process -FilePath ${psq(backendExe)} -ArgumentList '--port ${backendPort}' -Verb RunAs -WindowStyle Hidden`backendProc = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', ps,], { windowsHide: true, stdio: 'ignore' })@@ -576,8 +581,19 @@ function launchBackendElevated() {// SNITCH_TOKEN n'est qu'un repli quand cette écriture a échoué// (dossier de données possédé par root).const esc = s => s.replace(/(["\\$`])/g, '\\$1')- const tokenPrefix = tokenFileWritten ? '' : `SNITCH_TOKEN="${API_TOKEN}" `- const shellCmd = `SNITCH_DATA_DIR="${dataDir}" ${tokenPrefix}"${backendExe}" --port ${backendPort}`+ // EN: TWO escaping layers — the command crosses AppleScript THEN+ // /bin/sh. esc() only quotes for AppleScript: a " or $ in dataDir+ // or backendExe would survive it and hit the shell raw → inject+ // first at the shell layer with single quotes (' → '\''), which+ // sh cannot break out of.+ // FR: DEUX couches d'échappement — la commande traverse AppleScript+ // PUIS /bin/sh. esc() ne quote que pour AppleScript : un " ou $+ // dans dataDir/backendExe le traverserait et arriverait brut au+ // shell → échapper d'abord à la couche shell en apostrophes+ // (' → '\''), incassables pour sh.+ const shq = s => `'${String(s).replace(/'/g, `'\\''`)}'`+ const tokenPrefix = tokenFileWritten ? '' : `SNITCH_TOKEN=${shq(API_TOKEN)} `+ const shellCmd = `SNITCH_DATA_DIR=${shq(dataDir)} ${tokenPrefix}${shq(backendExe)} --port ${backendPort}`backendProc = spawn('osascript', ['-e', `do shell script "${esc(shellCmd)}" with administrator privileges`,], { stdio: 'ignore' })