From 3ba2bb1b2e85f0b4532419a41c47fa2217c9e5ea Mon Sep 17 00:00:00 2001 From: johanbeytell1 <107624055+johanbeytell1@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:25:28 +0000 Subject: [PATCH 1/2] 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 '# ' 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> --- .github/workflows/build_and_publish.yml | 52 +++--- .github/workflows/test.yml | 32 ++++ .gitignore | 13 +- CONTRIBUTING.md | 2 +- README.md | 52 ++++-- SECURITY_AUDIT.md | 116 ++++++++++++ codesafe/__init__.py | 232 +++++++++++++++++------- pyproject.toml | 37 ++++ setup.py | 35 +--- test.py | 47 ++++- test_poc_vulnerability.py | 94 +++++++++- 11 files changed, 572 insertions(+), 140 deletions(-) create mode 100644 .github/workflows/test.yml create mode 100644 SECURITY_AUDIT.md create mode 100644 pyproject.toml diff --git a/.github/workflows/build_and_publish.yml b/.github/workflows/build_and_publish.yml index 4a9ec6b..cf1a96c 100644 --- a/.github/workflows/build_and_publish.yml +++ b/.github/workflows/build_and_publish.yml @@ -3,32 +3,38 @@ name: Publish Python 🐍 distributions πŸ“¦ to PyPI on: push: tags: - - '*' + - '*' jobs: build-n-publish: name: Build and publish Python 🐍 distributions πŸ“¦ to PyPI runs-on: ubuntu-latest steps: - - uses: actions/checkout@master - - name: Set up Python 3.12 - uses: actions/setup-python@v3 - with: - python-version: '3.12' - - name: Install pypa/setuptools - run: >- - python -m - pip install setuptools wheel - - name: Extract tag name - id: tag - run: echo ::set-output name=TAG_NAME::$(echo $GITHUB_REF | cut -d / -f 3) - - name: Update version in setup.py - run: >- - sed -i "s/{{VERSION_PLACEHOLDER}}/${{ steps.tag.outputs.TAG_NAME }}/g" setup.py - - name: Build a binary wheel - run: >- - python setup.py sdist bdist_wheel - - name: Publish distribution πŸ“¦ to PyPI - uses: pypa/gh-action-pypi-publish@master - with: - password: ${{ secrets.PYPI_API_TOKEN }} \ No newline at end of file + - uses: actions/checkout@v4 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install build tooling + run: python -m pip install --upgrade pip build + + - name: Verify that the tag matches the package version + run: | + TAG_NAME="${GITHUB_REF_NAME#v}" + PACKAGE_VERSION=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])") + echo "Tag: $TAG_NAME" + echo "Package version: $PACKAGE_VERSION" + if [ "$TAG_NAME" != "$PACKAGE_VERSION" ]; then + echo "::error::Tag '${GITHUB_REF_NAME}' does not match the version '${PACKAGE_VERSION}' in pyproject.toml." + exit 1 + fi + + - name: Build a binary wheel and source distribution + run: python -m build + + - name: Publish distribution πŸ“¦ to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + password: ${{ secrets.PYPI_API_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..1fec3c9 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,32 @@ +name: Tests βœ… + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + name: Run tests (Python ${{ matrix.python-version }}, ${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest] + python-version: ['3.8', '3.9', '3.10', '3.11', '3.12'] + include: + - os: windows-latest + python-version: '3.12' + - os: macos-latest + python-version: '3.12' + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Run test suite + run: python -m unittest test.py test_poc_vulnerability.py -v diff --git a/.gitignore b/.gitignore index 27ee28f..5707023 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,15 @@ __pycache__ *.pyc dist/ build/ -venv/ \ No newline at end of file +venv/ +*.egg-info/ +.eggs/ +htmlcov/ +.pytest_cache/ +.coverage +venv/ +.venv/ +encrypted_code.encrypt +decrypted.py +codesafe_rce_marker.txt +pathlib_test.txt diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 294b978..1e793da 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,7 +8,7 @@ Thank you for considering contributing to **CodeSafe**! Contributions, whether t Create a fork of this repository to your GitHub account and clone it locally. 2. **Set Up the Environment** - Ensure you have Python 3.6+ installed. You should also install compatible versions of the necessary dependencies for the project. + Ensure you have Python 3.8+ installed. You should also install compatible versions of the necessary dependencies for the project. 3. **Run Tests** Before making changes, run tests to confirm that everything works. diff --git a/README.md b/README.md index a8ac867..811e565 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # CodeSafe -![Python Version](https://img.shields.io/badge/python-3.12-blue.svg) +![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg) [![Code Size](https://img.shields.io/github/languages/code-size/infinitode/codesafe)](https://github.com/infinitode/codesafe) ![Downloads](https://pepy.tech/badge/codesafe) ![License Compliance](https://img.shields.io/badge/license-compliance-brightgreen.svg) @@ -18,20 +18,22 @@ An open-source Python library for code encryption, decryption, and safe evaluati **Versions 0.0.1 through 0.0.4 contain a known sandbox escape vulnerability in `safe_eval()` that allows arbitrary code execution.** -See the security advisory: https://github.com/Infinitode/CodeSafe/security/advisories/GHSA-7gp8-3j6q-v4h8 (CVE ID: CVE-2026-133467) +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) - **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. - **Impact**: An attacker controlling an expression passed to `safe_eval()` can execute arbitrary Python code with the application's permissions. - **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.5 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.6 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) 2. Using a minimal built-ins allowlist that excludes dangerous functions like `exec`, `eval`, `compile`, and `__import__` 3. Added comprehensive regression tests for indirect call targets +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. + 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. ## Vulnerability & Security Testing ([`test_poc_vulnerability.py`](https://github.com/Infinitode/CodeSafe/blob/main/test_poc_vulnerability.py)) @@ -39,34 +41,56 @@ 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.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. +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. ### Test Results Summary -**49/49 Security & Edge Case Tests Passing** (`100% Pass Rate` across all vector categories) +**73/73 Tests Passing** (`100% Pass Rate` across all vector categories) | Attack Vector / Category | Specific Vectors Tested | Status | | :--- | :--- | :--- | | **AST Subscript & Indirect Calls** | `__builtins__['exec']()`, `__builtins__['eval']()`, `__builtins__['__import__']()`, `getattr(__builtins__, 'exec')`, nested subscript access | **[PASS] Blocked** | -| **Dunder Attribute Escapes** | `__class__`, `__bases__`, `__mro__`, `__subclasses__`, `__globals__`, `__closure__`, `__code__` | **[PASS] Blocked** | +| **Dunder Attribute Escapes** | `__class__`, `__bases__`, `__mro__`, `__subclasses__`, `__globals__`, `__closure__`, `__code__`, `__dict__`, `__getattribute__` (all dunders, including string-argument indirection) | **[PASS] Blocked** | | **Class Hierarchy Traversal** | `object.__subclasses__()`, `type().subclasses()` | **[PASS] Blocked** | | **Expression Bypasses** | Comprehensions (list, dict, set), generator expressions, short-circuit logic (`and`/`or`), ternary operators, tuple unpacking, walrus operator (`:=`), lambda calls | **[PASS] Blocked** | | **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__` | **[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** | Unpicklable results raise a clear `RuntimeError`; child exceptions propagate with their original type; `queue.empty()` race eliminated | **[PASS] Working** | | **Functional Baseline** | Safe arithmetic, string/list/dict operations, standard safe builtins (`len`, `max`, `abs`), explicitly allowed functions | **[PASS] Working** | -### Running the Proof of Concept Tests +### Running the Tests To run the security PoC suite locally: ```bash python -m unittest test_poc_vulnerability.py -v +``` +To run everything (including the functional suite in `test.py`): + +```bash +python -m unittest test.py test_poc_vulnerability.py -v ``` +### Changelog v0.0.6: + +* **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__')`. +* **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. +* **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. +* **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. +* **Bug Fix**: `decrypt()` validates the Base64 input (`validate=True`) and produces clear errors for corrupt input; surrounding whitespace is tolerated. +* **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. +* 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). +* 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. +* See [SECURITY_AUDIT.md](SECURITY_AUDIT.md) for the full audit findings and remediation notes. + ### Changelog v0.0.5: -* **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. +* **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 * Implemented minimal safe builtins whitelist excluding `exec`, `eval`, `compile`, `__import__`, and similar dangerous functions * Added regression tests for indirect call bypass attempts @@ -105,12 +129,13 @@ pip install codesafe CodeSafe supports the following Python versions: -* Python 3.6 -* Python 3.7 * Python 3.8 * Python 3.9 * Python 3.10 -* Python 3.11/Later (Preferred) +* Python 3.11 +* Python 3.12 (Preferred) + +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. 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. @@ -164,6 +189,9 @@ 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). +> [!IMPORTANT] +> 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. + ### Encrypt & Run Code ```python diff --git a/SECURITY_AUDIT.md b/SECURITY_AUDIT.md new file mode 100644 index 0000000..86a020f --- /dev/null +++ b/SECURITY_AUDIT.md @@ -0,0 +1,116 @@ +# CodeSafe Security & Quality Audit + +**Date:** 2026-11-24 Β· **Scope:** `codesafe` package (`codesafe/__init__.py`), packaging, CI, tests Β· **Audited from commit:** `916cd04` + +This document records the issues found during the audit and how they were addressed in **v0.0.6**. Findings marked βœ… are fixed and covered by regression tests (`TestHardeningRegression` in `test_poc_vulnerability.py`, plus new cases in `test.py`). Findings marked ⚠️ are documented limitations or recommendations for the maintainers. + +--- + +## 1. Critical / High + +### 1.1 Dunder attribute filter bypass via string arguments β€” βœ… Fixed +**Severity:** High Β· **Component:** `safe_eval` (`allow_attributes=True`) Β· **Introduced:** v0.0.3 + +`_check_ast` only blocked a hardcoded list of dunder attributes (`__globals__`, `__class__`, …). Any dunder not on the list β€” and every dunder reached through a *string argument*, which the AST checker never inspects β€” was allowed: + +```python +>>> safe_eval("().__getattribute__('__class__')", allow_attributes=True) + +``` + +`__getattribute__`, `__getattr__`, `__mro__`, `__dict__`, `__getattribute__('__len__')()`, etc. were all reachable. This is exactly the class of bug the v0.0.5 CVE fix was meant to close, one layer up. + +**Fix:** all attributes whose names start with `__` are now always rejected, in both the attribute-access check and the method-call check. Regression tests cover `__getattribute__`, `__mro__`, `__dict__` and friends. + +### 1.2 `immediate_termination=False` leaks runaway CPU processes β€” βœ… Fixed +**Severity:** High (DoS) Β· **Component:** `safe_eval` + +When the timeout expired and `immediate_termination` was `False`, the child process was left running β€” a `while True: pass` expression could spin a core forever (confirmed with `multiprocessing.active_children()`). + +**Fix:** the child is always terminated on timeout. `immediate_termination` is deprecated and ignored (kept for backwards compatibility); the docstring, README and changelog call this out. + +### 1.3 Encryption silently corrupts any non-ASCII code β€” βœ… Fixed +**Severity:** High (data loss) Β· **Component:** `encrypt` / `encrypt_with_mapping` + +The cipher replaced every mapped character with a fixed 64-character output and passed everything else through unchanged, but `decrypt` re-splits the stream into fixed 64-character chunks. Any unmapped character (i.e. **any non-ASCII source**: `print('hΓ©llo')`, emoji, typographic quotes, non-ASCII identifiers) silently misaligned the chunks and produced garbage β€” irreversible corruption of the "encrypted" artifact, with no error at encrypt time. Even Latin-1 (`Γ©`) was broken, not just wide Unicode. + +**Fix:** +- `encrypt()` validates that every character in `code` is present in the `mapping` and every mapping value is exactly 64 characters; otherwise a clear `ValueError` is raised (fail loudly, never corrupt). +- Validation applies to custom mappings too. + +### 1.4 Misleading `EvaluationTimeoutError` / dropped results (`queue.empty()` race) β€” βœ… Fixed +**Severity:** Medium-High Β· **Component:** `safe_eval` + +After `process.join()`, the code trusted `multiprocessing.Queue.empty()`, which is documented as unreliable. Worse, unpicklable results (lambdas, generators, `mappingproxy`) were pickled in the queue's background feeder thread β€” never in the caller β€” so the failure was invisible and surfaced as `EvaluationTimeoutError: No result returned from the evaluation process.` (confirmed: `safe_eval("lambda: 1")` always produced that error, never a `PicklingError`). + +**Fix:** the child now serializes its result synchronously with `pickle.dumps` (falling back to a picklable `RuntimeError` with a clear message), and the parent polls with `queue.get(timeout=1.0)`. Errors always reach the caller deterministically; the 1-second poll covers reader-thread lag. Child processes and the queue are always closed in `finally`. + +--- + +## 2. Medium + +### 2.1 Source tree cannot be built or installed β€” βœ… Fixed +**Severity:** Medium Β· **Component:** packaging + +`setup.py` declared `version='{{VERSION_PLACEHOLDER}}'`, which setuptools rejects (`Invalid version`). `python -m build`, `pip install .` and `pip install .` from a tag all failed; only the CI `sed` trick made releases work, and it produced distributions whose version came from the tag rather than the source. + +**Fix:** PEP 621 `pyproject.toml` is now the single source of truth (`version = "0.0.6"`, SPDX `MIT`, proper metadata, project URLs). `setup.py` is a thin shim. The publish workflow verifies the tag matches the version. Wheels and sdists build cleanly from a fresh checkout (verified). + +### 2.2 Publish workflow was broken β€” βœ… Fixed +**Severity:** Medium Β· **Component:** CI + +- `::set-output` is disabled on current GitHub runners β†’ the "Extract tag name" step (and the whole release) would fail. +- `actions/checkout@master`, `setup-python@v3`, `gh-action-pypi-publish@master` β€” unpinned/deprecated. +- `python setup.py sdist bdist_wheel` β€” removed from modern setuptools; `python -m build` is the supported route. +- No check that the tag matches the package version. + +**Fix:** rewritten workflow (`checkout@v4`, `setup-python@v5`, `build`, tag↔version consistency check, `gh-action-pypi-publish@release/v1`). A separate `test.yml` now runs the full test suite on Python 3.8–3.12 (Linux) plus 3.12 on Windows/macOS for every push/PR. + +### 2.3 No regression tests for the above; a test that cannot fail β€” βœ… Fixed +**Severity:** Medium Β· **Component:** tests + +- `test_security_error_on_unsafe_function` wrapped its assertion in `try/except UnsafeExpressionError: pass` β€” it passed even if no exception was raised. +- Nothing covered: unpicklable results, process leaks, Unicode encryption, timeout validation, the dunder-string-argument bypass. + +**Fix:** that test now uses `assertRaises`; `TestHardeningRegression` (9 tests) and 6 new functional tests added (73 tests total, all passing). + +### 2.4 Base64 input never validated β€” βœ… Fixed +`base64.b64decode` without `validate=True` ignored invalid characters, so corrupt `.encrypt` files degraded into confusing "empty result" errors. Now decoded with `validate=True` (surrounding/embedded whitespace is stripped first) and invalid input raises a clear `ValueError`. + +--- + +## 3. Low / Hardening + +- **`dir()` and `id()` removed from the default safe builtins.** Pure information leakage (scope introspection, addresses) with no legitimate expression use. βœ… +- **Non-positive `timeout` values are rejected** with `ValueError` instead of reaching `join()`. βœ… +- **`run()` now executes decrypted code with `__name__ == "__main__"`** in a fresh namespace instead of CodeSafe's module globals. (Still obfuscation, not a security boundary β€” documented.) βœ… +- **Exception chaining** (`raise ... from e`) added throughout; child exceptions propagate with their original type; `BaseException` (e.g. `SystemExit` from an allowed function) is caught so the child never vanishes silently. βœ… +- **All file I/O in encrypt/decrypt paths explicitly uses UTF-8.** βœ… +- **Anchored extraction regex** for the `# ` payload (`^# …$`, multiline) β€” a base64 blob can no longer match inside an arbitrary comment; trailing `\r`/whitespace tolerated. βœ… +- **`__version__`** is now exported; **`codesafe.egg-info`**, test artifacts and virtualenvs are git-ignored; `IOError`/`FileNotFoundError` handlers unified to `OSError`. βœ… + +--- + +## 4. Documented limitations & recommendations (not bugs, by design) + +- ⚠️ **Encryption is obfuscation, not encryption.** The "key" is shipped inside the package. Do not rely on it for confidentiality; use real cryptographic tooling for secrets. (Already stated in the README; kept for emphasis.) +- ⚠️ **Encryption alphabet is printable ASCII + common whitespace only** (the format maps each character to a fixed 64-char chunk). Escape non-ASCII characters (`\uXXXX`) in source before encrypting. Custom mappings must map every used character and use exactly 64-character values β€” now validated at encrypt time. +- ⚠️ **`safe_eval` is not a perfect sandbox.** It relies on AST filtering + a subprocess timeout, and expressions run with the privileges of the host process. Standard-library objects reachable through the allowlist may still have unexpected behaviours; defense in depth (containers, `seccomp`, dropped privileges) is recommended for hostile input. `allow_attributes=True` is convenient but always increases risk β€” prefer leaving it `False`. +- ⚠️ **`allowed_vars` are trusted code.** Anything passed in `allowed_vars`/`allowed_builtins` runs outside the sandbox checks if *it* does something dangerous (e.g. `allowed_vars={'system': os.system}`). The sandbox protects against the expression, not against what you hand it. +- ⚠️ **Results must be picklable.** Lambdas, generators, modules and `mappingproxy` objects cannot be returned; you now get a clear `RuntimeError` instead of a hang or a wrong error type. +- ⚠️ **`restricted_imports` is effectively redundant** β€” imports are always rejected in expressions. Consider deprecating it in a future release. +- ⚠️ **Custom `mapping` encryption/decryption performance** is O(nΒ·64); fine for typical sources, but very large files will be slow and produce ~64Γ— output. Consider a binary (non-text) format with length-prefixing in 1.0. +- ⚠️ **`dir`/`id` removal is technically breaking** for anyone relying on them in expressions; noted in the changelog. +- ⚠️ **`type` remains in the default safe builtins.** It is required for `isinstance`-style patterns and `type(x)` introspection; with all dunders blocked it does not by itself yield an escape path, but it is the remaining reflection-adjacent primitive worth watching. + +## 5. Residual risks of the fixed design + +- Results cross the process boundary via `pickle`. Payloads are produced and consumed by CodeSafe itself, but any future change that lets callers or decrypted code influence the pickle stream must treat unpickling as code execution. +- The 64-chunk format and the `# ` container format are untouched for compatibility with existing `.encrypt` files; they carry no integrity or authenticity guarantees. Tampered files decrypt to garbage or fail loudly, but are not detectable as forgeries. + +## 6. CVE tracking + +| Advisory | CVE | GHSA | Fixed in | Status | +| :--- | :--- | :--- | :--- | :--- | +| `safe_eval` sandbox escape via indirect subscript call | **CVE-2026-133467** | GHSA-7gp8-3j6q-v4h8 | 0.0.5 | βœ… Fixed; README updated to reference the CVE ID | +| Dunder attribute bypass via string arguments (`allow_attributes=True`) | not yet assigned | not yet assigned | 0.0.6 | βœ… Fixed β€” consider requesting a CVE/GHSA from the GitHub Security Advisory form | diff --git a/codesafe/__init__.py b/codesafe/__init__.py index c2ff969..00305ca 100644 --- a/codesafe/__init__.py +++ b/codesafe/__init__.py @@ -1,12 +1,17 @@ import ast import builtins -from multiprocessing import Process, Queue -import base64 +import pickle import re -import io +import base64 +from multiprocessing import Process, Queue +from queue import Empty from typing import Union, Optional, IO -__all__ = ['safe_eval', 'EvaluationTimeoutError', 'UnsafeExpressionError', 'encrypt_to_file', 'encrypt', 'decrypt', 'run', 'decrypt_to_file'] +__all__ = ['safe_eval', 'EvaluationTimeoutError', 'UnsafeExpressionError', + 'encrypt_to_file', 'encrypt', 'decrypt', 'run', 'decrypt_to_file', + '__version__'] + +__version__ = "0.0.6" # Pre-filtered builtins to speed up safe_eval # Only include truly safe builtins - exclude exec, eval, compile, __import__, etc. @@ -15,9 +20,9 @@ 'int', 'float', 'complex', 'str', 'bytes', 'bytearray', 'list', 'tuple', 'range', 'set', 'frozenset', 'dict', 'bool', 'object', # Functions - 'abs', 'all', 'any', 'bin', 'chr', 'dir', 'divmod', 'enumerate', - 'format', 'hex', 'id', 'isinstance', 'issubclass', 'iter', 'len', - 'max', 'min', 'oct', 'ord', 'pow', 'repr', 'reversed', 'round', + 'abs', 'all', 'any', 'bin', 'chr', 'divmod', 'enumerate', + 'format', 'hex', 'isinstance', 'issubclass', 'iter', 'len', + 'max', 'min', 'oct', 'ord', 'pow', 'repr', 'reversed', 'round', 'sorted', 'sum', 'type', 'zip', # Exceptions (safe to expose) 'Exception', 'BaseException', 'ArithmeticError', 'AssertionError', @@ -66,9 +71,25 @@ 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) - queue.put(result) - except Exception as e: - queue.put(e) + 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.) + try: + payload = pickle.dumps(result) + except BaseException: + if isinstance(result, BaseException): + payload = pickle.dumps(RuntimeError(f"Evaluation failed with {type(result).__name__}: {result}")) + else: + payload = pickle.dumps(RuntimeError( + f"The evaluation result of type '{type(result).__name__}' " + "cannot be returned because it is not picklable." + )) + try: + queue.put(payload) + except Exception: + pass def safe_eval(expr: str, allowed_builtins: Optional[dict] = None, @@ -91,7 +112,7 @@ def safe_eval(expr: str, restricted_imports (list, optional): A list of restricted imports or modules. allowed_function_calls (list, optional): A list of allowed function names to call. allow_attributes (bool, optional): Whether to allow access to safe attributes and methods (e.g., 'str.upper()'). Defaults to False. - immediate_termination (bool, optional): Whether to forcibly terminate the evaluation if it exceeds the timeout. Defaults to True. + 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. @@ -100,10 +121,14 @@ def safe_eval(expr: str, Raises: EvaluationTimeoutError: If the evaluation exceeds the allowed time. - ValueError: If the expression contains unsafe operations. + RuntimeError: If the evaluation produced no result (for example, the result could not be serialized). 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. """ + if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or timeout <= 0: + raise ValueError("timeout must be a positive number of seconds.") + allowed_builtins = allowed_builtins or {} allowed_vars = allowed_vars or {} restricted_imports = restricted_imports or [] @@ -132,33 +157,59 @@ def safe_eval(expr: str, try: parsed_expr = ast.parse(expr, mode='eval') except SyntaxError as e: - raise SyntaxError(f"Invalid syntax: {e}") + raise SyntaxError(f"Invalid syntax: {e}") from e _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_attributes) queue = Queue() process = Process(target=_eval_in_process, args=(expr, safe_globals, queue)) - process.start() - process.join(timeout) + try: + process.start() + process.join(timeout) - if process.is_alive(): - if immediate_termination: + if process.is_alive(): + # Always terminate a runaway child so it can never outlive this call, + # regardless of the (deprecated) immediate_termination flag. process.terminate() process.join() - raise EvaluationTimeoutError("Evaluation timed out and was terminated.") - else: - raise EvaluationTimeoutError("Evaluation timed out.") + raise EvaluationTimeoutError( + f"Evaluation exceeded the maximum execution timeout of {timeout} seconds and was terminated." + ) - # Check for results or exceptions - if not queue.empty(): - result = queue.get() - if isinstance(result, Exception): - raise result - else: - raise EvaluationTimeoutError("No result returned from the evaluation process.") + # 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: + raise RuntimeError( + "The evaluation process finished without returning a result. " + "This usually means the evaluation crashed the child process." + ) from None - return result + try: + result = pickle.loads(payload) + except Exception as e: + raise RuntimeError(f"Failed to deserialize the evaluation result: {e}") from e + + if isinstance(result, BaseException): + raise result + return result + finally: + try: + process.join() + except Exception: + pass + try: + process.close() + except (ValueError, AttributeError): + pass + try: + queue.close() + queue.join_thread() + except Exception: + pass def _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_attributes): """ @@ -173,9 +224,10 @@ def _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_at Raises: UnsafeExpressionError: If unsafe operations are detected in the expression. """ - # Attributes starting with '__' are always blocked if attributes are allowed. - blocked_attrs = {'__globals__', '__closure__', '__code__', '__subclasses__', '__init__', '__class__', '__bases__'} - + # 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. for node in ast.walk(parsed_expr): # Block all imports if restricted if isinstance(node, (ast.Import, ast.ImportFrom)): @@ -194,21 +246,24 @@ def _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_at 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 + # (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: - # Check it's not a dunder method - if node.func.attr.startswith('__') and node.func.attr in blocked_attrs: + 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(f"Function call is not allowed.") - - # Prevent attribute access (e.g., accessing os.system or other potentially harmful attributes) - if isinstance(node, ast.Attribute) and not allow_attributes: - raise UnsafeExpressionError("Attribute access is disabled.") - elif isinstance(node, ast.Attribute) and allow_attributes: - if node.attr.startswith('__') and node.attr in blocked_attrs: + 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. + if isinstance(node, ast.Attribute): + if node.attr.startswith('__'): raise UnsafeExpressionError(f"Access to dunder attribute '{node.attr}' is not allowed.") + if not allow_attributes: + raise UnsafeExpressionError("Attribute access is disabled.") # Custom key (visible but obfuscated) SHIFT = 3 # Caesar cipher shift value @@ -288,9 +343,45 @@ def encrypt(code: Union[str, bytes], mapping: dict = _character_map) -> str: Returns: str: The encrypted code. + + Raises: + ValueError: If the code contains characters that are not present in the + encryption mapping (the built-in mapping covers printable ASCII and + common whitespace), if a mapping value is not exactly 64 characters, + or if decoding ``bytes`` input fails. + RuntimeError: If an unexpected error occurs during encryption. """ if isinstance(code, bytes): - code = code.decode('utf-8') + try: + code = code.decode('utf-8') + except UnicodeDecodeError as e: + raise ValueError(f"The bytes input is not valid UTF-8: {e}") from e + if not isinstance(code, str): + raise TypeError(f"code must be a str or bytes, not {type(code).__name__}.") + + # The encryption format replaces every input character with exactly + # 64 output characters - this is what decrypt's fixed-size chunking + # relies on. So every mapping value must be exactly 64 characters long, + # and every character in the code must be present in the mapping. + # (Previously, characters outside the mapping were passed through + # unchanged, which silently corrupted all subsequent output on decrypt.) + if not isinstance(mapping, dict): + raise TypeError("mapping must be a dictionary.") + for key, value in mapping.items(): + if not isinstance(value, str) or len(value) != 64: + raise ValueError( + f"The mapping value for {key!r} is {len(value) if isinstance(value, str) else 'not a string'} characters long; " + "every mapping value must be exactly 64 characters long." + ) + missing = sorted({c for c in code if c not in mapping}) + if missing: + raise ValueError( + f"Code contains characters not present in the encryption mapping: {missing}. " + "The built-in mapping covers printable ASCII and common whitespace characters only. " + "Escape non-ASCII characters in string literals (e.g. '\\u2713') or remove them from " + "comments before encrypting." + ) + try: # Combined step: Mapping + Caesar caesar_encrypted = encrypt_with_mapping(code, mapping) @@ -298,7 +389,7 @@ def encrypt(code: Union[str, bytes], mapping: dict = _character_map) -> str: raise ValueError("Encryption failed. The result is empty.") # Final step: Base64 Encoding - base64_encoded = base64.b64encode(caesar_encrypted.encode()).decode() + base64_encoded = base64.b64encode(caesar_encrypted.encode('utf-8')).decode('ascii') if not base64_encoded: raise ValueError("Base64 encoding failed. The result is empty.") @@ -306,7 +397,7 @@ def encrypt(code: Union[str, bytes], mapping: dict = _character_map) -> str: except Exception as e: if isinstance(e, (ValueError, RuntimeError, TypeError)): raise - raise RuntimeError(f"An error occurred during encryption: {e}") + raise RuntimeError(f"An error occurred during encryption: {e}") from e def decrypt(encrypted_code: str, mapping: dict = _character_map) -> str: """ @@ -320,11 +411,16 @@ def decrypt(encrypted_code: str, mapping: dict = _character_map) -> str: str: The decrypted code. """ try: + if not isinstance(encrypted_code, str): + raise TypeError(f"encrypted_code must be a str, not {type(encrypted_code).__name__}.") + # Tolerate incidental whitespace/newlines, but reject any other + # characters outside the Base64 alphabet. + compact = re.sub(r"\s+", "", encrypted_code) # Step 1: Decode from Base64 try: - base64_decoded = base64.b64decode(encrypted_code).decode() + base64_decoded = base64.b64decode(compact, validate=True).decode('utf-8') except Exception as e: - raise ValueError(f"Base64 decryption failed: {e}") + raise ValueError(f"Base64 decryption failed: {e}") from e if not base64_decoded: raise ValueError("Base64 decryption failed. The result is empty.") @@ -336,16 +432,16 @@ def decrypt(encrypted_code: str, mapping: dict = _character_map) -> str: return original_code except Exception as e: - if isinstance(e, (ValueError, RuntimeError)): + if isinstance(e, (ValueError, RuntimeError, TypeError)): raise - raise RuntimeError(f"An error occurred during decryption: {e}") + raise RuntimeError(f"An error occurred during decryption: {e}") from e -def encrypt_to_file(code: str, output_file: str, mapping: dict = _character_map) -> None: +def encrypt_to_file(code: Union[str, bytes], output_file: str, mapping: dict = _character_map) -> None: """ Encrypt the given Python code using multiple methods and embed it as comments in a Python file. Parameters: - code (str): The Python code to encrypt. + code (str or bytes): The Python code to encrypt. output_file (str): The path to the output Python file to embed encrypted code. mapping (dict): The mapping dictionary for character replacements. @@ -354,10 +450,10 @@ def encrypt_to_file(code: str, output_file: str, mapping: dict = _character_map) """ encrypted_code = encrypt(code, mapping) try: - with open(output_file, 'w') as file: + with open(output_file, 'w', encoding='utf-8') as file: file.write(f"# {encrypted_code}") - except IOError as e: - raise IOError(f"Failed to write to file '{output_file}': {e}") + except OSError as e: + raise OSError(f"Failed to write to file '{output_file}': {e}") from e def decrypt_code(encrypted_code: str, mapping: dict) -> str: """Decrypts the encrypted code using the reverse of the encryption methods.""" @@ -367,6 +463,11 @@ def run(encrypted_source: Union[str, IO], mapping: dict = _character_map) -> Non """ Decrypt and execute the Python code embedded in the specified file or stream. + The decrypted code is executed with ``__name__`` set to ``"__main__"`` in a clean + namespace, isolated from CodeSafe's module globals. Note that this is code + obfuscation, not a security boundary: the decrypted code runs with the full + permissions of the current process. + Parameters: encrypted_source (str or stream): Path to the file or a file-like object with embedded encrypted code. mapping (dict): The mapping dictionary for character replacements. @@ -376,7 +477,7 @@ def run(encrypted_source: Union[str, IO], mapping: dict = _character_map) -> Non """ try: if isinstance(encrypted_source, str): - with open(encrypted_source, 'r') as file: + with open(encrypted_source, 'r', encoding='utf-8') as file: content = file.read() else: content = encrypted_source.read() @@ -384,7 +485,7 @@ def run(encrypted_source: Union[str, IO], mapping: dict = _character_map) -> Non content = content.decode('utf-8') # Extract the encrypted code from the comments - match = re.search(r'# ([A-Za-z0-9+/=]+)', content) + match = re.search(r'^# ([A-Za-z0-9+/=]+)\s*$', content, re.MULTILINE) if not match: raise ValueError("No valid encrypted code found in the source.") @@ -392,13 +493,14 @@ def run(encrypted_source: Union[str, IO], mapping: dict = _character_map) -> Non # Decrypt the code decrypted_code = decrypt(encrypted_code, mapping) - - # Execute the decrypted Python code - exec(decrypted_code) except Exception as e: - if isinstance(e, RuntimeError): + if isinstance(e, (RuntimeError, ValueError, OSError)): raise - raise RuntimeError(f"An error occurred during decryption and execution: {e}") + raise RuntimeError(f"An error occurred during decryption and execution: {e}") from e + + # Execute the decrypted Python code in a clean namespace that looks like a + # script run as __main__, isolated from CodeSafe's own module globals. + exec(decrypted_code, {"__name__": "__main__"}) def decrypt_to_file(encrypted_file: Union[str, IO], output_file: Union[str, IO], mapping: dict = _character_map) -> None: """ @@ -419,7 +521,7 @@ def decrypt_to_file(encrypted_file: Union[str, IO], output_file: Union[str, IO], # Read the encrypted code if isinstance(encrypted_file, str): - with open(encrypted_file, 'r') as file: + with open(encrypted_file, 'r', encoding='utf-8') as file: content = file.read() else: content = encrypted_file.read() @@ -427,7 +529,7 @@ def decrypt_to_file(encrypted_file: Union[str, IO], output_file: Union[str, IO], content = content.decode('utf-8') # Extract the encrypted code - match = re.search(r'# ([A-Za-z0-9+/=]+)', content) + match = re.search(r'^# ([A-Za-z0-9+/=]+)\s*$', content, re.MULTILINE) if not match: raise ValueError("No encrypted code found in the source.") @@ -438,12 +540,12 @@ def decrypt_to_file(encrypted_file: Union[str, IO], output_file: Union[str, IO], # Write the decrypted code if isinstance(output_file, str): - with open(output_file, 'w') as file: + with open(output_file, 'w', encoding='utf-8') as file: file.write(decrypted_code) else: output_file.write(decrypted_code) except Exception as e: - if isinstance(e, (ValueError, RuntimeError, IOError, FileNotFoundError)): + if isinstance(e, (ValueError, RuntimeError, OSError)): raise - raise RuntimeError(f"An error occurred during decryption to file: {e}") \ No newline at end of file + raise RuntimeError(f"An error occurred during decryption to file: {e}") from e \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..d3f2a3b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,37 @@ +[build-system] +requires = ["setuptools>=77"] +build-backend = "setuptools.build_meta" + +[project] +name = "codesafe" +version = "0.0.6" +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" +license = "MIT" +license-files = ["LICENSE"] +authors = [ + {name = "Infinitode Pty Ltd", email = "infinitode.ltd@gmail.com"}, +] +keywords = ["eval", "safe-eval", "sandbox", "encryption", "obfuscation", "ast", "security"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Operating System :: OS Independent", + "Topic :: Security", + "Topic :: Software Development :: Libraries :: Python Modules", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] + +[project.urls] +Homepage = "https://github.com/infinitode/codesafe" +Repository = "https://github.com/infinitode/codesafe" +Issues = "https://github.com/infinitode/codesafe/issues" + +[tool.setuptools] +packages = ["codesafe"] diff --git a/setup.py b/setup.py index 77bb89e..8886c85 100644 --- a/setup.py +++ b/setup.py @@ -1,29 +1,10 @@ -from setuptools import setup, find_packages +"""Compatibility shim. -with open("README.md", "r", encoding="utf-8") as fh: - long_description = fh.read() +The canonical project metadata lives in ``pyproject.toml`` (PEP 621). +This file exists so that legacy tooling that expects a ``setup.py`` +keeps working. The published version is defined in ``pyproject.toml`` +and must match the release tag. +""" +from setuptools import setup -setup( - name='codesafe', - version='{{VERSION_PLACEHOLDER}}', - author='Infinitode Pty Ltd', - author_email='infinitode.ltd@gmail.com', - 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.", - long_description=long_description, - long_description_content_type='text/markdown', - url='https://github.com/infinitode/codesafe', - packages=find_packages(), - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - ], - python_requires='>=3.6', -) +setup() diff --git a/test.py b/test.py index 0956a8b..9542b37 100644 --- a/test.py +++ b/test.py @@ -68,7 +68,7 @@ def test_attribute_access_disabled(self): def test_security_error_on_unsafe_function(self): expression = "os.getcwd()" # Attempting to call an unsafe function - try: + with self.assertRaises(UnsafeExpressionError): safe_eval( expression, allowed_builtins=self.safe_builtins, @@ -76,16 +76,13 @@ def test_security_error_on_unsafe_function(self): timeout=3, restricted_imports=self.restricted_imports, allowed_function_calls=self.allowed_function_calls - ) - except UnsafeExpressionError: - pass + ) def test_timeout_error(self): expression = "long_running_function()" # This will run indefinitely - # expression = "sleep(5)" # Sleep for 5 seconds # Check if EvaluationTimeoutError is raised - try: + with self.assertRaises(EvaluationTimeoutError): safe_eval( expression, allowed_builtins=self.safe_builtins, @@ -95,9 +92,6 @@ def test_timeout_error(self): allowed_function_calls=self.allowed_function_calls, immediate_termination=True ) - self.fail("EvaluationTimeoutError not raised") # Fail if no exception is raised - except EvaluationTimeoutError: - pass def test_encryption(self): # Encrypt and save the code to a file @@ -144,6 +138,41 @@ def test_bytes_and_streams(self): decrypt_to_file(io.StringIO(f"# {enc}"), out_stream) self.assertEqual(out_stream.getvalue(), "print('Bytes work')") + def test_encrypt_rejects_unmapped_characters(self): + # Non-ASCII characters cannot be represented by the 64-char mapping + # format, so encrypt() must fail loudly instead of corrupting the output. + with self.assertRaises(ValueError): + encrypt("print('hΓ©llo')") + with self.assertRaises(ValueError): + encrypt(b"print('\xe2\x9c\x93')") # UTF-8 for βœ“ + + def test_encrypt_validates_mapping_values(self): + # Every mapping value must be exactly 64 characters (fixed chunk size). + with self.assertRaises(ValueError): + encrypt("print('hi')", mapping={"p": "too-short"}) + + def test_decrypt_rejects_invalid_base64(self): + with self.assertRaises(ValueError): + decrypt("!!! definitely not base64 !!!") + + def test_exception_propagates_from_evaluation(self): + with self.assertRaises(ZeroDivisionError): + safe_eval("1/0") + with self.assertRaises(NameError): + safe_eval("this_name_is_not_defined") + + def test_timeout_must_be_positive(self): + for invalid in (0, -1): + with self.assertRaises(ValueError): + safe_eval("1 + 1", timeout=invalid) + + def test_dir_and_id_are_not_available(self): + # Removed from the default safe builtins: pure information leakage. + with self.assertRaises(UnsafeExpressionError): + safe_eval("dir()") + with self.assertRaises(UnsafeExpressionError): + safe_eval("id(1)") + def tearDown(self): # Clean up: remove the files created during the tests if os.path.exists(self.encrypted_file): diff --git a/test_poc_vulnerability.py b/test_poc_vulnerability.py index 46cebcd..9995bcb 100644 --- a/test_poc_vulnerability.py +++ b/test_poc_vulnerability.py @@ -3,9 +3,10 @@ Tests the fix for the sandbox escape vulnerability and other potential attack vectors. """ import unittest -import os +import time from pathlib import Path -from codesafe import safe_eval, UnsafeExpressionError +from multiprocessing import active_children +from codesafe import safe_eval, UnsafeExpressionError, EvaluationTimeoutError # Top-level helper function for multiprocessing pickling compatibility on Windows @@ -13,6 +14,12 @@ def custom_func(x): return x * 2 +# Top-level helper that runs forever (used by the process-leak regression test) +def _busy_forever(): + while True: + pass + + class TestVulnerabilityFixes(unittest.TestCase): """Test cases for security vulnerabilities and their fixes.""" @@ -520,5 +527,88 @@ def test_walrus_operator_call_blocked(self): print("[SKIP] Walrus operator not available in this Python version") +class TestHardeningRegression(unittest.TestCase): + """Regression tests for the v0.0.6 hardening and bug-fix release.""" + + # ==================== DUNDER ATTRIBUTE ESCAPES ==================== + # A fixed blocklist of dunder names is not enough: dunders can be reached + # through string arguments that the AST checker never sees. All dunder + # attributes must be rejected. + + def test_dunder_getattribute_class_blocked(self): + """Reading __class__ via __getattribute__ string argument is blocked.""" + payload = "().__getattribute__('__class__')" + with self.assertRaises(UnsafeExpressionError): + safe_eval(payload, allow_attributes=True) + print("[PASS] __getattribute__('__class__') is blocked") + + def test_dunder_getattribute_len_blocked(self): + """Calling __getattribute__ at all is blocked.""" + payload = "''.__getattribute__('__len__')()" + with self.assertRaises(UnsafeExpressionError): + safe_eval(payload, allow_attributes=True) + print("[PASS] __getattribute__('__len__')() is blocked") + + def test_dunder_mro_blocked(self): + """__mro__ attribute access is blocked.""" + payload = "type('').__mro__" + with self.assertRaises(UnsafeExpressionError): + safe_eval(payload, allow_attributes=True) + print("[PASS] type('').__mro__ is blocked") + + def test_dunder_dict_blocked(self): + """__dict__ attribute access is blocked.""" + payload = "type('X', (), {}).__dict__" + with self.assertRaises(UnsafeExpressionError): + safe_eval(payload, allow_attributes=True) + print("[PASS] type('X').__dict__ is blocked") + + def test_safe_non_dunder_attribute_calls_still_work(self): + """Non-dunder method calls keep working with allow_attributes=True.""" + result = safe_eval("'hello'.upper()", allow_attributes=True) + self.assertEqual(result, "HELLO") + print("[PASS] Safe non-dunder method calls still work") + + # ==================== RESULT SERIALIZATION ==================== + + def test_unpicklable_result_raises_runtime_error(self): + """An unpicklable result raises a clear RuntimeError, not a timeout.""" + with self.assertRaises(RuntimeError): + safe_eval("lambda: 1") + print("[PASS] Unpicklable lambda result raises RuntimeError") + + def test_unpicklable_generator_raises_runtime_error(self): + """An unpicklable generator result raises a clear RuntimeError.""" + with self.assertRaises(RuntimeError): + safe_eval("(x for x in range(3))") + print("[PASS] Unpicklable generator result raises RuntimeError") + + # ==================== PROCESS CLEANUP ==================== + + def test_no_process_leak_on_timeout(self): + """A timed-out evaluation never outlives the call, even with + immediate_termination=False (deprecated).""" + with self.assertRaises(EvaluationTimeoutError): + safe_eval( + "_busy_forever()", + allowed_vars={"_busy_forever": _busy_forever}, + allowed_function_calls=["_busy_forever"], + timeout=0.2, + immediate_termination=False, + ) + time.sleep(0.5) + self.assertEqual(active_children(), []) + print("[PASS] Timed-out child process is always terminated") + + # ==================== INPUT VALIDATION ==================== + + def test_non_positive_timeout_rejected(self): + """Zero and negative timeouts are rejected with ValueError.""" + for invalid in (0, -5): + with self.assertRaises(ValueError): + safe_eval("1 + 1", timeout=invalid) + print("[PASS] Non-positive timeouts are rejected") + + if __name__ == "__main__": unittest.main(verbosity=2) \ No newline at end of file From dc2d23ed2aa73870eed9183ae9591806a8bac209 Mon Sep 17 00:00:00 2001 From: johanbeytell1 <107624055+johanbeytell1@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:47:25 +0000 Subject: [PATCH 2/2] Use authenticated crypto for encryption, drop restricted_imports, TP release flow Encryption (breaking change, documented): - encrypt() now uses Fernet (AES-128-CBC + HMAC-SHA256) with a 256-bit key; any Unicode source round-trips losslessly (plaintext is UTF-8) - New generate_key() helper; keys resolve via key= > CODESAFE_KEY env > built-in default (public, obfuscation-grade, documented) - Files written by encrypt_to_file() are self-describing: # codesafe:v2: - Legacy pre-0.0.6 Base64 Caesar payloads remain fully decryptable/runnable via decrypt()/decrypt_to_file()/run(); legacy mapping still honored there - encrypt() no longer accepts the Caesar mapping parameter (TypeError) safe_eval: - Restricted imports parameter removed (redundant with the blanket import ban) - Results are serialized with cloudpickle: lambdas and dynamically created classes can now be returned; generators/modules still raise a clear RuntimeError (instead of the old misleading EvaluationTimeoutError) CI/release: - Tests run on 3.8/3.9 via ubuntu-22.04 (not available on ubuntu-latest/24.04, which is why those jobs failed at setup); deps installed directly - Publish workflow uses PyPI Trusted Publishing (OIDC, id-token: write); no stored API tokens; distributions carry PEP 740 provenance attestations - README gains a provenance badge linked to the PyPI security tab Docs: - New SECURITY.md (private reporting instructions, supported versions, published advisories) - SECURITY_AUDIT.md dropped; its content now lives in the README (Security Advisory + Security Limitations & Notes sections) - v0.0.5 changelog now carries a prominent warning about the second, known sandbox-escape issue (allow_attributes=True, fixed in 0.0.6) - _ = backwards-compatible positional legacy mapping for decrypt-time calls Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .github/workflows/build_and_publish.yml | 13 +- .github/workflows/test.yml | 16 +- .gitignore | 1 + README.md | 90 ++++-- SECURITY.md | 57 ++++ SECURITY_AUDIT.md | 116 -------- codesafe/__init__.py | 363 +++++++++++++++--------- pyproject.toml | 11 +- test.py | 84 ++++-- test_poc_vulnerability.py | 24 +- 10 files changed, 470 insertions(+), 305 deletions(-) create mode 100644 SECURITY.md delete mode 100644 SECURITY_AUDIT.md diff --git a/.github/workflows/build_and_publish.yml b/.github/workflows/build_and_publish.yml index cf1a96c..36c4dcc 100644 --- a/.github/workflows/build_and_publish.yml +++ b/.github/workflows/build_and_publish.yml @@ -9,6 +9,14 @@ jobs: build-n-publish: name: Build and publish Python 🐍 distributions πŸ“¦ to PyPI runs-on: ubuntu-latest + + # Required for PyPI Trusted Publishing (OIDC). No API token or + # password is stored in this repository. The token is minted on + # demand by GitHub and verified by PyPI against the trusted + # publisher configuration for this project. + permissions: + id-token: write + steps: - uses: actions/checkout@v4 @@ -34,7 +42,8 @@ jobs: - name: Build a binary wheel and source distribution run: python -m build + # Publishes via PyPI Trusted Publishing (OIDC). The distribution + # is attested (PEP 740) and the provenance is shown on PyPI under + # the "Provenance" information for the release files. - name: Publish distribution πŸ“¦ to PyPI uses: pypa/gh-action-pypi-publish@release/v1 - with: - password: ${{ secrets.PYPI_API_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1fec3c9..ab5dee4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,8 +13,14 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest] - python-version: ['3.8', '3.9', '3.10', '3.11', '3.12'] + python-version: ['3.10', '3.11', '3.12'] include: + # Python 3.8/3.9 are not available in the ubuntu-latest (24.04) + # toolcache, so they run on ubuntu-22.04 instead. + - os: ubuntu-22.04 + python-version: '3.8' + - os: ubuntu-22.04 + python-version: '3.9' - os: windows-latest python-version: '3.12' - os: macos-latest @@ -28,5 +34,13 @@ jobs: with: python-version: ${{ matrix.python-version }} + - name: Install dependencies + # The test suite imports codesafe from the repository root, so the + # package itself does not need to be built; only its runtime + # dependencies are required. + run: | + python -m pip install --upgrade pip + python -m pip install "cryptography>=41" "cloudpickle>=2.2" + - name: Run test suite run: python -m unittest test.py test_poc_vulnerability.py -v diff --git a/.gitignore b/.gitignore index 5707023..516cd64 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ encrypted_code.encrypt decrypted.py codesafe_rce_marker.txt pathlib_test.txt +v2_test_prog.encrypt diff --git a/README.md b/README.md index 811e565..61bd3a5 100644 --- a/README.md +++ b/README.md @@ -4,16 +4,39 @@ ![Downloads](https://pepy.tech/badge/codesafe) ![License Compliance](https://img.shields.io/badge/license-compliance-brightgreen.svg) ![PyPI Version](https://img.shields.io/pypi/v/codesafe) +[![PyPI - Provenance](https://img.shields.io/badge/provenance-trusted%20publishing-3673A5?logo=pypi&logoColor=white)](https://pypi.org/project/codesafe/#security) 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. *CodeSafe is an experimental library, and we're still running some tests on it. If you encounter any issues or have an edge use case, please let us know.* > [!NOTE] -> **CodeSafe** is intended to quickly encrypt/decrypt code files and run them (only for Python script files) while in their encrypted form, but not as a means for powerful encryption, just code obfuscation. We have also included a `safe_eval` function, that can safely evaluate expressions within a safe environment. +> **CodeSafe** encrypts Python files with authenticated encryption (Fernet: AES-128-CBC + HMAC-SHA256) and can run them without exposing the plaintext on disk (e.g. to end-users). Note that the built-in default key is public, so for real confidentiality you must supply your own key - see [Security Limitations & Notes](#security-limitations--notes). We have also included a `safe_eval` function, that can safely evaluate expressions within a safe environment. ## Security Advisory +### Reporting a vulnerability + +**Please do not report security vulnerabilities through public issues.** See [SECURITY.md](SECURITY.md) for how to report vulnerabilities to us privately (private vulnerability reporting or email). We maintain this page with published advisories: + +| Advisory | CVE / GHSA | Affected | Fixed in | +| :--- | :--- | :--- | :--- | +| `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__')`) | Pending assignment | 0.0.3 - 0.0.5 | **0.0.6** | + +You can browse all advisories at https://github.com/Infinitode/CodeSafe/security/advisories + +### 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.** + +- **Vulnerability**: The dunder blocklist only inspected attribute names written literally in the expression. `().__getattribute__('__class__')` walked past it and returned ``, instead of being rejected. All dunder names (`__class__`, `__mro__`, `__globals__`, `__dict__`, `__subclasses__`, ...) were affected via `__getattribute__`/`__mro__`/`__dict__` and similar indirection. +- **Impact**: Reading dunder attributes defeats the class-hierarchy-traversal protections and, depending on the allowed functions/attributes in the evaluation context, can lead to a full sandbox escape and arbitrary code execution (the same impact class as GHSA-7gp8-3j6q-v4h8). +- **Affected versions**: 0.0.3, 0.0.4, 0.0.5 +- **Fixed in**: Version **0.0.6** - all attribute names starting with `__` are now always rejected. +- **Workaround for older versions**: leave `allow_attributes` at its default (`False`). There is no complete workaround otherwise - upgrade. +- **Advisory**: a GitHub Security Advisory is being prepared for this issue and will be published together with v0.0.6, at which point a CVE ID will be requested and assigned. Track it under [GitHub Security Advisories](https://github.com/Infinitode/CodeSafe/security/advisories). + ### Critical Vulnerability Fixed in v0.0.5 **Versions 0.0.1 through 0.0.4 contain a known sandbox escape vulnerability in `safe_eval()` that allows arbitrary code execution.** @@ -32,7 +55,7 @@ The fix includes: 2. Using a minimal built-ins allowlist that excludes dangerous functions like `exec`, `eval`, `compile`, and `__import__` 3. Added comprehensive regression tests for indirect call targets -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. +Version **0.0.6** additionally closes this second, related sandbox issue: 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. 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. @@ -45,7 +68,7 @@ CodeSafe v0.0.6 includes a rigorous test suite (`TestVulnerabilityFixes`, `TestE ### Test Results Summary -**73/73 Tests Passing** (`100% Pass Rate` across all vector categories) +**79/79 Tests Passing** (`100% Pass Rate` across all vector categories) | Attack Vector / Category | Specific Vectors Tested | Status | | :--- | :--- | :--- | @@ -56,7 +79,7 @@ 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** | Unpicklable results raise a clear `RuntimeError`; child exceptions propagate with their original type; `queue.empty()` race eliminated | **[PASS] Working** | +| **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** | | **Functional Baseline** | Safe arithmetic, string/list/dict operations, standard safe builtins (`len`, `max`, `abs`), explicitly allowed functions | **[PASS] Working** | ### Running the Tests @@ -75,21 +98,27 @@ python -m unittest test.py test_poc_vulnerability.py -v ### Changelog v0.0.6: -* **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__')`. -* **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. -* **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. -* **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. -* **Bug Fix**: `decrypt()` validates the Base64 input (`validate=True`) and produces clear errors for corrupt input; surrounding whitespace is tolerated. +* **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**: `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. -* 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). -* 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. -* See [SECURITY_AUDIT.md](SECURITY_AUDIT.md) for the full audit findings and remediation notes. +* The package now depends on `cryptography` and `cloudpickle` (installed automatically by pip). +* 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)). ### 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.** + * **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 * Implemented minimal safe builtins whitelist excluding `exec`, `eval`, `compile`, `__import__`, and similar dangerous functions @@ -118,7 +147,7 @@ python -m unittest test.py test_poc_vulnerability.py -v ## Installation -You can install CodeSafe using pip: +You can install CodeSafe using pip (it automatically installs the `cryptography` and `cloudpickle` dependencies): ```bash pip install codesafe @@ -142,7 +171,7 @@ Please ensure that you have one of these Python versions installed before using ## Features * **Safe Eval**: Safely allow `eval()` expressions to run, while maintaining complete control over the entire evaluation process. -* **Code Encryption/Decryption**: Quickly encrypt your code. This is meant for code obfuscation, and not high-level encryption. +* **Code Encryption/Decryption**: Encrypt your code with authenticated cryptography (Fernet: AES-128-CBC + HMAC-SHA256), including full Unicode support. Legacy pre-0.0.6 `.encrypt` files can still be decrypted. * **Run encrypted code at runtime**: Run your encrypted code files, without needing to expose your code to end-users. > [!NOTE] @@ -181,8 +210,8 @@ if __name__ == '__main__': expression = "1 + 1" disallowed_expression = "os.getcwd()" - result1 = safe_eval(expression, timeout=10, immediate_termination=True) - result2 = safe_eval(disallowed_expression, timeout=10, immediate_termination=True) + result1 = safe_eval(expression, timeout=10) + result2 = safe_eval(disallowed_expression, timeout=10) # raises UnsafeExpressionError ``` @@ -190,12 +219,12 @@ if __name__ == '__main__': > 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). > [!IMPORTANT] -> 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. +> 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. ### Encrypt & Run Code ```python -from codesafe import encrypt_to_file, decrypt_to_file, run +from codesafe import encrypt_to_file, decrypt_to_file, run, generate_key code = """ greetJohnny = "Hello Johnny!" @@ -206,19 +235,38 @@ def greet_someone(greeting): greet_someone(greetJohnny) """ +# Generate a key (do this once and keep it secret!) +key = generate_key() +# ...or set the CODESAFE_KEY environment variable instead of passing key= everywhere + # Encrypt the code encrypted_file_path = "encrypted_code.encrypt" -encrypt_to_file(code, encrypted_file_path) +encrypt_to_file(code, encrypted_file_path, key=key) # Run the encrypted code -run(encrypted_file_path) # Hello Johnny! +run(encrypted_file_path, key=key) # Hello Johnny! # Decrypt code to another file output_file = "decrypted_code.py" -decrypt_to_file(encrypted_file_path, output_file) +decrypt_to_file(encrypted_file_path, output_file, key=key) ``` +If you omit `key=`, CodeSafe uses the `CODESAFE_KEY` environment variable, falling back to a built-in default key that is public knowledge - fine for hiding code from casual reading, useless against anyone determined. **Pass your own key for real confidentiality.** Legacy pre-0.0.6 `.encrypt` files can still be opened by the same functions (pass the old Caesar `mapping` positionally to decrypt legacy payloads if you used a custom one). + +## Security Limitations & Notes + +CodeSafe is designed for practical code protection, not absolute guarantees. Please read these before relying on it: + +* **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. +* **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. + ## Contributing Contributions are welcome! If you encounter any issues, have suggestions, or want to contribute to CodeSafe, please open an issue or submit a pull request on [GitHub](https://github.com/infinitode/codesafe?utm_source=gemini). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..257abea --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,57 @@ +# Security Policy + +We take the security of CodeSafe seriously. Thank you for helping keep CodeSafe and its users safe. + +## Reporting a vulnerability + +**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.** + +Instead, please report them privately using one of the following channels: + +1. **GitHub private vulnerability reporting (preferred):** open the [Security tab](https://github.com/Infinitode/CodeSafe/security) of this repository and choose **Report a vulnerability** (or go directly to https://github.com/Infinitode/CodeSafe/security/advisories/new). This creates a private advisory visible only to the maintainers, and allows us to collaborate on the fix and publish a coordinated disclosure. +2. **Email:** [infinitode.ltd@gmail.com](mailto:infinitode.ltd@gmail.com) with a subject line starting with `[SECURITY] CodeSafe`. + +Please include as much of the following as you can: + +- The package version(s) affected +- A description of the vulnerability and its impact +- Steps to reproduce / a proof of concept +- The environment (OS, Python version) +- Any suggested mitigations or fixes (optional) + +## What to expect + +- We aim to acknowledge your report within **7 days** (best effort; this is a small open-source project). +- We will assess the report, determine the severity (CVSS) and the affected version range, and keep you informed of progress. +- We will develop the fix privately, prepare a draft GitHub Security Advisory, and publish the advisory, the fix (a new release) and (if applicable) request a CVE ID when the release is out β€” following coordinated disclosure. +- With your permission, we will credit you in the advisory and changelog. If you prefer to remain anonymous, just say so. + +We ask that you give us reasonable time to release a fix before any public disclosure. + +## Supported versions + +| Version | Supported | +| :--- | :--- | +| 0.0.6 and later | βœ… Yes | +| 0.0.5 | ⚠️ Known issue β€” see [Security Advisory](README.md#security-advisory); upgrade to 0.0.6 | +| 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. + +## Published advisories + +| Advisory | CVE / GHSA | Affected | Fixed in | +| :--- | :--- | :--- | :--- | +| `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`) | Pending assignment (draft advisory) | 0.0.3 - 0.0.5 | 0.0.6 | + +See https://github.com/Infinitode/CodeSafe/security/advisories for the canonical list. + +## Scope notes + +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. +- **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/SECURITY_AUDIT.md b/SECURITY_AUDIT.md deleted file mode 100644 index 86a020f..0000000 --- a/SECURITY_AUDIT.md +++ /dev/null @@ -1,116 +0,0 @@ -# CodeSafe Security & Quality Audit - -**Date:** 2026-11-24 Β· **Scope:** `codesafe` package (`codesafe/__init__.py`), packaging, CI, tests Β· **Audited from commit:** `916cd04` - -This document records the issues found during the audit and how they were addressed in **v0.0.6**. Findings marked βœ… are fixed and covered by regression tests (`TestHardeningRegression` in `test_poc_vulnerability.py`, plus new cases in `test.py`). Findings marked ⚠️ are documented limitations or recommendations for the maintainers. - ---- - -## 1. Critical / High - -### 1.1 Dunder attribute filter bypass via string arguments β€” βœ… Fixed -**Severity:** High Β· **Component:** `safe_eval` (`allow_attributes=True`) Β· **Introduced:** v0.0.3 - -`_check_ast` only blocked a hardcoded list of dunder attributes (`__globals__`, `__class__`, …). Any dunder not on the list β€” and every dunder reached through a *string argument*, which the AST checker never inspects β€” was allowed: - -```python ->>> safe_eval("().__getattribute__('__class__')", allow_attributes=True) - -``` - -`__getattribute__`, `__getattr__`, `__mro__`, `__dict__`, `__getattribute__('__len__')()`, etc. were all reachable. This is exactly the class of bug the v0.0.5 CVE fix was meant to close, one layer up. - -**Fix:** all attributes whose names start with `__` are now always rejected, in both the attribute-access check and the method-call check. Regression tests cover `__getattribute__`, `__mro__`, `__dict__` and friends. - -### 1.2 `immediate_termination=False` leaks runaway CPU processes β€” βœ… Fixed -**Severity:** High (DoS) Β· **Component:** `safe_eval` - -When the timeout expired and `immediate_termination` was `False`, the child process was left running β€” a `while True: pass` expression could spin a core forever (confirmed with `multiprocessing.active_children()`). - -**Fix:** the child is always terminated on timeout. `immediate_termination` is deprecated and ignored (kept for backwards compatibility); the docstring, README and changelog call this out. - -### 1.3 Encryption silently corrupts any non-ASCII code β€” βœ… Fixed -**Severity:** High (data loss) Β· **Component:** `encrypt` / `encrypt_with_mapping` - -The cipher replaced every mapped character with a fixed 64-character output and passed everything else through unchanged, but `decrypt` re-splits the stream into fixed 64-character chunks. Any unmapped character (i.e. **any non-ASCII source**: `print('hΓ©llo')`, emoji, typographic quotes, non-ASCII identifiers) silently misaligned the chunks and produced garbage β€” irreversible corruption of the "encrypted" artifact, with no error at encrypt time. Even Latin-1 (`Γ©`) was broken, not just wide Unicode. - -**Fix:** -- `encrypt()` validates that every character in `code` is present in the `mapping` and every mapping value is exactly 64 characters; otherwise a clear `ValueError` is raised (fail loudly, never corrupt). -- Validation applies to custom mappings too. - -### 1.4 Misleading `EvaluationTimeoutError` / dropped results (`queue.empty()` race) β€” βœ… Fixed -**Severity:** Medium-High Β· **Component:** `safe_eval` - -After `process.join()`, the code trusted `multiprocessing.Queue.empty()`, which is documented as unreliable. Worse, unpicklable results (lambdas, generators, `mappingproxy`) were pickled in the queue's background feeder thread β€” never in the caller β€” so the failure was invisible and surfaced as `EvaluationTimeoutError: No result returned from the evaluation process.` (confirmed: `safe_eval("lambda: 1")` always produced that error, never a `PicklingError`). - -**Fix:** the child now serializes its result synchronously with `pickle.dumps` (falling back to a picklable `RuntimeError` with a clear message), and the parent polls with `queue.get(timeout=1.0)`. Errors always reach the caller deterministically; the 1-second poll covers reader-thread lag. Child processes and the queue are always closed in `finally`. - ---- - -## 2. Medium - -### 2.1 Source tree cannot be built or installed β€” βœ… Fixed -**Severity:** Medium Β· **Component:** packaging - -`setup.py` declared `version='{{VERSION_PLACEHOLDER}}'`, which setuptools rejects (`Invalid version`). `python -m build`, `pip install .` and `pip install .` from a tag all failed; only the CI `sed` trick made releases work, and it produced distributions whose version came from the tag rather than the source. - -**Fix:** PEP 621 `pyproject.toml` is now the single source of truth (`version = "0.0.6"`, SPDX `MIT`, proper metadata, project URLs). `setup.py` is a thin shim. The publish workflow verifies the tag matches the version. Wheels and sdists build cleanly from a fresh checkout (verified). - -### 2.2 Publish workflow was broken β€” βœ… Fixed -**Severity:** Medium Β· **Component:** CI - -- `::set-output` is disabled on current GitHub runners β†’ the "Extract tag name" step (and the whole release) would fail. -- `actions/checkout@master`, `setup-python@v3`, `gh-action-pypi-publish@master` β€” unpinned/deprecated. -- `python setup.py sdist bdist_wheel` β€” removed from modern setuptools; `python -m build` is the supported route. -- No check that the tag matches the package version. - -**Fix:** rewritten workflow (`checkout@v4`, `setup-python@v5`, `build`, tag↔version consistency check, `gh-action-pypi-publish@release/v1`). A separate `test.yml` now runs the full test suite on Python 3.8–3.12 (Linux) plus 3.12 on Windows/macOS for every push/PR. - -### 2.3 No regression tests for the above; a test that cannot fail β€” βœ… Fixed -**Severity:** Medium Β· **Component:** tests - -- `test_security_error_on_unsafe_function` wrapped its assertion in `try/except UnsafeExpressionError: pass` β€” it passed even if no exception was raised. -- Nothing covered: unpicklable results, process leaks, Unicode encryption, timeout validation, the dunder-string-argument bypass. - -**Fix:** that test now uses `assertRaises`; `TestHardeningRegression` (9 tests) and 6 new functional tests added (73 tests total, all passing). - -### 2.4 Base64 input never validated β€” βœ… Fixed -`base64.b64decode` without `validate=True` ignored invalid characters, so corrupt `.encrypt` files degraded into confusing "empty result" errors. Now decoded with `validate=True` (surrounding/embedded whitespace is stripped first) and invalid input raises a clear `ValueError`. - ---- - -## 3. Low / Hardening - -- **`dir()` and `id()` removed from the default safe builtins.** Pure information leakage (scope introspection, addresses) with no legitimate expression use. βœ… -- **Non-positive `timeout` values are rejected** with `ValueError` instead of reaching `join()`. βœ… -- **`run()` now executes decrypted code with `__name__ == "__main__"`** in a fresh namespace instead of CodeSafe's module globals. (Still obfuscation, not a security boundary β€” documented.) βœ… -- **Exception chaining** (`raise ... from e`) added throughout; child exceptions propagate with their original type; `BaseException` (e.g. `SystemExit` from an allowed function) is caught so the child never vanishes silently. βœ… -- **All file I/O in encrypt/decrypt paths explicitly uses UTF-8.** βœ… -- **Anchored extraction regex** for the `# ` payload (`^# …$`, multiline) β€” a base64 blob can no longer match inside an arbitrary comment; trailing `\r`/whitespace tolerated. βœ… -- **`__version__`** is now exported; **`codesafe.egg-info`**, test artifacts and virtualenvs are git-ignored; `IOError`/`FileNotFoundError` handlers unified to `OSError`. βœ… - ---- - -## 4. Documented limitations & recommendations (not bugs, by design) - -- ⚠️ **Encryption is obfuscation, not encryption.** The "key" is shipped inside the package. Do not rely on it for confidentiality; use real cryptographic tooling for secrets. (Already stated in the README; kept for emphasis.) -- ⚠️ **Encryption alphabet is printable ASCII + common whitespace only** (the format maps each character to a fixed 64-char chunk). Escape non-ASCII characters (`\uXXXX`) in source before encrypting. Custom mappings must map every used character and use exactly 64-character values β€” now validated at encrypt time. -- ⚠️ **`safe_eval` is not a perfect sandbox.** It relies on AST filtering + a subprocess timeout, and expressions run with the privileges of the host process. Standard-library objects reachable through the allowlist may still have unexpected behaviours; defense in depth (containers, `seccomp`, dropped privileges) is recommended for hostile input. `allow_attributes=True` is convenient but always increases risk β€” prefer leaving it `False`. -- ⚠️ **`allowed_vars` are trusted code.** Anything passed in `allowed_vars`/`allowed_builtins` runs outside the sandbox checks if *it* does something dangerous (e.g. `allowed_vars={'system': os.system}`). The sandbox protects against the expression, not against what you hand it. -- ⚠️ **Results must be picklable.** Lambdas, generators, modules and `mappingproxy` objects cannot be returned; you now get a clear `RuntimeError` instead of a hang or a wrong error type. -- ⚠️ **`restricted_imports` is effectively redundant** β€” imports are always rejected in expressions. Consider deprecating it in a future release. -- ⚠️ **Custom `mapping` encryption/decryption performance** is O(nΒ·64); fine for typical sources, but very large files will be slow and produce ~64Γ— output. Consider a binary (non-text) format with length-prefixing in 1.0. -- ⚠️ **`dir`/`id` removal is technically breaking** for anyone relying on them in expressions; noted in the changelog. -- ⚠️ **`type` remains in the default safe builtins.** It is required for `isinstance`-style patterns and `type(x)` introspection; with all dunders blocked it does not by itself yield an escape path, but it is the remaining reflection-adjacent primitive worth watching. - -## 5. Residual risks of the fixed design - -- Results cross the process boundary via `pickle`. Payloads are produced and consumed by CodeSafe itself, but any future change that lets callers or decrypted code influence the pickle stream must treat unpickling as code execution. -- The 64-chunk format and the `# ` container format are untouched for compatibility with existing `.encrypt` files; they carry no integrity or authenticity guarantees. Tampered files decrypt to garbage or fail loudly, but are not detectable as forgeries. - -## 6. CVE tracking - -| Advisory | CVE | GHSA | Fixed in | Status | -| :--- | :--- | :--- | :--- | :--- | -| `safe_eval` sandbox escape via indirect subscript call | **CVE-2026-133467** | GHSA-7gp8-3j6q-v4h8 | 0.0.5 | βœ… Fixed; README updated to reference the CVE ID | -| Dunder attribute bypass via string arguments (`allow_attributes=True`) | not yet assigned | not yet assigned | 0.0.6 | βœ… Fixed β€” consider requesting a CVE/GHSA from the GitHub Security Advisory form | diff --git a/codesafe/__init__.py b/codesafe/__init__.py index 00305ca..6314262 100644 --- a/codesafe/__init__.py +++ b/codesafe/__init__.py @@ -1,15 +1,18 @@ import ast import builtins -import pickle +import os import re 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 + __all__ = ['safe_eval', 'EvaluationTimeoutError', 'UnsafeExpressionError', 'encrypt_to_file', 'encrypt', 'decrypt', 'run', 'decrypt_to_file', - '__version__'] + 'generate_key', '__version__'] __version__ = "0.0.6" @@ -77,14 +80,14 @@ def _eval_in_process(expr: str, safe_globals: dict, queue: Queue): # queue would defer pickling to the queue's background feeder thread, where # a pickling error can never be reported back to the parent.) try: - payload = pickle.dumps(result) + payload = cloudpickle.dumps(result) except BaseException: if isinstance(result, BaseException): - payload = pickle.dumps(RuntimeError(f"Evaluation failed with {type(result).__name__}: {result}")) + payload = cloudpickle.dumps(RuntimeError(f"Evaluation failed with {type(result).__name__}: {result}")) else: - payload = pickle.dumps(RuntimeError( + payload = cloudpickle.dumps(RuntimeError( f"The evaluation result of type '{type(result).__name__}' " - "cannot be returned because it is not picklable." + "cannot be returned because it cannot be serialized." )) try: queue.put(payload) @@ -95,7 +98,6 @@ def safe_eval(expr: str, allowed_builtins: Optional[dict] = None, allowed_vars: Optional[dict] = None, timeout: float = 5, - restricted_imports: Optional[list] = None, allowed_function_calls: Optional[list] = None, allow_attributes: bool = False, immediate_termination: bool = True, @@ -109,7 +111,6 @@ def safe_eval(expr: str, allowed_builtins (dict, optional): A dictionary of allowed built-in functions. allowed_vars (dict, optional): A dictionary of allowed variables and functions. timeout (float, optional): Time limit for evaluation in seconds. Defaults to 5. - restricted_imports (list, optional): A list of restricted imports or modules. allowed_function_calls (list, optional): A list of allowed function names to call. allow_attributes (bool, optional): Whether to allow access to safe attributes and methods (e.g., 'str.upper()'). Defaults to False. 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. @@ -131,7 +132,6 @@ def safe_eval(expr: str, allowed_builtins = allowed_builtins or {} allowed_vars = allowed_vars or {} - restricted_imports = restricted_imports or [] allowed_function_calls = allowed_function_calls or [] # Optimization: Use pre-filtered builtins base @@ -159,7 +159,7 @@ def safe_eval(expr: str, except SyntaxError as e: raise SyntaxError(f"Invalid syntax: {e}") from e - _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_attributes) + _check_ast(parsed_expr, allowed_function_calls, allow_attributes) queue = Queue() process = Process(target=_eval_in_process, args=(expr, safe_globals, queue)) @@ -189,7 +189,7 @@ def safe_eval(expr: str, ) from None try: - result = pickle.loads(payload) + result = cloudpickle.loads(payload) except Exception as e: raise RuntimeError(f"Failed to deserialize the evaluation result: {e}") from e @@ -211,13 +211,12 @@ def safe_eval(expr: str, except Exception: pass -def _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_attributes): +def _check_ast(parsed_expr, allowed_function_calls, allow_attributes): """ Check the AST for unsafe operations such as imports and function calls. Parameters: parsed_expr (ast.AST): The parsed AST expression. - restricted_imports (list): A list of restricted import statements. allowed_function_calls (list): A list of allowed function calls. allow_attributes (bool): Whether to allow attribute access. @@ -229,11 +228,8 @@ def _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_at # enough: dunders can be reached indirectly through string arguments such # as obj.__getattribute__('__class__'), which the AST checker never sees. for node in ast.walk(parsed_expr): - # Block all imports if restricted + # Imports are never allowed in expressions. if isinstance(node, (ast.Import, ast.ImportFrom)): - for alias in node.names: - if alias.name in restricted_imports: - raise UnsafeExpressionError(f"Use of '{alias.name}' is restricted.") raise UnsafeExpressionError("Imports are not allowed in expressions.") # Prevent ALL function calls except for whitelisted ones @@ -265,7 +261,96 @@ def _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_at if not allow_attributes: raise UnsafeExpressionError("Attribute access is disabled.") -# Custom key (visible but obfuscated) +# --------------------------------------------------------------------------- +# Encryption +# +# Since v0.0.6 CodeSafe uses real, authenticated cryptography for new +# encryptions: Fernet (AES-128-CBC + HMAC-SHA256, from the `cryptography` +# package) with a 256-bit key. Payloads are UTF-8 safe, so ANY source code, +# including non-ASCII text, round-trips losslessly. +# +# The key is resolved in this order: +# 1. the ``key`` argument (``generate_key()`` creates a fresh key), +# 2. the ``CODESAFE_KEY`` environment variable, +# 3. a built-in default key that ships with the package. +# +# The built-in default key is public, so it only protects against casual +# inspection of the payload - it does NOT protect against someone willing to +# read CodeSafe's source. For real protection of confidential code, generate +# your own key and keep it secret. +# +# File format written by encrypt_to_file(): +# # codesafe:v2: +# +# Legacy (<= v0.0.5) payloads - Base64-encoded Caesar cipher - are still fully +# supported by decrypt(), decrypt_to_file() and run() so existing .encrypt +# files keep working. New encryptions always produce v2 payloads. +# --------------------------------------------------------------------------- +_V2_MARKER = "codesafe:v2:" +_V2_TOKEN_PREFIX = "gAAAAA" # urlsafe-base64 of Fernet's 0x80 version byte + +# Built-in default key. Public knowledge - obfuscation-grade only, see above. +_CODESAFE_DEFAULT_KEY = b"mp-yFpyWDo-ho-U1mAFboxbNaESEh-NBnEb_mtQ_4q8=" + +def generate_key() -> str: + """ + Generate a fresh encryption key suitable for use with the ``key`` parameter + or the ``CODESAFE_KEY`` environment variable. + + Returns: + str: A URL-safe Base64-encoded 256-bit key. + """ + return Fernet.generate_key().decode("ascii") + +def _load_key(key): + """Resolve the Fernet key: explicit argument > CODESAFE_KEY env > built-in default.""" + if key is None: + env_key = os.environ.get("CODESAFE_KEY") + if env_key: + key = env_key + else: + return _CODESAFE_DEFAULT_KEY + if isinstance(key, str): + try: + key = key.encode("ascii") + except UnicodeEncodeError: + raise ValueError("The encryption key must be URL-safe Base64 ASCII.") from None + if not isinstance(key, bytes): + raise TypeError(f"key must be a str, bytes or None, not {type(key).__name__}.") + try: + Fernet(key) + except Exception as e: + raise ValueError(f"Invalid encryption key: {e}") from None + return key + +def _classify_payload(text: str): + """Classify an encrypted payload as ``(payload, 'v2' | 'legacy')``.""" + compact = re.sub(r"\s+", "", text.strip()) + if compact.startswith("#"): + compact = compact[1:] + if compact.startswith(_V2_MARKER): + return compact[len(_V2_MARKER):], "v2" + if compact.startswith(_V2_TOKEN_PREFIX): + # Bare v2 token (marker stripped) + return compact, "v2" + return compact, "legacy" + +def _decrypt_v2(token: str, key) -> str: + if not token: + raise ValueError("Encryption payload is empty.") + try: + plaintext = Fernet(_load_key(key)).decrypt(token.encode("ascii")) + except InvalidToken: + raise ValueError( + "Decryption failed: the key is wrong, or the data is corrupted or tampered with." + ) from None + except Exception as e: + raise ValueError(f"Decryption failed: {e}") from e + return plaintext.decode("utf-8") + +# Legacy (<= v0.0.5) obfuscation layer. Retained only so that existing +# .encrypt files can still be decrypted and executed. New encryptions never +# use this. Not cryptographically secure - never rely on it for confidentiality. SHIFT = 3 # Caesar cipher shift value _character_map = {'0': '5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9', '1': '6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b', '2': 'd4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35', '3': '4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce', '4': '4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a', '5': 'ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d', '6': 'e7f6c011776e8db7cd330b54174fd76f7d0216b612387a5ffcfb81e6f0919683', '7': '7902699be42c8a8e46fbbb4501726517e86b22c56a189f7625a6da49081b2451', '8': '2c624232cdd221771294dfbb310aca000a0df6ac8b66b696d90ef06fdefb64a3', '9': '19581e27de7ced00ff1ce50b2047e7a567c76b1cbaebabe5ef03f7c3017bb5b7', 'a': 'ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb', 'b': '3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d', 'c': '2e7d2c03a9507ae265ecf5b5356885a53393a2029d241394997265a1a25aefc6', 'd': '18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4', 'e': '3f79bb7b435b05321651daefd374cdc681dc06faa65e374e38337b88ca046dea', 'f': '252f10c83610ebca1a059c0bae8255eba2f95be4d1d7bcfa89d7248a82d9f111', 'g': 'cd0aa9856147b6c5b4ff2b7dfee5da20aa38253099ef1b4a64aced233c9afe29', 'h': 'aaa9402664f1a41f40ebbc52c9993eb66aeb366602958fdfaa283b71e64db123', 'i': 'de7d1b721a1e0632b7cf04edf5032c8ecffa9f9a08492152b926f1a5a7e765d7', 'j': '189f40034be7a199f1fa9891668ee3ab6049f82d38c68be70f596eab2e1857b7', 'k': '8254c329a92850f6d539dd376f4816ee2764517da5e0235514af433164480d7a', 'l': 'acac86c0e609ca906f632b0e2dacccb2b77d22b0621f20ebece1a4835b93f6f0', 'm': '62c66a7a5dd70c3146618063c344e531e6d4b59e379808443ce962b3abd63c5a', 'n': '1b16b1df538ba12dc3f97edbb85caa7050d46c148134290feba80f8236c83db9', 'o': '65c74c15a686187bb6bbf9958f494fc6b80068034a659a9ad44991b08c58f2d2', 'p': '148de9c5a7a44d19e56cd9ae1a554bf67847afb0c58f6e12fa29ac7ddfca9940', 'q': '8e35c2cd3bf6641bdb0e2050b76932cbb2e6034a0ddacc1d9bea82a6ba57f7cf', 'r': '454349e422f05297191ead13e21d3db520e5abef52055e4964b82fb213f593a1', 's': '043a718774c572bd8a25adbeb1bfcd5c0256ae11cecf9f9c3f925d0e52beaf89', 't': 'e3b98a4da31a127d4bde6e43033f66ba274cab0eb7eb1c70ec41402bf6273dd8', 'u': '0bfe935e70c321c7ca3afc75ce0d0ca2f98b5422e008bb31c00c6d7f1f1c0ad6', 'v': '4c94485e0c21ae6c41ce1dfe7b6bfaceea5ab68e40a2476f50208e526f506080', 'w': '50e721e49c013f00c62cf59f2163542a9d8df02464efeb615d31051b0fddc326', 'x': '2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881', 'y': 'a1fce4363854ff888cff4b8e7875d600c2682390412a8cf79b37d0b11148b0fa', 'z': '594e519ae499312b29433b7dd8a97ff068defcba9755b6d5d00e84c524d67b06', 'A': '559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd', 'B': 'df7e70e5021544f4834bbee64a9e3789febc4be81470df629cad6ddb03320a5c', 'C': '6b23c0d5f35d1b11f9b683f0b0a617355deb11277d91ae091d399c655b87940d', 'D': '3f39d5c348e5b79d06e842c114e6cc571583bbf44e4b0ebfda1a01ec05745d43', 'E': 'a9f51566bd6705f7ea6ad54bb9deb449f795582d6529a0e22207b8981233ec58', 'F': 'f67ab10ad4e4c53121b6a5fe4da9c10ddee905b978d3788d2723d7bfacbe28a9', 'G': '333e0a1e27815d0ceee55c473fe3dc93d56c63e3bee2b3b4aee8eed6d70191a3', 'H': '44bd7ae60f478fae1061e11a7739f4b94d1daf917982d33b6fc8a01a63f89c21', 'I': 'a83dd0ccbffe39d071cc317ddf6e97f5c6b1c87af91919271f9fa140b0508c6c', 'J': '6da43b944e494e885e69af021f93c6d9331c78aa228084711429160a5bbd15b5', 'K': '86be9a55762d316a3026c2836d044f5fc76e34da10e1b45feee5f18be7edb177', 'L': '72dfcfb0c470ac255cde83fb8fe38de8a128188e03ea5ba5b2a93adbea1062fa', 'M': '08f271887ce94707da822d5263bae19d5519cb3614e0daedc4c7ce5dab7473f1', 'N': '8ce86a6ae65d3692e7305e2c58ac62eebd97d3d943e093f577da25c36988246b', 'O': 'c4694f2e93d5c4e7d51f9c5deb75e6cc8be5e1114178c6a45b6fc2c566a0aa8c', 'P': '5c62e091b8c0565f1bafad0dad5934276143ae2ccef7a5381e8ada5b1a8d26d2', 'Q': '4ae81572f06e1b88fd5ced7a1a000945432e83e1551e6f721ee9c00b8cc33260', 'R': '8c2574892063f995fdf756bce07f46c1a5193e54cd52837ed91e32008ccf41ac', 'S': '8de0b3c47f112c59745f717a626932264c422a7563954872e237b223af4ad643', 'T': 'e632b7095b0bf32c260fa4c539e9fd7b852d0de454e9be26f24d0d6f91d069d3', 'U': 'a25513c7e0f6eaa80a3337ee18081b9e2ed09e00af8531c8f7bb2542764027e7', 'V': 'de5a6f78116eca62d7fc5ce159d23ae6b889b365a1739ad2cf36f925a140d0cc', 'W': 'fcb5f40df9be6bae66c1d77a6c15968866a9e6cbd7314ca432b019d17392f6f4', 'X': '4b68ab3847feda7d6c62c1fbcbeebfa35eab7351ed5e78f4ddadea5df64b8015', 'Y': '18f5384d58bcb1bba0bcd9e6a6781d1a6ac2cc280c330ecbab6cb7931b721552', 'Z': 'bbeebd879e1dff6918546dc0c179fdde505f2a21591c9a9c96e36b054ec5af83', '!': 'bb7208bc9b5d7c04f1236a82a0093a5e33f40423d5ba8d4266f7092c3ba43b62', '"': '8a331fdde7032f33a71e1b2e257d80166e348e00fcb17914f48bdb57a1c63007', '#': '334359b90efed75da5f0ada1d5e6b256f4a6bd0aee7eb39c0f90182a021ffc8b', '$': '09fc96082d34c2dfc1295d92073b5ea1dc8ef8da95f14dfded011ffb96d3e54b', '%': 'bbf3f11cb5b43e700273a78d12de55e4a7eab741ed2abf13787a4d2dc832b8ec', '&': '951dcee3a7a4f3aac67ec76a2ce4469cc76df650f134bf2572bf60a65c982338', "'": '265fda17a34611b1533d8a281ff680dc5791b0ce0a11c25b35e11c8e75685509', '(': '32ebb1abcc1c601ceb9c4e3c4faba0caa5b85bb98c4f1e6612c40faa528a91c9', ')': 'ba5ec51d07a4ac0e951608704431d59a02b21a4e951acc10505a8dc407c501ee', '*': '684888c0ebb17f374298b65ee2807526c066094c701bcc7ebbe1c1095f494fc1', '+': 'a318c24216defe206feeb73ef5be00033fa9c4a74d0b967f6532a26ca5906d3b', ',': 'd03502c43d74a30b936740a9517dc4ea2b2ad7168caa0a774cefe793ce0b33e7', '-': '3973e022e93220f9212c18d0d0c543ae7c309e46640da93a4a0314de999f5112', '.': 'cdb4ee2aea69cc6a83331bbe96dc2caa9a299d21329efb0336fc02a82e1839a8', '/': '8a5edab282632443219e051e4ade2d1d5bbc671c781051bf1437897cbdfea0f1', ':': 'e7ac0786668e0ff0f02b62bd04f45ff636fd82db63b1104601c975dc005f3a67', ';': '41b805ea7ac014e23556e98bb374702a08344268f92489a02f0880849394a1e4', '<': 'dabd3aff769f07eb2965401eb029974ebba3407afd02b26ddb564ea5f8efae72', '=': '380918b946a526640a40df5dced6516794f3d97bbd9e6bb553d037c4439f31c3', '>': '62b67e1f685b7fef51102005dddd27774be3fee38c42965c53aab035d0b6b221', '?': '8a8de823d5ed3e12746a62ef169bcf372be0ca44f0a1236abc35df05d96928e1', '@': 'c3641f8544d7c02f3580b07c0f9887f0c6a27ff5ab1d4a3e29caf197cfc299ae', '[': '245843abef9e72e7efac30138a994bf6301e7e1d7d7042a33d42e863d2638811', '\\': 'a9253dc8529dd214e5f22397888e78d3390daa47593e26f68c18f97fd7a3876b', ']': 'cfae0d4248f7142f7b17f826cd7a519280e312577690e957830d23dcf35a3fff', '^': '74cd9ef9c7e15f57bdad73c511462ca65cb674c46c49639c60f1b44650fa1dcb', '_': 'd2e2adf7177b7a8afddbc12d1634cf23ea1a71020f6a1308070a16400fb68fde', '`': '8d33f520a3c4cef80d2453aef81b612bfe1cb44c8b2025630ad38662763f13d3', '{': '021fb596db81e6d02bf3d2586ee3981fe519f275c0ac9ca76bbcf2ebb4097d96', '|': 'cbe5cfdf7c2118a9c3d78ef1d684f3afa089201352886449a06a6511cfef74a7', '}': 'd10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2', '~': '7ace431cb61584cb9b8dc7ec08cf38ac0a2d649660be86d349fb43108b542fa4', ' ': '36a9e7f1c95b82ffb99743e0c5c4ce95d83c9a430aac59f84ef3cbfab6145068', '\t': '2b4c342f5433ebe591a1da77e013d1b72475562d48578dca8b84bac6651c3cb9', '\n': '01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b', '\r': '9d1e0e2d9459d06523ad13e28a4093c2316baafe7aec5b25f30eba2e113599c4', '\x0b': 'e7cf46a078fed4fafd0b5e3aff144802b853f8ae459a4f0c14add3314b7cc3a6', '\x0c': 'ef6cbd2161eaea7943ce8693b9824d23d1793ffb1c0fca05b600d3899b44c977'} @@ -333,24 +418,37 @@ def reverse_string(text: str) -> str: """Reverses the input string.""" return text[::-1] -def encrypt(code: Union[str, bytes], mapping: dict = _character_map) -> str: +def encrypt(code: Union[str, bytes], key: Optional[Union[str, bytes]] = None, mapping: Optional[dict] = None) -> str: """ - Encrypt the code using multiple methods and return it. + Encrypt the code using authenticated cryptography: Fernet (AES-128-CBC + + HMAC-SHA256) with a 256-bit key. Any Unicode source code is supported - + the plaintext is UTF-8, so non-ASCII code round-trips losslessly. Parameters: code (str or bytes): The Python code to encrypt. - mapping (dict): The mapping dictionary for character replacements. + key (str or bytes, optional): URL-safe Base64 256-bit key, as produced by + ``generate_key()``. Resolution order: this argument, then the + ``CODESAFE_KEY`` environment variable, then a built-in default key + (public - obfuscation-grade only). + mapping (dict): **Removed.** The Caesar-cipher mapping parameter was removed + in v0.0.6. Passing it raises TypeError. Returns: - str: The encrypted code. + str: The encrypted payload, prefixed with ``codesafe:v2:``. Raises: - ValueError: If the code contains characters that are not present in the - encryption mapping (the built-in mapping covers printable ASCII and - common whitespace), if a mapping value is not exactly 64 characters, - or if decoding ``bytes`` input fails. - RuntimeError: If an unexpected error occurs during encryption. + TypeError: If a legacy ``mapping`` dictionary is passed. + ValueError: If ``bytes`` input is not valid UTF-8, or the key is invalid. """ + if mapping is not None or isinstance(key, dict): + raise TypeError( + "The 'mapping' parameter was removed in CodeSafe v0.0.6. " + "Encryption now uses authenticated cryptography (Fernet). " + "Use generate_key() to create a key, pass it as key=..., " + "or set the CODESAFE_KEY environment variable. " + "Old mapping-encrypted content can still be decrypted by passing " + "the mapping to decrypt()/decrypt_to_file()/run()." + ) if isinstance(code, bytes): try: code = code.decode('utf-8') @@ -359,60 +457,17 @@ def encrypt(code: Union[str, bytes], mapping: dict = _character_map) -> str: if not isinstance(code, str): raise TypeError(f"code must be a str or bytes, not {type(code).__name__}.") - # The encryption format replaces every input character with exactly - # 64 output characters - this is what decrypt's fixed-size chunking - # relies on. So every mapping value must be exactly 64 characters long, - # and every character in the code must be present in the mapping. - # (Previously, characters outside the mapping were passed through - # unchanged, which silently corrupted all subsequent output on decrypt.) - if not isinstance(mapping, dict): - raise TypeError("mapping must be a dictionary.") - for key, value in mapping.items(): - if not isinstance(value, str) or len(value) != 64: - raise ValueError( - f"The mapping value for {key!r} is {len(value) if isinstance(value, str) else 'not a string'} characters long; " - "every mapping value must be exactly 64 characters long." - ) - missing = sorted({c for c in code if c not in mapping}) - if missing: - raise ValueError( - f"Code contains characters not present in the encryption mapping: {missing}. " - "The built-in mapping covers printable ASCII and common whitespace characters only. " - "Escape non-ASCII characters in string literals (e.g. '\\u2713') or remove them from " - "comments before encrypting." - ) - - try: - # Combined step: Mapping + Caesar - caesar_encrypted = encrypt_with_mapping(code, mapping) - if not caesar_encrypted: - raise ValueError("Encryption failed. The result is empty.") - - # Final step: Base64 Encoding - base64_encoded = base64.b64encode(caesar_encrypted.encode('utf-8')).decode('ascii') - if not base64_encoded: - raise ValueError("Base64 encoding failed. The result is empty.") - - return base64_encoded - except Exception as e: - if isinstance(e, (ValueError, RuntimeError, TypeError)): - raise - raise RuntimeError(f"An error occurred during encryption: {e}") from e + token = Fernet(_load_key(key)).encrypt(code.encode('utf-8')).decode('ascii') + return _V2_MARKER + token -def decrypt(encrypted_code: str, mapping: dict = _character_map) -> str: +def _decrypt_legacy(encrypted_code: str, mapping: dict) -> str: """ - Decrypt the code using multiple methods and return it. + Decrypt a pre-0.0.6 Base64 Caesar-cipher payload. - Parameters: - encrypted_code (str): The Python code to decrypt. - mapping (dict): The mapping dictionary for character replacements. - - Returns: - str: The decrypted code. + Kept only so existing .encrypt files keep working. This format is not + cryptographically secure - never use it for new encryptions. """ try: - if not isinstance(encrypted_code, str): - raise TypeError(f"encrypted_code must be a str, not {type(encrypted_code).__name__}.") # Tolerate incidental whitespace/newlines, but reject any other # characters outside the Base64 alphabet. compact = re.sub(r"\s+", "", encrypted_code) @@ -436,65 +491,120 @@ def decrypt(encrypted_code: str, mapping: dict = _character_map) -> str: raise raise RuntimeError(f"An error occurred during decryption: {e}") from e -def encrypt_to_file(code: Union[str, bytes], output_file: str, mapping: dict = _character_map) -> None: +def decrypt(encrypted_code: str, key: Optional[Union[str, bytes]] = None, mapping: Optional[dict] = None) -> str: + """ + Decrypt a payload produced by :func:`encrypt` (v2) or by CodeSafe <= v0.0.5 (legacy). + + Parameters: + encrypted_code (str): The payload. May be the string returned by + ``encrypt()`` (``codesafe:v2:...``), a bare v2 token, or a full + ``# codesafe:v2:...`` comment line such as the one embedded by + ``encrypt_to_file()``. Legacy Base64 Caesar payloads are detected + automatically. + key (str or bytes, optional): Key for v2 payloads. Resolution order: + this argument, then the ``CODESAFE_KEY`` environment variable, then + the built-in default key. + mapping (dict, optional): Legacy Caesar mapping, used only for pre-0.0.6 + payloads. Defaults to the built-in mapping. + + Returns: + str: The decrypted code. + + Raises: + ValueError: If the v2 payload cannot be decrypted (wrong key, or the data + is corrupted or tampered with), or a legacy payload is malformed. + TypeError: If a v2 payload is combined with a ``mapping`` argument. + """ + if isinstance(key, dict): # Legacy positional call: decrypt(payload, legacy_mapping) + mapping = key + key = None + if not isinstance(encrypted_code, str): + raise TypeError(f"encrypted_code must be a str, not {type(encrypted_code).__name__}.") + + payload, kind = _classify_payload(encrypted_code) + if kind == "v2": + if mapping is not None: + raise TypeError( + "The 'mapping' parameter only applies to legacy (pre-0.0.6) encrypted " + "content. For v2 content, pass key=... (or set CODESAFE_KEY) instead." + ) + return _decrypt_v2(payload, key) + return _decrypt_legacy(payload, mapping if mapping is not None else _character_map) + +def encrypt_to_file(code: Union[str, bytes], output_file: str, key: Optional[Union[str, bytes]] = None, mapping: Optional[dict] = None) -> None: """ - Encrypt the given Python code using multiple methods and embed it as comments in a Python file. + Encrypt the given Python code with authenticated cryptography and embed it + as a comment in a Python file. + + The output file contains a single line of the form ``# codesafe:v2:``, + which can be executed with :func:`run` and decrypted with :func:`decrypt_to_file`. Parameters: code (str or bytes): The Python code to encrypt. - output_file (str): The path to the output Python file to embed encrypted code. - mapping (dict): The mapping dictionary for character replacements. + output_file (str): Path of the output Python file to write. + key (str or bytes, optional): Key for encryption. See :func:`encrypt`. + mapping (dict): **Removed.** Passing it raises TypeError. Returns: None """ - encrypted_code = encrypt(code, mapping) + encrypted_code = encrypt(code, key=key, mapping=mapping) try: with open(output_file, 'w', encoding='utf-8') as file: file.write(f"# {encrypted_code}") except OSError as e: raise OSError(f"Failed to write to file '{output_file}': {e}") from e -def decrypt_code(encrypted_code: str, mapping: dict) -> str: - """Decrypts the encrypted code using the reverse of the encryption methods.""" - return decrypt(encrypted_code, mapping) - -def run(encrypted_source: Union[str, IO], mapping: dict = _character_map) -> None: +def decrypt_code(encrypted_code: str, mapping: Optional[dict] = None, key: Optional[Union[str, bytes]] = None) -> str: + """Decrypt an encrypted payload. Alias of :func:`decrypt` kept for backwards compatibility.""" + return decrypt(encrypted_code, key=key, mapping=mapping) + +def _extract_payload(content: str) -> str: + """Extract the encrypted payload from a file's content (v2 comment, or legacy comment).""" + match = re.search(r'^# (codesafe:v2:[A-Za-z0-9_-]+={0,2})\s*$', content, re.MULTILINE) + if match: + return match.group(1) + match = re.search(r'^# ([A-Za-z0-9+/=]+)\s*$', content, re.MULTILINE) + if match: + return match.group(1) + raise ValueError("No encrypted code found in the source.") + +def _read_source(source) -> str: + if isinstance(source, str): + with open(source, 'r', encoding='utf-8') as file: + return file.read() + content = source.read() + if isinstance(content, bytes): + content = content.decode('utf-8') + return content + +def run(encrypted_source: Union[str, IO], key: Optional[Union[str, bytes]] = None, mapping: Optional[dict] = None) -> None: """ Decrypt and execute the Python code embedded in the specified file or stream. - The decrypted code is executed with ``__name__`` set to ``"__main__"`` in a clean - namespace, isolated from CodeSafe's module globals. Note that this is code - obfuscation, not a security boundary: the decrypted code runs with the full - permissions of the current process. + The decrypted code is executed with ``__name__`` set to ``"__main__"`` in a + clean namespace, isolated from CodeSafe's module globals. Encryption + protects the code at rest and on disk; the decrypted code still runs with + the full permissions of the current process, so only run code you trust. Parameters: - encrypted_source (str or stream): Path to the file or a file-like object with embedded encrypted code. - mapping (dict): The mapping dictionary for character replacements. + encrypted_source (str or stream): Path to the file, or a file-like object + with embedded encrypted code. + key (str or bytes, optional): Key for v2 payloads. Defaults to + ``CODESAFE_KEY`` or the built-in default key. A legacy positional + argument in the ``key`` slot receives a dict and is treated as the + legacy Caesar ``mapping``. + mapping (dict, optional): Legacy Caesar mapping for pre-0.0.6 payloads. Returns: None """ try: - if isinstance(encrypted_source, str): - with open(encrypted_source, 'r', encoding='utf-8') as file: - content = file.read() - else: - content = encrypted_source.read() - if isinstance(content, bytes): - content = content.decode('utf-8') - - # Extract the encrypted code from the comments - match = re.search(r'^# ([A-Za-z0-9+/=]+)\s*$', content, re.MULTILINE) - if not match: - raise ValueError("No valid encrypted code found in the source.") - - encrypted_code = match.group(1) - - # Decrypt the code - decrypted_code = decrypt(encrypted_code, mapping) + content = _read_source(encrypted_source) + payload = _extract_payload(content) + decrypted_code = decrypt(payload, key=key, mapping=mapping) except Exception as e: - if isinstance(e, (RuntimeError, ValueError, OSError)): + if isinstance(e, (RuntimeError, ValueError, OSError, TypeError)): raise raise RuntimeError(f"An error occurred during decryption and execution: {e}") from e @@ -502,41 +612,26 @@ def run(encrypted_source: Union[str, IO], mapping: dict = _character_map) -> Non # script run as __main__, isolated from CodeSafe's own module globals. exec(decrypted_code, {"__name__": "__main__"}) -def decrypt_to_file(encrypted_file: Union[str, IO], output_file: Union[str, IO], mapping: dict = _character_map) -> None: +def decrypt_to_file(encrypted_file: Union[str, IO], output_file: Union[str, IO], key: Optional[Union[str, bytes]] = None, mapping: Optional[dict] = None) -> None: """ Decrypt the code embedded in the specified file/stream and write it to an output file/stream. Parameters: encrypted_file (str or stream): Path to the source or a file-like object. output_file (str or stream): Path to the destination or a file-like object. - mapping (dict): The mapping dictionary for character replacements. + key (str or bytes, optional): Key for v2 payloads (see :func:`encrypt`). + mapping (dict, optional): Legacy Caesar mapping for pre-0.0.6 payloads. Returns: None """ try: - # Check if the mapping is valid - if not isinstance(mapping, dict): + if mapping is not None and not isinstance(mapping, dict): raise ValueError("The mapping parameter must be a dictionary.") - # Read the encrypted code - if isinstance(encrypted_file, str): - with open(encrypted_file, 'r', encoding='utf-8') as file: - content = file.read() - else: - content = encrypted_file.read() - if isinstance(content, bytes): - content = content.decode('utf-8') - - # Extract the encrypted code - match = re.search(r'^# ([A-Za-z0-9+/=]+)\s*$', content, re.MULTILINE) - if not match: - raise ValueError("No encrypted code found in the source.") - - encrypted_code = match.group(1) - - # Decrypt the code - decrypted_code = decrypt(encrypted_code, mapping) + content = _read_source(encrypted_file) + payload = _extract_payload(content) + decrypted_code = decrypt(payload, key=key, mapping=mapping) # Write the decrypted code if isinstance(output_file, str): @@ -546,6 +641,6 @@ def decrypt_to_file(encrypted_file: Union[str, IO], output_file: Union[str, IO], output_file.write(decrypted_code) except Exception as e: - if isinstance(e, (ValueError, RuntimeError, OSError)): + if isinstance(e, (ValueError, RuntimeError, OSError, TypeError)): raise - raise RuntimeError(f"An error occurred during decryption to file: {e}") from e \ No newline at end of file + raise RuntimeError(f"An error occurred during decryption to file: {e}") from e diff --git a/pyproject.toml b/pyproject.toml index d3f2a3b..b77a8ae 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=77"] +requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [project] @@ -8,12 +8,15 @@ version = "0.0.6" 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" -license = "MIT" -license-files = ["LICENSE"] +license = {text = "MIT"} authors = [ {name = "Infinitode Pty Ltd", email = "infinitode.ltd@gmail.com"}, ] -keywords = ["eval", "safe-eval", "sandbox", "encryption", "obfuscation", "ast", "security"] +keywords = ["eval", "safe-eval", "sandbox", "encryption", "security", "ast", "cryptography"] +dependencies = [ + "cryptography>=41", + "cloudpickle>=2.2", +] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", diff --git a/test.py b/test.py index 9542b37..e2f9269 100644 --- a/test.py +++ b/test.py @@ -4,6 +4,8 @@ from time import sleep +LEGACY_PAYLOAD = "NDc7Z2g8ZjhkOmQ3N2c0PGg4OWZnPGRoNGQ4ODdlaTk6Ozc6ZGllM2Y4O2k5aDQ1aWQ1PGRmOmdnaWZkPDw3Mzc4NzY3PGg3NTVpMzg1PDo0PDRoZGc0Nmg1NGc2Z2U4NTNoOGRlaGk4NTM4OGg3PDk3ZTs1aWU1NDZpODw2ZDRnaDpnNGU6NTRkNGgzOTY1ZTpmaTM3aGdpODM2NWY7aGZpaWQ8aTxkMzs3PDU0ODVlPDU5aTRkOGQ6aDo5OGc6NGU0OWU0Z2k4NjtlZDQ1Z2Y2aTw6aGdlZTs4ZmRkOjM4M2c3OWY0Nzs0Njc1PDNpaGVkOzNpOzU2OWY7NmdlPGg2ZTw7ZDdnZDY0ZDQ1Omc3ZWdoOWg3NjM2Nmk5OWVkNTo3ZmRlM2hlOmhlNGY6M2hmNzQ3MzVlaTk1OjZnZzs2NWhlZTRkZWZmNGY5MzRmaGU8ZjdoNmY3aWRlZDNmZGQ4ZTs4ZWU8O2Y3aTRoOTk0NWY3M2lkZDg1O2Q8NGY8NTk4aWdkNDpkNjc5NDRlNDg2Nmc7ZDU7NGlpOTszZ2Y4Ojw0ZTNmaDNkNDRmNThlNjhoNDRmO2g6ODk7ODgzPGRmZGY7OWYzaDkzPGZkPDM5aTk2NWUzaDVnZGZmZmU1ZTo6ZzU1ZTM5NTRpNTNoZWhmaDRkNzs2OGU8Nmk5aTM2aTo8ZWU6ZTc2OGUzODY1NDk4NGdkaGlnNjo3ZmdmOTs0Z2YzOWlkZDk4aDY6N2g2OzY2OmU7O2ZkMzc5Z2hkZmczZGQ8Ozg5NDc6ZTlmOGU3aWk1ZTpnaWhoOGdkNTNkZDY7NTg2Mzw8aGk0ZTdkOTdkZmhnNTY2ZjxkaWg1PGZkPDo7NDQ1ZmQ0ZWVnZmRpZGY1NjRlNjxkNTZnZjdnZDo7OWhpaTs0NzpmN2g6NWU8OzM6Ojs4ZGloaDc7ZWU1aDpnNWYzNmQ8ODM6ZGg1OThoZmk4ZTg2ODk7OzhkODY2PDZkNTM1PGc1NzQ2PDc8PDo1OThkNGQ1OGRoaWY5ZDRpZmg3Njk2Ozg3aWk7OztmaWk3ZTtoOjs6OGc5MzNmNTk7NTY8Mzc0NWQ7Zmk6PGU2OmczZTQ0NDc7ZTNpZDY5ZDxoOmk0Zjw4ZTs1aWllPDw6NzZoM2Y4ZjdmaDw4Zzs2ZjxkNzYzZGRmODxpOzdoaTZmZWlkZTk0NzgzOTs4M2g6NTRoNzxmMzQ2aTMzZjk1Zmk4PGk1NDk2ODc1ZDxnO2dpMzU3OTdoaWhlOTQ4ZzY0Mzg0ZTNpZ2dmNjU5OThmOjdmNDhkOTs5NDs6ZWU5ZWVpPDw4O2k3PDdpZjllOzMzOTszNjdkOTg8ZDxkZzc3PDw0ZTM7Zjg7aTVnNTc4NzY3PGg3NTVpMzg1PDo0PDRoZGc0Nmg1NGc2Z2U4NTNoOGRlaGk4NTM4OGg3PDk3ZTs1aWU1NDZpODw2ZDQ7NTg3ZjY1PGQ8NTs4M2k5Zzg2PGdnNjo5aTc7NDloaDU6OTc4NDpnZDhoMzU2ODg0N2RpNzY2NDk3NzszZzpkMzc2ZDo0Ozo6N2Y4OjVlZztkNThkZ2VoZTRlaWZnOGYzNTg5ZGg0NGZoZmk8aTxmNmk8NThnM2g4NWVoZGk7PDU5OGlnZDQ6ZDY3OTQ0ZTQ4NjZnO2Q1OzRpaTk7M2dmODo8NGUzZmgzZDQ0ZjU4ZTY4aDQ0ZjtoOjg5Ozg4MzxlZDhoZjg0ZzM6ZDdkZjNoPDg0OTM7OjM3NzY0Zzg8ZDM1ZTU0ZDdoPDg0ZGZmNDM4MzhkO2dmNzM6ZjgzNGho" # produced by CodeSafe <= v0.0.5 encrypt() + # Custom function defined for testing def custom_sum(a, b): return a + b @@ -18,7 +20,6 @@ def setUp(self): # Set up the safe environment with custom variables and functions self.safe_builtins = {"abs": abs, "max": max} self.safe_vars = {"x": 10, "y": 20, "custom_sum": custom_sum, "long_running_function": long_running_function, "sleep": sleep} - self.restricted_imports = ['os', 'sys'] self.allowed_function_calls = ['custom_sum', 'max', 'abs', 'long_running_function', 'sleep'] # Sample Python code for testing encryption and decryption @@ -41,7 +42,6 @@ def test_custom_sum(self): allowed_builtins=self.safe_builtins, allowed_vars=self.safe_vars, timeout=3, - restricted_imports=self.restricted_imports, allowed_function_calls=self.allowed_function_calls, file_access=False ) @@ -74,8 +74,7 @@ def test_security_error_on_unsafe_function(self): allowed_builtins=self.safe_builtins, allowed_vars=self.safe_vars, timeout=3, - restricted_imports=self.restricted_imports, - allowed_function_calls=self.allowed_function_calls + allowed_function_calls=self.allowed_function_calls ) def test_timeout_error(self): @@ -88,8 +87,7 @@ def test_timeout_error(self): allowed_builtins=self.safe_builtins, allowed_vars=self.safe_vars, timeout=1, # Setting a short timeout - restricted_imports=self.restricted_imports, - allowed_function_calls=self.allowed_function_calls, + allowed_function_calls=self.allowed_function_calls, immediate_termination=True ) @@ -138,22 +136,70 @@ def test_bytes_and_streams(self): decrypt_to_file(io.StringIO(f"# {enc}"), out_stream) self.assertEqual(out_stream.getvalue(), "print('Bytes work')") - def test_encrypt_rejects_unmapped_characters(self): - # Non-ASCII characters cannot be represented by the 64-char mapping - # format, so encrypt() must fail loudly instead of corrupting the output. - with self.assertRaises(ValueError): - encrypt("print('hΓ©llo')") - with self.assertRaises(ValueError): - encrypt(b"print('\xe2\x9c\x93')") # UTF-8 for βœ“ - - def test_encrypt_validates_mapping_values(self): - # Every mapping value must be exactly 64 characters (fixed chunk size). - with self.assertRaises(ValueError): + def test_encrypt_supports_unicode(self): + # v2 crypto payloads are UTF-8 safe: any Unicode code round-trips. + code = "print('hΓ©llo, βœ“, δ½ ε₯½')" + encrypted = encrypt(code) + self.assertTrue(encrypted.startswith("codesafe:v2:")) + self.assertEqual(decrypt(encrypted), code) + encrypted_bytes = encrypt(code.encode("utf-8")) + self.assertEqual(decrypt(encrypted_bytes), code) + + def test_encrypt_rejects_mapping_argument(self): + # The Caesar mapping parameter was removed in v0.0.6. + with self.assertRaises(TypeError): encrypt("print('hi')", mapping={"p": "too-short"}) + with self.assertRaises(TypeError): + encrypt("print('hi')", {"p": "too-short"}) + + def test_custom_key_roundtrip_and_wrong_key(self): + from codesafe import generate_key + key = generate_key() + encrypted = encrypt("print('secret')", key=key) + self.assertEqual(decrypt(encrypted, key=key), "print('secret')") + with self.assertRaises(ValueError): + decrypt(encrypted, key=generate_key()) + + def test_environment_key_roundtrip(self): + import os + from codesafe import generate_key + key = generate_key() + os.environ["CODESAFE_KEY"] = key + try: + encrypted = encrypt("print('env secret')") + self.assertEqual(decrypt(encrypted), "print('env secret')") + finally: + del os.environ["CODESAFE_KEY"] + + def test_legacy_payload_still_decrypts(self): + # A payload produced by CodeSafe <= v0.0.5 (Base64 Caesar) must keep + # working. Generated with codesafe.encrypt_with_mapping() and + # base64.b64encode(), exactly as <= v0.0.5 produced it. + legacy = LEGACY_PAYLOAD + self.assertEqual(decrypt(legacy), "print('legacy works')") + + def test_legacy_file_still_runs_and_decrypts(self): + import io + legacy = LEGACY_PAYLOAD + out = io.StringIO() + decrypt_to_file(io.StringIO(f"# {legacy}"), out) + self.assertEqual(out.getvalue(), "print('legacy works')") - def test_decrypt_rejects_invalid_base64(self): + def test_v2_file_roundtrip(self): + import io + encrypt_to_file("print('v2 works')", "v2_test_prog.encrypt") + with open("v2_test_prog.encrypt", "r") as f: + data = f.read() + self.assertTrue(data.startswith("# codesafe:v2:")) + out = io.StringIO() + decrypt_to_file("v2_test_prog.encrypt", out) + self.assertEqual(out.getvalue(), "print('v2 works')") + + def test_decrypt_rejects_invalid_input(self): with self.assertRaises(ValueError): decrypt("!!! definitely not base64 !!!") + with self.assertRaises(ValueError): + decrypt("codesafe:v2:bm90LWEtdmFsaWQtdG90ZW4") def test_exception_propagates_from_evaluation(self): with self.assertRaises(ZeroDivisionError): @@ -179,6 +225,8 @@ def tearDown(self): os.remove(self.encrypted_file) if os.path.exists(self.decrypted_file): os.remove(self.decrypted_file) + if os.path.exists("v2_test_prog.encrypt"): + os.remove("v2_test_prog.encrypt") if __name__ == '__main__': unittest.main() diff --git a/test_poc_vulnerability.py b/test_poc_vulnerability.py index 9995bcb..23103d7 100644 --- a/test_poc_vulnerability.py +++ b/test_poc_vulnerability.py @@ -571,17 +571,23 @@ def test_safe_non_dunder_attribute_calls_still_work(self): # ==================== RESULT SERIALIZATION ==================== - def test_unpicklable_result_raises_runtime_error(self): - """An unpicklable result raises a clear RuntimeError, not a timeout.""" - with self.assertRaises(RuntimeError): - safe_eval("lambda: 1") - print("[PASS] Unpicklable lambda result raises RuntimeError") - - def test_unpicklable_generator_raises_runtime_error(self): - """An unpicklable generator result raises a clear RuntimeError.""" + 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_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_unserializable_generator_raises_runtime_error(self): + """A generator result (live frame state) raises a clear RuntimeError.""" with self.assertRaises(RuntimeError): safe_eval("(x for x in range(3))") - print("[PASS] Unpicklable generator result raises RuntimeError") + print("[PASS] Unserializable generator result raises RuntimeError") # ==================== PROCESS CLEANUP ====================