SPB Git

Repository Public

pysandbox.test.ts 34.3 KB 571 lines typescript

1import { afterAll, beforeAll, describe, expect, it } from "vitest";2import { spawn, type ChildProcess } from "node:child_process";3import { createHash, randomBytes } from "node:crypto";4import { createSocket, type Socket as UdpSocket } from "node:dgram";5import { existsSync, readFileSync } from "node:fs";6import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";7import { createServer, type Server } from "node:net";8import os from "node:os";9import path from "node:path";10import { ALLOWED_MODULES, MAX_CODE_BYTES, PySandboxError, checkPythonSource, ensurePyEnv, pySandboxCapabilities, runPython, type PyResult, type PyRunOptions } from "../src/engine/pysandbox";1112/**13 * Bac à sable Python : exécutions RÉELLES (sandbox-exec du noyau, venv figé de py/sandbox). Les tentatives d'évasion tournent deux fois :14 * gardes Python actives (le code doit d'abord tromper le contrôle statique et le filtre d'import), puis gardes COUPÉES15 * (CLIP_PYSANDBOX_TEST_NO_PYGUARD=1) pour prouver que le noyau seul retient tout.16 */17const REPO = process.cwd();18const uvFound = [...(process.env.PATH ?? "").split(":"), path.join(os.homedir(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin"].some((d) => d && existsSync(path.join(d, "uv")));19const venvReady = existsSync(path.join(REPO, "py/sandbox/.venv/bin/python"));20const sandboxExec = process.platform === "darwin" && existsSync("/usr/bin/sandbox-exec");21const SKIP = !sandboxExec ? "sandbox-exec absent (macOS requis)" : !uvFound && !venvReady ? "uv absent et venv py/sandbox/.venv non préparé" : "";22if (SKIP) console.warn(`[pysandbox] tests d'exécution réelle SAUTÉS : ${SKIP}`);2324const sha = (b: Buffer) => createHash("sha256").update(b).digest("hex");25const rand = randomBytes(6).toString("hex");26const API_MARKER = `sk-ant-FAUSSE-CLE-${rand}`;27const SECRET_MARKER = `SECRET-LEURRE-${rand}`;28/** Valeurs du vrai `.env` du dépôt (s'il existe) : aucune ne doit jamais apparaître dans ce que rend le bac à sable. */29const realEnvFile = path.join(REPO, ".env");30const realEnvValues = existsSync(realEnvFile)31  ? readFileSync(realEnvFile, "utf8").split("\n").map((l) => /^\s*([A-Za-z_][\w]*)\s*=\s*["']?(.+?)["']?\s*$/.exec(l)).filter((m): m is RegExpExecArray => !!m).map((m) => ({ key: m[1], value: m[2] }))32    // Les chemins absolus (CLIP_PY_DIR, STORAGE_ROOT…) ne sont pas des secrets et sont des préfixes des cibles que ces tests visent eux-mêmes33    // (dépôt, venv) : ils apparaissent légitimement dans les comptes rendus d'essai. Tout le reste (clés, URL de base, secret d'application) est surveillé.34    .filter((e) => e.value.length >= 12 && !e.value.startsWith("/"))35  : [];3637let tmp = "", secretFile = "", server: Server, udp: UdpSocket, port = 0, udpPort = 0, tcpHits = 0, udpHits = 0, victim: ChildProcess;38const outside: string[] = [];                                   // fichiers que les évasions tentent de créer hors du dossier de sortie39const savedKey = process.env.ANTHROPIC_API_KEY;4041beforeAll(async () => {42  process.env.ANTHROPIC_API_KEY = API_MARKER;43  tmp = await mkdtemp(path.join(os.tmpdir(), "spclip-pysandbox-test-"));44  await mkdir(path.join(tmp, ".ssh"));45  secretFile = path.join(tmp, ".ssh", "id_ed25519");46  await writeFile(secretFile, `-----BEGIN OPENSSH PRIVATE KEY-----\n${SECRET_MARKER}\n`, { mode: 0o600 });47  await writeFile(path.join(tmp, ".env"), `ANTHROPIC_API_KEY=${SECRET_MARKER}\n`);48  server = createServer((s) => { tcpHits++; s.destroy(); });49  await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));50  port = (server.address() as { port: number }).port;51  udp = createSocket("udp4");52  udp.on("message", () => { udpHits++; });53  await new Promise<void>((r) => udp.bind(0, "127.0.0.1", r));54  udpPort = udp.address().port;55  victim = spawn("/bin/sleep", ["600"], { stdio: "ignore" });56  outside.push(`/tmp/escape-${rand}`, path.join(REPO, `escape-${rand}.txt`), path.join(os.tmpdir(), `escape-${rand}`), path.join(tmp, "escape"),57    path.join(REPO, "py/sandbox/.venv/lib/python3.12/site-packages", `escape_${rand}.py`), path.join(os.homedir(), `.escape-${rand}`));58});59afterAll(async () => {60  if (savedKey === undefined) delete process.env.ANTHROPIC_API_KEY; else process.env.ANTHROPIC_API_KEY = savedKey;61  delete process.env.CLIP_PYSANDBOX_TEST_NO_PYGUARD;62  victim?.kill("SIGKILL");63  await new Promise<void>((r) => server.close(() => r()));64  udp.close();65  for (const f of outside) await rm(f, { force: true, recursive: true });66  await rm(tmp, { recursive: true, force: true });67});6869/** Exécute et rend TOUT ce qui sort du bac à sable (résultat ou erreur) sous forme de texte, pour y chercher des fuites. */70async function attempt(o: PyRunOptions): Promise<{ result?: PyResult; error?: PySandboxError; text: string }> {71  try {72    const result = await runPython(o);73    await result.cleanup();74    return { result, text: JSON.stringify({ ...result, sandbox: undefined }) };75  } catch (e) {76    if (!(e instanceof PySandboxError)) throw e;77    return { error: e, text: JSON.stringify({ message: e.message, code: e.code, details: e.details }) };78  }79}80function expectNoLeak(text: string): void {81  expect(text).not.toContain(API_MARKER);82  expect(text).not.toContain(SECRET_MARKER);83  for (const e of realEnvValues) expect(text.includes(e.value), `la valeur de ${e.key} (vrai .env du dépôt) est sortie du bac à sable`).toBe(false);84}85function expectNoSideEffect(): void {86  for (const f of outside) expect(existsSync(f), `fichier créé hors du dossier de sortie : ${f}`).toBe(false);87  expect(tcpHits).toBe(0);88  expect(udpHits).toBe(0);89  expect(victim.exitCode === null && victim.signalCode === null, "le processus témoin a été tué depuis le bac à sable").toBe(true);90}91const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };92const pidOf = (text: string) => Number(/PID=(\d+)/.exec(text)?.[1] ?? 0);93const escapeParams = () => ({ port, udpPort, secret: secretFile, decoyEnv: path.join(tmp, ".env"), repoEnv: realEnvFile, repo: REPO, home: os.homedir(), storage: process.env.STORAGE_ROOT ?? "/tmp/spclip-test-storage",94  victim: victim.pid, outside, runner: path.join(REPO, "py/sandbox/runner.py"), tmpdir: os.tmpdir() });9596/** Chaque sonde rend « blocked: … » si l'action a levé, « ESCAPED: … » si elle a réussi. */97const PROBE = `98def probe(fn):99    try:100        return "ESCAPED: " + repr(fn())[:300]101    except BaseException as e:102        return "blocked: " + type(e).__name__ + ": " + str(e)[:160]103`;104105describe.skipIf(!!SKIP)("pysandbox — environnement", () => {106  it("prépare le venv figé et annonce ses capacités", async () => {107    const env = await ensurePyEnv();108    expect(env.python).toContain("py/sandbox/.venv/bin/python");109    for (const k of ["python", "numpy", "scipy", "matplotlib", "sympy"]) expect(env.versions[k]).toMatch(/^\d+\.\d+/);110    const caps = await pySandboxCapabilities();111    expect(caps).toMatchObject({ available: true, kernel: true, unsafe: false, modes: ["data", "frames"] });112    // La liste blanche du contrôle statique (TypeScript) et celle du harnais (Python) doivent rester identiques.113    const marker = JSON.parse(await readFile(path.join(REPO, "py/sandbox/.venv/.spclip-pysandbox/env.json"), "utf8")) as { allowed: string[] };114    expect([...marker.allowed].sort()).toEqual([...ALLOWED_MODULES].sort());115  }, 900_000);116});117118describe.skipIf(!!SKIP)("pysandbox — mode data", () => {119  it("calcule une densité normale validée (intégrale ≈ 1) et la rend en JSON strict", async () => {120    const r = await runPython({ mode: "data", params: { mu: 1.5, sigma: 0.7, n: 801 }, code: `121import numpy as np122from scipy import stats123124def compute(params):125    mu, sigma = params["mu"], params["sigma"]126    x = np.linspace(mu - 8 * sigma, mu + 8 * sigma, params["n"])127    print("points :", len(x))128    return {"x": x, "pdf": stats.norm.pdf(x, mu, sigma), "mean": np.float64(mu), "n": np.int64(len(x)), "label": "N(mu, sigma)"}129130def validate(result):131    failed = []132    area = float(np.trapezoid(result["pdf"], result["x"]))133    if abs(area - 1) > 1e-6:134        failed.append(f"la densité n'intègre pas à 1 (aire = {area})")135    if (result["pdf"] < 0).any():136        failed.append("densité négative")137    return failed138` });139    expect(r.ok).toBe(true);140    expect(r.checks).toEqual([]);141    expect(r.sandbox.kernel).toBe(true);142    expect(r.sandbox.profile).toContain("(deny default)");143    expect(r.stdout).toContain("points : 801");144    const d = r.data as { x: number[]; pdf: number[]; mean: number; n: number; label: string };145    expect(d.x).toHaveLength(801);146    expect(d.n).toBe(801);147    expect(d.label).toBe("N(mu, sigma)");148    // Vérification indépendante, côté Node : aire par trapèzes et valeur au mode.149    let area = 0;150    for (let i = 1; i < d.x.length; i++) area += ((d.pdf[i] + d.pdf[i - 1]) / 2) * (d.x[i] - d.x[i - 1]);151    expect(area).toBeCloseTo(1, 6);152    expect(Math.max(...d.pdf)).toBeCloseTo(1 / (0.7 * Math.sqrt(2 * Math.PI)), 9);153  }, 60_000);154155  it("rend ok=false et les invariants quand validate() en signale", async () => {156    const r = await runPython({ mode: "data", code: `157import numpy as np158def compute(params):159    x = np.linspace(-1, 1, 101)160    return {"x": x, "pdf": np.exp(-x**2 / 2)}161def validate(result):162    area = float(np.trapezoid(result["pdf"], result["x"]))163    return [] if abs(area - 1) < 1e-6 else [f"la densité n'intègre pas à 1 (aire = {area:.4f})"]164` });165    expect(r.ok).toBe(false);166    expect(r.checks).toHaveLength(1);167    expect(r.error).toContain("n'intègre pas à 1");168    expect((r.data as { x: number[] }).x).toHaveLength(101);169  }, 60_000);170171  it("refuse NaN/Inf, signale l'erreur du code avec SES lignes, accepte sympy et les dataclasses", async () => {172    const nan = await runPython({ mode: "data", code: "import numpy as np\ndef compute(params):\n    return {'y': np.log(np.linspace(-1, 1, 5))}\n" });173    expect(nan.ok).toBe(false);174    expect(nan.error).toMatch(/non finie\(s\).*résultat\.y/);175    const boom = await runPython({ mode: "data", code: "def helper(v):\n    return 1 / v\n\ndef compute(params):\n    return {'a': helper(0)}\n" });176    expect(boom.ok).toBe(false);177    expect(boom.error).toBe("ZeroDivisionError: division by zero");178    expect(boom.traceback).toContain("ligne 2, dans helper : return 1 / v");179    expect(boom.traceback).not.toContain("runner.py");180    const sym = await runPython({ mode: "data", code: `181import sympy as sp182from dataclasses import dataclass183from scipy import integrate184@dataclass185class Gauss:186    sigma: float = 1.0187def compute(params):188    x = sp.symbols("x")189    exact = sp.integrate(sp.exp(-x**2), (x, -sp.oo, sp.oo))190    num, _ = integrate.quad(lambda t: float(sp.exp(-t**2)), -10, 10)191    return {"exact": exact, "num": num, "third": sp.Rational(1, 3), "sigma": Gauss().sigma}192def validate(r):193    return [] if abs(float(r["exact"]) - r["num"]) < 1e-9 else ["quadrature et forme close divergent"]194` });195    expect(sym.ok, sym.error).toBe(true);196    expect((sym.data as { exact: number }).exact).toBeCloseTo(Math.sqrt(Math.PI), 12);197    expect((sym.data as { third: number }).third).toBeCloseTo(1 / 3, 15);198  }, 120_000);199200  it("est déterministe : aléa semé, même résultat d'une exécution à l'autre", async () => {201    const code = "import random\nimport numpy as np\ndef compute(params):\n    rng = np.random.default_rng(7)\n    return {'a': np.random.rand(5), 'b': random.random(), 'c': rng.normal(size=4), 'h': hash('clip') % 1000}\n";202    const a = await runPython({ mode: "data", code }), b = await runPython({ mode: "data", code });203    expect(a.ok).toBe(true);204    expect(b.data).toEqual(a.data);205  }, 60_000);206});207208describe.skipIf(!!SKIP)("pysandbox — mode frames", () => {209  const code = `210import numpy as np211x = np.linspace(-4, 4, 400)212213def draw(fig, t, params):214    ax = fig.add_subplot(111)215    y = np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)216    ax.plot(x, y, lw=3, color="#1f9e89")217    ax.fill_between(x, 0, np.where(x < -4 + 8 * t / params["seconds"], y, 0), alpha=0.35)218    ax.scatter(np.random.rand(20) * 8 - 4, np.random.rand(20) * 0.4, s=12)219    ax.set_title(f"Loi normale, t = {t:.2f} s")220`;221  it("rend exactement N PNG de la taille demandée, identiques d'une exécution à l'autre", async () => {222    const o = { mode: "frames" as const, code, width: 642, height: 362, fps: 12, seconds: 1, params: { seconds: 1 } };223    const hashes = async () => {224      const r = await runPython(o);225      try {226        expect(r.ok).toBe(true);227        expect(r.frames).toBe(12);228        const files = (await readdir(r.framesDir!)).sort();229        expect(files).toEqual(Array.from({ length: 12 }, (_, i) => `f${String(i).padStart(6, "0")}.png`));230        const out: string[] = [];231        for (const f of files) {232          const png = await readFile(path.join(r.framesDir!, f));233          expect(png.subarray(1, 4).toString("latin1")).toBe("PNG");234          expect([png.readUInt32BE(16), png.readUInt32BE(20)]).toEqual([642, 362]);235          out.push(sha(png));236        }237        return { out, dir: r.framesDir!, r };238      } finally { await r.cleanup(); }239    };240    const a = await hashes(), b = await hashes();241    expect(b.out).toEqual(a.out);242    expect(new Set(a.out).size).toBe(12);                     // l'image change vraiment d'une trame à l'autre243    expect(existsSync(a.dir)).toBe(false);                    // cleanup() a tout retiré244  }, 120_000);245246  it("rend l'erreur de draw() avec la ligne fautive", async () => {247    const r = await runPython({ mode: "frames", width: 320, height: 180, fps: 5, seconds: 1, code: "def draw(fig, t, params):\n    ax = fig.add_subplot(111)\n    ax.plot([0, 1], [0, undefined_name])\n" });248    expect(r.ok).toBe(false);249    expect(r.error).toContain("NameError");250    expect(r.traceback).toContain("ligne 3, dans draw");251  }, 60_000);252});253254describe("pysandbox — contrôle statique (sans exécution)", () => {255  it.each([256    ["import os\ndef compute(p):\n    return {}", /module « os » interdit/],257    ["import numpy as np, socket\ndef compute(p):\n    return {}", /module « socket » interdit/],258    ["from urllib.request import urlopen\ndef compute(p):\n    return {}", /module « urllib » interdit/],259    ["def compute(p):\n    import subprocess; return {}", /module « subprocess » interdit/],260    ["import ctypes\ndef compute(p):\n    return {}", /module « ctypes » interdit/],261    ["def compute(p):\n    return {'a': open('/etc/passwd').read()}", /open\(\)/],262    ["def compute(p):\n    return {'a': eval('1+1')}", /eval\(\)/],263    ["def compute(p):\n    return {'a': __import__('os').getcwd()}", /__import__/],264    ["def compute(p):\n    return {'a': len(().__class__.__bases__[0].__subclasses__())}", /introspection/],265    ["x = 1", /doit définir `def compute/],266  ])("refuse %j", (code, why) => {267    expect(checkPythonSource(code, "data").join("\n")).toMatch(why);268  });269  it("accepte le code légitime, ignore chaînes et commentaires, plafonne la taille", () => {270    expect(checkPythonSource("import numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n# import os\nTITLE = 'open(the door) and import socket'\ndef draw(fig, t, params):\n    fig.suptitle(TITLE)\n", "frames")).toEqual([]);271    expect(checkPythonSource(`def compute(p):\n    return {}\n#${"x".repeat(MAX_CODE_BYTES)}`, "data")[0]).toMatch(/trop volumineux/);272  });273  it.skipIf(!!SKIP)("runPython lève bad_input sans rien exécuter", async () => {274    await expect(runPython({ mode: "data", code: "import os\ndef compute(p):\n    return {'env': dict(os.environ)}" })).rejects.toMatchObject({ code: "bad_input", message: expect.stringContaining("module « os » interdit") as unknown });275    await expect(runPython({ mode: "frames", code: "def draw(fig, t, params):\n    pass", width: 99999 })).rejects.toMatchObject({ code: "bad_input" });276  });277});278279describe.skipIf(!!SKIP)("pysandbox — évasions, gardes Python ACTIVES (le code trompe le contrôle statique et le filtre d'import)", () => {280  /** Atteint os, socket, subprocess et ctypes sans aucune instruction `import` interdite ni attribut à double soulignement en clair. */281  const REACH = `282import collections283${PROBE}284_sys = collections._sys285_mods = _sys.modules286_os = _mods["o" + "s"]287_il = _mods["imp" + "ortlib"]288def _mod(name):289    return _il.import_module(name)290`;291  it("le filtre d'import se contourne (os, socket, subprocess, ctypes atteints) mais rien ne sort", async () => {292    const a = await attempt({ mode: "data", params: escapeParams(), code: `${REACH}293def compute(params):294    out = {"reached": [m.__name__ for m in (_os, _mod("socket"), _mod("subprocess"), _mod("ctypes"))]}295    sk = _mod("socket")296    out["tcp"] = probe(lambda: sk.create_connection(("127.0.0.1", params["port"]), timeout=2).getpeername())297    out["read_secret"] = probe(lambda: _mods["io"].FileIO(params["secret"]).read())298    out["read_env"] = probe(lambda: _mods["io"].FileIO(params["repoEnv"]).read())299    out["listdir_home"] = probe(lambda: _os.listdir(params["home"]))300    out["write_tmp"] = probe(lambda: _os.close(_os.open(params["outside"][0], _os.O_WRONLY | _os.O_CREAT)))301    out["write_repo"] = probe(lambda: _mods["io"].FileIO(params["outside"][1], "w").write(b"x"))302    out["system"] = probe(lambda: _os.system("touch " + params["outside"][0]) == 0 or 1 / 0)303    out["popen"] = probe(lambda: _mod("subprocess").run(["/usr/bin/touch", params["outside"][0]]))304    out["ctypes"] = probe(lambda: _mod("ctypes").CDLL(None).system(("touch " + params["outside"][0]).encode()))305    out["kill"] = probe(lambda: _os.kill(params["victim"], 9))306    # Appels sans événement d'audit : ils traversent TOUTES les gardes Python et atteignent le noyau, qui refuse (EPERM).307    out["kernel_mkfifo"] = probe(lambda: _os.mkfifo(params["outside"][0]))308    out["kernel_stat"] = probe(lambda: _os.stat(params["secret"]).st_size)309    out["kernel_access"] = "blocked: invisible" if not _os.access(params["secret"], _os.R_OK) else "ESCAPED: lisible"310    out["environ"] = sorted(_os.environ)311    out["api_key"] = str(_os.environ.get("ANTHROPIC_API_KEY"))312    return out313` });314    expect(a.error, a.text).toBeUndefined();315    const d = a.result!.data as Record<string, string> & { reached: string[]; environ: string[] };316    expect(d.reached).toEqual(["os", "socket", "subprocess", "ctypes"]);                  // la garde d'import EST contournée…317    for (const k of ["tcp", "read_secret", "read_env", "listdir_home", "write_tmp", "write_repo", "system", "popen", "ctypes", "kill"]) expect(d[k], k).toMatch(/^blocked: /);318    for (const k of ["kernel_mkfifo", "kernel_stat"]) expect(d[k], k).toMatch(/^blocked: PermissionError: \[Errno 1\] Operation not permitted/);319    expect(d.kernel_access).toBe("blocked: invisible");320    expect(d.api_key).toBe("None");321    expect(d.environ.every((k) => /^(PATH|HOME|TMPDIR|LANG|TZ|MPL\w+|PYTHON\w+|SOURCE_DATE_EPOCH|\w+_NUM_THREADS|VECLIB_MAXIMUM_THREADS)$/.test(k)), d.environ.join(",")).toBe(true);322    expectNoLeak(a.text);323    expectNoSideEffect();324  }, 60_000);325326  it("un fork lancé sous le crochet d'audit (_posixsubprocess brut) est arrêté par le noyau", async () => {327    const a = await attempt({ mode: "data", params: escapeParams(), code: `${REACH}328def compute(params):329    ps = _mods["_posixsubprocess"]330    r, w = _os.pipe()331    def raw():332        # fork_exec(args, executable_list, close_fds, pass_fds, cwd, env, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite,333        #           errpipe_read, errpipe_write, restore_signals, call_setsid, pgid_to_set, gid, extra_groups, uid, child_umask, preexec_fn, allow_vfork)334        return ps.fork_exec([b"/usr/bin/touch", params["outside"][0].encode()], [b"/usr/bin/touch"], True, (w,), None, None,335                            -1, -1, -1, -1, -1, -1, r, w, True, False, -1, None, None, None, -1, None, False)336    return {"fork_exec": probe(raw)}337` });338    expect(a.error, a.text).toBeUndefined();339    expect((a.result!.data as { fork_exec: string }).fork_exec).toMatch(/^blocked: (BlockingIOError|PermissionError|OSError)/);340    expectNoSideEffect();341  }, 60_000);342});343344describe.skipIf(!!SKIP)("pysandbox — évasions, gardes Python COUPÉES : le noyau seul", () => {345  beforeAll(() => { process.env.CLIP_PYSANDBOX_TEST_NO_PYGUARD = "1"; });346  afterAll(() => { delete process.env.CLIP_PYSANDBOX_TEST_NO_PYGUARD; });347  const run = async (body: string, extra: Partial<PyRunOptions> = {}) => {348    const a = await attempt({ mode: "data", params: escapeParams(), code: `import os, sys, socket, subprocess, ctypes, signal, shutil, pathlib, urllib.request\n${PROBE}\ndef compute(params):\n    out = {}\n${body.split("\n").map((l) => `    ${l}`).join("\n")}\n    return out\n`, ...extra });349    expectNoLeak(a.text);350    return a;351  };352  const allBlocked = (a: Awaited<ReturnType<typeof attempt>>) => {353    expect(a.error, a.text).toBeUndefined();354    const d = a.result!.data as Record<string, string>;355    for (const [k, v] of Object.entries(d)) expect(v, k).toMatch(/^blocked: /);356    expect(Object.keys(d).length).toBeGreaterThan(0);357    expectNoSideEffect();358    return d;359  };360361  it("réseau : TCP, UDP, DNS, HTTP (urllib) et socket Unix refusés", async () => {362    const d = allBlocked(await run(`363out["tcp"] = probe(lambda: socket.create_connection(("127.0.0.1", params["port"]), timeout=2).getpeername())364out["tcp6"] = probe(lambda: socket.create_connection(("::1", params["port"]), timeout=2).getpeername())365out["udp"] = probe(lambda: socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b"x", ("127.0.0.1", params["udpPort"])))366out["dns"] = probe(lambda: socket.getaddrinfo("example.com", 443))367out["http"] = probe(lambda: urllib.request.urlopen("http://127.0.0.1:%d/" % params["port"], timeout=2).read())368out["https"] = probe(lambda: urllib.request.urlopen("https://example.com/", timeout=3).read(20))369out["listen"] = probe(lambda: socket.create_server(("127.0.0.1", 0)).getsockname())370def unix():371    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM); s.connect("/var/run/mDNSResponder"); return "connected"372out["unix"] = probe(unix)373def libc_connect():374    libc = ctypes.CDLL(None, use_errno=True)375    fd = libc.socket(2, 1, 0)376    if fd < 0: raise OSError(ctypes.get_errno(), "socket() refusé")377    return fd378out["libc_socket"] = probe(lambda: socket.fromfd(libc_connect(), 2, 1).connect(("127.0.0.1", params["port"])))379`));380    expect(d.tcp).toMatch(/PermissionError|Operation not permitted/);381  }, 60_000);382383  it("lecture : leurre ~/.ssh, .env du dépôt, trousseau, dossiers personnels, stockage de l'app, variables du parent", async () => {384    const a = await run(`385home = params["home"]386out["secret"] = probe(lambda: open(params["secret"]).read())387out["secret_stat"] = probe(lambda: os.stat(params["secret"]).st_size)388out["decoy_env"] = probe(lambda: open(params["decoyEnv"]).read())389out["repo_env"] = probe(lambda: open(params["repoEnv"]).read())390out["repo_env_pathlib"] = probe(lambda: pathlib.Path(params["repoEnv"]).read_text())391out["repo_ls"] = probe(lambda: os.listdir(params["repo"]))392out["repo_src"] = probe(lambda: open(params["repo"] + "/package.json").read()[:40])393out["ssh_ls"] = probe(lambda: os.listdir(home + "/.ssh"))394out["ssh_cfg"] = probe(lambda: open(home + "/.ssh/config").read()[:40])395out["keychains"] = probe(lambda: os.listdir(home + "/Library/Keychains"))396out["home_ls"] = probe(lambda: os.listdir(home))397out["users_ls"] = probe(lambda: os.listdir("/Users"))398out["shared"] = probe(lambda: os.listdir("/Users/Shared"))399out["passwd"] = probe(lambda: open("/etc/passwd").read()[:40])400out["storage"] = probe(lambda: os.listdir(params["storage"]))401out["tmp_ls"] = probe(lambda: os.listdir(params["tmpdir"]))402out["profile"] = probe(lambda: open(os.path.dirname(os.getcwd()) + "/profile.sb").read()[:40])403out["proc_env"] = probe(lambda: subprocess.check_output(["/bin/ps", "eww", str(os.getppid())]))404out["copy_secret"] = probe(lambda: shutil.copy(params["secret"], "stolen"))405out["link_secret"] = probe(lambda: os.link(params["secret"], "hard"))406out["rename_secret"] = probe(lambda: os.rename(params["secret"], "moved"))407out["api_key"] = "blocked: absent" if "ANTHROPIC_API_KEY" not in os.environ else "ESCAPED: " + os.environ["ANTHROPIC_API_KEY"]408out["env_extra"] = "blocked: rien" if set(os.environ) <= {"PATH", "HOME", "TMPDIR", "LANG", "TZ", "MPLCONFIGDIR", "MPLBACKEND", "PYTHONHASHSEED", "PYTHONDONTWRITEBYTECODE", "SOURCE_DATE_EPOCH", "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "VECLIB_MAXIMUM_THREADS"} else "ESCAPED: " + ",".join(sorted(os.environ))409`);410    allBlocked(a);411    expect(existsSync(secretFile)).toBe(true);412    expect(await readFile(secretFile, "utf8")).toContain(SECRET_MARKER);413  }, 60_000);414415  it("écriture : /tmp, dépôt, dossier personnel, venv, harnais et dossier d'entrée restent intacts", async () => {416    const runnerBefore = sha(await readFile(path.join(REPO, "py/sandbox/runner.py")));417    allBlocked(await run(`418for i, target in enumerate(params["outside"]):419    out["write_%d" % i] = probe(lambda: open(target, "w").write("x"))420    out["mkdir_%d" % i] = probe(lambda: os.mkdir(target))421    out["pathlib_%d" % i] = probe(lambda: pathlib.Path(target).write_text("x"))422out["runner"] = probe(lambda: open(params["runner"], "a").write("# pwn"))423out["scene"] = probe(lambda: open(os.path.dirname(os.getcwd()) + "/in/scene.py", "a").write("# pwn"))424out["params"] = probe(lambda: open(os.path.dirname(os.getcwd()) + "/in/params.json", "w").write("{}"))425out["profile"] = probe(lambda: open(os.path.dirname(os.getcwd()) + "/profile.sb", "w").write("(version 1)(allow default)"))426out["rm_secret"] = probe(lambda: os.remove(params["secret"]))427out["chmod_secret"] = probe(lambda: os.chmod(params["secret"], 0o777))428out["trunc_env"] = probe(lambda: os.truncate(params["repoEnv"], 0))429out["fifo"] = probe(lambda: os.mkfifo(params["outside"][0]))430out["symlink_out"] = probe(lambda: os.symlink("/etc", params["outside"][0]))431out["shutil"] = probe(lambda: shutil.copy("/dev/null", params["outside"][0]))432`));433    expect(sha(await readFile(path.join(REPO, "py/sandbox/runner.py")))).toBe(runnerBefore);434    expect(await readFile(secretFile, "utf8")).toContain(SECRET_MARKER);435    if (existsSync(realEnvFile)) expect(readFileSync(realEnvFile).length).toBeGreaterThan(0);436  }, 60_000);437438  it("le témoin d'écriture DANS le dossier de sortie réussit (le test d'écriture n'est pas vide de sens)", async () => {439    const a = await run(`440def inside():441    open("dedans.txt", "w").write("ok"); return os.path.getsize("dedans.txt")442out["control"] = probe(inside)443`);444    expect((a.result!.data as { control: string }).control).toBe("ESCAPED: 2");445  }, 60_000);446447  it("processus : subprocess, os.system, fork, posix_spawn, exec, ctypes et signaux refusés", async () => {448    allBlocked(await run(`449t = params["outside"][0]450out["subprocess"] = probe(lambda: subprocess.run(["/usr/bin/touch", t], check=True))451out["shell"] = probe(lambda: subprocess.check_output("id", shell=True))452out["system"] = probe(lambda: 1 / (os.system("/usr/bin/touch " + t) == 0))453out["fork"] = probe(lambda: os.fork() or os._exit(0))454out["posix_spawn"] = probe(lambda: os.posix_spawn("/usr/bin/touch", ["touch", t], {}))455out["ctypes_system"] = probe(lambda: 1 / (ctypes.CDLL(None).system(("/usr/bin/touch " + t).encode()) == 0))456out["ctypes_fork"] = probe(lambda: 1 / (ctypes.CDLL(None).fork() > 0))457out["kill_victim"] = probe(lambda: os.kill(params["victim"], signal.SIGKILL))458out["kill_parent"] = probe(lambda: os.kill(os.getppid(), 0))459out["osascript"] = probe(lambda: subprocess.check_output(["/usr/bin/osascript", "-e", "return 1"]))460out["setrlimit"] = probe(lambda: __import__("resource").setrlimit(__import__("resource").RLIMIT_NPROC, (100, 100)))461`));462  }, 60_000);463464  it("exec d'un autre binaire refusé (le processus Python n'est pas remplacé)", async () => {465    const a = await run(`466out["execv"] = probe(lambda: os.execv("/bin/sh", ["sh", "-c", "touch " + params["outside"][0]]))467out["execv_python"] = probe(lambda: os.execv("/usr/bin/python3", ["python3", "-c", "open('" + params["outside"][0] + "','w')"]))468`);469    allBlocked(a);470  }, 60_000);471472  it("bombe à fork : aucun enfant créé", async () => {473    const a = await run(`474made = 0475errors = set()476for _ in range(2000):477    try:478        pid = os.fork()479        if pid == 0:480            os._exit(0)481        made += 1482    except OSError as e:483        errors.add(e.errno)484out["forks"] = "blocked: 0 enfant, errno %s" % sorted(errors) if made == 0 else "ESCAPED: %d enfants" % made485`, { timeoutMs: 30_000 });486    allBlocked(a);487  }, 60_000);488489  it("boucle sans fin : délai appliqué, processus tué", async () => {490    const t0 = Date.now();491    const a = await attempt({ mode: "data", timeoutMs: 2500, code: "import os, sys\nsys.__stderr__.write('PID=%d\\n' % os.getpid()); sys.__stderr__.flush()\ndef compute(params):\n    while True:\n        pass\n" });492    expect(a.error?.code).toBe("timeout");493    expect(Date.now() - t0).toBeLessThan(8000);494    const pid = pidOf(a.text);495    expect(pid).toBeGreaterThan(1);496    expect(alive(pid)).toBe(false);497  }, 30_000);498499  it("boucle sans fin qui ignore les signaux et dort : tuée quand même (SIGKILL du groupe)", async () => {500    const a = await attempt({ mode: "data", timeoutMs: 2000, code: "import os, sys, signal, time\nsys.__stderr__.write('PID=%d\\n' % os.getpid()); sys.__stderr__.flush()\nfor s in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGXCPU):\n    signal.signal(s, signal.SIG_IGN)\ndef compute(params):\n    while True:\n        time.sleep(1)\n" });501    expect(a.error?.code).toBe("timeout");502    expect(alive(pidOf(a.text))).toBe(false);503  }, 30_000);504505  it("bombe mémoire : bornée par le plafond, processus disparu", async () => {506    const t0 = Date.now();507    const a = await attempt({ mode: "data", memoryMb: 256, timeoutMs: 30_000, code: "import os, sys\nsys.__stderr__.write('PID=%d\\n' % os.getpid()); sys.__stderr__.flush()\ndef compute(params):\n    blocks = []\n    while True:\n        blocks.append(bytearray(os.urandom(1 << 20)) * 32)\n" });508    expect(a.error?.code, a.text).toBe("memory");509    expect(Date.now() - t0).toBeLessThan(20_000);510    expect(alive(pidOf(a.text))).toBe(false);511    const b = await attempt({ mode: "data", memoryMb: 256, timeoutMs: 30_000, code: "import numpy as np\ndef compute(params):\n    return {'s': float(np.ones((40000, 40000)).sum())}\n" });512    expect(b.error?.code, b.text).toBe("memory");513  }, 60_000);514515  it("bombe mémoire qui avale MemoryError : la surveillance extérieure ou le plafond l'arrête, sans résultat", async () => {516    const a = await attempt({ mode: "data", memoryMb: 128, timeoutMs: 6000, code: "import os, sys\nsys.__stderr__.write('PID=%d\\n' % os.getpid()); sys.__stderr__.flush()\ndef compute(params):\n    blocks = []\n    while True:\n        try:\n            blocks.append(bytearray(8 << 20))\n        except MemoryError:\n            pass\n" });517    expect(["memory", "timeout"]).toContain(a.error?.code);518    expect(alive(pidOf(a.text))).toBe(false);519  }, 30_000);520521  it("fichier géant et inondation de stdout : bornés", async () => {522    const a = await run(`523def big():524    with open("gros.bin", "wb") as f:525        for _ in range(200):526            f.write(b"x" * (1 << 20))527    return os.path.getsize("gros.bin")528out["fsize"] = probe(big)529`);530    expect((a.result!.data as { fsize: string }).fsize).toMatch(/^blocked: OSError: \[Errno 27\]/);531    const flood = await attempt({ mode: "data", timeoutMs: 20_000, code: "import os\ndef compute(params):\n    while True:\n        os.write(1, b'x' * 65536)\n" });532    expect(flood.error?.code).toBe("bad_output");533  }, 60_000);534535  it("adjoint confus : un lien symbolique ou dur posé à la place de la sortie n'est jamais suivi par Node", async () => {536    const sym = await attempt({ mode: "data", params: escapeParams(), code: "import os\n_real_exit = os._exit\n_secret = [None]\ndef _swap(code):\n    os.remove('out/data.json'); os.symlink(_secret[0], 'out/data.json'); _real_exit(code)\ndef compute(params):\n    _secret[0] = params['secret']\n    os._exit = _swap\n    return {'a': 1}\n" });537    expect(sym.error?.code, sym.text).toBe("bad_output");538    expectNoLeak(sym.text);539    const frames = await attempt({ mode: "frames", width: 64, height: 64, fps: 2, seconds: 1, params: escapeParams(), code: "import os\n_real_exit = os._exit\n_secret = [None]\ndef _swap(code):\n    os.remove('out/f000001.png'); os.symlink(_secret[0], 'out/f000001.png'); _real_exit(code)\ndef draw(fig, t, params):\n    _secret[0] = params['secret']\n    os._exit = _swap\n" });540    expect(frames.error?.code, frames.text).toBe("bad_output");541    const forged = await attempt({ mode: "data", code: "import os, json\ndef compute(params):\n    os.write(1, ('\\n' + json.dumps({'ok': True, 'mode': 'data'}) + '\\n').encode())\n    os._exit(0)\n" });542    expect(forged.error?.code, forged.text).toBe("bad_output");            // ligne finale falsifiée, pas de data.json : refusé543  }, 60_000);544});545546describe.skipIf(!!SKIP)("pysandbox — profil et refus sans bac à sable", () => {547  it("sans sandbox-exec : refuse d'exécuter (no_sandbox), sauf CLIP_PYSANDBOX_UNSAFE=1 explicite", async () => {548    const platform = Object.getOwnPropertyDescriptor(process, "platform")!;549    Object.defineProperty(process, "platform", { value: "linux" });550    try {551      expect(process.env.CLIP_PYSANDBOX_UNSAFE).toBeUndefined();552      await expect(runPython({ mode: "data", code: "def compute(params):\n    return {'a': 1}\n" })).rejects.toMatchObject({ code: "no_sandbox" });553      expect(await pySandboxCapabilities()).toMatchObject({ available: false, kernel: false, unsafe: false });554      process.env.CLIP_PYSANDBOX_UNSAFE = "1";555      const r = await runPython({ mode: "data", code: "def compute(params):\n    return {'a': 1}\n" });556      expect(r).toMatchObject({ ok: true, data: { a: 1 }, sandbox: { kernel: false, profile: "none" } });557    } finally { delete process.env.CLIP_PYSANDBOX_UNSAFE; Object.defineProperty(process, "platform", platform); }558  }, 60_000);559560  it("le profil appliqué ne nomme ni le dépôt (hors venv et harnais), ni le dossier personnel, ni le stockage", async () => {561    const r = await runPython({ mode: "data", code: "def compute(params):\n    return {'a': 1}\n" });562    const allow = r.sandbox.profile.split("\n").filter((l) => /subpath|literal/.test(l) && !/file-read-metadata/.test(l));563    const writable = r.sandbox.profile.split("\n").filter((l) => l.startsWith("(allow file-write*"));564    expect(writable).toHaveLength(1);565    expect(writable[0]).toMatch(/\(subpath ".*\/spclip-py-[^/]+\/w"\)\)$/);566    expect(r.sandbox.profile).toContain("(deny network*)");567    expect(r.sandbox.profile).not.toMatch(/\(allow (default|network|process-fork|mach|iokit|ipc)/);568    expect(allow.some((l) => l.includes(`(subpath "${REPO}")`) || l.includes(`(subpath "${os.homedir()}")`) || l.includes(".ssh") || l.includes("Keychains") || l.includes(".env"))).toBe(false);569  }, 60_000);570});571
Files main
Menu

Theme