CodeSafe
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.
Security Advisory
Reporting a vulnerability
Please do not report security vulnerabilities through public issues. See 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 | 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<class 'tuple'>, 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_attributesat 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.
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 · 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.6 or later immediately. These earlier versions should not be used in untrusted expression evaluation environments.
The fix includes:
- Rejecting all
ast.Callnodes unless the exact target is explicitly whitelisted (including calls via subscript, attribute, and other indirect targets) - Using a minimal built-ins allowlist that excludes dangerous functions like
exec,eval,compile, and__import__ - 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/Linkedin for finding and reporting this vulnerability.
Vulnerability & Security Testing (test_poc_vulnerability.py)
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
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__, __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__, 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 Tests
To run the security PoC suite locally:
python -m unittest test_poc_vulnerability.py -v
To run everything (including the functional suite in test.py):
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 above. - Security: Timed-out evaluations always terminate the child process. Previously
immediate_termination=Falseleaked 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 thekeyargument (see the newgenerate_key()), theCODESAFE_KEYenvironment variable, or a built-in default key (public; obfuscation-grade only - supply your own key for real confidentiality). Files written byencrypt_to_file()now contain# codesafe:v2:<token>; legacy pre-0.0.6.encryptfiles are still fully readable and runnable viadecrypt(),decrypt_to_file()andrun(). - Changed: The Caesar
mappingparameter was removed fromencrypt()(passing it raisesTypeError). It is still accepted bydecrypt()/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 fromsafe_eval(). Results that cannot be serialized (e.g. generators) still raise a clearRuntimeErrorinstead of a misleadingEvaluationTimeoutError, and thequeue.empty()race that could drop valid results is eliminated. - Changed:
restricted_importswas removed fromsafe_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
timeoutvalues are rejected withValueError. - 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 viarun()gets a clean__main__namespace isolated from CodeSafe's module globals. - Removed
dir()andid()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
cryptographyandcloudpickle(installed automatically by pip). - Packaging modernized: PEP 621
pyproject.toml; source distributions and wheels build correctly from a fresh checkout (the{{VERSION_PLACEHOLDER}}version madepip install .andpython -m buildfail). 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 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).
Changelog v0.0.5:
- Security Fix: Patched critical sandbox escape vulnerability in
safe_eval()(CVE-2026-133467), thanks to @hkmj19/Linkedin for reporting. - Blocked indirect function calls via
ast.Subscript,ast.Attribute, and other non-ast.Nametargets - Implemented minimal safe builtins whitelist excluding
exec,eval,compile,__import__, and similar dangerous functions - Added regression tests for indirect call bypass attempts
Changelog v0.0.4:
- Major performance optimizations for encryption and decryption (~10x speedup).
- Optimized
safe_evalby pre-filtering builtins and reducing internal overhead. - Added support for
bytesinput inencrypt. - Added support for file-like stream objects in
runanddecrypt_to_file. - Standardized error handling (replaced
printwith exceptions).
Changelog v0.0.3:
- Added an
allow_attributesparameter tosafe_evaland setimmediate_terminationto beTrueby default for safer function calling.
Changelog v0.0.2:
- Fixed function returns.
- Added error handling to
CodeSafe, removed some print statements with edits from@0XC7R.
Changelog v0.0.1:
- Initial release
Installation
You can install CodeSafe using pip (it automatically installs the cryptography and cloudpickle dependencies):
pip install codesafe
Supported Python Versions
CodeSafe supports the following Python versions:
- Python 3.8
- Python 3.9
- Python 3.10
- 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: Encrypt your code with authenticated cryptography (Fernet: AES-128-CBC + HMAC-SHA256), including full Unicode support. Legacy pre-0.0.6
.encryptfiles can still be decrypted. - Run encrypted code at runtime: Run your encrypted code files, without needing to expose your code to end-users.
Usage
Safe Eval
from codesafe import safe_eval
if __name__ == '__main__':
# Run a normal, safe expression
expression = "1 + 1"
disallowed_expression = "os.getcwd()"
result1 = safe_eval(expression, timeout=10)
result2 = safe_eval(disallowed_expression, timeout=10) # raises UnsafeExpressionError
Encrypt & Run Code
from codesafe import encrypt_to_file, decrypt_to_file, run, generate_key
code = """
greetJohnny = "Hello Johnny!"
def greet_someone(greeting):
print(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, key=key)
# Run the encrypted code
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, 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 theCODESAFE_KEYenvironment 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=Trueconvenience comes at increased risk (prefer the defaultFalse), and anything passed viaallowed_vars/allowed_builtinsruns 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 clearRuntimeError). Only deserialize results produced by CodeSafe's own child process - like any pickle-family tool, cloudpickle data must come from a trusted producer. typeremains in the default safe builtins (needed forisinstance-style patterns andtype(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.
License
CodeSafe is released under the terms of the MIT License (Modified). Please see the LICENSE file for the full text.
Modified License Clause
The modified license clause grants users the permission to make derivative works based on the CodeSafe software. However, it requires any substantial changes to the software to be clearly distinguished from the original work and distributed under a different name.
Metadata
Release files for codesafe 0.0.6
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| codesafe-0.0.6.tar.gz | 30.6 kB | With provenance | Details for codesafe-0.0.6.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| codesafe-0.0.6-py3-none-any.whl | Python 3 | none | any | Details for codesafe-0.0.6-py3-none-any.whl |
Total release size: 53.9 kB
Release files / codesafe-0.0.6.tar.gz
| Download URL | codesafe-0.0.6.tar.gz |
|---|---|
| Size | 30.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
be876a7e44a46c1d17cacaed9672d160d7c196431d7d57f1871a6beb8e53fc35
|
|
BLAKE2b-256 checksum How to use checksums |
36a2c4b80ce948e01a0541769d1d02b5b912881d573c701b9fb76bcb4d83c84d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logRelease files / codesafe-0.0.6-py3-none-any.whl
| Download URL | codesafe-0.0.6-py3-none-any.whl |
|---|---|
| Size | 23.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
37a29272945a540b08ab359896b977e009681cd72f6b7a64bc0600426022214d
|
|
BLAKE2b-256 checksum How to use checksums |
9f5c58024bb0b823bae14328bfa8b09f257beca048f5558f1d4b29bf2dca559c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logSecurity for codesafe 0.0.6
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for codesafe-0.0.6.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.