diff --git a/CHANGELOG.md b/CHANGELOG.md index e46a8e554..4c158a7df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +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. 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 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..3d633dbac 100644 --- a/sandbox/docker.go +++ b/sandbox/docker.go @@ -562,6 +562,9 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma "HOME=/home/exec", "LANG=C.UTF-8", "TERM=xterm", + "PYTHONPYCACHEPREFIX=" + WorkerPycachePrefix, + "PYTHONDONTWRITEBYTECODE=1", + "PYTHONNOUSERSITE=1", "HTTP_PROXY=" + proxyURL, "HTTPS_PROXY=" + proxyURL, "ALL_PROXY=" + socksURL, @@ -583,9 +586,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 18b8920e9..eb037922d 100644 --- a/sandbox/docker_e2e_test.go +++ b/sandbox/docker_e2e_test.go @@ -175,6 +175,53 @@ 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. + // 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 + 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)" + 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", + 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", "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.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, // 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 diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go index 2b1da01e2..4d2ec9188 100644 --- a/sandbox/sandbox_test.go +++ b/sandbox/sandbox_test.go @@ -43,6 +43,18 @@ func TestValidateEnvRejectsForbiddenPatternsAndOversizedValues(t *testing.T) { } } +func TestFilterPanelEnvKeepsWorkerPythonBytecodeEnv(t *testing.T) { + 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) + } +} + type fakeBackend struct { mu sync.Mutex pingErr error @@ -515,3 +527,102 @@ 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 + var workerTmpfs map[string]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 + 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 + } + _ = 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 + tmpfs := workerTmpfs + mu.Unlock() + for _, want := range []string{ + "PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache", + "PYTHONDONTWRITEBYTECODE=1", + "PYTHONNOUSERSITE=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) + } + } + // 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) + } +} 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. diff --git a/sandbox/validate.go b/sandbox/validate.go index 9061b7702..fd4c1f4f9 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", "PYTHONNOUSERSITE": continue } out[k] = v