diff --git a/.github/workflows/build_and_publish.yml b/.github/workflows/build_and_publish.yml index 4a9ec6b..36c4dcc 100644 --- a/.github/workflows/build_and_publish.yml +++ b/.github/workflows/build_and_publish.yml @@ -3,32 +3,47 @@ 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 + + # 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@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 + + # 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 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..ab5dee4 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,46 @@ +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.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 + 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: 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 27ee28f..516cd64 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,16 @@ __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 +v2_test_prog.encrypt 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..61bd3a5 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,62 @@ # 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) ![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.** -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 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. ## Vulnerability & Security Testing ([`test_poc_vulnerability.py`](https://github.com/Infinitode/CodeSafe/blob/main/test_poc_vulnerability.py)) @@ -39,34 +64,62 @@ 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) +**79/79 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** | 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 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 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. +* 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: -* **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. +> [!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 * Added regression tests for indirect call bypass attempts @@ -94,7 +147,7 @@ python -m unittest 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 @@ -105,19 +158,20 @@ 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. ## 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] @@ -156,18 +210,21 @@ 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 ``` > [!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] +> 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!" @@ -178,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/codesafe/__init__.py b/codesafe/__init__.py index c2ff969..6314262 100644 --- a/codesafe/__init__.py +++ b/codesafe/__init__.py @@ -1,12 +1,20 @@ import ast import builtins -from multiprocessing import Process, Queue -import base64 +import os import re -import io +import base64 +import cloudpickle +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'] +from cryptography.fernet import Fernet, InvalidToken + +__all__ = ['safe_eval', 'EvaluationTimeoutError', 'UnsafeExpressionError', + 'encrypt_to_file', 'encrypt', 'decrypt', 'run', 'decrypt_to_file', + 'generate_key', '__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 +23,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,15 +74,30 @@ 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 = cloudpickle.dumps(result) + except BaseException: + if isinstance(result, BaseException): + payload = cloudpickle.dumps(RuntimeError(f"Evaluation failed with {type(result).__name__}: {result}")) + else: + payload = cloudpickle.dumps(RuntimeError( + f"The evaluation result of type '{type(result).__name__}' " + "cannot be returned because it cannot be serialized." + )) + try: + queue.put(payload) + except Exception: + pass 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, @@ -88,10 +111,9 @@ 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): 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,13 +122,16 @@ 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 [] allowed_function_calls = allowed_function_calls or [] # Optimization: Use pre-filtered builtins base @@ -132,56 +157,79 @@ 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) + _check_ast(parsed_expr, 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 + + try: + result = cloudpickle.loads(payload) + except Exception as e: + raise RuntimeError(f"Failed to deserialize the evaluation result: {e}") from e - return result + 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): +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. 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 + # 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 @@ -194,23 +242,115 @@ 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.") + +# --------------------------------------------------------------------------- +# 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") -# Custom key (visible but obfuscated) +# 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'} @@ -278,53 +418,64 @@ 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: + 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): - code = code.decode('utf-8') - try: - # Combined step: Mapping + Caesar - caesar_encrypted = encrypt_with_mapping(code, mapping) - if not caesar_encrypted: - raise ValueError("Encryption failed. The result is empty.") + 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__}.") - # Final step: Base64 Encoding - base64_encoded = base64.b64encode(caesar_encrypted.encode()).decode() - if not base64_encoded: - raise ValueError("Base64 encoding failed. The result is empty.") + token = Fernet(_load_key(key)).encrypt(code.encode('utf-8')).decode('ascii') + return _V2_MARKER + token - return base64_encoded - except Exception as e: - if isinstance(e, (ValueError, RuntimeError, TypeError)): - raise - raise RuntimeError(f"An error occurred during encryption: {e}") - -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. - - Parameters: - encrypted_code (str): The Python code to decrypt. - mapping (dict): The mapping dictionary for character replacements. + Decrypt a pre-0.0.6 Base64 Caesar-cipher payload. - 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: + # 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,114 +487,160 @@ 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 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. -def encrypt_to_file(code: str, output_file: str, mapping: dict = _character_map) -> None: + 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): 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. + code (str or bytes): The Python code to encrypt. + 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') 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}") - -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: + except OSError as e: + raise OSError(f"Failed to write to file '{output_file}': {e}") from e + +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. 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') 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+/=]+)', content) - 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) - - # Execute the decrypted Python code - exec(decrypted_code) + 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): + if isinstance(e, (RuntimeError, ValueError, OSError, TypeError)): 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: +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') 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+/=]+)', content) - 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): - 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, TypeError)): 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 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b77a8ae --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,40 @@ +[build-system] +requires = ["setuptools>=68"] +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 = {text = "MIT"} +authors = [ + {name = "Infinitode Pty Ltd", email = "infinitode.ltd@gmail.com"}, +] +keywords = ["eval", "safe-eval", "sandbox", "encryption", "security", "ast", "cryptography"] +dependencies = [ + "cryptography>=41", + "cloudpickle>=2.2", +] +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..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 ) @@ -68,36 +68,28 @@ 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, allowed_vars=self.safe_vars, timeout=3, - restricted_imports=self.restricted_imports, - allowed_function_calls=self.allowed_function_calls - ) - except UnsafeExpressionError: - pass + allowed_function_calls=self.allowed_function_calls + ) 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, 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 ) - 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,12 +136,97 @@ 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_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_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): + 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): 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 46cebcd..23103d7 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,94 @@ 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_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] Unserializable 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