Repository navigation
v0.0.7: fix critical RCE via unsafe result deserialization, plus sandbox hardening - #6
Merged
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
cloudpickleand the parent callscloudpickle.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.Fix
The result boundary no longer involves pickle at all:
multiprocessing.Pipe; the parent rebuilds it with a non-executable decoder.None,bool,int,float,complex,str,bytes,Decimal,Fraction. Containers are opt-in via the newallow_objects=True.RuntimeErrorinstead of being serialized. This removes a 0.0.6 feature — it was also the attack surface.(builtin type name, message);SystemExit/KeyboardInterrupt/GeneratorExitarrive as catchableRuntimeError; user-defined exception types are never reconstructed.cloudpickledependency removed.Also fixed (found during the audit)
'{0.__init__.__globals__[SECRET]}'.format(obj)reads dunders and mapping keys the checker never sees (5.9).(len := f)(),[f() for len in [..]],(lambda len: len())(f)called non-allowlisted callables in the default config.sorted(key=f),iter(f, None).__builtins__readable/mutable from expressions.SystemExit(1)terminated the host process;KeyboardInterrupt/GeneratorExitescapedexcept Exception.file_access=Falsebypass by re-introducingopenviaallowed_builtins.Verification
TestResultBoundaryV007holds the new regressions).forkand a forcibly pinnedspawnstart method.cryptographyonly.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.tomland__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_evalleaked aMemoryErroron Python 3.8 (availability)safe_eval("[" * 150 + "]" * 150)reachedast.parse, where CPython 3.8overflows the C parser stack and raises a bare
MemoryError(
s_push: parser stack overflow) out of the library. A caller got an unrelatedinternal error instead of a security rejection, and it could be triggered by
untrusted input.
_reject_excessive_nestingnow scans the expression beforeparsing and rejects more than 64 levels of bracket nesting with
UnsafeExpressionError; brackets inside string literals are ignored. Refusalcosts ~0.05 ms even at 20,000 levels.
ast.parseis additionally wrapped so anyMemoryError/RecursionErrorthat 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 thecaller and pointed at the wrong cause.
_wait_for_outcomenow waits for theresult, the child's exit or the timeout in short slices; a child that exits
non-zero on its own is reported as a
RuntimeErrornaming the likely cause.The parent's own
terminate()(exit code-SIGTERM) is excluded, so genuinetimeouts are still timeouts.
Process.exitcodeis used rather thanis_alive(), becauseis_alive()joins internally and blocks on abootstrapping spawned child.
3. Unpicklable
allowed_varsleaked a multiprocessing errorOn
spawnplatforms the argument pickling happens in the caller, so a lambda orlocally defined class in
allowed_varssurfaced as a rawAttributeErrorfrommultiprocessing. It is now a clear
RuntimeErrorexplaining that thesedictionaries 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, soobjects in
allowed_vars/allowed_builtinsare reduced before any sandboxexists. 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
forkis available and the hosthas not pinned a start method, CodeSafe now selects
forkso nothing is pickledon the way in. It is documented in the
safe_evaldocstring for Windows and forhosts 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
spawnstart method.