From 687c05450151d41b33b99c0c7034eb83a8dfa3fa Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:28:10 -0500 Subject: [PATCH 1/8] fix(sandbox): do not load a workspace __pycache__ in the worker (#767) --- Dockerfile.worker | 6 +++ sandbox/docker.go | 2 + sandbox/sandbox_test.go | 83 +++++++++++++++++++++++++++++++++++++++++ sandbox/types.go | 3 ++ 4 files changed, 94 insertions(+) diff --git a/Dockerfile.worker b/Dockerfile.worker index f18c63a14..2b4ef262d 100644 --- a/Dockerfile.worker +++ b/Dockerfile.worker @@ -23,6 +23,12 @@ RUN set -eux; \ chown -R 10001:10001 /workspace /home/exec; \ find / -xdev -perm /6000 -type f -exec chmod a-s {} + +# artex-runner sets PYTHONPYCACHEPREFIX to this directory so Python never reads +# a __pycache__ shipped inside /workspace. Prebuilding the system modules here +# keeps imports from recompiling the stdlib on every run. +RUN python3 -X pycache_prefix=/usr/local/lib/artex-pycache -m compileall -q -j0 \ + "$(python3 -c 'import sysconfig; print(sysconfig.get_path("stdlib"))')" /usr/lib/python3/dist-packages + COPY --from=wrap-build /out/artex-exec-wrap /usr/local/bin/artex-exec-wrap RUN chmod 0755 /usr/local/bin/artex-exec-wrap diff --git a/sandbox/docker.go b/sandbox/docker.go index b197276d4..0d98de468 100644 --- a/sandbox/docker.go +++ b/sandbox/docker.go @@ -562,6 +562,8 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma "HOME=/home/exec", "LANG=C.UTF-8", "TERM=xterm", + "PYTHONPYCACHEPREFIX=" + WorkerPycachePrefix, + "PYTHONDONTWRITEBYTECODE=1", "HTTP_PROXY=" + proxyURL, "HTTPS_PROXY=" + proxyURL, "ALL_PROXY=" + socksURL, diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go index 2b1da01e2..74d4ea2c2 100644 --- a/sandbox/sandbox_test.go +++ b/sandbox/sandbox_test.go @@ -515,3 +515,86 @@ func TestDockerBackendRecreatesDeadWorker(t *testing.T) { t.Fatalf("expected 1 worker create call, got %d", workerCreates.Load()) } } + +// TestDockerBackendWorkerPythonBytecodeEnv pins the worker env that keeps Python +// from loading a __pycache__ shipped in /workspace. +func TestDockerBackendWorkerPythonBytecodeEnv(t *testing.T) { + sock := filepath.Join(t.TempDir(), "docker.sock") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var workerEnv []string + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + p := r.URL.Path + switch { + case r.Method == http.MethodGet && strings.HasPrefix(p, "/networks/artex-task-"): + _ = json.NewEncoder(w).Encode(map[string]any{ + "Internal": true, + "Labels": map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: "tpy"}, + }) + case r.Method == http.MethodGet && strings.HasPrefix(p, "/networks/"): + _ = json.NewEncoder(w).Encode(map[string]any{"Internal": false, "Labels": map[string]string{}}) + case r.Method == http.MethodPost && p == "/containers/create": + if strings.HasPrefix(r.URL.Query().Get("name"), "artex-worker-") { + var spec struct{ Env []string } + _ = json.NewDecoder(r.Body).Decode(&spec) + mu.Lock() + workerEnv = spec.Env + mu.Unlock() + _ = json.NewEncoder(w).Encode(map[string]string{"Id": "worker-1"}) + return + } + _ = json.NewEncoder(w).Encode(map[string]string{"Id": "proxy-1"}) + case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"): + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodPost && strings.HasSuffix(p, "/start"): + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusOK) + } + })} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { + _ = srv.Close() + _ = ln.Close() + }) + + ws := t.TempDir() + au := t.TempDir() + b := NewDockerBackend(DockerConfig{ + SocketPath: sock, + WorkspaceRoot: ws, + HostWorkspaceRoot: ws, + AuditRoot: au, + HostAuditRoot: au, + }) + if _, err := b.ensureTask(context.Background(), "tpy", nil, nil); err != nil { + t.Fatalf("ensureTask failed: %v", err) + } + + mu.Lock() + env := workerEnv + mu.Unlock() + for _, want := range []string{ + "PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache", + "PYTHONDONTWRITEBYTECODE=1", + } { + found := false + for _, kv := range env { + if kv == want { + found = true + break + } + } + if !found { + t.Fatalf("worker env missing %q: %v", want, env) + } + } + for _, kv := range env { + if strings.HasPrefix(kv, "PYTHONSAFEPATH=") { + t.Fatalf("worker env sets %q; sibling imports from /workspace would break", kv) + } + } +} diff --git a/sandbox/types.go b/sandbox/types.go index 9995e26d1..bc8571085 100644 --- a/sandbox/types.go +++ b/sandbox/types.go @@ -49,6 +49,9 @@ const ( WorkerUID = 10001 WorkerGID = 10001 + + // WorkerPycachePrefix is prebuilt by Dockerfile.worker on the read-only rootfs. + WorkerPycachePrefix = "/usr/local/lib/artex-pycache" ) // Typed client / runner errors. From 9781023bf10f7847f6854aecbc54d2ebaac46756 Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:28:10 -0500 Subject: [PATCH 2/8] test(sandbox): live check that a forged workspace .pyc is not loaded --- sandbox/docker_e2e_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/sandbox/docker_e2e_test.go b/sandbox/docker_e2e_test.go index 18b8920e9..c2b6984a3 100644 --- a/sandbox/docker_e2e_test.go +++ b/sandbox/docker_e2e_test.go @@ -175,6 +175,44 @@ func TestDockerSandboxE2EContainment(t *testing.T) { t.Fatalf("cross-task isolation check failed:\n%s", wsRes.Stdout) } + // 3b) A __pycache__ shipped in the workspace, with its header forged to match + // the reviewed source, is not loaded, and the stdlib cache comes from the image. + // The -E run ignores the worker env and proves the fixture is live. + pycRes, err := backend.Exec(ctx, taskA, ExecRequest{ + Argv: []string{"bash", "-c", ` + mkdir -p /workspace/pyc && cd /workspace/pyc + printf "print('GOOD')\n" > mod.py + printf "import mod\n" > main.py + python3 -I -c ' +import importlib._bootstrap_external as be, os, sys +st = os.stat("mod.py") +code = compile("print(\"EVIL\")\n", os.path.abspath("mod.py"), "exec") +os.makedirs("__pycache__", exist_ok=True) +open("__pycache__/mod.%s.pyc" % sys.implementation.cache_tag, "wb").write(be._code_to_timestamp_pyc(code, int(st.st_mtime), st.st_size)) +' + python3 -E main.py 2>&1 | sed 's/^/CONTROL=/' + python3 main.py + python3 -c 'import sys; print("PREFIX=%s" % sys.pycache_prefix)' + python3 -c 'import json, os, importlib.util as u; print("STDLIB_CACHED=%s" % os.path.exists(u.cache_from_source(json.__file__)))' + echo "PYC_COUNT=$(find /workspace/pyc -name '*.pyc' | wc -l)" + rm -rf /workspace/pyc + `}, + Workdir: "/workspace", + TimeoutMS: 30000, + }) + if err != nil { + t.Fatalf("exec pyc shadowing check failed: %v", err) + } + t.Logf("worker pyc shadowing stdout:\n%s", pycRes.Stdout) + for _, want := range []string{"CONTROL=EVIL", "\nGOOD\n", "PREFIX=" + WorkerPycachePrefix, "STDLIB_CACHED=True", "PYC_COUNT=1"} { + if !strings.Contains(pycRes.Stdout, want) { + t.Fatalf("missing pyc assertion %q in stdout:\n%s\nstderr:\n%s", want, pycRes.Stdout, pycRes.Stderr) + } + } + if strings.Contains(strings.ReplaceAll(pycRes.Stdout, "CONTROL=EVIL", ""), "EVIL") { + t.Fatalf("worker loaded a workspace __pycache__ over the reviewed source:\n%s", pycRes.Stdout) + } + // 4) Adversarial Kill-switch: setsid, rm -rf /tmp/.artex-pgids /tmp/*, nohup, // nested double-fork ignoring SIGTERM, and an active setsid egress loop. // Assert ALL non-PID-1 uid-10001 processes are dead in <= 5s AND zero From f65ac20f1478dcffa42ff6b5e7f48d94041db756 Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:29:39 -0500 Subject: [PATCH 3/8] docs(changelog): record the workspace __pycache__ change (#767) --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e46a8e554..686a7fe3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ All notable changes to this project are documented in this file. The format is b - **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only. - **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out. +- **The worker does not load a `__pycache__` shipped in the workspace** (#767). A target tree can carry `__pycache__/*.pyc` whose header matches the reviewed `.py` (forged mtime and size, or an unchecked hash-based pyc), and Python ran that bytecode instead of the source. `artex-runner` now starts the worker with `PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache` and `PYTHONDONTWRITEBYTECODE=1`, so in-tree `__pycache__` directories are never read or written. `Dockerfile.worker` prebuilds the system modules into that directory on the read-only rootfs, so stdlib imports do not recompile on every run. Not covered: a sourceless `foo.pyc` with no `foo.py` still imports, and `python3 -E` or a command that unsets the variable ignores it. `PYTHONSAFEPATH` is not set, because a script in `/workspace` must still import the modules next to it. + ### Added - **`domain_suffix` asset interception rule kind**: a domain and its subdomains, matched on a label boundary. `example.com` matches `example.com` and `a.example.com`, but not `a.example.com.other.net` or `badexample.com`, which `fuzzy_domain`'s substring match also lets through; that makes it the kind to use for a task allow-list that covers a site. `*.example.com` and `.example.com` are stored as `example.com`. It is the label-boundary semantics the sandbox egress policy already applies, and a `domain_suffix` allow rule is now a scope domain for that policy too (`taskSandboxRunInfo` already read the kind). `fuzzy_domain` is unchanged. Migration `0026_asset_intercept_domain_suffix.sql` widens the `kind` CHECK constraint of both rule tables. From 988e78a27846f4099bad7457647fa847ce6a04fb Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:43:39 -0500 Subject: [PATCH 4/8] fix(sandbox): keep py_compile working under the pycache prefix --- sandbox/docker.go | 10 ++++++++-- sandbox/docker_e2e_test.go | 5 ++++- sandbox/sandbox_test.go | 17 ++++++++++++++++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/sandbox/docker.go b/sandbox/docker.go index 0d98de468..5bea83122 100644 --- a/sandbox/docker.go +++ b/sandbox/docker.go @@ -585,9 +585,15 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma "PidsLimit": int64(512), "Memory": int64(2 << 30), "NanoCpus": int64(2_000_000_000), + // The pycache prefix mirrors absolute source paths. Only the subtrees for + // writable source directories are writable, so py_compile still works and + // the prebuilt stdlib entries stay on the read-only rootfs. "Tmpfs": map[string]string{ - "/tmp": "rw,noexec,nosuid,size=512m", - "/home/exec": fmt.Sprintf("rw,nosuid,size=128m,uid=%d,gid=%d,mode=0700", WorkerUID, WorkerGID), + "/tmp": "rw,noexec,nosuid,size=512m", + "/home/exec": fmt.Sprintf("rw,nosuid,size=128m,uid=%d,gid=%d,mode=0700", WorkerUID, WorkerGID), + WorkerPycachePrefix + "/workspace": fmt.Sprintf("rw,noexec,nosuid,size=64m,uid=%d,gid=%d,mode=0700", WorkerUID, WorkerGID), + WorkerPycachePrefix + "/tmp": fmt.Sprintf("rw,noexec,nosuid,size=64m,uid=%d,gid=%d,mode=0700", WorkerUID, WorkerGID), + WorkerPycachePrefix + "/home/exec": fmt.Sprintf("rw,noexec,nosuid,size=64m,uid=%d,gid=%d,mode=0700", WorkerUID, WorkerGID), }, "Binds": []string{b.hostTaskDir(ctx, taskID) + ":/workspace:rw"}, "NetworkMode": netName, diff --git a/sandbox/docker_e2e_test.go b/sandbox/docker_e2e_test.go index c2b6984a3..20f741585 100644 --- a/sandbox/docker_e2e_test.go +++ b/sandbox/docker_e2e_test.go @@ -195,6 +195,9 @@ open("__pycache__/mod.%s.pyc" % sys.implementation.cache_tag, "wb").write(be._co python3 -c 'import sys; print("PREFIX=%s" % sys.pycache_prefix)' python3 -c 'import json, os, importlib.util as u; print("STDLIB_CACHED=%s" % os.path.exists(u.cache_from_source(json.__file__)))' echo "PYC_COUNT=$(find /workspace/pyc -name '*.pyc' | wc -l)" + python3 -m py_compile /workspace/pyc/mod.py && echo "PY_COMPILE=ok" + p=$(python3 -c 'import sys; print(sys.pycache_prefix)') + touch "$p/usr/poison" 2>/dev/null || echo "STDLIB_CACHE_RO" rm -rf /workspace/pyc `}, Workdir: "/workspace", @@ -204,7 +207,7 @@ open("__pycache__/mod.%s.pyc" % sys.implementation.cache_tag, "wb").write(be._co t.Fatalf("exec pyc shadowing check failed: %v", err) } t.Logf("worker pyc shadowing stdout:\n%s", pycRes.Stdout) - for _, want := range []string{"CONTROL=EVIL", "\nGOOD\n", "PREFIX=" + WorkerPycachePrefix, "STDLIB_CACHED=True", "PYC_COUNT=1"} { + for _, want := range []string{"CONTROL=EVIL", "\nGOOD\n", "PREFIX=" + WorkerPycachePrefix, "STDLIB_CACHED=True", "PYC_COUNT=1", "PY_COMPILE=ok", "STDLIB_CACHE_RO"} { if !strings.Contains(pycRes.Stdout, want) { t.Fatalf("missing pyc assertion %q in stdout:\n%s\nstderr:\n%s", want, pycRes.Stdout, pycRes.Stderr) } diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go index 74d4ea2c2..14d7757ec 100644 --- a/sandbox/sandbox_test.go +++ b/sandbox/sandbox_test.go @@ -526,6 +526,7 @@ func TestDockerBackendWorkerPythonBytecodeEnv(t *testing.T) { } var mu sync.Mutex var workerEnv []string + var workerTmpfs map[string]string srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := r.URL.Path switch { @@ -538,10 +539,14 @@ func TestDockerBackendWorkerPythonBytecodeEnv(t *testing.T) { _ = json.NewEncoder(w).Encode(map[string]any{"Internal": false, "Labels": map[string]string{}}) case r.Method == http.MethodPost && p == "/containers/create": if strings.HasPrefix(r.URL.Query().Get("name"), "artex-worker-") { - var spec struct{ Env []string } + var spec struct { + Env []string + HostConfig struct{ Tmpfs map[string]string } + } _ = json.NewDecoder(r.Body).Decode(&spec) mu.Lock() workerEnv = spec.Env + workerTmpfs = spec.HostConfig.Tmpfs mu.Unlock() _ = json.NewEncoder(w).Encode(map[string]string{"Id": "worker-1"}) return @@ -576,6 +581,7 @@ func TestDockerBackendWorkerPythonBytecodeEnv(t *testing.T) { mu.Lock() env := workerEnv + tmpfs := workerTmpfs mu.Unlock() for _, want := range []string{ "PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache", @@ -597,4 +603,13 @@ func TestDockerBackendWorkerPythonBytecodeEnv(t *testing.T) { t.Fatalf("worker env sets %q; sibling imports from /workspace would break", kv) } } + // py_compile on a workspace file writes under the prefix; the stdlib part must stay read-only. + for _, dir := range []string{"/workspace", "/tmp", "/home/exec"} { + if _, ok := tmpfs[WorkerPycachePrefix+dir]; !ok { + t.Fatalf("no writable pycache subtree for %s: %v", dir, tmpfs) + } + } + if _, ok := tmpfs[WorkerPycachePrefix]; ok { + t.Fatalf("pycache prefix root is writable, stdlib cache could be replaced: %v", tmpfs) + } } From b76669ab8519683e2ac000b0469394af8788fd9a Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:43:52 -0500 Subject: [PATCH 5/8] fix(sandbox): reserve the worker Python bytecode vars in panel env --- sandbox/sandbox_test.go | 13 +++++++++++++ sandbox/validate.go | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go index 14d7757ec..5f58c1b8a 100644 --- a/sandbox/sandbox_test.go +++ b/sandbox/sandbox_test.go @@ -43,6 +43,19 @@ func TestValidateEnvRejectsForbiddenPatternsAndOversizedValues(t *testing.T) { } } +func TestFilterPanelEnvKeepsWorkerPythonBytecodeEnv(t *testing.T) { + got := FilterPanelEnv([]string{"PYTHONPYCACHEPREFIX=/workspace/c", "PYTHONDONTWRITEBYTECODE=", "FOO=bar"}) + if _, ok := got["PYTHONPYCACHEPREFIX"]; ok { + t.Fatalf("panel env overrides PYTHONPYCACHEPREFIX: %v", got) + } + if _, ok := got["PYTHONDONTWRITEBYTECODE"]; ok { + t.Fatalf("panel env overrides PYTHONDONTWRITEBYTECODE: %v", got) + } + if got["FOO"] != "bar" { + t.Fatalf("FOO dropped: %v", got) + } +} + type fakeBackend struct { mu sync.Mutex pingErr error diff --git a/sandbox/validate.go b/sandbox/validate.go index 9061b7702..23b2fca45 100644 --- a/sandbox/validate.go +++ b/sandbox/validate.go @@ -70,9 +70,9 @@ func FilterPanelEnv(kvs []string) map[string]string { if !ok || !envNameRE.MatchString(k) || IsForbiddenEnvName(k) || len(v) > MaxEnvValueBytes || strings.ContainsRune(v, 0) { continue } - // Never override worker proxy or home variables from panel process env. + // Never override worker proxy, home or Python bytecode variables from panel process env. switch strings.ToUpper(k) { - case "PATH", "HOME", "XDG_CACHE_HOME", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY": + case "PATH", "HOME", "XDG_CACHE_HOME", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "PYTHONPYCACHEPREFIX", "PYTHONDONTWRITEBYTECODE": continue } out[k] = v From e81c4c6530e46222ba3bb9460b9fdee8df101cb9 Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:44:37 -0500 Subject: [PATCH 6/8] docs(changelog): note py_compile, panel env and open import gaps (#767) --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 686a7fe3b..ea879673e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ All notable changes to this project are documented in this file. The format is b - **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only. - **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out. -- **The worker does not load a `__pycache__` shipped in the workspace** (#767). A target tree can carry `__pycache__/*.pyc` whose header matches the reviewed `.py` (forged mtime and size, or an unchecked hash-based pyc), and Python ran that bytecode instead of the source. `artex-runner` now starts the worker with `PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache` and `PYTHONDONTWRITEBYTECODE=1`, so in-tree `__pycache__` directories are never read or written. `Dockerfile.worker` prebuilds the system modules into that directory on the read-only rootfs, so stdlib imports do not recompile on every run. Not covered: a sourceless `foo.pyc` with no `foo.py` still imports, and `python3 -E` or a command that unsets the variable ignores it. `PYTHONSAFEPATH` is not set, because a script in `/workspace` must still import the modules next to it. +- **The worker does not load a `__pycache__` shipped in the workspace** (#767). A target tree can carry `__pycache__/*.pyc` whose header matches the reviewed `.py` (forged mtime and size, an unchecked hash-based pyc, or a checked one built with the source's own hash), and Python ran that bytecode instead of the source. `artex-runner` now starts the worker with `PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache` and `PYTHONDONTWRITEBYTECODE=1`, so in-tree `__pycache__` directories are never read or written. `Dockerfile.worker` prebuilds the system modules into that directory on the read-only rootfs, so stdlib imports do not recompile on every run. The prefix mirrors absolute paths, and only its `/workspace`, `/tmp` and `/home/exec` subtrees are tmpfs, so `py_compile` and `compileall` on workspace files still work while the stdlib entries stay read-only. The panel env cannot override either variable. Not covered: a sourceless `foo.pyc` with no `foo.py` still imports, a native `foo.cpython-311-x86_64-linux-gnu.so` next to `foo.py` still wins, and `python3 -E` or a command that unsets the variable ignores it. `ARTEX_SANDBOX=off` gets none of this, and a worker adopted at runner restart keeps its old environment until it is recreated. `PYTHONSAFEPATH` is not set, because a script in `/workspace` must still import the modules next to it. ### Added From 90042e92899fee1fdf7f9ef6658efa43db885f26 Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:15:04 -0500 Subject: [PATCH 7/8] fix(sandbox): set PYTHONNOUSERSITE in the worker so a user-site .pth does not run --- CHANGELOG.md | 2 +- sandbox/docker.go | 1 + sandbox/docker_e2e_test.go | 14 ++++++++++---- sandbox/sandbox_test.go | 12 ++++++------ sandbox/validate.go | 2 +- 5 files changed, 19 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea879673e..e5f3711a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ All notable changes to this project are documented in this file. The format is b - **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only. - **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out. -- **The worker does not load a `__pycache__` shipped in the workspace** (#767). A target tree can carry `__pycache__/*.pyc` whose header matches the reviewed `.py` (forged mtime and size, an unchecked hash-based pyc, or a checked one built with the source's own hash), and Python ran that bytecode instead of the source. `artex-runner` now starts the worker with `PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache` and `PYTHONDONTWRITEBYTECODE=1`, so in-tree `__pycache__` directories are never read or written. `Dockerfile.worker` prebuilds the system modules into that directory on the read-only rootfs, so stdlib imports do not recompile on every run. The prefix mirrors absolute paths, and only its `/workspace`, `/tmp` and `/home/exec` subtrees are tmpfs, so `py_compile` and `compileall` on workspace files still work while the stdlib entries stay read-only. The panel env cannot override either variable. Not covered: a sourceless `foo.pyc` with no `foo.py` still imports, a native `foo.cpython-311-x86_64-linux-gnu.so` next to `foo.py` still wins, and `python3 -E` or a command that unsets the variable ignores it. `ARTEX_SANDBOX=off` gets none of this, and a worker adopted at runner restart keeps its old environment until it is recreated. `PYTHONSAFEPATH` is not set, because a script in `/workspace` must still import the modules next to it. +- **The worker does not load a `__pycache__` shipped in the workspace** (#767). A target tree can carry `__pycache__/*.pyc` whose header matches the reviewed `.py` (forged mtime and size, an unchecked hash-based pyc, or a checked one built with the source's own hash), and Python ran that bytecode instead of the source. `artex-runner` now starts the worker with `PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache` and `PYTHONDONTWRITEBYTECODE=1`, so in-tree `__pycache__` directories are never read or written, and with `PYTHONNOUSERSITE=1`, so a `.pth` dropped in the user site under `/home/exec` does not run at interpreter start. `Dockerfile.worker` prebuilds the system modules into that directory on the read-only rootfs, so stdlib imports do not recompile on every run. The prefix mirrors absolute paths, and only its `/workspace`, `/tmp` and `/home/exec` subtrees are tmpfs, so `py_compile` and `compileall` on workspace files still work while the stdlib entries stay read-only. The panel env cannot override any of the three variables. Not covered: a sourceless `foo.pyc` with no `foo.py` still imports, a native `foo.cpython-311-x86_64-linux-gnu.so` next to `foo.py` still wins, and `python3 -E` or a command that unsets the variables ignores them. `ARTEX_SANDBOX=off` gets none of this, and a worker adopted at runner restart keeps its old environment until it is recreated. `PYTHONSAFEPATH` is not set, because a script in `/workspace` must still import the modules next to it. ### Added diff --git a/sandbox/docker.go b/sandbox/docker.go index 5bea83122..3d633dbac 100644 --- a/sandbox/docker.go +++ b/sandbox/docker.go @@ -564,6 +564,7 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma "TERM=xterm", "PYTHONPYCACHEPREFIX=" + WorkerPycachePrefix, "PYTHONDONTWRITEBYTECODE=1", + "PYTHONNOUSERSITE=1", "HTTP_PROXY=" + proxyURL, "HTTPS_PROXY=" + proxyURL, "ALL_PROXY=" + socksURL, diff --git a/sandbox/docker_e2e_test.go b/sandbox/docker_e2e_test.go index 20f741585..eb037922d 100644 --- a/sandbox/docker_e2e_test.go +++ b/sandbox/docker_e2e_test.go @@ -177,7 +177,8 @@ func TestDockerSandboxE2EContainment(t *testing.T) { // 3b) A __pycache__ shipped in the workspace, with its header forged to match // the reviewed source, is not loaded, and the stdlib cache comes from the image. - // The -E run ignores the worker env and proves the fixture is live. + // A user-site .pth does not run. The -E runs ignore the worker env and prove + // the fixtures are live. pycRes, err := backend.Exec(ctx, taskA, ExecRequest{ Argv: []string{"bash", "-c", ` mkdir -p /workspace/pyc && cd /workspace/pyc @@ -198,6 +199,11 @@ open("__pycache__/mod.%s.pyc" % sys.implementation.cache_tag, "wb").write(be._co python3 -m py_compile /workspace/pyc/mod.py && echo "PY_COMPILE=ok" p=$(python3 -c 'import sys; print(sys.pycache_prefix)') touch "$p/usr/poison" 2>/dev/null || echo "STDLIB_CACHE_RO" + us=$(python3 -c 'import site; print(site.getusersitepackages())') + mkdir -p "$us" && echo 'import sys; print("EVIL_USERSITE")' > "$us/artex-test.pth" + python3 -E -c pass 2>&1 | sed 's/^/CONTROL_USERSITE=/' + python3 -c 'print("USERSITE_SKIPPED")' + rm -f "$us/artex-test.pth" rm -rf /workspace/pyc `}, Workdir: "/workspace", @@ -207,13 +213,13 @@ open("__pycache__/mod.%s.pyc" % sys.implementation.cache_tag, "wb").write(be._co t.Fatalf("exec pyc shadowing check failed: %v", err) } t.Logf("worker pyc shadowing stdout:\n%s", pycRes.Stdout) - for _, want := range []string{"CONTROL=EVIL", "\nGOOD\n", "PREFIX=" + WorkerPycachePrefix, "STDLIB_CACHED=True", "PYC_COUNT=1", "PY_COMPILE=ok", "STDLIB_CACHE_RO"} { + for _, want := range []string{"CONTROL=EVIL", "\nGOOD\n", "PREFIX=" + WorkerPycachePrefix, "STDLIB_CACHED=True", "PYC_COUNT=1", "PY_COMPILE=ok", "STDLIB_CACHE_RO", "CONTROL_USERSITE=EVIL_USERSITE", "USERSITE_SKIPPED"} { if !strings.Contains(pycRes.Stdout, want) { t.Fatalf("missing pyc assertion %q in stdout:\n%s\nstderr:\n%s", want, pycRes.Stdout, pycRes.Stderr) } } - if strings.Contains(strings.ReplaceAll(pycRes.Stdout, "CONTROL=EVIL", ""), "EVIL") { - t.Fatalf("worker loaded a workspace __pycache__ over the reviewed source:\n%s", pycRes.Stdout) + if strings.Contains(strings.NewReplacer("CONTROL=EVIL", "", "CONTROL_USERSITE=EVIL_USERSITE", "").Replace(pycRes.Stdout), "EVIL") { + t.Fatalf("worker loaded planted bytecode or a user-site .pth:\n%s", pycRes.Stdout) } // 4) Adversarial Kill-switch: setsid, rm -rf /tmp/.artex-pgids /tmp/*, nohup, diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go index 5f58c1b8a..4d2ec9188 100644 --- a/sandbox/sandbox_test.go +++ b/sandbox/sandbox_test.go @@ -44,12 +44,11 @@ func TestValidateEnvRejectsForbiddenPatternsAndOversizedValues(t *testing.T) { } func TestFilterPanelEnvKeepsWorkerPythonBytecodeEnv(t *testing.T) { - got := FilterPanelEnv([]string{"PYTHONPYCACHEPREFIX=/workspace/c", "PYTHONDONTWRITEBYTECODE=", "FOO=bar"}) - if _, ok := got["PYTHONPYCACHEPREFIX"]; ok { - t.Fatalf("panel env overrides PYTHONPYCACHEPREFIX: %v", got) - } - if _, ok := got["PYTHONDONTWRITEBYTECODE"]; ok { - t.Fatalf("panel env overrides PYTHONDONTWRITEBYTECODE: %v", got) + got := FilterPanelEnv([]string{"PYTHONPYCACHEPREFIX=/workspace/c", "PYTHONDONTWRITEBYTECODE=", "PYTHONNOUSERSITE=", "FOO=bar"}) + for _, k := range []string{"PYTHONPYCACHEPREFIX", "PYTHONDONTWRITEBYTECODE", "PYTHONNOUSERSITE"} { + if _, ok := got[k]; ok { + t.Fatalf("panel env overrides %s: %v", k, got) + } } if got["FOO"] != "bar" { t.Fatalf("FOO dropped: %v", got) @@ -599,6 +598,7 @@ func TestDockerBackendWorkerPythonBytecodeEnv(t *testing.T) { for _, want := range []string{ "PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache", "PYTHONDONTWRITEBYTECODE=1", + "PYTHONNOUSERSITE=1", } { found := false for _, kv := range env { diff --git a/sandbox/validate.go b/sandbox/validate.go index 23b2fca45..fd4c1f4f9 100644 --- a/sandbox/validate.go +++ b/sandbox/validate.go @@ -72,7 +72,7 @@ func FilterPanelEnv(kvs []string) map[string]string { } // Never override worker proxy, home or Python bytecode variables from panel process env. switch strings.ToUpper(k) { - case "PATH", "HOME", "XDG_CACHE_HOME", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "PYTHONPYCACHEPREFIX", "PYTHONDONTWRITEBYTECODE": + case "PATH", "HOME", "XDG_CACHE_HOME", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "PYTHONPYCACHEPREFIX", "PYTHONDONTWRITEBYTECODE", "PYTHONNOUSERSITE": continue } out[k] = v From cdc41dc9ec936e6bfb079c982ab25d3712a93796 Mon Sep 17 00:00:00 2001 From: SREsAreHumanToo <88474954+sresarehumantoo@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:15:11 -0500 Subject: [PATCH 8/8] docs(changelog): list the accepted #767 bytecode limits --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5f3711a9..4c158a7df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,7 @@ All notable changes to this project are documented in this file. The format is b - **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only. - **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out. - -- **The worker does not load a `__pycache__` shipped in the workspace** (#767). A target tree can carry `__pycache__/*.pyc` whose header matches the reviewed `.py` (forged mtime and size, an unchecked hash-based pyc, or a checked one built with the source's own hash), and Python ran that bytecode instead of the source. `artex-runner` now starts the worker with `PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache` and `PYTHONDONTWRITEBYTECODE=1`, so in-tree `__pycache__` directories are never read or written, and with `PYTHONNOUSERSITE=1`, so a `.pth` dropped in the user site under `/home/exec` does not run at interpreter start. `Dockerfile.worker` prebuilds the system modules into that directory on the read-only rootfs, so stdlib imports do not recompile on every run. The prefix mirrors absolute paths, and only its `/workspace`, `/tmp` and `/home/exec` subtrees are tmpfs, so `py_compile` and `compileall` on workspace files still work while the stdlib entries stay read-only. The panel env cannot override any of the three variables. Not covered: a sourceless `foo.pyc` with no `foo.py` still imports, a native `foo.cpython-311-x86_64-linux-gnu.so` next to `foo.py` still wins, and `python3 -E` or a command that unsets the variables ignores them. `ARTEX_SANDBOX=off` gets none of this, and a worker adopted at runner restart keeps its old environment until it is recreated. `PYTHONSAFEPATH` is not set, because a script in `/workspace` must still import the modules next to it. +- **The worker does not load a `__pycache__` shipped in the workspace** (#767). A target tree can carry `__pycache__/*.pyc` whose header matches the reviewed `.py` (forged mtime and size, an unchecked hash-based pyc, or a checked one built with the source's own hash), and Python ran that bytecode instead of the source. `artex-runner` now starts the worker with `PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache` and `PYTHONDONTWRITEBYTECODE=1`, so in-tree `__pycache__` directories are never read or written, and with `PYTHONNOUSERSITE=1`, so a `.pth` dropped in the user site under `/home/exec` does not run at interpreter start. `Dockerfile.worker` prebuilds the system modules into that directory on the read-only rootfs, so stdlib imports do not recompile on every run. The prefix mirrors absolute paths, and only its `/workspace`, `/tmp` and `/home/exec` subtrees are tmpfs, so `py_compile` and `compileall` on workspace files still work while the stdlib entries stay read-only. The panel env cannot override any of the three variables. Accepted limits, each measured on the worker: a sourceless `foo.pyc` with no `foo.py` still imports; a `.zip` or `.egg` on `sys.path` is read by `zipimport`, which runs a sourceless pyc or a forged pyc next to its source inside the archive; an explicit `SourcelessFileLoader` or a custom import hook loads whatever it is given; a native `foo.cpython-311-x86_64-linux-gnu.so` next to `foo.py` still wins; `python3 -E`, `-I`, or a command that unsets the variables ignores them; and the `/workspace`, `/tmp` and `/home/exec` subtrees of the prefix are writable by uid 10001, so a pyc a command writes there (`py_compile`, or an extraction that follows absolute or `../` paths) is loaded for the matching source. `ARTEX_SANDBOX=off` gets none of this, and a worker adopted at runner restart keeps its old environment until it is recreated. `PYTHONSAFEPATH` is not set, because a script in `/workspace` must still import the modules next to it. ### Added