Skip to content

Commit 3ba2bb1

Browse files
Release v0.0.6: security hardening, bug fixes, packaging & CI modernization
Security: - Block ALL attribute names starting with __ (was a hardcoded dunder list), closing a sandbox-escape bypass where dunders were read through string arguments, e.g. ().__getattribute__('__class__') with allow_attributes=True - Always terminate the evaluation child on timeout; immediate_termination=False previously leaked unkillable CPU-spinning processes (now deprecated) - Remove dir() and id() from the default safe builtins Bug fixes: - Serialize eval results synchronously in the child via pickle; unpicklable results (lambdas, generators, mappingproxy) now raise a clear RuntimeError instead of a misleading EvaluationTimeoutError from the queue.empty() race - encrypt() fails loudly on characters outside the mapping alphabet instead of silently corrupting non-ASCII code; custom mapping values validated to be exactly 64 characters - decrypt() validates Base64 input (validate=True); whitespace-tolerant - Non-positive timeout values rejected with ValueError - run() executes decrypted code with __name__='__main__' in an isolated namespace - Explicit UTF-8 for all file I/O; exception chaining; original exception types propagate from child processes; anchored '# <base64>' extraction regex Packaging/CI: - New PEP 621 pyproject.toml (SPDX MIT) - pip install/python -m build now work from a fresh checkout (was {{VERSION_PLACEHOLDER}}, an invalid version) - Publish workflow fixed (deprecated set-output, @master actions), added tag<->version consistency check; added test.yml (py3.8-3.12, linux/win/mac) Docs/tests: - CVE-2026-133467 referenced in changelog (was 'CVE pending') - README, supported Python versions (>=3.8), v0.0.6 changelog - New SECURITY_AUDIT.md with full findings and remediation notes - 73 tests passing; test_security_error_on_unsafe_function can no longer pass silently Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
1 parent 916cd04 commit 3ba2bb1

11 files changed

Lines changed: 572 additions & 140 deletions

File tree

‎.github/workflows/build_and_publish.yml‎

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,32 +3,38 @@ name: Publish Python 🐍 distributions 📦 to PyPI
33
on:
44
push:
55
tags:
6-
- '*'
6+
- '*'
77

88
jobs:
99
build-n-publish:
1010
name: Build and publish Python 🐍 distributions 📦 to PyPI
1111
runs-on: ubuntu-latest
1212
steps:
13-
- uses: actions/checkout@master
14-
- name: Set up Python 3.12
15-
uses: actions/setup-python@v3
16-
with:
17-
python-version: '3.12'
18-
- name: Install pypa/setuptools
19-
run: >-
20-
python -m
21-
pip install setuptools wheel
22-
- name: Extract tag name
23-
id: tag
24-
run: echo ::set-output name=TAG_NAME::$(echo $GITHUB_REF | cut -d / -f 3)
25-
- name: Update version in setup.py
26-
run: >-
27-
sed -i "s/{{VERSION_PLACEHOLDER}}/${{ steps.tag.outputs.TAG_NAME }}/g" setup.py
28-
- name: Build a binary wheel
29-
run: >-
30-
python setup.py sdist bdist_wheel
31-
- name: Publish distribution 📦 to PyPI
32-
uses: pypa/gh-action-pypi-publish@master
33-
with:
34-
password: ${{ secrets.PYPI_API_TOKEN }}
13+
- uses: actions/checkout@v4
14+
15+
- name: Set up Python 3.12
16+
uses: actions/setup-python@v5
17+
with:
18+
python-version: '3.12'
19+
20+
- name: Install build tooling
21+
run: python -m pip install --upgrade pip build
22+
23+
- name: Verify that the tag matches the package version
24+
run: |
25+
TAG_NAME="${GITHUB_REF_NAME#v}"
26+
PACKAGE_VERSION=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])")
27+
echo "Tag: $TAG_NAME"
28+
echo "Package version: $PACKAGE_VERSION"
29+
if [ "$TAG_NAME" != "$PACKAGE_VERSION" ]; then
30+
echo "::error::Tag '${GITHUB_REF_NAME}' does not match the version '${PACKAGE_VERSION}' in pyproject.toml."
31+
exit 1
32+
fi
33+
34+
- name: Build a binary wheel and source distribution
35+
run: python -m build
36+
37+
- name: Publish distribution 📦 to PyPI
38+
uses: pypa/gh-action-pypi-publish@release/v1
39+
with:
40+
password: ${{ secrets.PYPI_API_TOKEN }}

‎.github/workflows/test.yml‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
name: Tests ✅
2+
3+
on:
4+
push:
5+
branches: [main]
6+
pull_request:
7+
8+
jobs:
9+
test:
10+
name: Run tests (Python ${{ matrix.python-version }}, ${{ matrix.os }})
11+
runs-on: ${{ matrix.os }}
12+
strategy:
13+
fail-fast: false
14+
matrix:
15+
os: [ubuntu-latest]
16+
python-version: ['3.8', '3.9', '3.10', '3.11', '3.12']
17+
include:
18+
- os: windows-latest
19+
python-version: '3.12'
20+
- os: macos-latest
21+
python-version: '3.12'
22+
23+
steps:
24+
- uses: actions/checkout@v4
25+
26+
- name: Set up Python ${{ matrix.python-version }}
27+
uses: actions/setup-python@v5
28+
with:
29+
python-version: ${{ matrix.python-version }}
30+
31+
- name: Run test suite
32+
run: python -m unittest test.py test_poc_vulnerability.py -v

‎.gitignore‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,15 @@ __pycache__
22
*.pyc
33
dist/
44
build/
5-
venv/
5+
venv/
6+
*.egg-info/
7+
.eggs/
8+
htmlcov/
9+
.pytest_cache/
10+
.coverage
11+
venv/
12+
.venv/
13+
encrypted_code.encrypt
14+
decrypted.py
15+
codesafe_rce_marker.txt
16+
pathlib_test.txt

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ Thank you for considering contributing to **CodeSafe**! Contributions, whether t
88
Create a fork of this repository to your GitHub account and clone it locally.
99

1010
2. **Set Up the Environment**
11-
Ensure you have Python 3.6+ installed. You should also install compatible versions of the necessary dependencies for the project.
11+
Ensure you have Python 3.8+ installed. You should also install compatible versions of the necessary dependencies for the project.
1212

1313
3. **Run Tests**
1414
Before making changes, run tests to confirm that everything works.

‎README.md‎

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# CodeSafe
2-
![Python Version](https://img.shields.io/badge/python-3.12-blue.svg)
2+
![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)
33
[![Code Size](https://img.shields.io/github/languages/code-size/infinitode/codesafe)](https://github.com/infinitode/codesafe)
44
![Downloads](https://pepy.tech/badge/codesafe)
55
![License Compliance](https://img.shields.io/badge/license-compliance-brightgreen.svg)
@@ -18,55 +18,79 @@ An open-source Python library for code encryption, decryption, and safe evaluati
1818

1919
**Versions 0.0.1 through 0.0.4 contain a known sandbox escape vulnerability in `safe_eval()` that allows arbitrary code execution.**
2020

21-
See the security advisory: https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-7gp8-3j6q-v4h8 (CVE ID: CVE-2026-133467)
21+
See the security advisory: https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-7gp8-3j6q-v4h8 (CVE ID: CVE-2026-133467 · CVSS 3.1 score: 9.8)
2222

2323
- **Vulnerability**: The `safe_eval()` function in versions 0.0.1-0.0.4 is vulnerable to a sandbox escape via indirect subscript lookup (e.g., `__builtins__['exec'](...)`). This bypasses the AST validation and allows execution of arbitrary Python code.
2424
- **Impact**: An attacker controlling an expression passed to `safe_eval()` can execute arbitrary Python code with the application's permissions.
2525
- **Affected Versions**: 0.0.1, 0.0.2, 0.0.3, 0.0.4
2626
- **Fixed In**: Version 0.0.5 and later
2727

28-
**If you are using any version from 0.0.1 to 0.0.4, you should upgrade to version 0.0.5 or later immediately.** These earlier versions should **not** be used in untrusted expression evaluation environments.
28+
**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.
2929

3030
The fix includes:
3131
1. Rejecting all `ast.Call` nodes unless the exact target is explicitly whitelisted (including calls via subscript, attribute, and other indirect targets)
3232
2. Using a minimal built-ins allowlist that excludes dangerous functions like `exec`, `eval`, `compile`, and `__import__`
3333
3. Added comprehensive regression tests for indirect call targets
3434

35+
Version **0.0.6** additionally closes a second, related sandbox issue (details in the v0.0.6 changelog and [SECURITY_AUDIT.md](SECURITY_AUDIT.md)): with `allow_attributes=True`, dunder attributes such as `__class__` could be read indirectly through string arguments (e.g., `().__getattribute__('__class__')`), bypassing the dunder blocklist. All attribute names starting with `__` are now always rejected.
36+
3537
A huge thanks to [@hkmj19](https://github.com/hkmj19)/[Linkedin](https://www.linkedin.com/in/hemanth-kumar-mj-24b50a256/) for finding and reporting this vulnerability.
3638

3739
## Vulnerability & Security Testing ([`test_poc_vulnerability.py`](https://github.com/Infinitode/CodeSafe/blob/main/test_poc_vulnerability.py))
3840

3941
> [!NOTE]
4042
> These tests are only available on GitHub, and not on PyPI. They are external tests that aren't built along with `CodeSafe` versions.
4143
42-
CodeSafe v0.0.5+ includes a rigorous test suite (`TestVulnerabilityFixes` and `TestEdgeCases` in `test_poc_vulnerability.py`) to systematically verify that `safe_eval` blocks sandbox escapes while preserving standard evaluation features.
44+
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.
4345

4446
### Test Results Summary
4547

46-
**49/49 Security & Edge Case Tests Passing** (`100% Pass Rate` across all vector categories)
48+
**73/73 Tests Passing** (`100% Pass Rate` across all vector categories)
4749

4850
| Attack Vector / Category | Specific Vectors Tested | Status |
4951
| :--- | :--- | :--- |
5052
| **AST Subscript & Indirect Calls** | `__builtins__['exec']()`, `__builtins__['eval']()`, `__builtins__['__import__']()`, `getattr(__builtins__, 'exec')`, nested subscript access | **[PASS] Blocked** |
51-
| **Dunder Attribute Escapes** | `__class__`, `__bases__`, `__mro__`, `__subclasses__`, `__globals__`, `__closure__`, `__code__` | **[PASS] Blocked** |
53+
| **Dunder Attribute Escapes** | `__class__`, `__bases__`, `__mro__`, `__subclasses__`, `__globals__`, `__closure__`, `__code__`, `__dict__`, `__getattribute__` (all dunders, including string-argument indirection) | **[PASS] Blocked** |
5254
| **Class Hierarchy Traversal** | `object.__subclasses__()`, `type().subclasses()` | **[PASS] Blocked** |
5355
| **Expression Bypasses** | Comprehensions (list, dict, set), generator expressions, short-circuit logic (`and`/`or`), ternary operators, tuple unpacking, walrus operator (`:=`), lambda calls | **[PASS] Blocked** |
5456
| **Module & I/O Execution** | Direct/from `import`, `os.system`, `subprocess`, `io.open`, `socket`, `requests`, `urllib`, `pathlib` write operations | **[PASS] Blocked** |
55-
| **Dangerous Built-ins** | `exec()`, `eval()`, `compile()`, `input()`, `open()` (default settings), modifying `__builtins__` | **[PASS] Blocked** |
57+
| **Dangerous Built-ins** | `exec()`, `eval()`, `compile()`, `input()`, `open()` (default settings), modifying `__builtins__`, `dir()`, `id()` | **[PASS] Blocked** |
58+
| **Resource & Process Safety** | Timeout always terminates the child process (no leaked runaway processes); non-positive timeouts rejected | **[PASS] Enforced** |
59+
| **Error Handling** | Unpicklable results raise a clear `RuntimeError`; child exceptions propagate with their original type; `queue.empty()` race eliminated | **[PASS] Working** |
5660
| **Functional Baseline** | Safe arithmetic, string/list/dict operations, standard safe builtins (`len`, `max`, `abs`), explicitly allowed functions | **[PASS] Working** |
5761

58-
### Running the Proof of Concept Tests
62+
### Running the Tests
5963

6064
To run the security PoC suite locally:
6165

6266
```bash
6367
python -m unittest test_poc_vulnerability.py -v
68+
```
6469

70+
To run everything (including the functional suite in `test.py`):
71+
72+
```bash
73+
python -m unittest test.py test_poc_vulnerability.py -v
6574
```
6675

76+
### Changelog v0.0.6:
77+
78+
* **Security Hardening**: With `allow_attributes=True`, *all* attribute names starting with `__` are now rejected (previously only a cherry-picked list of dunders). This closes a bypass where dunder attributes could be read through string arguments, e.g. `().__getattribute__('__class__')`.
79+
* **Bug Fix**: A timed-out evaluation now always terminates the child process. Previously `immediate_termination=False` leaked an unkillable, CPU-spinning process. The `immediate_termination` parameter is deprecated and ignored.
80+
* **Bug Fix**: Unpicklable evaluation results (e.g. lambdas, generators, `mappingproxy` objects) now raise a clear `RuntimeError` instead of a misleading `EvaluationTimeoutError`. Results are serialized synchronously inside the child, eliminating the unreliable `queue.empty()` race that could drop valid results.
81+
* **Bug Fix**: `encrypt()` now fails loudly with a clear `ValueError` when the code contains characters outside its supported alphabet. Previously such code — anything non-ASCII — was **silently corrupted** and could not be decrypted. Custom `mapping` values are validated to be exactly 64 characters, as the fixed-size decrypt chunking requires.
82+
* **Bug Fix**: `decrypt()` validates the Base64 input (`validate=True`) and produces clear errors for corrupt input; surrounding whitespace is tolerated.
83+
* **Bug Fix**: Non-positive `timeout` values are rejected with `ValueError`.
84+
* 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.
85+
* Removed `dir()` and `id()` from the default safe builtins (pure information leakage with no legitimate use in expressions).
86+
* All encryption/decryption file operations now explicitly use UTF-8.
87+
* Packaging modernized: PEP 621 `pyproject.toml` (SPDX `MIT` license); source distributions and wheels build correctly from a fresh checkout (the `{{VERSION_PLACEHOLDER}}` version made `pip install .` and `python -m build` fail).
88+
* CI modernized: fixed the broken publish workflow (deprecated `set-output`, unpinned `@master` actions), added a tag-vs-version consistency check, and added a test workflow running both suites on Python 3.8-3.12 across Linux, Windows and macOS.
89+
* See [SECURITY_AUDIT.md](SECURITY_AUDIT.md) for the full audit findings and remediation notes.
90+
6791
### Changelog v0.0.5:
6892

69-
* **Security Fix**: Patched critical sandbox escape vulnerability in `safe_eval()` (CVE pending), thanks to [@hkmj19](https://github.com/hkmj19)/[Linkedin](https://www.linkedin.com/in/hemanth-kumar-mj-24b50a256/) for reporting.
93+
* **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.
7094
* Blocked indirect function calls via `ast.Subscript`, `ast.Attribute`, and other non-`ast.Name` targets
7195
* Implemented minimal safe builtins whitelist excluding `exec`, `eval`, `compile`, `__import__`, and similar dangerous functions
7296
* Added regression tests for indirect call bypass attempts
@@ -105,12 +129,13 @@ pip install codesafe
105129

106130
CodeSafe supports the following Python versions:
107131

108-
* Python 3.6
109-
* Python 3.7
110132
* Python 3.8
111133
* Python 3.9
112134
* Python 3.10
113-
* Python 3.11/Later (Preferred)
135+
* Python 3.11
136+
* Python 3.12 (Preferred)
137+
138+
Versions 0.0.5 and earlier supported Python 3.6/3.7, but those versions are end-of-life and are no longer supported as of 0.0.6.
114139

115140
Please ensure that you have one of these Python versions installed before using CodeSafe. CodeSafe may not work as expected on lower versions of Python than the supported.
116141

@@ -164,6 +189,9 @@ if __name__ == '__main__':
164189
> [!NOTE]
165190
> 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).
166191
192+
> [!IMPORTANT]
193+
> CodeSafe's obfuscation format replaces every character with a fixed 64-character output, so **only characters present in the encryption mapping (printable ASCII + common whitespace) can be encrypted**. Since v0.0.6, `encrypt()` raises a clear `ValueError` for anything else (e.g. non-ASCII strings or comments) instead of silently corrupting the code. Escape non-ASCII characters in string literals (e.g. `"\u2713"`) or remove them from comments before encrypting.
194+
167195
### Encrypt & Run Code
168196

169197
```python

0 commit comments

Comments
 (0)