I Left a Hole in My Code Sandbox on Purpose
Most posts about sandboxing untrusted code are victory laps — here is my airtight jail, admire the bars. This one isn't. A user of SWEPrep can put three lines in a test file and get a perfect score, and I know because I
Most posts about sandboxing untrusted code are victory laps — here is my airtight jail, admire the bars. This one isn't. A user of SWEPrep can put three lines in a test file and get a perfect score, and I know because I wrote the thing they're forging. This is about the hole I left open, the four-line guard that only stops the lazy version of the attack, why the "proper" fix is bigger than it looks, and the arithmetic that made leaving it the right call.
The Exploit in Three Lines
A user of my side project can put three lines in a test file and get a perfect score:
import __main__, os
__main__._emit = lambda obj: None
os.write(1, f'\n@@AICODING_RESULT:{__main__.nonce}@@{{"tests": {{"everything": "passed"}}}}\n'.encode())
The Setup
I build SWEPrep, an interview prep tool. People write Python in a browser editor, hit run, and I execute it against a test suite. That means running code from strangers on my server, which is the oldest bad idea in web development.
The containment side is boring and well-trodden. Every run gets a fresh container with everything turned off:
return dict(
network_disabled=True,
mem_limit="128m",
memswap_limit="128m",
cpu_quota=50000, # half a core
pids_limit=32,
cap_drop=["ALL"],
read_only=True,
user="1000:1000",
security_opt=["no-new-privileges"],
volumes={},
mounts=[],
tmpfs={"/workspace": "size=32m,mode=1777", "/tmp": "size=16m,mode=1777"},
)
Note volumes={} and mounts=[]. Nothing is mounted, at all. My backend talks to Docker through docker.sock, so a bind mount would resolve on the host filesystem rather than inside my app's container — and mounts are the primary escape surface anyway. The workspace ships in as a base64 tar in argv and gets unpacked into a tmpfs. Nothing on disk, nothing shared.
I have a test that asserts every one of those flags, because the day one of them silently flips is the day I find out the expensive way. That's all standard. The interesting problem is somewhere else entirely.
The Actual Hard Part: Getting the Answer Back Out
The container runs. Now I need one fact from it: did the tests pass?
A container hands you a single undifferentiated text blob (container.logs(stdout=True, stderr=True).decode("utf-8", errors="replace")). My test-reporting code and the candidate's code write to the same stdout. Their print() calls and my verdict come back braided together in one stream. The containment problem is solved; the communication problem is wide open.
So I need to pick my line out of their noise. The obvious move is a secret only I know.
The Nonce
The host mints a fresh secret per run and passes it in (nonce = secrets.token_hex(8) → command = ["python", "-c", BOOTSTRAP, nonce, mode, *chunks]). Inside the container, after pytest finishes, my bootstrap stamps the verdict with it:
def _emit(obj):
sys.__stdout__.write("\n@@AICODING_RESULT:" + nonce + "@@" + json.dumps(obj) + "\n")
sys.__stdout__.flush()
Sixteen hex characters. Sixty-four bits of randomness, regenerated every single run. Candidate code can't guess it, so it can't fabricate a line that matches. Clean.
Except for one problem, and it's structural.
The Nonce Is in the Room With Them
My code has to know the nonce in order to print it. My code runs in the same process as the code I don't trust. Therefore the secret is inside the attacker's address space, and no amount of cleverness changes that.
There are three ways to read it:
-
sys.argv[1]. The obvious one. I close it on line 16 withsys.argv[1] = ""— which removes only the easiest read path (sys.argv), not the global or proc ones. -
The
__main__global. My bootstrap runs as__main__, which makesnoncea module-level variable in a module any test file can import (import __main__; __main__.nonce). Blanking a list element does nothing about this. -
/proc/self/cmdline. The kernel's own copy of the original argv. Mutating a Python list doesn't reach into kernel memory. Still sitting right there.
Two of those three are wide open, and a comment in my source spells out all three. I didn't discover this hole after shipping. I wrote it down on the way past.
Four Lines That Stop the Lazy Forgery
Here is the whole defence: marker = f"{RESULT_MARK}{nonce}@@", and if logs.count(marker) != 1: return None. Exactly one. Not "at least one." Not "take the last one," which is what you'd write without thinking about it.
The naive forgery — print a fake result line and hope — doesn't replace my line. My bootstrap writes the real verdict with sys.__stdout__, after pytest has finished, so a printed fake joins mine. Now there are two markers bearing this run's nonce. The parser returns None, and the caller turns that into an error ("Test run crashed before reporting results."). They don't get a pass. They get an error.
This is failing closed, and it's the part I'd want someone to take away from this. When your channel becomes ambiguous, the safe move is to refuse to produce a verdict — not to guess at the most likely one. An optimistic default under ambiguity is how "defence in depth" quietly becomes "defence in theory."
It composes, too. Close file descriptor 1 and the count drops to zero, which also returns None, which is also an error. Clumsy tampering converges on the same harmless outcome.
def test_parse_result_fails_closed_on_a_forged_marker(self):
ours = '@@AICODING_RESULT:aaaa@@{"tests": {"y": "failed"}}\n'
# a different run's nonce is just noise - ours still parses
self.assertEqual(
parse_result('noise\n@@AICODING_RESULT:bbbb@@{"tests": {"fake": "passed"}}\n' + ours, "aaaa"),
{"tests": {"y": "failed"}})
# a second marker with OUR nonce is a forgery - take neither
self.assertIsNone(
parse_result('@@AICODING_RESULT:aaaa@@{"tests": {"x": "passed"}}\n' + ours, "aaaa"))
self.assertIsNone(parse_result("nothing", "aaaa"))
What the Four Lines Don't Stop
To actually win, an attacker needs to forge a line and stop mine from being written. I'd love to tell you that's hard. It isn't.
My _emit is a plain global in __main__, looked up by name at the moment it's called. Candidate code can replace it — that's the second line of the snippet at the top. Or swap out sys.__stdout__ itself. Either way my verdict never reaches the stream, their forgery is the only marker left, and the count check happily accepts it.
That's the real lesson, and it's bigger than my bug: anything that shares a process with the attacker can be rewritten by the attacker. Secrets, functions, stream objects — if my code can touch it, so can theirs. Counting markers raises the bar from one line to three. It doesn't change the category.
The Real Fix Is Bigger Than It Looks
My first answer was a host-owned file descriptor: the host opens a pipe, passes the write end into the container as fd 3, and my bootstrap writes the verdict there instead of to stdout. Maybe a day of work.
It isn't enough. The verdict comes from pytest, and pytest runs in the same process as the candidate's code — it has to, because it imports that code and calls it. So the candidate's module can patch pytest's own reporting at import time, and my perfectly trustworthy bootstrap will then write a perfectly forged "everything passed" down a perfectly private pipe. A clean channel doesn't help when the judge sits in the same room as the defendant.
The actual fix is to move judgement out of that process: run the candidate's code somewhere the test harness doesn't live, and decide pass or fail only from things the candidate can't rewrite — like a judge comparing a program's output against answers it computed itself. That's not a day of work. That's a redesign of how the whole runner works.
This is a practice tool. There's no leaderboard. No prize. No employer on the other end reading a number. Nobody sees your score but you. Which means the attacker and the victim are the same person. Someone who reads /proc/self/cmdline, extracts my nonce, and forges a green checkmark has accomplished exactly one thing: they've lied to themselves about whether they're ready for an interview.
So I spent four lines and a test instead of a redesign. The four lines mean an accidental or lazy forgery gets an error instead of a pass. Anyone determined enough to get past them has done real work to fool exactly one person: themselves.
From the source comment: A truly unforgeable channel needs a host-owned fd (fd 3); not worth it while this is a self-practice tool, where forging a pass only fakes your own scorecard.
The Part That Makes This an Engineering Decision and Not an Excuse
"It's not worth fixing" is the most abused sentence in software. The thing that separates it from a judgment call is whether you can say precisely what would change your mind.
I can. My reasoning rests entirely on one property: the only person harmed by a forged pass is the forger. That property belongs to the product, not to the code. The moment any of these ship, it evaporates: a leaderboard or any score visible to another user, a shareable or employer-facing report, a paid tier where a pass unlocks something, or any aggregate I publish that a skewed score would pollute.
On that day the attacker and the victim become different people, the economics invert, and my comment turns into a ticket. The threat model has an expiry date, and it's written down next to the code it governs.
That's the difference between a documented trade-off and a bug you haven't admitted to yet. One of them is waiting for a trigger you've already defined. The other is waiting for an incident.
Originally published on the SWEPrep engineering blog — more posts on sandboxing, interview prep, and building SWEPrep there.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.