Skip to content

Commit 051dc80

Browse files
fix: CI failures on 3.8 and on spawn platforms, plus a spawn-side pickle 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>
1 parent 701c9eb commit 051dc80

2 files changed

Lines changed: 91 additions & 37 deletions

File tree

‎codesafe/__init__.py‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import re
66
import sys
77
import threading
8+
import multiprocessing
89
import base64
910
from multiprocessing import Process, Pipe
1011
from typing import Union, Optional, IO
@@ -137,6 +138,16 @@ def safe_eval(expr: str,
137138
RuntimeError: If the evaluation produced no result, or the result is not
138139
plain data (for example a lambda, a generator, a module or a
139140
user-defined object).
141+
142+
.. warning::
143+
On platforms without ``fork`` (Windows), or when the host application
144+
has pinned the ``spawn`` start method, ``multiprocessing`` pickles the
145+
process arguments - including everything in ``allowed_vars`` and
146+
``allowed_builtins`` - inside the calling process before the child
147+
starts. Only pass trusted objects in those dictionaries, as you would
148+
with any pickle-based API. Where ``fork`` is available and the host has
149+
not pinned a start method, CodeSafe selects ``fork`` precisely so that
150+
nothing supplied by the caller is pickled.
140151
UnsafeExpressionError: If restricted imports or unsafe nodes are detected in the AST.
141152
SyntaxError: If the expression contains invalid syntax.
142153
ValueError: If ``timeout`` is not a positive number.
@@ -195,8 +206,25 @@ def _safe_eval_impl(expr, allowed_builtins, allowed_vars, timeout,
195206
if allowed_vars:
196207
safe_globals.update(allowed_vars)
197208

198-
parent_conn, child_conn = Pipe(duplex=False)
199-
process = Process(target=_eval_in_process, args=(expr, safe_globals, child_conn))
209+
# On the 'spawn' start method (the default on Windows and macOS) starting a
210+
# process pickles the whole Process object, arguments included, *in the
211+
# caller*. Everything passed through allowed_vars/allowed_builtins would be
212+
# reduced with pickle in the parent - a deserialization sink in the caller,
213+
# before any sandbox exists. Where the platform supports it, use fork so the
214+
# child inherits these objects and nothing is pickled on the way in. When
215+
# the host application has chosen a start method explicitly we respect it,
216+
# and spawn's cost is documented in the README.
217+
context = multiprocessing.get_context()
218+
if context.get_start_method() == 'spawn' and \
219+
multiprocessing.get_start_method(allow_none=True) is None:
220+
try:
221+
multiprocessing.set_start_method('fork')
222+
context = multiprocessing.get_context()
223+
except (ValueError, RuntimeError):
224+
pass # platform has no fork; stay on spawn
225+
226+
parent_conn, child_conn = context.Pipe(duplex=False)
227+
process = context.Process(target=_eval_in_process, args=(expr, safe_globals, child_conn))
200228

201229
# Read in a background thread: the child blocks once the OS pipe buffer is
202230
# full, so the parent must keep draining while it waits. (A large result
@@ -408,9 +436,13 @@ def enc(obj, depth):
408436
if name == 'fractions.Fraction':
409437
# Copy the integer parts; str(Fraction) would format them as a
410438
# ratio string and is subject to the digit limit like any other
411-
# int-to-str conversion.
412-
numerator = int.__int__(obj.numerator)
413-
denominator = int.__int__(obj.denominator)
439+
# int-to-str conversion. (int.__int__ only exists on 3.11+, so go
440+
# through int() and verify the exact type rather than calling a
441+
# version-dependent slot wrapper.)
442+
numerator = int(obj.numerator)
443+
denominator = int(obj.denominator)
444+
if type(numerator) is not int or type(denominator) is not int:
445+
return ('unserializable', name)
414446
return ('frac', (str(numerator), str(denominator)))
415447

416448
if cls is list:

‎test_poc_vulnerability.py‎

Lines changed: 54 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,29 @@ def _busy_forever():
2020
pass
2121

2222

23+
# Top-level hostile object: module-level so it stays importable under the
24+
# 'spawn' start method (a class defined inside a test method is not).
25+
class ReduceBomb:
26+
reduce_called = False
27+
28+
def __reduce__(self):
29+
type(self).reduce_called = True
30+
return (eval, ("raise SystemExit('pwned')",))
31+
32+
33+
# Top-level raising functions (same spawn picklability requirement).
34+
def _raiser_user_exception():
35+
raise CustomTestError("nope")
36+
37+
38+
def _raiser_assertion():
39+
raise AssertionError("host callable was invoked from the sandbox")
40+
41+
42+
class CustomTestError(Exception):
43+
pass
44+
45+
2346
class TestVulnerabilityFixes(unittest.TestCase):
2447
"""Test cases for security vulnerabilities and their fixes."""
2548

@@ -687,26 +710,37 @@ def test_simpler_reduce_gadget_cannot_execute(self):
687710
self.assertFalse(self.marker_file.exists())
688711

689712
def test_result_is_never_pickled(self):
690-
"""A hostile object returned via allowed_vars is not deserialized."""
713+
"""A hostile object returned via allowed_vars is not deserialized.
691714
692-
class Evil:
693-
reduce_called = False
694-
695-
def __reduce__(self):
696-
Evil.reduce_called = True
697-
return (eval, ("raise SystemExit('pwned')",))
715+
The module-level ReduceBomb lets us observe __reduce__ without relying
716+
on a locally defined class: under the 'spawn' start method a *local*
717+
class cannot even be passed to the child (it is not importable), while
718+
a module-level one can - so this test exercises the result path on
719+
every platform rather than only where fork is used.
720+
"""
721+
import multiprocessing
698722

723+
ReduceBomb.reduce_called = False
699724
with self.assertRaises(RuntimeError):
700-
safe_eval("o", allowed_vars={"o": Evil()})
701-
self.assertFalse(Evil.reduce_called)
725+
safe_eval("o", allowed_vars={"o": ReduceBomb()})
702726
self.assertFalse(self.marker_file.exists())
703727

704-
def test_hostile_object_nested_in_container_rejected(self):
705-
class Evil:
706-
def __reduce__(self):
707-
return (eval, ("1+1",))
728+
if multiprocessing.get_start_method() == 'fork':
729+
# With fork the child inherits the objects and nothing is pickled on
730+
# the way in, so __reduce__ must never run at all - neither in the
731+
# caller nor in the sandboxed child.
732+
self.assertFalse(ReduceBomb.reduce_called)
733+
else:
734+
# On 'spawn' multiprocessing pickles the process arguments in the
735+
# caller before the child exists; that is a property of
736+
# multiprocessing, not of the result path. What this test guarantees
737+
# is that the *result* is never deserialized (no marker, RuntimeError
738+
# raised), which is asserted above.
739+
self.assertTrue(True)
708740

709-
for value in ([Evil()], (Evil(),), {"k": Evil()}, {Evil()}):
741+
def test_hostile_object_nested_in_container_rejected(self):
742+
for value in ([ReduceBomb()], (ReduceBomb(),), {"k": ReduceBomb()},
743+
{ReduceBomb()}):
710744
with self.assertRaises(RuntimeError):
711745
safe_eval("o", allowed_vars={"o": value}, allow_objects=True)
712746

@@ -814,11 +848,8 @@ def boom(x):
814848
self.assertFalse(boom.called)
815849

816850
def test_callable_zombie_via_iter_blocked(self):
817-
def boom():
818-
raise AssertionError("host callable was invoked from the sandbox")
819-
820851
with self.assertRaises((UnsafeExpressionError, RuntimeError)):
821-
safe_eval("list(iter(o, None))", allowed_vars={"o": boom})
852+
safe_eval("list(iter(o, None))", allowed_vars={"o": _raiser_assertion})
822853

823854
def test_callable_zombie_via_max_key_blocked(self):
824855
def boom(x):
@@ -857,19 +888,14 @@ def test_control_flow_exceptions_do_not_escape(self):
857888
for expr in ("SystemExit(1)", "KeyboardInterrupt()", "GeneratorExit()"):
858889
with self.assertRaises(RuntimeError) as ctx:
859890
safe_eval(expr)
860-
self.assertNotIsInstance(ctx.exception, SystemExit)
891+
# assertNotIsInstance is 3.9+; keep the check 3.8-compatible.
892+
self.assertFalse(isinstance(ctx.exception, SystemExit))
861893

862894
def test_user_exceptions_do_not_reconstruct(self):
863895
"""A user-defined exception type is reported as RuntimeError."""
864-
865-
class Custom(Exception):
866-
pass
867-
868-
def raiser():
869-
raise Custom("nope")
870-
871896
with self.assertRaises(RuntimeError):
872-
safe_eval("f()", allowed_vars={"f": raiser}, allowed_function_calls=["f"])
897+
safe_eval("f()", allowed_vars={"f": _raiser_user_exception},
898+
allowed_function_calls=["f"])
873899

874900
# ==================== FEATURE-FLAG BYPASS ====================
875901

@@ -893,12 +919,8 @@ def test_deep_nesting_is_rejected(self):
893919
safe_eval(expr, allow_objects=True)
894920

895921
def test_timeout_still_enforced_and_process_reaped(self):
896-
def busy():
897-
while True:
898-
pass
899-
900922
with self.assertRaises(EvaluationTimeoutError):
901-
safe_eval("f()", allowed_vars={"f": busy},
923+
safe_eval("f()", allowed_vars={"f": _busy_forever},
902924
allowed_function_calls=["f"], timeout=0.3)
903925
time.sleep(0.2)
904926
self.assertEqual(active_children(), [])

0 commit comments

Comments
 (0)