GitHub advisory · PyPI
asteval Sandbox Escape: arbitrary native memory read/write via numpy ctypes in default asteval Interpreter
Description
With its default configuration (numpy enabled, import disabled), asteval's Interpreter lets an attacker-controlled expression obtain a raw arbitrary process-memory read and write primitive, without using import, any __dunder__ attribute, or eval/exec/getattr. Arbitrary in-process read/write is equivalent to arbitrary code execution and is a complete escape of the sandbox whose entire purpose is "untrusted string in, no arbitrary execution out." Any application that feeds untrusted input to asteval with numpy installed (the default) is affected.
asteval's attribute filter (asteval/astutils.py: safe_getattr) blocks every __dunder__ name and blocks objects whose attribute value is identity-equal to one of the modules in UNSAFE_MODULES = {io, os, sys, ctypes}. The ctypes module entry was added recently (commit 9d9d430) and correctly blocks ndarray.ctypes._ctypes.
However, the module check is identity-only against the ctypes module. It does not cover ctypes type objects and their metaclass methods, which are reachable through numpy's ndarray.ctypes wrapper using only ordinary (non-dunder) attribute names:
zeros(1, dtype=int32).ctypes.shape._type_ -> <class 'ctypes.c_long'>
ndarray.ctypes exposes .shape (a ctypes array) whose element type ._type_ is ctypes.c_long. None of ctypes, .shape, ._type_ is a dunder, none is in UNSAFE_ATTRS, and the returned value is a type, not the ctypes module, so safe_getattr permits all of them.
On that ctypes type, the metaclass method from_address is reachable (non-dunder, not in UNSAFE_ATTRS; it is not even listed by dir(), which is likely why it was missed):
c_long.from_address(addr).value reads 8 bytes at any address. id() (a permitted builtin) supplies arbitrary object addresses.cell = c_long.from_address(addr); cell.value = X writes 8 bytes to any address. The write half rides…Manual fix · PyPI
pip install --upgrade "asteval>=1.0.9"Sources