diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ab5dee4..68e0af1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -40,7 +40,12 @@ jobs: # dependencies are required. run: | python -m pip install --upgrade pip - python -m pip install "cryptography>=41" "cloudpickle>=2.2" + python -m pip install "cryptography>=41" - name: Run test suite - run: python -m unittest test.py test_poc_vulnerability.py -v + # Plain `python -m unittest` in every shell: the previous version piped + # through tee with POSIX syntax, which the Windows runners execute with + # PowerShell, so the Windows job failed on the shell rather than on a + # test. Runners print full output on failure, so no log scraping is + # needed here. + run: python run_ci_tests.py diff --git a/README.md b/README.md index 8b02f4b..7a70fe0 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,23 @@ An open-source Python library for code encryption, decryption, and safe evaluati | :--- | :--- | :--- | :--- | | `safe_eval` sandbox escape via indirect subscript call | CVE-2026-133467 · [GHSA-7gp8-3j6q-v4h8](https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-7gp8-3j6q-v4h8) | 0.0.1 - 0.0.4 | 0.0.5 | | `safe_eval` sandbox escape via dunder attribute access with `allow_attributes=True` (string-argument indirection, e.g. `().__getattribute__('__class__')`) | [GHSA-m85r-gp57-6p5q](https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-m85r-gp57-6p5q) · CVE pending | 0.0.3 - 0.0.5 | **0.0.6** | +| Remote code execution in the calling process via unsafe deserialization of the `safe_eval()` result (cloudpickle) | GHSA to be assigned · CVE pending | 0.0.6 | **0.0.7** | You can browse all advisories at https://github.com/Infinitode/CodeSafe/security/advisories +### Remote code execution in the caller via result deserialization (fixed in v0.0.7) + +**Version 0.0.6 deserialized the result of `safe_eval()` in the calling process with `cloudpickle.loads()` - outside the sandbox it had just enforced.** + +- **Vulnerability**: The AST checker only guarded what ran inside the evaluation subprocess. The child serialized whatever the expression produced with `cloudpickle.dumps()`, and the parent called `cloudpickle.loads()` on it with full builtins. An expression could return an object whose `__reduce__` chain ran arbitrary code *the moment the parent unpickled it* - the injected code executed in the caller's process, not the sandbox, and the default configuration was enough. +- **Impact**: An attacker who controls only the expression passed to `safe_eval()` obtained arbitrary code execution in the host application, with the host's privileges (CVSS 3.1: 9.8, `AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H`). This is a distinct root cause from CVE-2026-133467: the sandbox itself worked; the boundary back to the caller did not. +- **Affected versions**: 0.0.6 only. Versions 0.0.1-0.0.5 are not affected by this specific bug: they return results through a `multiprocessing.Queue` with the standard library's `pickle`, and this gadget cannot survive that encoder (`Can't pickle local object`). Those versions are affected by the earlier advisories instead. Note that 0.0.5's `Queue.get()` does unpickle in the parent, so the underlying pattern is similar, but no working payload of this kind was found for 0.0.5. +- **Fixed in**: Version **0.0.7**. The result boundary no longer involves pickle at all: the child encodes only plain data (see below) and the parent reconstructs it from primitives. A returned value has no code path into the caller. +- **Workaround for 0.0.6**: none that is complete - treat every expression as fully trusted, or upgrade. +- **Related hardening in the same release**: `str.format`/`format_map` templates that name attributes or keys (`'{0.__class__}'.format(obj)`) are rejected; rebinding a safe-builtin name (`(len := f)()`, `[f() for len in [..]]`, `(lambda len: len())(f)`) no longer lets an expression call a non-allowlisted callable; callables passed to builtins that invoke them (`sorted(key=...)`, `iter(f, None)`) follow the same allowlist; `__builtins__` is not reachable by name; `SystemExit`/`KeyboardInterrupt`/`GeneratorExit` raised by an expression arrive as a catchable `RuntimeError` instead of killing or unwinding the caller; and `file_access=False` can no longer be bypassed by re-introducing `open` through `allowed_builtins`. + +**What `safe_eval()` returns in 0.0.7.** Results are restricted to plain data: `None`, `bool`, `int`, `float`, `complex`, `str`, `bytes`, `decimal.Decimal`, `fractions.Fraction`. Containers of plain data (`list`, `tuple`, `dict`, `set`) are returned only when `allow_objects=True` is passed. Lambdas, classes, instances of user-defined types, modules and generators are no longer returned - they raise a clear `RuntimeError` instead of being serialized. If your code relied on returning lambdas or dynamic classes, restructure the expression to return data. + ### Second sandbox-escape issue fixed in v0.0.6 **Versions 0.0.3 through 0.0.5, when `safe_eval()` is called with `allow_attributes=True` (not the default), allowed dunder attributes to be read indirectly through string arguments that the AST validator never inspects.** @@ -48,7 +62,7 @@ See the security advisory: https://github.com/Infinitode/CodeSafe/security/advis - **Affected Versions**: 0.0.1, 0.0.2, 0.0.3, 0.0.4 - **Fixed In**: Version 0.0.5 and later -**If you are using any version from 0.0.1 to 0.0.4, you should upgrade to version 0.0.6 or later immediately.** These earlier versions should **not** be used in untrusted expression evaluation environments. +**If you are using any version from 0.0.1 to 0.0.4, you should upgrade to version 0.0.7 or later immediately.** These earlier versions should **not** be used in untrusted expression evaluation environments. The fix includes: 1. Rejecting all `ast.Call` nodes unless the exact target is explicitly whitelisted (including calls via subscript, attribute, and other indirect targets) @@ -64,11 +78,11 @@ A huge thanks to [@hkmj19](https://github.com/hkmj19)/[Linkedin](https://www.lin > [!NOTE] > These tests are only available on GitHub, and not on PyPI. They are external tests that aren't built along with `CodeSafe` versions. -CodeSafe v0.0.6 includes a rigorous test suite (`TestVulnerabilityFixes`, `TestEdgeCases` and `TestHardeningRegression` in `test_poc_vulnerability.py`, plus `test.py`) to systematically verify that `safe_eval` blocks sandbox escapes while preserving standard evaluation features. +CodeSafe v0.0.7 includes a rigorous test suite (`TestVulnerabilityFixes`, `TestEdgeCases`, `TestHardeningRegression` and `TestResultBoundaryV007` in `test_poc_vulnerability.py`, plus `test.py`) to systematically verify that `safe_eval` blocks sandbox escapes while preserving standard evaluation features. ### Test Results Summary -**79/79 Tests Passing** (`100% Pass Rate` across all vector categories) +**108/108 Tests Passing** (`100% Pass Rate` across all vector categories) | Attack Vector / Category | Specific Vectors Tested | Status | | :--- | :--- | :--- | @@ -79,7 +93,11 @@ CodeSafe v0.0.6 includes a rigorous test suite (`TestVulnerabilityFixes`, `TestE | **Module & I/O Execution** | Direct/from `import`, `os.system`, `subprocess`, `io.open`, `socket`, `requests`, `urllib`, `pathlib` write operations | **[PASS] Blocked** | | **Dangerous Built-ins** | `exec()`, `eval()`, `compile()`, `input()`, `open()` (default settings), modifying `__builtins__`, `dir()`, `id()` | **[PASS] Blocked** | | **Resource & Process Safety** | Timeout always terminates the child process (no leaked runaway processes); non-positive timeouts rejected | **[PASS] Enforced** | -| **Error Handling** | Unserializable results (e.g. generators) raise a clear `RuntimeError`; lambdas and dynamic classes round-trip via cloudpickle; child exceptions propagate with their original type; `queue.empty()` race eliminated | **[PASS] Working** | +| **Result Deserialization** (v0.0.7) | `__reduce__` gadgets returned as the result, in a list/tuple/dict/set, or via `allowed_vars`; lambdas, classes, modules, functions and user types as results | **[PASS] Blocked** | +| **Format-String Traversal** (v0.0.7) | `'{0.__class__}'.format(o)`, `format_map`, nested spec fields, mapping-key access (`'{0[k]}'`) | **[PASS] Blocked** | +| **Name Shadowing** (v0.0.7) | `(len := f)()`, `[f() for len in [..]]`, `(lambda len: len())(f)`, callables in `sorted(key=...)` / `iter(f, None)` | **[PASS] Blocked** | +| **Reserved Names & Flags** (v0.0.7) | `__builtins__` read/rebind, `open` re-introduced via `allowed_builtins`, `SystemExit`/`KeyboardInterrupt` from an expression | **[PASS] Blocked** | +| **Error Handling** | Plain-data results round-trip losslessly (`Decimal`/`Fraction` included); unserializable results (lambdas, classes, generators, modules) raise a clear `RuntimeError`; builtin exceptions propagate with their original type; user-defined exception types arrive as `RuntimeError`; no `Queue` race | **[PASS] Working** | | **Functional Baseline** | Safe arithmetic, string/list/dict operations, standard safe builtins (`len`, `max`, `abs`), explicitly allowed functions | **[PASS] Working** | ### Running the Tests @@ -96,20 +114,35 @@ To run everything (including the functional suite in `test.py`): python -m unittest test.py test_poc_vulnerability.py -v ``` +### Changelog v0.0.7: + +* **Security Fix (critical)**: `safe_eval()` no longer deserializes the evaluation result with `cloudpickle` in the calling process. In 0.0.6 the child serialized its result and the parent called `cloudpickle.loads()` on it with full builtins, so an expression could return a `__reduce__` gadget that ran arbitrary code in the *caller* - outside the sandbox that had just been enforced. The result now crosses the process boundary as plain primitives and is rebuilt with a non-executable decoder. See the [Security Advisory](#security-advisory) above. +* **Changed**: `safe_eval()` returns plain data only - `None`, `bool`, `int`, `float`, `complex`, `str`, `bytes`, `Decimal`, `Fraction`. Containers of plain data are opt-in via the new `allow_objects=True` parameter. Lambdas, dynamic classes, instances of user-defined types, modules and generators raise a clear `RuntimeError` instead of being pickled. **This removes a feature that 0.0.6 advertised**; it was also the attack surface. +* **Security Fix**: `str.format`/`format_map` templates that traverse attributes or mapping keys (`'{0.__class__}'.format(obj)`, `'{0[key]}'.format(obj)`) are rejected. They read attributes without ever producing an `ast.Attribute` node for the checker to inspect. +* **Security Fix**: An expression can no longer rebind a safe-builtin *name* and then call it - `(len := host_callable)()`, `[host_callable() for len in [..]]` and `(lambda len: len())(host_callable)` previously reached a caller-supplied callable that was not on `allowed_function_calls`. Such calls now require explicit allowlisting. +* **Security Fix**: Callables passed to builtins that invoke them (`sorted(key=...)`, `iter(f, None)`) follow the same allowlist as direct calls. `allowed_vars` entries are data, not implicit call permissions. +* **Security Fix**: `__builtins__` is no longer reachable by name from an expression, and can no longer be rebound or mutated. +* **Security Fix**: An expression raising `SystemExit`, `KeyboardInterrupt` or `GeneratorExit` no longer terminates or unwinds the calling process; it arrives as a catchable `RuntimeError`. Exceptions of user-defined types are reported the same way instead of being reconstructed in the parent. +* **Security Fix**: `file_access=False` and `network_access=False` are enforced *after* `allowed_builtins` is merged, so passing `open` (or similar) through `allowed_builtins` no longer bypasses the flag. +* **Security**: Returned data is bounded (nesting depth 100, 1M nodes, 1 MiB of `str`/`bytes`), and int-to-str conversion is capped for the duration of a call so a returned giant integer cannot burn CPU in the caller. +* **Changed**: The result transport is a `multiprocessing.Pipe` drained by a reader thread instead of a `Queue`. A result larger than the OS pipe buffer can no longer deadlock the parent, and the timing of `EvaluationTimeoutError` is tighter. +* **Changed**: The `cloudpickle` dependency was removed - CodeSafe no longer imports pickle on the evaluation path at all. +* Added regression tests for every item above (see [Vulnerability & Security Testing](#vulnerability--security-testing-test_poc_vulnerabilitypy)). + ### Changelog v0.0.6: * **Security Fix**: With `allow_attributes=True`, *all* attribute names starting with `__` are now rejected (previously only a cherry-picked list of dunders, which was bypassable via string arguments, e.g. `().__getattribute__('__class__')`). See the [Security Advisory](#security-advisory) above. * **Security**: Timed-out evaluations always terminate the child process. Previously `immediate_termination=False` leaked an unkillable, CPU-spinning process; the parameter is deprecated and ignored. * **Changed**: `encrypt()` now uses authenticated cryptography - Fernet (AES-128-CBC + HMAC-SHA256) with a 256-bit key - instead of the Caesar/mapping obfuscation. Any Unicode source code round-trips losslessly. Keys come from the `key` argument (see the new `generate_key()`), the `CODESAFE_KEY` environment variable, or a built-in default key (public; obfuscation-grade only - supply your own key for real confidentiality). Files written by `encrypt_to_file()` now contain `# codesafe:v2:`; legacy pre-0.0.6 `.encrypt` files are still fully readable and runnable via `decrypt()`, `decrypt_to_file()` and `run()`. * **Changed**: The Caesar `mapping` parameter was removed from `encrypt()` (passing it raises `TypeError`). It is still accepted by `decrypt()`/`decrypt_to_file()`/`run()` for decrypting legacy payloads. -* **Changed**: Evaluation results are serialized with `cloudpickle` (returned from a subprocess), so lambdas and dynamically created classes can now be returned from `safe_eval()`. Results that cannot be serialized (e.g. generators) still raise a clear `RuntimeError` instead of a misleading `EvaluationTimeoutError`, and the `queue.empty()` race that could drop valid results is eliminated. +* **Changed** (reverted in 0.0.7 for security reasons): Evaluation results were serialized with `cloudpickle` (returned from a subprocess), so lambdas and dynamically created classes could be returned from `safe_eval()`. Results that could not be serialized (e.g. generators) raised a clear `RuntimeError` instead of a misleading `EvaluationTimeoutError`, and the `queue.empty()` race that could drop valid results was eliminated. **This was the deserialization sink fixed in 0.0.7** - see the [Security Advisory](#security-advisory). * **Changed**: `restricted_imports` was removed from `safe_eval()` - it was redundant (imports are rejected in expressions regardless) and misleading. * **Bug Fix**: `decrypt()` validates its input and produces clear errors for corrupt/tampered payloads (wrong key, corrupted or tampered v2 data is detected by the HMAC). * **Bug Fix**: Non-positive `timeout` values are rejected with `ValueError`. * Exceptions from the evaluation child process now propagate with their original type (including `BaseException`); exception chaining (`raise ... from e`) is used throughout; decrypted code executed via `run()` gets a clean `__main__` namespace isolated from CodeSafe's module globals. * Removed `dir()` and `id()` from the default safe builtins (pure information leakage with no legitimate use in expressions). * All encryption/decryption file operations now explicitly use UTF-8. -* The package now depends on `cryptography` and `cloudpickle` (installed automatically by pip). +* The package depends on `cryptography` (installed automatically by pip). `cloudpickle` was a dependency in 0.0.6 only. * Packaging modernized: PEP 621 `pyproject.toml`; source distributions and wheels build correctly from a fresh checkout (the `{{VERSION_PLACEHOLDER}}` version made `pip install .` and `python -m build` fail). Trusted Publishing (OIDC) is used for PyPI releases - no stored API tokens - and releases carry PEP 740 provenance attestations, shown on PyPI. * A test workflow runs the full test suite on Python 3.8-3.12 across Linux, Windows and macOS for every push and PR. * Added [SECURITY.md](SECURITY.md) with instructions for reporting vulnerabilities privately. The security notes and limitations previously tracked in a separate audit file are now maintained in this README (see [Security Limitations & Notes](#security-limitations--notes)). @@ -117,7 +150,7 @@ python -m unittest test.py test_poc_vulnerability.py -v ### Changelog v0.0.5: > [!WARNING] -> **v0.0.5 (and earlier) has a second, known sandbox-escape issue**, fixed in v0.0.6: with `allow_attributes=True`, dunder attributes could be read through string arguments (e.g. `().__getattribute__('__class__')`), bypassing the dunder blocklist. See the [Security Advisory](#security-advisory) section. **If you use `allow_attributes=True` on 0.0.5 or earlier, upgrade to v0.0.6 now.** +> **v0.0.5 (and earlier) has a second, known sandbox-escape issue**, fixed in v0.0.6: with `allow_attributes=True`, dunder attributes could be read through string arguments (e.g. `().__getattribute__('__class__')`), bypassing the dunder blocklist. See the [Security Advisory](#security-advisory) section. **If you use `allow_attributes=True` on 0.0.5 or earlier, upgrade to v0.0.7 now.** * **Security Fix**: Patched critical sandbox escape vulnerability in `safe_eval()` (CVE-2026-133467), thanks to [@hkmj19](https://github.com/hkmj19)/[Linkedin](https://www.linkedin.com/in/hemanth-kumar-mj-24b50a256/) for reporting. * Blocked indirect function calls via `ast.Subscript`, `ast.Attribute`, and other non-`ast.Name` targets @@ -147,7 +180,7 @@ python -m unittest test.py test_poc_vulnerability.py -v ## Installation -You can install CodeSafe using pip (it automatically installs the `cryptography` and `cloudpickle` dependencies): +You can install CodeSafe using pip (it automatically installs the `cryptography` dependency): ```bash pip install codesafe @@ -218,6 +251,24 @@ if __name__ == '__main__': > [!NOTE] > Attribute inspection is disabled when using `safe_eval`. You can read more about how to use `safe_eval` from [here](https://infinitode-docs.gitbook.io/documentation/package-documentation/codesafe-package-documentation?utm_source=gemini). +#### What `safe_eval` can return + +Since v0.0.7 the result is plain data, transported from the evaluation subprocess as primitives and rebuilt without pickle: + +```python +from codesafe import safe_eval + +safe_eval("2 + 2") # 4 +safe_eval("'hello'.upper()", allow_attributes=True) # 'HELLO' +safe_eval("[1, 2, 3]") # RuntimeError: containers are opt-in +safe_eval("[1, 2, 3]", allow_objects=True) # [1, 2, 3] +safe_eval("lambda: 1") # RuntimeError: lambdas are not returned +``` + +Allowed values are `None`, `bool`, `int`, `float`, `complex`, `str`, `bytes`, `Decimal` and `Fraction`. Containers (`list`, `tuple`, `dict`, `set`) of those are returned only with `allow_objects=True`, up to 100 levels deep and 1 MiB of string/bytes data. Lambdas, classes, modules, generators and instances of user-defined types raise `RuntimeError` - nothing callable ever crosses back into your process. + +Names you pass in `allowed_vars` are **data**, not implicit call permissions: a function is only called from the expression when its name is in `allowed_function_calls` (or it is a safe builtin). This also applies to callables handed to builtins that invoke them, such as `sorted(xs, key=fn)`. + > [!IMPORTANT] > Since v0.0.6, encrypted payloads are self-describing (`# codesafe:v2:`) and any Unicode source code round-trips losslessly. Pre-0.0.6 `.encrypt` files (Base64 Caesar) keep working with `run()`, `decrypt()` and `decrypt_to_file()`, but they are no longer produced - and they were never cryptographically secure. @@ -261,11 +312,11 @@ CodeSafe is designed for practical code protection, not absolute guarantees. Ple * **Encryption is only as strong as your key.** The built-in default key is public (it ships with the package), so payloads encrypted with it are protected only from casual inspection. Generate your own key with `generate_key()` and keep it secret (e.g. via the `CODESAFE_KEY` environment variable) for real confidentiality. Even then, `run()` must be able to read the key at execution time - anyone with both the encrypted file and the key can decrypt it. * **Encrypted code runs with the full permissions of the current process.** Encryption protects code at rest; it is not a security boundary at runtime. Only run code you trust. * **`safe_eval()` is not a perfect sandbox.** It relies on AST filtering plus a subprocess with a timeout, and expressions run with the privileges of the host process. `allow_attributes=True` convenience comes at increased risk (prefer the default `False`), and anything passed via `allowed_vars`/`allowed_builtins` runs as trusted code - the sandbox protects against the *expression*, not against what you hand it. For hostile input, add defense in depth (containers, seccomp, dropped privileges). -* **Serialization boundary.** Results cross the subprocess boundary via `cloudpickle` (lambdas and dynamic classes round-trip; generators and modules cannot be serialized and raise a clear `RuntimeError`). Only deserialize results produced by CodeSafe's own child process - like any pickle-family tool, cloudpickle data must come from a trusted producer. -* **`type` remains in the default safe builtins** (needed for `isinstance`-style patterns and `type(x)` introspection). With all dunder attributes rejected, it does not on its own yield an escape path, but it is the remaining reflection-adjacent primitive and is worth watching. +* **Result boundary is data-only by design.** Since v0.0.7 the result of an evaluation is transported as plain primitives and rebuilt without pickle; nothing the expression produces executes in the calling process. The cost is that lambdas, dynamic classes, instances of user-defined types, modules and generators cannot be returned (they raise `RuntimeError`), and containers of plain data need `allow_objects=True`. +* **`type` remains in the default safe builtins** (needed for `isinstance`-style patterns and `type(x)` introspection). With all dunder attributes rejected and no deserialization of results, it does not on its own yield an escape path, but it is the remaining reflection-adjacent primitive and is worth watching. * **Integrity of v2 payloads is enforced by HMAC**, but payloads carry no identity - a valid token only proves it was produced with the key, not *who* produced it. The legacy Caesar format (pre-0.0.6) has no integrity or authenticity at all. * **Custom Caesar mappings** (legacy) had a fixed 64-character-value requirement and are no longer produced by `encrypt()`; they are only honored when decrypting legacy payloads. -* **Results must be serializable.** Lambdas and dynamic classes work; generators, modules, open file objects, frames and locks do not. +* **Results must be plain data.** `None`, `bool`, `int`, `float`, `complex`, `str`, `bytes`, `Decimal`, `Fraction`, and - with `allow_objects=True` - `list`/`tuple`/`dict`/`set` containing those. Everything else raises `RuntimeError`. ## Contributing diff --git a/SECURITY.md b/SECURITY.md index 345594a..5488c43 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -32,8 +32,9 @@ We ask that you give us reasonable time to release a fix before any public discl | Version | Supported | | :--- | :--- | -| 0.0.6 and later | ✅ Yes | -| 0.0.5 | ⚠️ Known issue — see [GHSA-m85r-gp57-6p5q](https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-m85r-gp57-6p5q); upgrade to 0.0.6 | +| 0.0.7 and later | ✅ Yes | +| 0.0.6 | ⚠️ Known critical issue — the `safe_eval()` result is deserialized in the caller (remote code execution); fixed in 0.0.7 | +| 0.0.5 | ⚠️ Known issue — see [GHSA-m85r-gp57-6p5q](https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-m85r-gp57-6p5q); upgrade to 0.0.7 | | 0.0.1 – 0.0.4 | ❌ No — critical sandbox escape, [CVE-2026-133467](https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-7gp8-3j6q-v4h8) | Only the latest release receives fixes. Please upgrade rather than report issues that may already be fixed. @@ -44,6 +45,7 @@ Only the latest release receives fixes. Please upgrade rather than report issues | :--- | :--- | :--- | :--- | | `safe_eval` sandbox escape via indirect subscript call | CVE-2026-133467 · [GHSA-7gp8-3j6q-v4h8](https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-7gp8-3j6q-v4h8) | 0.0.1 - 0.0.4 | 0.0.5 | | `safe_eval` sandbox escape via dunder attribute string-argument (`allow_attributes=True`) | [GHSA-m85r-gp57-6p5q](https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-m85r-gp57-6p5q) · CVE pending | 0.0.3 - 0.0.5 | 0.0.6 | +| Remote code execution in the calling process via unsafe deserialization of the `safe_eval()` result | GHSA to be assigned · CVE pending | 0.0.6 | 0.0.7 | See https://github.com/Infinitode/CodeSafe/security/advisories for the canonical list. @@ -51,7 +53,7 @@ See https://github.com/Infinitode/CodeSafe/security/advisories for the canonical CodeSafe contains two very different components, and reports are welcome for both, but keep in mind: -- **`safe_eval()`** is a best-effort sandbox, not a hard security boundary. Reports demonstrating escapes under documented usage are very much in scope. Reports that require you to defeat host-level isolation (containers, seccomp, etc.) are out of scope. +- **`safe_eval()`** is a best-effort sandbox, not a hard security boundary. Reports demonstrating escapes under documented usage are very much in scope. Reports that require you to defeat host-level isolation (containers, seccomp, etc.) are out of scope. Since 0.0.7 the evaluation result is data-only and never deserialized with pickle, so "the result object's `__reduce__` runs in the caller" is no longer reachable; being unable to return lambdas/classes is a documented limitation, not a vulnerability. - **Encryption** protects code at rest. The built-in default key is public by design; only payloads encrypted with a user-supplied key can be confidential (see [Security Limitations & Notes](README.md#security-limitations--notes)). Reports of integrity/confidentiality failures in the v2 format (wrong key accepted, tampered payload decrypting successfully) are in scope; "the default key is public" is by design, not a vulnerability. Thank you for helping make CodeSafe safer! diff --git a/codesafe/__init__.py b/codesafe/__init__.py index 6314262..8a204b3 100644 --- a/codesafe/__init__.py +++ b/codesafe/__init__.py @@ -1,11 +1,15 @@ import ast import builtins +import contextlib import os +import pickle import re +import signal +import sys +import threading +import time +import multiprocessing import base64 -import cloudpickle -from multiprocessing import Process, Queue -from queue import Empty from typing import Union, Optional, IO from cryptography.fernet import Fernet, InvalidToken @@ -14,7 +18,7 @@ 'encrypt_to_file', 'encrypt', 'decrypt', 'run', 'decrypt_to_file', 'generate_key', '__version__'] -__version__ = "0.0.6" +__version__ = "0.0.7" # Pre-filtered builtins to speed up safe_eval # Only include truly safe builtins - exclude exec, eval, compile, __import__, etc. @@ -70,29 +74,28 @@ def __init__(self, error): self.message = f"UnsafeExpressionError: An unsafe evaluation expression was detected. Reason: {error}" super().__init__(self.message) -def _eval_in_process(expr: str, safe_globals: dict, queue: Queue): - """Function to evaluate the expression in a separate process.""" - try: - result = eval(compile(ast.parse(expr, mode='eval'), "", "eval"), safe_globals) - except BaseException as e: - result = e - # Serialize synchronously in the child. (Putting the object straight on the - # queue would defer pickling to the queue's background feeder thread, where - # a pickling error can never be reported back to the parent.) +# Upper bound on int<->str conversions. Applied only for the duration of a +# safe_eval() call, so the host's own settings are restored afterwards. +_SAFE_INT_MAX_STR_DIGITS = 10_000 + + +@contextlib.contextmanager +def _digit_limit(limit): + """Temporarily cap int<->str conversion size (Python 3.11+; no-op before).""" + if not hasattr(sys, "set_int_max_str_digits"): + yield + return + original = sys.get_int_max_str_digits() try: - payload = cloudpickle.dumps(result) - except BaseException: - if isinstance(result, BaseException): - payload = cloudpickle.dumps(RuntimeError(f"Evaluation failed with {type(result).__name__}: {result}")) - else: - payload = cloudpickle.dumps(RuntimeError( - f"The evaluation result of type '{type(result).__name__}' " - "cannot be returned because it cannot be serialized." - )) + sys.set_int_max_str_digits(limit) + except ValueError: + yield + return try: - queue.put(payload) - except Exception: - pass + yield + finally: + sys.set_int_max_str_digits(original) + def safe_eval(expr: str, allowed_builtins: Optional[dict] = None, @@ -102,7 +105,8 @@ def safe_eval(expr: str, allow_attributes: bool = False, immediate_termination: bool = True, file_access: bool = False, - network_access: bool = False) -> object: + network_access: bool = False, + allow_objects: bool = False) -> object: """ Safely evaluate a Python expression with limited access to built-ins, custom variables, and optional file access restriction. @@ -116,13 +120,36 @@ def safe_eval(expr: str, immediate_termination (bool, optional): Deprecated and ignored. The evaluation process is always terminated when the timeout is exceeded, so a runaway expression can never outlive the call. Accepted for backwards compatibility. file_access (bool, optional): Whether to allow file access (open, etc.). Defaults to False. network_access (bool, optional): Whether to allow network access (requests, etc.). Defaults to False. + allow_objects (bool, optional): Whether the result may be a container + (list/tuple/dict/set) of plain data. Defaults to False, in which case + only a single plain value (None, bool, int, float, complex, str, + bytes, Decimal, Fraction) can be returned and a container raises + ``RuntimeError``. This keeps the default surface minimal; set it to + ``True`` if your expressions legitimately return collections. Returns: - object: The result of the evaluated expression. + object: The result of the evaluated expression. Results are restricted to + plain data - see ``allow_objects``. The outcome travels from the + evaluation subprocess as plain primitives and is never deserialized + with pickle/cloudpickle, so a returned value cannot execute code in + the calling process. Lambdas, classes and instances of user-defined + types are not returned; they raise ``RuntimeError``. Raises: EvaluationTimeoutError: If the evaluation exceeds the allowed time. - RuntimeError: If the evaluation produced no result (for example, the result could not be serialized). + RuntimeError: If the evaluation produced no result, or the result is not + plain data (for example a lambda, a generator, a module or a + user-defined object). + + .. warning:: + On platforms without ``fork`` (Windows), or when the host application + has pinned the ``spawn`` start method, ``multiprocessing`` pickles the + process arguments - including everything in ``allowed_vars`` and + ``allowed_builtins`` - inside the calling process before the child + starts. Only pass trusted objects in those dictionaries, as you would + with any pickle-based API. Where ``fork`` is available and the host has + not pinned a start method, CodeSafe selects ``fork`` precisely so that + nothing supplied by the caller is pickled. UnsafeExpressionError: If restricted imports or unsafe nodes are detected in the AST. SyntaxError: If the expression contains invalid syntax. ValueError: If ``timeout`` is not a positive number. @@ -130,13 +157,130 @@ def safe_eval(expr: str, if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0: raise ValueError("timeout must be a positive number of seconds.") + # An expression can build arbitrarily large integers in a few operations + # (e.g. ``10 ** 10 ** 8``). The child enforces a timeout, but constructing + # or converting such an int can burn CPU in the parent afterwards, so the + # limit is tightened for the duration of this call (Python 3.11+). + with _digit_limit(_SAFE_INT_MAX_STR_DIGITS): + return _safe_eval_impl( + expr, allowed_builtins, allowed_vars, timeout, + allowed_function_calls, allow_attributes, file_access, + network_access, allow_objects, + ) + + +def _wait_for_outcome(finished, process, timeout, slice_seconds=0.05): + """Wait for the child's result, the child's exit, or the overall timeout. + + ``Event.wait()`` has no way to observe a dying child, so waiting for the + whole timeout would report a crashed child as a hung one. Polling in short + slices returns as soon as either the result arrives or the child exits. + ``is_alive()`` cannot be used for this: it joins the process internally, and + under 'spawn' that blocks until ``start()`` has finished bootstrapping the + child. ``exitcode`` is a property that reflects the wait status without + joining, so it changes as soon as the child dies. + """ + deadline = time.monotonic() + timeout + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + return finished.is_set() + if finished.wait(min(slice_seconds, remaining)): + return True + if process.exitcode is not None: + # The child is gone; the reader thread will observe EOF on the pipe + # and set the event, so a short grace period is enough. + finished.wait(0.2) + return finished.is_set() + + +# Maximum bracket ()[]{} nesting depth accepted before parsing. Legitimate +# expressions never approach this; the limit exists so that hostile input is +# rejected by a cheap scan instead of crashing the C parser, whose behaviour on +# deep nesting differs between CPython versions (3.8 raises MemoryError). +_MAX_EXPRESSION_NESTING = 64 + +_SIGTERM = getattr(signal, 'SIGTERM', 15) + +_OPENING = {"(": ")", "[": "]", "{": "}"} +_CLOSING = {")", "]", "}"} + + +def _reject_excessive_nesting(expr, limit=_MAX_EXPRESSION_NESTING): + """Raise UnsafeExpressionError if brackets nest deeper than ``limit``. + + String literals are skipped so brackets inside them do not count. This is + deliberately a simple lexical scan: it runs before the real parser and only + needs to be conservative about very deep input, not exact about Python's + full grammar. + """ + if not isinstance(expr, str): + return # parser will produce its own error for non-str input + depth = 0 + max_depth = 0 + quote = None + escaped = False + for ch in expr: + if quote is not None: + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == quote: + quote = None + continue + if ch in ("'", '"'): + quote = ch + elif ch in _OPENING: + depth += 1 + if depth > max_depth: + max_depth = depth + if max_depth > limit: + raise UnsafeExpressionError( + f"Expression nesting exceeds the maximum depth of {limit}." + ) + elif ch in _CLOSING: + if depth > 0: + depth -= 1 + return None + + +def _safe_eval_impl(expr, allowed_builtins, allowed_vars, timeout, + allowed_function_calls, allow_attributes, file_access, + network_access, allow_objects): + """Body of :func:`safe_eval` (run under the int-digit limit).""" allowed_builtins = allowed_builtins or {} allowed_vars = allowed_vars or {} allowed_function_calls = allowed_function_calls or [] + _reject_excessive_nesting(expr) + + try: + parsed_expr = ast.parse(expr, mode='eval') + except SyntaxError as e: + raise SyntaxError(f"Invalid syntax: {e}") from e + except (MemoryError, RecursionError) as e: + # Deeply nested input can overflow the C parser's stack instead of a + # tidy SyntaxError; CPython 3.8 in particular raises MemoryError from + # compile() here ("s_push: parser stack overflow"). Treat it as a + # rejected expression rather than letting it escape as an unrelated + # MemoryError from inside the library. + raise UnsafeExpressionError( + "Expression is too deeply nested to evaluate safely." + ) from e + + _check_ast(parsed_expr, allowed_function_calls, allow_attributes, + allowed_builtins=allowed_builtins, allowed_vars=allowed_vars) + # Optimization: Use pre-filtered builtins base safe_builtins = _BASE_BUILTINS.copy() + # Caller-supplied builtins are merged BEFORE the feature flags are applied, + # so file_access=False cannot be bypassed by passing ``open`` through + # ``allowed_builtins``. + if allowed_builtins: + safe_builtins.update(allowed_builtins) + if not file_access: for func in _FILE_FUNCS: safe_builtins.pop(func, None) @@ -145,73 +289,501 @@ def safe_eval(expr: str, for func in _NETWORK_FUNCS: safe_builtins.pop(func, None) - if allowed_builtins: - safe_builtins.update(allowed_builtins) - - # Set up the globals for eval + # Set up the globals for eval. ``__builtins__`` cannot be named by the + # expression: the AST checker rejects it. safe_globals = {"__builtins__": safe_builtins} if allowed_vars: safe_globals.update(allowed_vars) - # Pre-evaluation AST checks - try: - parsed_expr = ast.parse(expr, mode='eval') - except SyntaxError as e: - raise SyntaxError(f"Invalid syntax: {e}") from e + # On the 'spawn' start method (the default on Windows and macOS) starting a + # process pickles the whole Process object, arguments included, *in the + # caller*. Everything passed through allowed_vars/allowed_builtins would be + # reduced with pickle in the parent - a deserialization sink in the caller, + # before any sandbox exists. Where the platform supports it, use fork so the + # child inherits these objects and nothing is pickled on the way in. When + # the host application has chosen a start method explicitly we respect it, + # and spawn's cost is documented in the README. + context = multiprocessing.get_context() + if context.get_start_method() == 'spawn' and \ + multiprocessing.get_start_method(allow_none=True) is None: + try: + multiprocessing.set_start_method('fork') + context = multiprocessing.get_context() + except (ValueError, RuntimeError): + pass # platform has no fork; stay on spawn - _check_ast(parsed_expr, allowed_function_calls, allow_attributes) + parent_conn, child_conn = context.Pipe(duplex=False) + process = context.Process(target=_eval_in_process, args=(expr, safe_globals, child_conn)) - queue = Queue() - process = Process(target=_eval_in_process, args=(expr, safe_globals, queue)) + # Read in a background thread: the child blocks once the OS pipe buffer is + # full, so the parent must keep draining while it waits. (A large result + # can exceed the buffer; a synchronous recv() would deadlock against it.) + received = [] + finished = threading.Event() - try: - process.start() - process.join(timeout) + def _reader(): + try: + received.append(parent_conn.recv()) + except (EOFError, OSError): + pass + finally: + finished.set() + reader = threading.Thread(target=_reader, name="codesafe-eval-reader", daemon=True) + + try: + try: + process.start() + except (AttributeError, TypeError, pickle.PicklingError) as exc: + # Under 'spawn' the argument pickling happens here, in the caller. + # It fails for anything not importable by name (lambdas, local + # classes, some closures), and the raw error would otherwise escape + # as an unrelated AttributeError/TypeError. + raise RuntimeError( + "The evaluation process could not be started: an object passed " + "through allowed_vars or allowed_builtins could not be pickled " + "for the 'spawn' start method used on this platform. Pass only " + "module-level, importable objects there, or use a start method " + "that inherits objects (fork on POSIX)." + ) from exc + child_conn.close() # parent must not hold the write end open + reader.start() + _wait_for_outcome(finished, process, timeout) + + if not finished.is_set(): + # Give the child a brief grace period to finish, then terminate any + # runaway process so it can never outlive this call, regardless of + # the (deprecated) immediate_termination flag. + finished.wait(0.2) + if not finished.is_set() or process.is_alive(): + process.terminate() + process.join() + exitcode = process.exitcode + # -SIGTERM is the termination we just requested, so that case is + # a genuine timeout; anything else non-zero means the child died + # by itself before it could report. + if exitcode is not None and exitcode not in (0, -_SIGTERM): + # The child died on its own without sending a result. On + # 'spawn' platforms a failure during child bootstrap (for + # example an object in allowed_vars that cannot be pickled + # to the child) kills the interpreter before it can report + # anything. That is a crash, not a slow evaluation, and + # reporting it as a timeout would be misleading. + raise RuntimeError( + "The evaluation process exited unexpectedly " + f"(exit code {exitcode}) without returning a result. " + "On platforms that start the child with 'spawn' (Windows, " + "or a host that pinned that start method) objects passed " + "through allowed_vars/allowed_builtins must be picklable " + "and importable." + ) + raise EvaluationTimeoutError( + f"Evaluation exceeded the maximum execution timeout of {timeout} seconds and was terminated." + ) + + process.join(0.2) if process.is_alive(): - # Always terminate a runaway child so it can never outlive this call, - # regardless of the (deprecated) immediate_termination flag. + # The child produced its result but has not exited (for example it + # spawned a thread); it can no longer affect us, so reap it. process.terminate() process.join() - raise EvaluationTimeoutError( - f"Evaluation exceeded the maximum execution timeout of {timeout} seconds and was terminated." - ) - # After join() the child has finished, but the reader thread may still be - # draining the pipe, so poll briefly instead of trusting queue.empty(), - # which is not reliable. - try: - payload = queue.get(timeout=1.0) - except Empty: + outcome = received[0] if received else None + if outcome is None: raise RuntimeError( "The evaluation process finished without returning a result. " "This usually means the evaluation crashed the child process." - ) from None + ) - try: - result = cloudpickle.loads(payload) - except Exception as e: - raise RuntimeError(f"Failed to deserialize the evaluation result: {e}") from e + if not isinstance(outcome, (tuple, list)) or len(outcome) != 5: + raise RuntimeError("Failed to deserialize the evaluation result: malformed outcome.") - if isinstance(result, BaseException): - raise result + kind, payload, error_name, error_message, error_attrs = outcome + if kind not in _RESULT_KINDS: + raise RuntimeError(f"Failed to deserialize the evaluation result: unknown kind {kind!r}") + + if kind == 'error': + raise _rebuild_error(error_name, error_message, error_attrs) + if kind == 'unserializable': + raise RuntimeError( + f"The evaluation result of type '{payload}' cannot be returned. " + "Only plain data (None, bool, int, float, complex, str, bytes, " + "Decimal, Fraction) is returned from safe_eval - lambdas, classes, " + "instances of user-defined types, modules and generators are not." + ) + if kind == 'depth_exceeded': + raise RuntimeError( + f"The evaluation result is nested more than {_MAX_DEPTH} levels deep " + "and cannot be returned." + ) + if kind == 'too_large': + raise RuntimeError("The evaluation result is too large to be returned.") + + result_kind, result_payload = payload + result = _decode_result((result_kind, result_payload)) + if isinstance(result, (list, tuple, dict, set, frozenset)) and not allow_objects: + raise RuntimeError( + "The evaluation returned a container (list, tuple, dict, set). " + "Returning containers across the process boundary is opt-in: pass " + "allow_objects=True to receive them, or select a single plain value " + "from the container (e.g. ``[...][0]``)." + ) return result finally: + finished.wait(0.5) # let the reader finish before the fd disappears try: - process.join() + parent_conn.close() + except Exception: + pass + try: + process.join(0) except Exception: pass try: process.close() except (ValueError, AttributeError): pass + + +# Exceptions that must never escape into the caller: they do not derive from +# Exception, so ``except Exception`` would not catch them, and SystemExit would +# terminate the host process. They are reported as RuntimeError instead. +_CONTROL_FLOW_EXCEPTIONS = frozenset({'SystemExit', 'KeyboardInterrupt', 'GeneratorExit'}) + + +def _rebuild_error(name, message, attrs): + """Recreate an exception raised by the child from plain, vetted parts.""" + exc_type = getattr(builtins, name, None) + if name in _CONTROL_FLOW_EXCEPTIONS or not _is_stdlib_error_type(exc_type): + exc_type = RuntimeError + try: + exc = exc_type(message) + except Exception: + exc = RuntimeError(message) + try: + for attr_name, attr_value in (attrs or ()): + if attr_name in _ERROR_ATTRS: + setattr(exc, attr_name, attr_value) + except Exception: + pass + return exc + + +# --------------------------------------------------------------------------- +# Safe-eval result channel +# +# The child process evaluates the expression and reports its outcome over a +# multiprocessing.Pipe as a self-describing, fixed-shape structure: the kind of +# outcome plus an already-encoded, primitive payload. The parent NEVER +# deserializes objects it receives - there is no pickle/cloudpickle on the +# boundary at all, so a value produced by the expression has no way to run code +# in the parent. (Up to v0.0.6 the child sent a cloudpickle blob and the parent +# called cloudpickle.loads() on it, which let an expression smuggle a +# __reduce__ gadget into the caller's process.) +# +# Accepted results are deliberately limited to plain data: +# * None, True/False, int, float, complex, str, bytes +# * decimal.Decimal and fractions.Fraction (returned as Decimal/Fraction) +# * ... optionally nested, but only inside list, tuple, dict and set/frozenset +# +# Anything else - lambdas, classes, instances of user-defined types, modules, +# generators, file objects - raises a clear RuntimeError instead of being +# serialized. This closes the parent-side deserialization sink completely: +# there is nothing left for a malicious result to hook into. +# --------------------------------------------------------------------------- +_MAX_DEPTH = 100 +_MAX_RESULT_NODES = 1_000_000 +_MAX_RESULT_BYTES = 1 * 1024 * 1024 # total size of returned str/bytes data +_ATOMIC_TYPES = (type(None), bool, int, float, complex, str, bytes) + +_RESULT_KINDS = frozenset({ + 'value', 'error', 'unserializable', 'depth_exceeded', 'too_large', +}) + +# Exception attributes that are safe to carry across the boundary for the +# exceptions CodeSafe itself produces (timeouts, blocked expressions). +_ERROR_ATTRS = ('message',) + + +def _is_stdlib_error_type(exc_type) -> bool: + """True if exc_type is a plain builtin exception (no user code attached).""" + return ( + isinstance(exc_type, type) + and issubclass(exc_type, BaseException) + and exc_type.__module__ == 'builtins' + and getattr(builtins, exc_type.__name__, None) is exc_type + ) + + +def _encode_result(value): + """Encode an evaluation result into plain, JSON-compatible primitives. + + Returns ``(kind, payload)`` where ``kind`` is one of ``_RESULT_KINDS``. + The encoder walks the object graph directly; it never calls ``pickle``, + ``__reduce__`` or any other serialization hook on the objects it sees. + """ + budget = [_MAX_RESULT_NODES, _MAX_RESULT_BYTES] # nodes, bytes + + def enc(obj, depth): + if depth > _MAX_DEPTH: + return ('depth_exceeded', None) + if budget[0] <= 0: + return ('too_large', None) + budget[0] -= 1 + + cls = type(obj) + if cls in _ATOMIC_TYPES or obj is None: + if cls is int: + return ('i', str(obj)) + if cls is float: + # float.hex() is exact and also round-trips NaN/inf. + return ('f', obj.hex()) + if cls is complex: + return ('c', str(obj)) + if cls in (str, bytes): + budget[1] -= len(obj) + if budget[1] < 0: + return ('too_large', None) + return (cls.__name__, obj) + + # Ordered check: subclasses of the atomic types are NOT accepted; only + # the exact builtin types above are. This keeps the decoder simple and + # immune to str/int subclasses carrying overridden behaviour. + name = cls.__module__ + '.' + cls.__qualname__ + # Leaf nodes are returned without the (kind, value) wrapper used for + # containers below. + if name == 'decimal.Decimal': + return ('dec', str(obj)) + if name == 'fractions.Fraction': + # Copy the integer parts; str(Fraction) would format them as a + # ratio string and is subject to the digit limit like any other + # int-to-str conversion. (int.__int__ only exists on 3.11+, so go + # through int() and verify the exact type rather than calling a + # version-dependent slot wrapper.) + numerator = int(obj.numerator) + denominator = int(obj.denominator) + if type(numerator) is not int or type(denominator) is not int: + return ('unserializable', name) + return ('frac', (str(numerator), str(denominator))) + + if cls is list: + items = [] + for item in obj: + kind, payload = enc(item, depth + 1) + if kind in ('depth_exceeded', 'too_large'): + return (kind, None) + if kind == 'unserializable': + return ('unserializable', payload + ' (inside a list)') + items.append((kind, payload)) + return ('list', items) + if cls is tuple: + items = [] + for item in obj: + kind, payload = enc(item, depth + 1) + if kind in ('depth_exceeded', 'too_large'): + return (kind, None) + if kind == 'unserializable': + return ('unserializable', payload + ' (inside a tuple)') + items.append((kind, payload)) + return ('tuple', items) + if cls is set or cls is frozenset: + items = [] + label = 'frozenset' if cls is frozenset else 'set' + for item in obj: + kind, payload = enc(item, depth + 1) + if kind in ('depth_exceeded', 'too_large'): + return (kind, None) + if kind == 'unserializable': + return ('unserializable', payload + f' (inside a {label})') + items.append((kind, payload)) + return (label, items) + if cls is dict: + items = [] + for key, val in obj.items(): + kk, kp = enc(key, depth + 1) + if kk in ('depth_exceeded', 'too_large'): + return (kk, None) + if kk == 'unserializable': + return ('unserializable', kp + ' (as a dict key)') + vk, vp = enc(val, depth + 1) + if vk in ('depth_exceeded', 'too_large'): + return (vk, None) + if vk == 'unserializable': + return ('unserializable', vp + ' (inside a dict)') + items.append((kk, kp, vk, vp)) + return ('dict', items) + + return ('unserializable', cls.__module__ + '.' + cls.__qualname__) + + try: + kind, payload = enc(value, 0) + except BaseException as exc: # a hostile container can raise from iteration + return ('unserializable', f'<{type(exc).__name__} while encoding the result>') + if kind in ('unserializable', 'depth_exceeded', 'too_large'): + return (kind, payload) + return ('value', (kind, payload)) + + +def _decode_result(payload): + """Rebuild a plain-data result from an encoded, primitive payload. + + Only the primitives produced by :func:`_encode_result` are constructed - + no class lookup, no imports, no dynamic code. + """ + def dec(kind, data): + if kind == 'NoneType': + return None + if kind == 'bool': + return bool(data) + if kind == 'i': + return int(data) + if kind == 'f': + return float.fromhex(data) + if kind == 'c': + return complex(data) + if kind == 'str': + return str(data) + if kind == 'bytes': + return bytes(data) + if kind == 'dec': + import decimal + return decimal.Decimal(data) + if kind == 'frac': + import fractions + return fractions.Fraction(int(data[0]), int(data[1])) + if kind == 'list': + return [dec(k, v) for k, v in data] + if kind == 'tuple': + return tuple(dec(k, v) for k, v in data) + if kind == 'set': + return {dec(k, v) for k, v in data} + if kind == 'frozenset': + return frozenset(dec(k, v) for k, v in data) + if kind == 'dict': + return {dec(kk, kp): dec(vk, vp) for kk, kp, vk, vp in data} + raise RuntimeError(f'Failed to deserialize the evaluation result: unknown kind {kind!r}') + + return dec(payload[0], payload[1]) + + +def _eval_in_process(expr: str, safe_globals: dict, conn): + """Evaluate ``expr`` in this (child) process and report over ``conn``. + + Only plain-data outcomes leave the process; see the module comment above. + """ + try: + result = eval(compile(ast.parse(expr, mode='eval'), "", "eval"), safe_globals) + except BaseException as exc: + _send_error(conn, exc) + return + + try: + kind, payload = _encode_result(result) + except BaseException as exc: + _send_error(conn, exc) + return + + try: + conn.send((kind, payload, None, None, None)) + except OSError: + pass # parent went away (timeout) - nothing left to report to + + +def _send_error(conn, exc): + """Report an exception raised by the expression, without pickling it. + + User-defined exception types are not reconstructed in the parent (that + would be a deserialization sink). Their type name is reported with a plain + ``RuntimeError`` instead, which keeps ``except RuntimeError`` working + without letting attacker-controlled code run in the parent. + """ + try: + if _is_stdlib_error_type(type(exc)): + attrs = [] + for attr in _ERROR_ATTRS: + if attr in getattr(exc, '__dict__', {}): + attrs.append((attr, str(getattr(exc, attr)))) + conn.send(('error', None, type(exc).__name__, + str(exc), tuple(attrs))) + else: + conn.send(('error', None, 'RuntimeError', + f'Evaluation failed with {type(exc).__name__}: {exc}', ())) + except BaseException: try: - queue.close() - queue.join_thread() - except Exception: + conn.send(('error', None, 'RuntimeError', + 'The evaluation failed with an exception that could not be reported.', ())) + except BaseException: pass -def _check_ast(parsed_expr, allowed_function_calls, allow_attributes): + +# Method names that interpret their string arguments as format templates. +# ``'{0.__class__}'.format(obj)`` never produces an ast.Attribute node for +# ``__class__`` - the traversal happens inside str.format - so these names are +# treated as attribute access for the purposes of the dunder/attribute policy. +_FORMAT_METHODS = frozenset({'format', 'format_map'}) + +# Keywords whose value is invoked by the callee. A function passed as a sort +# key or a default factory is called even though it is never the target of a +# Call node, so the same "is this callable allowed?" policy applies to them. +_CALLBACK_KEYWORDS = frozenset({'key', 'default_factory'}) + +# Builtins that invoke a callable argument. ``sorted(x, key=f)`` and +# ``iter(f, None)`` never spell a call to ``f``, but they do call it, so a +# callable passed to any of these is subject to the call policy too. +_CALLABLE_ACCEPTING_BUILTINS = frozenset({'sorted', 'iter', 'map', 'filter', 'min', 'max'}) + +# Names that are never resolvable from an expression. ``__builtins__`` exposes +# the whole (restricted) builtins mapping, which is unnecessary surface even +# though the mapping itself is already filtered. +_DENIED_NAMES = frozenset({'__builtins__', '__import__', 'eval', 'exec', 'compile', + 'globals', 'locals', 'vars', 'dir', 'getattr', 'setattr', + 'delattr', 'input', 'breakpoint', 'memoryview', 'open'}) + + +def _FORMAT_STRING_HAS_DUNDER(template: str) -> bool: + """True if a str.format template names a dunder attribute at all.""" + return re.search(r'(? bool: + """True if a str.format template reaches inside an object. + + ``format``/``format_map`` look up attribute names and mapping keys named in + a replacement field - ``'{0.__class__}'.format(obj)`` reads ``__class__`` + without ever producing an ``ast.Attribute`` node, and ``'{0[secret]}'`` + reads a mapping key. Both are access paths the AST never sees, so any field + that is more than a plain positional/named reference is rejected. Nested + fields in a format spec (``{0:{1}}``) are unwrapped and checked too. + """ + probe = template + for _ in range(4): # unwrap nested replacement fields a few levels deep + found = False + for match in re.finditer(r'\{([^{}]*)\}', probe): + field = match.group(1) + if not field or field.startswith(('!', ':')): + continue # automatic field, e.g. "{}", "{!r}" or "{:>10}" + name = re.split(r'[!:\[.]', field, maxsplit=1)[0] + if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*|\d+', name): + found = True + break + rest = re.split(r'[!:]', field[len(name):], maxsplit=1)[0] + if rest: + # Something other than a conversion/format spec follows the + # field name: ".attr" or "[key]" - an access we cannot see. + found = True + break + if found: + return True + # Re-scan the inside of nested spec fields (e.g. {0:{1.__class__}}). + inner = ''.join(m.group(1) for m in re.finditer(r'\{([^{}]*)\}', probe)) + if '{' not in inner and '}' not in inner: + break + probe = probe.replace('{{', '{').replace('}}', '}') + return False + + +def _check_ast(parsed_expr, allowed_function_calls, allow_attributes, + allowed_builtins=None, allowed_vars=None): """ Check the AST for unsafe operations such as imports and function calls. @@ -219,48 +791,179 @@ def _check_ast(parsed_expr, allowed_function_calls, allow_attributes): parsed_expr (ast.AST): The parsed AST expression. allowed_function_calls (list): A list of allowed function calls. allow_attributes (bool): Whether to allow attribute access. + allowed_builtins (dict, optional): Names supplied as builtins. + allowed_vars (dict, optional): Names supplied as variables. Raises: UnsafeExpressionError: If unsafe operations are detected in the expression. + + The checks are structural rather than name-by-name: + + * Every ``ast.Call`` target must be a plain ``ast.Name`` that is either a + safe builtin or explicitly allowed, or (with ``allow_attributes=True``) a + non-dunder attribute. Calls through subscripts, lambdas and other + indirections are rejected. + * A name that the expression itself rebinds (``(len := f)()``, ``[f() for + len in [..]]``, ``(lambda len: len())(f)``) no longer refers to the safe + builtin, so it may only be *called* if it is explicitly allowed. + * Callable values handed to builtins that invoke them (``sorted(key=...)``, + ``iter(f, None)``, ``map``/``filter``) follow the same policy. + * All attribute names starting with ``__`` are rejected, and + ``format``/``format_map`` templates that name attributes or keys are + rejected: they walk into objects without producing ``ast.Attribute``. + * The names in ``_DENIED_NAMES`` (``__builtins__``, ``eval``, ``exec``, + ``compile``, ``__import__``, ...) are never resolvable. """ - # Attributes whose names start with '__' (dunders) are always blocked, - # whether or not allow_attributes is enabled. A fixed name list is not - # enough: dunders can be reached indirectly through string arguments such - # as obj.__getattribute__('__class__'), which the AST checker never sees. + allowed_function_calls = set(allowed_function_calls or ()) + allowed_builtins = allowed_builtins or {} + allowed_vars = allowed_vars or {} + # Only these names may reach a callable. allowed_vars entries are data + # (values may still be callables, which is why passing one somewhere that + # invokes it is gated on the explicit allowlist); allowed_builtins are + # exposed names but are not call targets unless also allowlisted. + callable_names = set(allowed_function_calls) | set(allowed_builtins) + allowed_names = set(allowed_function_calls) | set(allowed_builtins) | set(allowed_vars) + + # ---- scope analysis ------------------------------------------------- + # Collect every name the expression binds. A comprehension target or a + # lambda parameter shadows the surrounding scope, so a rebound safe-builtin + # name is treated as caller data: it may only be called when explicitly + # allowlisted. This is deliberately conservative across sub-scopes. + rebound = set() + for node in ast.walk(parsed_expr): + if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)): + rebound.add(node.id) + + def _callable_allowed_name(name): + if name in _DENIED_NAMES: + return False + if name in rebound: + return name in callable_names # caller-supplied value + if name in _SAFE_BUILTIN_NAMES or name in callable_names: + return True + # Builtin exception/type names are safe callables too (map(str, ...)). + builtin = getattr(builtins, name, None) + return isinstance(builtin, type) and builtin.__module__ == 'builtins' + + def _callable_allowed_expr(expr): + if isinstance(expr, ast.Name): + return _callable_allowed_name(expr.id) + if isinstance(expr, ast.Attribute): + return allow_attributes and not expr.attr.startswith('__') + return False + for node in ast.walk(parsed_expr): # Imports are never allowed in expressions. if isinstance(node, (ast.Import, ast.ImportFrom)): raise UnsafeExpressionError("Imports are not allowed in expressions.") - # Prevent ALL function calls except for whitelisted ones - # This includes calls via ast.Name (e.g., exec()), ast.Attribute (e.g., obj.method()), - # ast.Subscript (e.g., __builtins__['exec']()), and any other call target - if isinstance(node, ast.Call): - # Only allow calls where the function is a simple Name that's in the allowlist - # OR a safe builtin function - if isinstance(node.func, ast.Name): - if node.func.id in allowed_function_calls or node.func.id in _SAFE_BUILTIN_NAMES: - continue # This call is allowed - # Also allow method calls on objects when attributes are allowed - # (e.g., 'hello'.upper()) - these are ast.Attribute calls. - # Dunder method calls are rejected below by the Attribute check. - if isinstance(node.func, ast.Attribute) and allow_attributes: - if node.func.attr.startswith('__'): - raise UnsafeExpressionError(f"Access to dunder attribute '{node.func.attr}' is not allowed.") - continue # Method call is allowed - # All other calls are rejected (including subscript, attribute without allow_attributes, lambda, etc.) - raise UnsafeExpressionError("Function call is not allowed.") - - # Prevent attribute access entirely unless explicitly allowed, - # and always block dunder attributes (e.g., __class__, __globals__, - # __mro__, __dict__, __getattribute__) since they are the backbone of - # every known sandbox escape. + # Names: reserved names are never resolvable, whatever the context. + if isinstance(node, ast.Name) and node.id in _DENIED_NAMES: + raise UnsafeExpressionError( + f"Use of the reserved name '{node.id}' is not allowed.") + + # Attribute access is off unless explicitly enabled, and dunder names + # (__class__, __globals__, __mro__, __dict__, __getattribute__, ...) + # are always blocked - they are the backbone of every sandbox escape. if isinstance(node, ast.Attribute): if node.attr.startswith('__'): - raise UnsafeExpressionError(f"Access to dunder attribute '{node.attr}' is not allowed.") + raise UnsafeExpressionError( + f"Access to dunder attribute '{node.attr}' is not allowed.") if not allow_attributes: raise UnsafeExpressionError("Attribute access is disabled.") + if not isinstance(node, ast.Call): + continue + + _check_call(node, allowed_function_calls, allowed_names, callable_names, + rebound, allow_attributes, _callable_allowed_name, _callable_allowed_expr) + + +def _check_call(node, allowed_function_calls, allowed_names, callable_names, + rebound, allow_attributes, callable_allowed_name, callable_allowed_expr): + """Validate a single ``ast.Call`` node.""" + func = node.func + + # A literal string equal to a reserved name (e.g. eval('...'), the module + # name argument of __import__) is never needed. Format templates are + # validated as templates instead - they may legitimately contain words + # such as "open" or "format". + is_format_call = ( + (isinstance(func, ast.Attribute) and func.attr in _FORMAT_METHODS) + or (isinstance(func, ast.Name) and func.id in _FORMAT_METHODS) + ) + if not is_format_call: + for arg in node.args: + if isinstance(arg, ast.Constant) and arg.value in _DENIED_NAMES: + raise UnsafeExpressionError( + f"Use of the reserved name '{arg.value}' is not allowed.") + + # The call target must be a safe name or an explicitly allowed one. + if isinstance(func, ast.Name): + if func.id in _DENIED_NAMES: + raise UnsafeExpressionError(f"Call to '{func.id}' is not allowed.") + if func.id in rebound and func.id not in callable_names: + raise UnsafeExpressionError( + f"Call through the rebound name '{func.id}' is not allowed. " + "The expression reassigns this name, so it no longer refers to " + "the safe builtin; allowlist it explicitly if that is intended.") + if func.id not in allowed_function_calls and func.id not in _SAFE_BUILTIN_NAMES: + if func.id not in rebound: # a rebound name was handled above + raise UnsafeExpressionError("Function call is not allowed.") + elif isinstance(func, ast.Attribute) and allow_attributes: + if func.attr.startswith('__'): + raise UnsafeExpressionError( + f"Access to dunder attribute '{func.attr}' is not allowed.") + else: + # Calls through subscripts, lambdas, calls, etc. are rejected. + raise UnsafeExpressionError("Function call is not allowed.") + + # Format templates can traverse attributes and mapping keys, which never + # appear as AST nodes. Reject templates that do; require attributes to be + # enabled for formatting at all, since that is what templates exercise. + if is_format_call: + if not allow_attributes: + raise UnsafeExpressionError( + "Format strings can traverse attributes, so str.format/format_map " + "require allow_attributes=True.") + templates = [] + if isinstance(func, ast.Attribute): + templates.append(func.value) + templates.extend(node.args) + for tmpl in templates: + if not (isinstance(tmpl, ast.Constant) and isinstance(tmpl.value, str)): + if isinstance(tmpl, ast.Name) and tmpl.id in ('str', 'format'): + continue + if isinstance(func, ast.Attribute) and func.value is tmpl: + raise UnsafeExpressionError( + "Formatting requires a literal format string.") + continue + if _FORMAT_STRING_TRAVERSES_ATTRIBUTES(tmpl.value): + raise UnsafeExpressionError( + "Attribute traversal inside a format string is not allowed.") + if _FORMAT_STRING_HAS_DUNDER(tmpl.value): + raise UnsafeExpressionError( + "Dunder attribute names inside a format string are not allowed.") + return + + # Callables passed as values to builtins that invoke them. + if isinstance(func, ast.Name) and func.id in _CALLABLE_ACCEPTING_BUILTINS: + for arg in list(node.args) + [kw.value for kw in node.keywords]: + if callable_allowed_expr(arg): + continue + if isinstance(arg, (ast.Constant, ast.List, ast.Tuple, ast.Dict, + ast.Set, ast.JoinedStr)): + continue # a literal/container, not a live callable + raise UnsafeExpressionError( + "Passing a non-allowed callable to a builtin that invokes it " + "is not allowed.") + for kw in node.keywords: + if kw.arg in _CALLBACK_KEYWORDS and not callable_allowed_expr(kw.value): + if not isinstance(kw.value, ast.Constant): + raise UnsafeExpressionError( + f"Passing a non-allowed callable as '{kw.arg}' is not allowed.") + + # --------------------------------------------------------------------------- # Encryption # diff --git a/pyproject.toml b/pyproject.toml index b77a8ae..5033037 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "codesafe" -version = "0.0.6" +version = "0.0.7" description = "An open-source Python library for code encryption, decryption, and safe evaluation using Python's built-in AST module, complete with allowed functions, variables, built-in imports, timeouts, and blocked access to attributes." readme = "README.md" requires-python = ">=3.8" @@ -15,7 +15,6 @@ authors = [ keywords = ["eval", "safe-eval", "sandbox", "encryption", "security", "ast", "cryptography"] dependencies = [ "cryptography>=41", - "cloudpickle>=2.2", ] classifiers = [ "Development Status :: 5 - Production/Stable", diff --git a/run_ci_tests.py b/run_ci_tests.py new file mode 100644 index 0000000..97ff6e6 --- /dev/null +++ b/run_ci_tests.py @@ -0,0 +1,41 @@ +"""Run the unit tests and surface failures as GitHub annotations. + +Windows runners execute ``run:`` steps with PowerShell, so shell tricks for +piping or scraping output are not portable. Doing it in Python keeps the +workflow identical on every runner, and the ``::error`` lines land in the +check-run annotations even when the raw job log cannot be retrieved. +""" +import io +import sys +import unittest + +RESULT_FILE = "suite-output.txt" + + +def main(): + sys.path.insert(0, ".") + loader = unittest.TestLoader() + suite = unittest.TestSuite([ + loader.loadTestsFromName("test"), + loader.loadTestsFromName("test_poc_vulnerability"), + ]) + buffer = io.StringIO() + runner = unittest.TextTestRunner(stream=buffer, verbosity=2) + result = runner.run(suite) + output = buffer.getvalue() + print(output) + + problems = [(str(test), traceback) for test, traceback in + result.errors + result.failures] + for name, traceback in problems: + print(f"::error title={name}::{traceback.strip().splitlines()[-1][:200]}") + + if problems: + with open(RESULT_FILE, "w", encoding="utf-8") as handle: + handle.write(output) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test_poc_vulnerability.py b/test_poc_vulnerability.py index 23103d7..f740e51 100644 --- a/test_poc_vulnerability.py +++ b/test_poc_vulnerability.py @@ -20,6 +20,40 @@ def _busy_forever(): pass +# Top-level hostile object: module-level so it stays importable under the +# 'spawn' start method (a class defined inside a test method is not). +class ReduceBomb: + """Records whether pickle ever reduces it; reduces to harmless data. + + The payload is deliberately inert. On 'spawn' platforms multiprocessing + pickles the process arguments in the caller, and a side-effecting payload + here would execute inside the spawned child during bootstrap (before + CodeSafe's sandbox runs), which is a property of multiprocessing rather + than of the result boundary. What these tests are about is whether the + *result* of safe_eval is ever deserialized and whether __reduce__ runs at + all where the child inherits the object instead of receiving it by pickle. + """ + + reduce_called = False + + def __reduce__(self): + type(self).reduce_called = True + return (str, ("reduced",)) + + +# Top-level raising functions (same spawn picklability requirement). +def _raiser_user_exception(): + raise CustomTestError("nope") + + +def _raiser_assertion(): + raise AssertionError("host callable was invoked from the sandbox") + + +class CustomTestError(Exception): + pass + + class TestVulnerabilityFixes(unittest.TestCase): """Test cases for security vulnerabilities and their fixes.""" @@ -571,17 +605,26 @@ def test_safe_non_dunder_attribute_calls_still_work(self): # ==================== RESULT SERIALIZATION ==================== - def test_lambda_result_is_returned(self): - """Results of dynamic code (lambdas) round-trip via cloudpickle.""" - func = safe_eval("lambda: 40 + 2") - self.assertEqual(func(), 42) - print("[PASS] Lambda result is returned and callable") + def test_lambda_result_is_rejected(self): + """Lambdas are not returned: nothing callable crosses the boundary.""" + with self.assertRaises(RuntimeError): + safe_eval("lambda: 40 + 2") + print("[PASS] Lambda result is rejected instead of pickled") - def test_dynamic_class_result_is_returned(self): - """Dynamically created classes round-trip via cloudpickle.""" - cls = safe_eval("type('Point', (), {'x': 10, 'y': 20})") - self.assertEqual((cls.x, cls.y), (10, 20)) - print("[PASS] Dynamic class result is returned") + def test_dynamic_class_result_is_rejected(self): + """Dynamically created classes are not returned to the parent.""" + with self.assertRaises(RuntimeError): + safe_eval("type('Point', (), {'x': 10, 'y': 20})") + print("[PASS] Dynamic class result is rejected instead of pickled") + + def test_plain_data_containers_require_opt_in(self): + """Containers of plain data are returned only with allow_objects=True.""" + with self.assertRaises(RuntimeError): + safe_eval("[1, 2, 3]") + self.assertEqual(safe_eval("[1, 2, 3]", allow_objects=True), [1, 2, 3]) + self.assertEqual(safe_eval("(1, 'a')", allow_objects=True), (1, "a")) + self.assertEqual(safe_eval("{'a': [1]}", allow_objects=True), {"a": [1]}) + print("[PASS] Plain-data containers are opt-in") def test_unserializable_generator_raises_runtime_error(self): """A generator result (live frame state) raises a clear RuntimeError.""" @@ -589,6 +632,20 @@ def test_unserializable_generator_raises_runtime_error(self): safe_eval("(x for x in range(3))") print("[PASS] Unserializable generator result raises RuntimeError") + def test_decimal_and_fraction_round_trip(self): + """Decimal and Fraction are plain data and round-trip losslessly.""" + from decimal import Decimal + from fractions import Fraction + self.assertEqual( + safe_eval("Decimal('1.10')", allowed_vars={"Decimal": Decimal}, + allowed_function_calls=["Decimal"]), + Decimal("1.10")) + self.assertEqual( + safe_eval("Fraction(1, 3)", allowed_vars={"Fraction": Fraction}, + allowed_function_calls=["Fraction"]), + Fraction(1, 3)) + print("[PASS] Decimal and Fraction round-trip") + # ==================== PROCESS CLEANUP ==================== def test_no_process_leak_on_timeout(self): @@ -616,5 +673,343 @@ def test_non_positive_timeout_rejected(self): print("[PASS] Non-positive timeouts are rejected") +class TestResultBoundaryV007(unittest.TestCase): + """Regression tests for the v0.0.7 fixes (parent-side deserialization). + + CVE-2026-XXXXX (GHSA-XXXX-XXXX-XXXX): the v0.0.6 child serialized its result + with cloudpickle and the parent called cloudpickle.loads() on it. An + expression could build a value whose __reduce__ chain ran in the *parent* + process - outside the sandbox - using only AST nodes the checker allowed. + """ + + def setUp(self): + self.marker_file = Path(__file__).parent / "codesafe_rce_marker.txt" + if self.marker_file.exists(): + self.marker_file.unlink() + + def tearDown(self): + if self.marker_file.exists(): + self.marker_file.unlink() + + def _rce_payload(self, marker): + """The reported PoC: a __reduce__ gadget smuggled through the result.""" + code = ( + "__import__('pathlib').Path(" + repr(str(marker)) + ")" + ".write_text(str(__import__('os').getpid()))" + ) + mk = lambda c: f"list(zip(range(1),iter({c},None)))[0][1]" + y = ("type('Y',(),{'__call__':lambda s,*a:None," + "'__reduce__':lambda s:(lambda:eval,())})") + x = f"type('X',(),{{'__reduce__':lambda s:({mk(y)},({code!r},))}})" + return mk(x) + + # ==================== DIRECT RCE REGRESSION ==================== + + def test_reported_reduce_gadget_cannot_execute(self): + """The reported PoC must not run code in the parent process.""" + payload = self._rce_payload(self.marker_file) + with self.assertRaises((RuntimeError, UnsafeExpressionError)): + safe_eval(payload) + self.assertFalse(self.marker_file.exists()) + + def test_simpler_reduce_gadget_cannot_execute(self): + """A minimal __reduce__ -> (eval, (code,)) gadget is also inert.""" + code = "__import__('pathlib').Path(" + repr(str(self.marker_file)) + ").write_text('x')" + payload = ("list(iter(type('X',(),{'__reduce__':lambda s:(eval,(" + repr(code) + ",))}),None))") + with self.assertRaises((RuntimeError, UnsafeExpressionError)): + safe_eval(payload) + self.assertFalse(self.marker_file.exists()) + + def test_result_is_never_pickled(self): + """A hostile object never executes, and never comes back as an object. + + Two distinct guarantees are checked: + + * Nothing in the result path executes attacker code - the marker file + must not appear - and the caller never receives a live object. + * Where the child inherits the caller's objects ('fork'), __reduce__ + never runs at all. + + A locally defined class cannot be pickled to a 'spawn' child (Windows, + macOS, or a host that pinned that method), so there the call fails + before the sandbox starts; that failure is still a safe outcome, which + is what this test asserts rather than the specific exception type. + """ + import multiprocessing + + class Hostile: + reduce_called = False + + def __reduce__(self): + Hostile.reduce_called = True + code = ("__import__('pathlib').Path(" + + repr(str(self.marker_file)) + + ").write_text(str(__import__('os').getpid()))") + return (eval, (code,)) + + forking = multiprocessing.get_start_method() == 'fork' + try: + outcome = safe_eval("o", allowed_vars={"o": Hostile()}) + except (RuntimeError, EvaluationTimeoutError, UnsafeExpressionError): + outcome = None + else: + self.fail("a hostile object was returned to the caller") + + self.assertIsNone(outcome) + self.assertFalse(self.marker_file.exists()) + if forking: + self.assertFalse(Hostile.reduce_called) + + def test_child_crash_is_not_reported_as_timeout(self): + """A dead child is reported as a crash, not a 5-second timeout. + + Regression: a child that died before sending a result left the parent + waiting for the full timeout and then claimed the evaluation had timed + out, which hid the real cause and stalled the call for seconds. + """ + import time + + class DieAtOnce: + def __reduce__(self): + return (eval, ("raise SystemExit(1)",)) + + started = time.monotonic() + with self.assertRaises(RuntimeError): + safe_eval("o", allowed_vars={"o": DieAtOnce()}) + elapsed = time.monotonic() - started + # Either the object cannot be pickled for the child (spawn) or the + # child dies; both must fail fast rather than after the full timeout. + self.assertLess(elapsed, 3.0) + + def test_unpicklable_variable_raises_clear_error(self): + """Passing a lambda through allowed_vars fails with a clear message. + + Under 'spawn' the pickling happens in the caller and the raw failure + used to escape as an AttributeError from multiprocessing. + """ + try: + safe_eval("f()", allowed_vars={"f": lambda: 1}, + allowed_function_calls=["f"]) + except RuntimeError as exc: + self.assertIn("pickled", str(exc).lower()) + # On fork platforms the object is inherited, and the call itself is + # still refused because callables cannot be returned - either way the + # caller never receives a function. + except Exception as exc: # noqa: BLE001 + self.assertNotIsInstance(exc, AttributeError) + + def test_plain_data_still_round_trips(self): + self.assertEqual(safe_eval("1 + 1"), 2) + self.assertEqual(safe_eval("'héllo'"), "héllo") + self.assertEqual(safe_eval("b'abc'"), b"abc") + self.assertEqual(safe_eval("1.5"), 1.5) + self.assertEqual(safe_eval("True"), True) + self.assertIsNone(safe_eval("None")) + self.assertEqual(safe_eval("[1, [2, {'a': (3,)}]]", allow_objects=True), + [1, [2, {"a": (3,)}]]) + + def test_int_digit_limit_restored(self): + import sys + if not hasattr(sys, "get_int_max_str_digits"): + self.skipTest("Python < 3.11") + before = sys.get_int_max_str_digits() + with self.assertRaises(RuntimeError): + safe_eval("10 ** 10 ** 6") + self.assertEqual(sys.get_int_max_str_digits(), before) + + def test_undersized_results_rejected(self): + with self.assertRaises(RuntimeError): + safe_eval("'x' * 2_000_000") + + # ==================== STRING-FORMAT ATTRIBUTE TRAVERSAL ==================== + + def test_format_string_dunder_traversal_blocked(self): + """'{0.__class__}'.format(o) never makes an ast.Attribute node.""" + class Host: + secret = "leaked" + + for expr in ( + "'{0.__class__}'.format(o)", + "'{0.__init__.__globals__}'.format(o)", + "'{0.__class__.__mro__}'.format(o)", + "'{a.__class__}'.format_map({'a': o})", + "'{0[secret]}'.format(o)", + ): + with self.assertRaises(UnsafeExpressionError): + safe_eval(expr, allow_attributes=True, allowed_vars={"o": Host()}) + + def test_format_string_leak_is_blocked_without_attributes(self): + with self.assertRaises(UnsafeExpressionError): + safe_eval("'{0.__class__}'.format(1)") + + def test_plain_formatting_still_works(self): + self.assertEqual(safe_eval("'{} {}'.format(1, 2)", allow_attributes=True), "1 2") + self.assertEqual(safe_eval("'{0:>3}'.format(5)", allow_attributes=True), " 5") + self.assertEqual(safe_eval("'{name}'.format(name='x')", allow_attributes=True), "x") + + # ==================== SHADOWING BYPASSES ==================== + + def test_walrus_shadowing_safe_builtin_blocked(self): + class Host: + def __call__(self, *a): + return "called" + + with self.assertRaises(UnsafeExpressionError): + safe_eval("((len := o), len())", allowed_vars={"o": Host()}) + + def test_comprehension_shadowing_safe_builtin_blocked(self): + class Host: + def __call__(self, *a): + return "called" + + with self.assertRaises(UnsafeExpressionError): + safe_eval("[len() for len in [o]]", allowed_vars={"o": Host()}) + + def test_lambda_param_shadowing_safe_builtin_blocked(self): + class Host: + def __call__(self, *a): + return "called" + + with self.assertRaises(UnsafeExpressionError): + safe_eval("(lambda len: len())(o)", allowed_vars={"o": Host()}) + + def test_shadowed_name_allowed_when_explicitly_allowlisted(self): + """Explicitly allowlisting a rebound name keeps the call working.""" + import ast + from codesafe import _check_ast + + parsed = ast.parse("((len := f), len(4))", mode="eval") + # Without the allowlist the shadowed call is rejected... + with self.assertRaises(UnsafeExpressionError): + _check_ast(parsed, [], False, allowed_vars={"f": len}) + # ...with it, the AST check passes (the returned function is then + # rejected by the result policy, which is what RuntimeError reports). + _check_ast(parsed, ["len"], False, allowed_vars={"f": len}) + + def test_callable_zombie_via_sorted_key_blocked(self): + def boom(x): + boom.called = True + return x + + boom.called = False + with self.assertRaises((UnsafeExpressionError, RuntimeError)): + safe_eval("sorted(['a'], key=o)", allowed_vars={"o": boom}) + self.assertFalse(boom.called) + + def test_callable_zombie_via_iter_blocked(self): + with self.assertRaises((UnsafeExpressionError, RuntimeError)): + safe_eval("list(iter(o, None))", allowed_vars={"o": _raiser_assertion}) + + def test_callable_zombie_via_max_key_blocked(self): + def boom(x): + boom.called = True + return x + + boom.called = False + with self.assertRaises((UnsafeExpressionError, RuntimeError)): + safe_eval("max([1], key=o)", allowed_vars={"o": boom}) + self.assertFalse(boom.called) + + def test_safe_callables_as_builtin_arguments_still_work(self): + # Builtin callables (types, allowlisted builtins) remain usable as + # arguments to builtins that invoke them. + self.assertEqual(safe_eval("max([1, 5, 3], key=str)"), 5) + self.assertEqual(safe_eval("min([1, 5, 3], key=abs)"), 1) + + # ==================== __builtins__ PRESENCE ==================== + + def test_builtins_name_not_readable(self): + with self.assertRaises(UnsafeExpressionError): + safe_eval("__builtins__") + with self.assertRaises(UnsafeExpressionError): + safe_eval("__builtins__['len'](1)") + with self.assertRaises(UnsafeExpressionError): + safe_eval("__builtins__.get('len')", allow_attributes=True) + + def test_builtins_rebinding_blocked(self): + with self.assertRaises(UnsafeExpressionError): + safe_eval("(__builtins__.update({'x': 1}))", allow_attributes=True) + + # ==================== EXCEPTION BOUNDARY ==================== + + def test_control_flow_exceptions_do_not_escape(self): + """SystemExit/KeyboardInterrupt must arrive as catchable exceptions.""" + for expr in ("SystemExit(1)", "KeyboardInterrupt()", "GeneratorExit()"): + with self.assertRaises(RuntimeError) as ctx: + safe_eval(expr) + # assertNotIsInstance is 3.9+; keep the check 3.8-compatible. + self.assertFalse(isinstance(ctx.exception, SystemExit)) + + def test_user_exceptions_do_not_reconstruct(self): + """A user-defined exception type is reported as RuntimeError.""" + with self.assertRaises(RuntimeError): + safe_eval("f()", allowed_vars={"f": _raiser_user_exception}, + allowed_function_calls=["f"]) + + # ==================== FEATURE-FLAG BYPASS ==================== + + def test_file_access_flag_not_bypassed_via_allowed_builtins(self): + import builtins + with self.assertRaises(UnsafeExpressionError): + safe_eval("open('/etc/passwd')", allowed_builtins={"open": builtins.open}, + file_access=False) + + def test_dangerous_builtins_cannot_be_reintroduced(self): + import builtins + for name in ("eval", "exec", "__import__"): + with self.assertRaises(UnsafeExpressionError): + safe_eval(f"{name}('1')", allowed_builtins={name: getattr(builtins, name)}) + + # ==================== RESOURCE LIMITS ==================== + + def test_deep_nesting_is_rejected(self): + """Over-deep input is rejected cleanly, never as a parser crash. + + Before 0.0.7 this input reached ``ast.parse``, where CPython 3.8 + overflows the C parser's stack and raises a bare MemoryError + ("s_push: parser stack overflow") out of the library. A cheap lexical + scan now rejects it up front, so every supported interpreter reports + the same UnsafeExpressionError. + """ + expr = "[" * 150 + "]" * 150 + with self.assertRaises(UnsafeExpressionError): + safe_eval(expr, allow_objects=True) + + def test_very_deep_nesting_is_rejected_quickly(self): + """The up-front scan keeps hostile nesting cheap to refuse.""" + import time + + expr = "[" * 20000 + "]" * 20000 + started = time.perf_counter() + with self.assertRaises(UnsafeExpressionError): + safe_eval(expr, allow_objects=True) + self.assertLess(time.perf_counter() - started, 1.0) + + def test_nesting_inside_string_literals_is_allowed(self): + """Brackets that only appear inside strings do not count as nesting.""" + self.assertEqual(safe_eval("'[[[[' + ']]]]'"), "[[[[]]]]") + self.assertEqual(safe_eval(r"'a(b[c{d'"), "a(b[c{d") + self.assertEqual(safe_eval("'\\'" + '(' * 70 + "'"), "'" + '(' * 70) + + def test_deeply_nested_via_variables_is_bounded(self): + """Depth is also bounded for nesting the parser never sees.""" + deep = [] + node = deep + for _ in range(150): + child = [] + node.append(child) + node = child + with self.assertRaises(RuntimeError): + safe_eval("o", allowed_vars={"o": deep}, allow_objects=True) + + def test_timeout_still_enforced_and_process_reaped(self): + with self.assertRaises(EvaluationTimeoutError): + safe_eval("f()", allowed_vars={"f": _busy_forever}, + allowed_function_calls=["f"], timeout=0.3) + time.sleep(0.2) + self.assertEqual(active_children(), []) + self.assertEqual(safe_eval("1 + 1"), 2) + + if __name__ == "__main__": unittest.main(verbosity=2) \ No newline at end of file