Skip to content

fix(sandbox): do not load a workspace __pycache__ in the worker (#767) - #777

Open
sresarehumantoo wants to merge 8 commits into
BaaRai:mainfrom
sresarehumantoo:harden/import-shadowing
Open

sresarehumantoo wants to merge 8 commits into
BaaRai:mainfrom
sresarehumantoo:harden/import-shadowing

Conversation

@sresarehumantoo

@sresarehumantoo sresarehumantoo commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

#767, the .pyc half of #771. A target tree can ship __pycache__/<mod>.cpython-311.pyc next to a .py that reads clean. If the pyc header carries the source's mtime and size, or the pyc is hash-based (unchecked, or checked and built with the source's own hash), import <mod> runs the shipped bytecode and never compiles the reviewed source. This is filesystem behavior, so it is not visible to an intercept rule on command text.

Change

  • artex-runner creates the worker with PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache and PYTHONDONTWRITEBYTECODE=1. Python then looks for bytecode only under the prefix, never in an in-tree __pycache__, and does not write any.
  • Dockerfile.worker runs compileall into that prefix at build time. The prefix sits on the read-only rootfs, so the worker cannot plant bytecode there. Without the prebuilt tree every run recompiles the stdlib: a 13-module import set went from 212 ms to 994 ms per start with an empty prefix, and is 179 ms with the prebuilt one. The tree adds 13 MB to the image.
  • The prefix mirrors absolute source paths, so py_compile of /workspace/x.py writes <prefix>/workspace/x.cpython-311.pyc. With the whole prefix read-only that failed ([Errno 30] Read-only file system, exit 1; main exits 0). The runner now mounts small tmpfs subtrees at <prefix>/workspace, <prefix>/tmp and <prefix>/home/exec (noexec, nosuid, 64m, uid 10001, mode 0700). py_compile and compileall exit 0 again, and the stdlib entries under <prefix>/usr stay on the read-only rootfs: touch <prefix>/usr/... and mkdir <prefix>/workspace/../usr/x both fail with EROFS.
  • Imports do read a pyc that a command compiled there, as Python normally does with its own cache. A file from the target tree gets there only if a command writes it, for example py_compile or an archive extraction that honors absolute or ../ paths (Python tarfile on this image, tar -P). This is an accepted limit: keeping the subtrees read-only would make py_compile on a workspace file fail with EROFS.
  • FilterPanelEnv reserves PYTHONPYCACHEPREFIX and PYTHONDONTWRITEBYTECODE next to PATH and the proxy variables, so a panel process env cannot override them per exec.
  • The env is set by the runner, not by ENV in the image, so a custom ARTEX_WORKER_IMAGE gets it too. On an image without the prebuilt tree it is slower, not open.
  • The worker env also sets PYTHONNOUSERSITE=1, so a .pth in the user site under /home/exec does not run at interpreter start. FilterPanelEnv reserves it too.
  • PYTHONSAFEPATH is not set. It stops a script in /workspace from importing the module next to it (measured below), which is the open question on Track B: reverse injection, target artifacts must stay data (pickle, .pyc, git hooks, SDKs) #767.

Measured

Python 3.11.2 from Dockerfile.worker (bookworm), worker shape: read-only rootfs, uid 10001, cap-drop ALL, tmpfs /tmp and /home/exec. Each vector is cd <dir> && python3 main.py, where main.py is import <mod> and <mod>.py prints GOOD; the planted bytecode prints EVIL.

Vector No env (main) DONTWRITEBYTECODE only This PR PYTHONSAFEPATH=1
a. __pycache__ timestamp pyc, header forged to the .py mtime and size EVIL EVIL GOOD import fails
a. same, python3 -m mod EVIL EVIL GOOD import fails
b. __pycache__ unchecked hash-based pyc EVIL EVIL GOOD import fails
c. __pycache__ checked hash-based pyc, wrong hash GOOD GOOD GOOD import fails
c2. __pycache__ checked hash-based pyc built with the correct source hash EVIL not run GOOD not run
d. sourceless mod.pyc, no mod.py EVIL EVIL EVIL import fails
e. legacy mod.pyc next to mod.py GOOD GOOD GOOD import fails
g. package __init__ via __pycache__ EVIL EVIL GOOD import fails
h. plain sibling import, no bytecode GOOD GOOD GOOD import fails
f. evil.pth next to the script not processed not processed not processed not processed
new pyc written in /workspace 3 0 0 0

--check-hash-based-pycs always closes only (b), not (c2) (EVIL on main with the flag), and has no environment variable. PYTHONPYCACHEPREFIX=/dev/null closes the same rows as this PR but costs the stdlib recompile.

Bypasses of this PR, all measured:

  • python3 -E main.py: EVIL. -E ignores every PYTHON* variable.
  • python3 -I with sys.path.insert(0, <script dir>) in the script: EVIL. -I implies -E.
  • env -u PYTHONPYCACHEPREFIX python3 main.py: EVIL. The variable is a default, not a boundary against the command itself.

A .pth only runs from a site directory. In /workspace it runs only through site.addsitedir(...) (#773 asks on that). The user site under /home/exec/.local is off with PYTHONNOUSERSITE=1; python3 -E turns it back on.

Repro, after docker build -f Dockerfile.worker -t artex-worker:local .:

docker run --rm --read-only --tmpfs /workspace:rw,uid=10001,gid=10001 \
  -e PYTHONPYCACHEPREFIX=/usr/local/lib/artex-pycache -e PYTHONDONTWRITEBYTECODE=1 \
  artex-worker:local bash -c '
cd /workspace
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\"); os.makedirs(\"__pycache__\", exist_ok=True)
code = compile(\"print(\\\"EVIL\\\")\", os.path.abspath(\"mod.py\"), \"exec\")
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   # EVIL: env ignored
python3 main.py      # GOOD
'

Not covered

  • Sourceless mod.pyc (row d). No interpreter variable turns off SourcelessFileLoader.
  • -E, -I plus a manual sys.path insert, and a command that unsets the variables. -E ignores PYTHONNOUSERSITE too, so it also brings back a .pth in the user site (-I does not, since it implies -s).
  • A native extension next to the source. A workspace mod.cpython-311-x86_64-linux-gnu.so beside mod.py wins over the source and runs native code (EVIL_SO on main and on this branch). Extensions come first in the FileFinder loader order, and /workspace is a bind mount that allows exec. Closing it needs /workspace noexec (the goal of fix(sandbox): add noexec,nosuid to /workspace bind mount #770, which docker refused as a bind option) or a loader that refuses extensions outside system paths.
  • A source swap after compiling. If a command runs py_compile on one version of mod.py and an extraction that keeps mtime then replaces it with another of the same size, the cached bytecode of the first version runs. That is normal timestamp-pyc behavior.
  • A .zip or .egg on sys.path (via PYTHONPATH, sys.path.insert or a .pth): zipimport runs a sourceless pyc, or a forged pyc next to its source, from the archive.
  • An explicit importlib.machinery.SourcelessFileLoader or a custom import hook. That is the command choosing to run bytecode, the same as exec.
  • The /workspace, /tmp and /home/exec subtrees of the prefix are writable by uid 10001, so a pyc written there is loaded (see Change).
  • ARTEX_SANDBOX=off. The env exists only in the worker container, so the panel-local path gets no protection.
  • Workers adopted by Recover() after a runner upgrade. Recover reuses the running container by label, so a worker created before this change keeps its old env and mounts until it is removed and recreated.

A follow-up I tested for the sourceless pyc and the -E bypass: a .pth in /usr/lib/python3/dist-packages on the read-only rootfs that sets sys.pycache_prefix and sys.dont_write_bytecode, and replaces the FileFinder path hook with one that has only the extension and source loaders. It does not touch the extension row. With it, rows a, b and g are GOOD under -E too, and row d is ModuleNotFoundError with and without -E. A workspace sitecustomize.py on PYTHONPATH does not displace it. python3 -S still skips it (EVIL). The code has to sit inline in the .pth line, not in an imported module, or a module of the same name on PYTHONPATH shadows it. It changes interpreter startup for every Python process in the worker, so I kept it out of this PR.

Overlap with #773

None in behavior. #773 matches command text (PYTHONPATH=, sitecustomize, site.addsitedir() and strips .git/config; this PR changes where Python reads bytecode. Textually both edit the worker Env list in sandbox/docker.go (this PR also adds to its Tmpfs map, which #773 does not touch) and Dockerfile.worker, so whichever lands second rebases the two env lines into workerEnv. If #773 lands, artex-exec-wrap is where a per-command check would go: it already runs before every command, so it could write a runtime_incident for a sourceless *.pyc or a .pth under the cwd, the same way neutralizeCwdGit does. That is detection; the .pth guard above is the enforcement.

Tests

go test ./sandbox/ -run 'TestDockerBackendWorkerPythonBytecodeEnv|TestFilterPanelEnvKeepsWorkerPythonBytecodeEnv'
ARTEX_SANDBOX_DOCKER_TEST=1 go test ./sandbox/ -run TestDockerSandboxE2EContainment

The second needs artex-worker:local and artex-egress-proxy:local.

The live test plants a forged __pycache__ pyc, checks that python3 -E loads it (the fixture works) and python3 does not, that sys.pycache_prefix is set, that the stdlib cache exists in the image, that py_compile on a workspace file exits 0, and that the stdlib part of the prefix is not writable. With #764 on main, the test passes end to end.

Refs #767

@sresarehumantoo

Copy link
Copy Markdown
Contributor Author

The step 5 failure in the live e2e (Delete cannot remove the task network while the worker is attached) is fixed by #778. With both applied, TestDockerSandboxE2EContainment passes end to end.

@thecorporatetractor

Copy link
Copy Markdown
Contributor

Built Dockerfile.worker from this branch and ran ARTEX_SANDBOX_DOCKER_TEST=1 go test ./sandbox/ -run TestDockerSandboxE2EContainment against it (Docker 27.5.1, with the #778 Delete fix applied locally so cleanup does not fail). The new pyc block passes: CONTROL=EVIL under -E, GOOD without it, PREFIX=/usr/local/lib/artex-pycache, STDLIB_CACHED=True, PYC_COUNT=1, PY_COMPILE=ok, STDLIB_CACHE_RO. go test -race ./sandbox/ passes too. The CHANGELOG entry keeps CRLF.

The branch currently conflicts with main in CHANGELOG.md only, so it needs a rebase.

@BaaRai BaaRai left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The worker environment change blocks the documented shadowing cases: timestamp and hash-based pyc with a matching source, symlinked __pycache__, a pyc next to its source, PYTHONPATH, sys.path.insert, python -B, subpackages and namespace packages. That part is right.

Four gaps remain:

  • a pyc inside a .zip or .egg is still executed through zipimport;
  • a sourceless pyc in the workspace is executed;
  • an explicit importlib SourcelessFileLoader or a custom import hook bypasses the prefix;
  • python -E ignores PYTHONPYCACHEPREFIX (documented), and a .pth in user site-packages is not covered (HOME is a writable tmpfs and PYTHONNOUSERSITE is not set).

The prefix itself is mounted writable for uid 10001, so a pyc forged under <prefix>/... is still loaded.

Please either close these gaps or state them explicitly as accepted limits in the PR body and CHANGELOG. The branch also conflicts with main and needs a rebase before it can be reviewed again.

@sresarehumantoo
sresarehumantoo force-pushed the harden/import-shadowing branch from 2b35e6f to d58255d Compare December 1, 2026 22:19
@sresarehumantoo

Copy link
Copy Markdown
Contributor Author

Rebased on 8f91643. The only conflict was CHANGELOG.md. With #764 on main, TestDockerSandboxE2EContainment passes end to end on this branch alone, so the step 5 note in the PR body no longer applies. My earlier comment credited #778 for that; it was #764.

I reproduced each gap on the worker image (uid 10001, read-only rootfs, this branch's env and tmpfs):

  • zip/egg: with PYTHONPATH=/workspace/z.zip, a forged pyc next to its source in the archive and a sourceless pyc both run. A zip that is not on sys.path is not imported.
  • sourceless mod.pyc in the cwd: runs (already listed).
  • SourcelessFileLoader(...).load_module(): runs.
  • python3 -E: runs the forged __pycache__ pyc (already listed).
  • user-site .pth: site.ENABLE_USER_SITE is True and a .pth in /home/exec/.local/lib/python3.11/site-packages runs on every start.
  • prefix subtree: a timestamp pyc written by uid 10001 at <prefix>/workspace/w.cpython-311.pyc is loaded for /workspace/w.py.

Changes:

  • 82045a0 sets PYTHONNOUSERSITE=1 in the worker env and reserves it in FilterPanelEnv with the other two. The worker image has no pip, so nothing installs into the user site. The live test now plants a user-site .pth, checks that python3 -E runs it (fixture is live) and that python3 does not.
  • d58255d lists the rest as accepted limits in the CHANGELOG: sourceless pyc, zipimport, explicit loaders or import hooks, a native extension next to the source, -E/-I/unset, and the writable prefix subtrees.

On the writable subtrees: dropping them makes python3 -m py_compile /workspace/x.py fail with EROFS, which exits 0 on main, so I kept them and documented the limit. A pyc only lands there if a command writes it (py_compile, or an extraction that follows absolute or ../ paths). If you would rather close it, the option I see is artex-exec-wrap emptying the three subtrees before each command, so bytecode never outlives the command that compiled it. That changes the wrapper and the image, so I kept it out.

An explicit SourcelessFileLoader or import hook is the command choosing to run bytecode, the same as exec, so I do not plan to chase it. The zip and sourceless cases are what the .pth guard in the PR body would close (drop the sourceless loader from the FileFinder hook; zipimport would need zipimporter removed from sys.path_hooks too). That changes every Python start in the worker, so I would send it as a separate PR if you want it.

Tests: go build ./..., go vet ./..., go test -race ./sandbox/, and the live e2e against images built from this branch (Docker 29.10.1) pass.

PR body updated: the "Not covered" list matches the CHANGELOG, and the step 5 note is gone.

@thecorporatetractor

Copy link
Copy Markdown
Contributor

My earlier review on this PR checked only the forged __pycache__ case and missed the gaps in BaaRai's review. Thanks for working through them.

I checked d58255d myself. I built Dockerfile.worker from it and ran it with the runner's worker shape: uid 10001, read-only rootfs, cap-drop ALL, this branch's env, and the three prefix tmpfs mounts. The fixtures print EVIL, and the reviewed sources print GOOD.

Check Output
user-site .pth, python3 -c pass nothing printed; site.ENABLE_USER_SITE=False, no_user_site=1
same .pth, python3 -E EVIL_USERPTH
same .pth, python3 -I not run (-I implies -s)
forged __pycache__ pyc, plain python3 GOOD_SHADOW
same, -E / -I + sys.path.insert / env -u PYTHONPYCACHEPREFIX EVIL_SHADOW each
sourceless srcless.pyc (-c, a script, -E, -I) EVIL_SRCLESS
.zip or .egg on sys.path or PYTHONPATH, sourceless pyc / pyc next to its .py EVIL_ZIP_SRCLESS / EVIL_ZIP_SHADOW
zip that is not on sys.path ModuleNotFoundError
SourcelessFileLoader(...).exec_module / .load_module() / custom path hook EVIL_SRCLESS
pyc written by uid 10001 at <prefix>/workspace/pshadow.cpython-311.pyc EVIL_PREFIX
mod.cpython-311-x86_64-linux-gnu.so next to mod.py the .so is loaded first (ImportError: ... file too short for a junk file)
py_compile and compileall on workspace files exit 0; no new .pyc anywhere on the rootfs or in /workspace
stdlib imports, sibling import from a workspace script, package + python3 -m pk.sub.m, zipapp with .py only OK; nothing on stderr at startup

All of these match the CHANGELOG and the PR body. The CHANGELOG diff against main adds one line and removes none. The added line ends in \r, and file still reports CRLF.

One small wording point: python3 -E also brings back the user-site .pth (row 2). The CHANGELOG covers this, since -E ignores all three variables, but the body's -E bullet only mentions "the variable". Naming PYTHONNOUSERSITE there would make it explicit.

Tests on d58255d: go vet ./sandbox/ and go test -race ./sandbox/ pass. With worker and proxy images built from this head, ARTEX_SANDBOX_DOCKER_TEST=1 go test ./sandbox/ -run TestDockerSandboxE2EContainment passes (CONTROL=EVIL, GOOD, CONTROL_USERSITE=EVIL_USERSITE, USERSITE_SKIPPED, PY_COMPILE=ok, STDLIB_CACHE_RO) and leaves no containers or networks behind. Docker was 27.5.1.

This looks right to us.

On the guard you mentioned as a possible follow-up: while checking this I prototyped one as a root-owned module loaded from a system .pth. It keeps the prefix under -E/-I/env -u, drops the sourceless loader from FileFinder, stops zipimport from loading .pyc, and only trusts the read-only stdlib part of the prefix. In the same worker it turns the zip, sourceless, -E shadow and <prefix>/workspace rows above into GOOD/ModuleNotFoundError. python3 -S, explicit loaders and -E + user-site stay open. It's on thecorporatetractor/ARTEX@ec93686 if any of it is useful for that PR.

@sresarehumantoo

Copy link
Copy Markdown
Contributor Author

Thanks for the independent run, especially the -I and zipapp rows. I updated the -E bullet under "Not covered" to name PYTHONNOUSERSITE and the user-site .pth, and to note that -I still skips it.

The guard on ec93686 looks like the right shape for the follow-up. I'll go through it once #777 settles and build the separate PR on it if it holds up, with credit to you.

@sresarehumantoo

Copy link
Copy Markdown
Contributor Author

I ran ec93686 in Docker with the worker shape. On the system interpreter it does what you said: the e2e passes, and the -E/-I/env -u, prefix, sourceless and zip/egg cases come out GOOD or ModuleNotFoundError. Startup cost was about 0.3 ms.

I found two holes.

A venv doesn't load the guard. With python3 -m venv --without-pip /tmp/v, or a venv shipped in the target tree, the system dist-packages are never read, so the .pth doesn't run. /tmp/v/bin/python -E then loads the forged __pycache__, the prefix pyc, the sourceless pyc and the zip pyc. I appended the same exec line to /etc/python3.11/sitecustomize.py (the stdlib copy symlinks to it) and that blocked all four, under -E and -I too. Running the guard twice did no harm. I'd keep the .pth alongside it, since a sitecustomize.py on PYTHONPATH replaces the sitecustomize copy but can't touch the .pth.

importlib.util.spec_from_file_location and imp.load_source also get around it. They construct a plain SourceFileLoader, which happily reads a forged pyc from <prefix>/workspace. I tried patching the classes instead of the path hook: wrap SourceFileLoader.get_data, and have SourcelessFileLoader.get_code raise ImportError. That stopped both, plus the explicit SourcelessFileLoader case, and the stdlib still came from the cache. The zip filter still has to stay.

A few minor ones:

If you'd rather hand it off, I can build the follow-up on your branch once #777 settles and keep your commits.

@sresarehumantoo

Copy link
Copy Markdown
Contributor Author

@BaaRai the four gaps from your review are now either closed or listed as accepted limits in the PR body and CHANGELOG. PYTHONNOUSERSITE=1 closes the user-site .pth. Zip/egg, sourceless pyc, explicit loaders, -E/-I, a native extension next to the source, and the writable prefix subtrees are documented limits. The branch is rebased on main (8f91643), CI is green, and thecorporatetractor verified d58255d independently. Ready for another look.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants