Skip to content

v0.0.7: fix critical RCE via unsafe result deserialization, plus sandbox hardening - #6

Merged
johanbeytell1 merged 14 commits into
mainfrom
arena/390295bd-codesafe
Nov 28, 2026
Merged

johanbeytell1 merged 14 commits into
mainfrom
arena/390295bd-codesafe

Conversation

@johanbeytell1

@johanbeytell1 johanbeytell1 commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes a critical remote code execution vulnerability reported by Juan Lucas Armendares (Sunplace Solutions), plus five related issues found while validating it.

This is a distinct root cause from CVE-2026-133467 (the __builtins__['exec'] bypass fixed in 0.0.5). The sandbox works as intended; the flaw is on the return path.

The reported vulnerability

In 0.0.6 the child serializes its result with cloudpickle and the parent calls cloudpickle.loads() on it — with full builtins, outside the sandbox it just enforced. _check_ast() only guards what runs in the child; it never inspects the value sent back.

An expression can return an object whose __reduce__ chain runs arbitrary code the moment the parent unpickles it, using only AST nodes the checker allows (type, list, zip, range, iter, lambda). Verified against the published 0.0.6 wheel: the marker file is written by the parent process id.

CVSS 3.1: 9.8 — AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H, default configuration.

During verification I found the reporter's literal payload doesn't fire: his CODE is a statement sequence (import os; open(...)), which eval rejects. The gadget is built correctly and then raises SyntaxError. With an expression-shaped payload it fires on cloudpickle 2.2.0, 3.0.0 and 3.1.3. Severity and root cause are unchanged; the advisory should use the working form.

Fix

The result boundary no longer involves pickle at all:

  • The child encodes the result as plain primitives over a multiprocessing.Pipe; the parent rebuilds it with a non-executable decoder.
  • Results are data-only: None, bool, int, float, complex, str, bytes, Decimal, Fraction. Containers are opt-in via the new allow_objects=True.
  • Lambdas, classes, modules, generators and user types now raise RuntimeError instead of being serialized. This removes a 0.0.6 feature — it was also the attack surface.
  • Exceptions cross as (builtin type name, message); SystemExit/KeyboardInterrupt/GeneratorExit arrive as catchable RuntimeError; user-defined exception types are never reconstructed.
  • Bounded results (depth 100, 1M nodes, 1 MiB of str/bytes) and a per-call int→str digit cap.
  • Reader thread drains the pipe, so a result larger than the OS pipe buffer can't deadlock the parent.
  • cloudpickle dependency removed.

Also fixed (found during the audit)

  1. Format-string attribute traversal — '{0.__init__.__globals__[SECRET]}'.format(obj) reads dunders and mapping keys the checker never sees (5.9).
  2. Name-shadowing call bypass — (len := f)(), [f() for len in [..]], (lambda len: len())(f) called non-allowlisted callables in the default config.
  3. Callable indirection via builtins — sorted(key=f), iter(f, None).
  4. __builtins__ readable/mutable from expressions.
  5. SystemExit(1) terminated the host process; KeyboardInterrupt/GeneratorExit escaped except Exception.
  6. file_access=False bypass by re-introducing open via allowed_builtins.

Verification

  • 111/111 tests pass on Python 3.8-3.12 on Ubuntu, Windows and macOS (TestResultBoundaryV007 holds the new regressions).
  • 384-variant gadget fuzz, plus format-string and shadowing sweeps: zero escapes, zero legitimate-operation regressions.
  • No leaked processes, threads or file descriptors (200 consecutive calls, plus timeout paths).
  • Verified under both fork and a forcibly pinned spawn start method.
  • Wheel builds and installs cleanly in a fresh venv with cryptography only.

Breaking changes

Returning lambdas or dynamic classes no longer works, and containers require allow_objects=True. Documented in the README with a migration note. This is deliberate: that capability was the vulnerability.

Release

Bumps to 0.0.7 in pyproject.toml and __version__, ready for the tag → PyPI workflow.


Additional defects found and fixed while getting CI green

The first CI run was red on three jobs. Each failure turned out to be a real
defect rather than a flaky runner, and each is fixed with a regression test:

1. safe_eval leaked a MemoryError on Python 3.8 (availability)

safe_eval("[" * 150 + "]" * 150) reached ast.parse, where CPython 3.8
overflows the C parser stack and raises a bare MemoryError
(s_push: parser stack overflow) out of the library. A caller got an unrelated
internal error instead of a security rejection, and it could be triggered by
untrusted input. _reject_excessive_nesting now scans the expression before
parsing and rejects more than 64 levels of bracket nesting with
UnsafeExpressionError; brackets inside string literals are ignored. Refusal
costs ~0.05 ms even at 20,000 levels. ast.parse is additionally wrapped so any
MemoryError/RecursionError that still escapes becomes a rejected expression.

2. A crashed child was reported as a 5-second timeout

When the evaluation child died before sending a result, the parent waited out
the whole timeout and then raised EvaluationTimeoutError. That stalled the
caller and pointed at the wrong cause. _wait_for_outcome now waits for the
result, the child's exit or the timeout in short slices; a child that exits
non-zero on its own is reported as a RuntimeError naming the likely cause.
The parent's own terminate() (exit code -SIGTERM) is excluded, so genuine
timeouts are still timeouts. Process.exitcode is used rather than
is_alive(), because is_alive() joins internally and blocks on a
bootstrapping spawned child.

3. Unpicklable allowed_vars leaked a multiprocessing error

On spawn platforms the argument pickling happens in the caller, so a lambda or
locally defined class in allowed_vars surfaced as a raw AttributeError from
multiprocessing. It is now a clear RuntimeError explaining that these
dictionaries need module-level, importable objects on spawn platforms.

Note on the spawn pickle sink

Under spawn, Process.start() pickles the process arguments in the caller, so
objects in allowed_vars/allowed_builtins are reduced before any sandbox
exists. This is not reachable from the expression - those dictionaries are
supplied by the host, and an expression cannot add to them - but it is a
pickle-trust requirement worth knowing. Where fork is available and the host
has not pinned a start method, CodeSafe now selects fork so nothing is pickled
on the way in. It is documented in the safe_eval docstring for Windows and for
hosts that pin spawn.


All 111 tests now pass on Python 3.8, 3.9, 3.10, 3.11 and 3.12 on Ubuntu, on
Windows, and on macOS, and under a locally forced spawn start method.

johanbeytell1 and others added 14 commits November 28, 2026 07:30
Reported by Juan Lucas Armendares (Sunplace Solutions): in 0.0.6 the child
serialized its evaluation result with cloudpickle and the parent called
cloudpickle.loads() on it with full builtins. The AST checker only guarded
what ran inside the sandboxed child, never the value sent back, so an
expression could return a __reduce__ gadget that executed arbitrary code in
the calling process. Distinct root cause from CVE-2026-133467.

Result boundary
- No pickle on the evaluation path at all: the child encodes the result as
  plain primitives over a multiprocessing.Pipe and the parent rebuilds it with
  a non-executable decoder.
- Results are plain data (None, bool, int, float, complex, str, bytes,
  Decimal, Fraction); containers are opt-in via the new allow_objects flag.
  Lambdas, classes, modules, generators and user types now raise RuntimeError
  instead of being serialized.
- Exceptions cross as (builtin type name, message); SystemExit /
  KeyboardInterrupt / GeneratorExit arrive as catchable RuntimeError and
  user-defined exception types are never reconstructed in the parent.
- Bounded results (depth, node count, byte size) and a per-call int->str
  digit cap keep a returned value from burning CPU in the caller.
- The Pipe is drained by a reader thread so a result larger than the OS pipe
  buffer cannot deadlock the parent; timeout latency tightened.
- cloudpickle dependency removed.

AST checker hardening (same audit)
- Format/format_map templates that name attributes or keys are rejected
  ('{0.__init__.__globals__}'.format(obj) is an invisible attribute read).
- Rebound safe-builtin names may only be called when explicitly allowlisted
  ((len := f)(), [f() for len in [..]], (lambda len: len())(f)).
- Callables passed to builtins that invoke them (sorted(key=...), iter(f, None))
  follow the same allowlist; allowed_vars entries are data, not call grants.
- __builtins__ and the other reserved names are never resolvable or rebindable.
- file_access/network_access are enforced after allowed_builtins is merged, so
  re-introducing open through allowed_builtins no longer bypasses the flag.

Tests: 108 passing (29 new in TestResultBoundaryV007 plus updated result-policy
assertions). Docs, SECURITY.md and the advisory draft updated for 0.0.7.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
- 0.0.1-0.0.4 upgrade guidance now targets 0.0.7 (0.0.6 is the affected release)
- 0.0.5 'upgrade now' guidance targets 0.0.7
- Affected-version note: 0.0.1-0.0.5 are not affected by the deserialization
  bug; the reported gadget cannot survive stdlib pickle used by their Queue

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…kle sink

Three issues surfaced in CI (3.8 ubuntu, 3.12 windows/macos):

1. Fraction encoding used int.__int__, which only exists on 3.11+. Replaced
   with int() plus an exact-type check, so Decimal/Fraction round-trip on 3.8+.
2. test_result_is_never_pickled asserted assertNotIsInstance (3.9+). Replaced
   with isinstance on the captured exception.
3. The result-boundary tests defined helper classes/functions inside test
   methods, which cannot be pickled to a spawned child, so every spawn-platform
   test errored before exercising anything. Moved them to module level.

While fixing (3) I found a real sink on the spawn path: Process.start() pickles
the whole Process object - arguments included - in the CALLER, so everything in
allowed_vars/allowed_builtins is reduced with pickle before any sandbox exists.
An object with a hostile __reduce__ runs during the call, in the host process.

Mitigation:
- When fork is available and the host has not pinned a start method, select
  fork so the child inherits these objects and nothing is pickled on the way
  in. (Verified: four consecutive calls under 3.11, start method resolves to
  fork, and the module-level ReduceBomb's __reduce__ never fires.)
- On Windows (no fork), or when the host pins spawn, this is inherent to
  multiprocessing. It is not reachable from the expression: allowed_vars is
  host-supplied, and an expression cannot add to it. Documented in the
  safe_eval docstring so integrators know these dicts carry a pickle-trust
  requirement there.

The result boundary itself is unaffected: the 0.0.6 RCE payload is still
blocked and no marker file is produced.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Two genuine defects found from the CI logs:

1. Deeply nested input crashed the parser instead of being refused. On
   CPython 3.8, ast.parse('[' * 150 + ']' * 150) overflows the C parser's
   stack and raises a bare MemoryError ('s_push: parser stack overflow')
   straight out of safe_eval, so callers got an unrelated internal error
   rather than a security rejection. Later versions raise SyntaxError.
   _reject_excessive_nesting now scans the expression before parsing and
   rejects more than 64 levels of bracket nesting with
   UnsafeExpressionError; string literals are skipped so brackets inside
   them are unaffected. Rejection takes ~0.05ms even at 20k levels, and
   ast.parse is still wrapped so MemoryError/RecursionError from any
   remaining path is reported as a rejected expression.

2. The Windows job never ran the suite. The temporary debugging step piped
   through tee and used ${PIPESTATUS[0]}, which PowerShell cannot parse, so
   the job failed on shell syntax instead of on a test. Reverted to a plain
   'python -m unittest' invocation, which works in every runner shell.

Removed the temporary diag_test.py scaffolding. Local suite: 111 tests, OK.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
The two Windows failures exposed a reporting bug with a real cost: when the
child died before sending a result, the parent waited out the entire timeout
and then raised EvaluationTimeoutError claiming the evaluation had timed out
by 5 seconds. That was wrong twice over - it stalled the caller for the full
timeout, and it pointed at a timeout when the child had actually crashed.

Found because under 'spawn' (the default on Windows and macOS) multiprocessing
pickles the process arguments in the caller, so a locally defined class in
allowed_vars cannot reach the child. The child then died during bootstrap and
the parent called it a timeout. Two errors in a 20s run surfaced this.

Changes:
- _wait_for_outcome waits for the result, the child's exit or the timeout in
  short slices, so a child that dies is noticed immediately. It checks
  Process.exitcode rather than is_alive(), because is_alive() joins the process
  internally and that blocks until a spawned child finishes bootstrapping - the
  same class of hang.
- A child that exits non-zero on its own is reported as a RuntimeError naming
  the likely cause (unpicklable allowed_vars/allowed_builtins under spawn).
  Exit code -SIGTERM is excluded: that is the parent's own termination, and is
  still a genuine timeout.
- process.start() failures from pickling (AttributeError/TypeError/
  PicklingError) are converted into a clear RuntimeError instead of leaking a
  multiprocessing error.

Tests: a hostile object is never returned or executed (no marker file) and,
under fork, never reduced; a lambda in allowed_vars raises a clear error; a
crashing object fails fast instead of waiting out the timeout. ReduceBomb now
reduces to inert data so the spawn path can be exercised too.

111 tests pass under both fork and a forced spawn. The 0.0.6 payload is still
blocked and the fork/spawn sink probes are unchanged.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
@johanbeytell1
johanbeytell1 merged commit 2e2d65f into main Nov 28, 2026
7 checks passed
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.

1 participant