Skip to content

Commit 27f19e2

Browse files
committed
Fixed CodeSafe vulnerabilities and removed unsafe default sandbox environment.
1 parent ec57722 commit 27f19e2

3 files changed

Lines changed: 667 additions & 26 deletions

File tree

‎README.md‎

Lines changed: 91 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,49 +12,110 @@ An open-source Python library for code encryption, decryption, and safe evaluati
1212
> [!NOTE]
1313
> **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.
1414
15+
## Security Advisory
16+
17+
### Critical Vulnerability Fixed in v0.0.5
18+
19+
**Versions 0.0.1 through 0.0.4 contain a known sandbox escape vulnerability in `safe_eval()` that allows arbitrary code execution.**
20+
21+
- **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.
22+
- **Impact**: An attacker controlling an expression passed to `safe_eval()` can execute arbitrary Python code with the application's permissions.
23+
- **Affected Versions**: 0.0.1, 0.0.2, 0.0.3, 0.0.4
24+
- **Fixed In**: Version 0.0.5 and later
25+
26+
**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.
27+
28+
The fix includes:
29+
1. Rejecting all `ast.Call` nodes unless the exact target is explicitly whitelisted (including calls via subscript, attribute, and other indirect targets)
30+
2. Using a minimal built-ins allowlist that excludes dangerous functions like `exec`, `eval`, `compile`, and `__import__`
31+
3. Added comprehensive regression tests for indirect call targets
32+
33+
---
34+
35+
## Vulnerability & Security Testing (`test_poc.py`)
36+
37+
CodeSafe v0.0.5+ includes a rigorous test suite (`TestVulnerabilityFixes` and `TestEdgeCases` in `test_poc.py`) to systematically verify that `safe_eval` blocks sandbox escapes while preserving standard evaluation features.
38+
39+
### Test Results Summary
40+
41+
**49/49 Security & Edge Case Tests Passing** (`100% Pass Rate` across all vector categories)
42+
43+
| Attack Vector / Category | Specific Vectors Tested | Status |
44+
| :--- | :--- | :--- |
45+
| **AST Subscript & Indirect Calls** | `__builtins__['exec']()`, `__builtins__['eval']()`, `__builtins__['__import__']()`, `getattr(__builtins__, 'exec')`, nested subscript access | **[PASS] Blocked** |
46+
| **Dunder Attribute Escapes** | `__class__`, `__bases__`, `__mro__`, `__subclasses__`, `__globals__`, `__closure__`, `__code__` | **[PASS] Blocked** |
47+
| **Class Hierarchy Traversal** | `object.__subclasses__()`, `type().subclasses()` | **[PASS] Blocked** |
48+
| **Expression Bypasses** | Comprehensions (list, dict, set), generator expressions, short-circuit logic (`and`/`or`), ternary operators, tuple unpacking, walrus operator (`:=`), lambda calls | **[PASS] Blocked** |
49+
| **Module & I/O Execution** | Direct/from `import`, `os.system`, `subprocess`, `io.open`, `socket`, `requests`, `urllib`, `pathlib` write operations | **[PASS] Blocked** |
50+
| **Dangerous Built-ins** | `exec()`, `eval()`, `compile()`, `input()`, `open()` (default settings), modifying `__builtins__` | **[PASS] Blocked** |
51+
| **Functional Baseline** | Safe arithmetic, string/list/dict operations, standard safe builtins (`len`, `max`, `abs`), explicitly allowed functions | **[PASS] Working** |
52+
53+
### Running the Proof of Concept Tests
54+
55+
To run the security PoC suite locally:
56+
57+
```bash
58+
python -m unittest test_poc.py -v
59+
60+
```
61+
62+
---
63+
64+
### Changelog v0.0.5:
65+
66+
* **Security Fix**: Patched critical sandbox escape vulnerability in `safe_eval()` (CVE pending)
67+
* Blocked indirect function calls via `ast.Subscript`, `ast.Attribute`, and other non-`ast.Name` targets
68+
* Implemented minimal safe builtins whitelist excluding `exec`, `eval`, `compile`, `__import__`, and similar dangerous functions
69+
* Added regression tests for indirect call bypass attempts
70+
1571
### Changelog v0.0.4:
16-
- Major performance optimizations for encryption and decryption (~10x speedup).
17-
- Optimized `safe_eval` by pre-filtering builtins and reducing internal overhead.
18-
- Added support for `bytes` input in `encrypt`.
19-
- Added support for file-like stream objects in `run` and `decrypt_to_file`.
20-
- Standardized error handling (replaced `print` with exceptions).
72+
73+
* Major performance optimizations for encryption and decryption (~10x speedup).
74+
* Optimized `safe_eval` by pre-filtering builtins and reducing internal overhead.
75+
* Added support for `bytes` input in `encrypt`.
76+
* Added support for file-like stream objects in `run` and `decrypt_to_file`.
77+
* Standardized error handling (replaced `print` with exceptions).
2178

2279
### Changelog v0.0.3:
23-
- Added an `allow_attributes` parameter to `safe_eval` and set `immediate_termination` to be `True` by default for safer function calling.
80+
81+
* Added an `allow_attributes` parameter to `safe_eval` and set `immediate_termination` to be `True` by default for safer function calling.
2482

2583
### Changelog v0.0.2:
26-
- Fixed function returns.
27-
- Added error handling to `CodeSafe`, removed some print statements with edits from `@0XC7R`.
84+
85+
* Fixed function returns.
86+
* Added error handling to `CodeSafe`, removed some print statements with edits from `@0XC7R`.
2887

2988
### Changelog v0.0.1:
30-
- Initial release
89+
90+
* Initial release
3191

3292
## Installation
3393

3494
You can install CodeSafe using pip:
3595

3696
```bash
3797
pip install codesafe
98+
3899
```
39100

40101
## Supported Python Versions
41102

42103
CodeSafe supports the following Python versions:
43104

44-
- Python 3.6
45-
- Python 3.7
46-
- Python 3.8
47-
- Python 3.9
48-
- Python 3.10
49-
- Python 3.11/Later (Preferred)
105+
* Python 3.6
106+
* Python 3.7
107+
* Python 3.8
108+
* Python 3.9
109+
* Python 3.10
110+
* Python 3.11/Later (Preferred)
50111

51112
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.
52113

53114
## Features
54115

55-
- **Safe Eval**: Safely allow `eval()` expressions to run, while maintaining complete control over the entire evaluation process.
56-
- **Code Encryption/Decryption**: Quickly encrypt your code. This is meant for code obfuscation, and not high-level encryption.
57-
- **Run encrypted code at runtime**: Run your encrypted code files, without needing to expose your code to end-users.
116+
* **Safe Eval**: Safely allow `eval()` expressions to run, while maintaining complete control over the entire evaluation process.
117+
* **Code Encryption/Decryption**: Quickly encrypt your code. This is meant for code obfuscation, and not high-level encryption.
118+
* **Run encrypted code at runtime**: Run your encrypted code files, without needing to expose your code to end-users.
58119

59120
> [!NOTE]
60121
> Running encrypted files at runtime using `run()` are only available in formats that can be understood by Python.
@@ -64,14 +125,20 @@ Please ensure that you have one of these Python versions installed before using
64125
> ```python
65126
> if __name__ == '__main__':
66127
> # Run eval, etc.
128+
>
67129
> ```
130+
>
131+
>
68132
> If you're planning on including `safe_eval` in executables:
69133
> ```python
70134
> import multiprocessing
71135
> if __name__ == '__main__':
72136
> multiprocessing.freeze_support()
73137
> # Call safe_eval afterwards
138+
>
74139
> ```
140+
>
141+
>
75142
> You can read more about why this needs to be done here: https://pytorch.org/docs/stable/notes/windows.html#multiprocessing-error-without-if-clause-protection
76143
77144
## Usage
@@ -88,10 +155,11 @@ if __name__ == '__main__':
88155
89156
result1 = safe_eval(expression, timeout=10, immediate_termination=True)
90157
result2 = safe_eval(disallowed_expression, timeout=10, immediate_termination=True)
158+
91159
```
92160
93161
> [!NOTE]
94-
> 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).
162+
> 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).
95163
96164
### Encrypt & Run Code
97165

@@ -117,16 +185,17 @@ run(encrypted_file_path) # Hello Johnny!
117185
# Decrypt code to another file
118186
output_file = "decrypted_code.py"
119187
decrypt_to_file(encrypted_file_path, output_file)
188+
120189
```
121190

122191
## Contributing
123192

124-
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).
193+
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).
125194

126195
## License
127196

128-
CodeSafe is released under the terms of the **MIT License (Modified)**. Please see the [LICENSE](https://github.com/infinitode/codesafe/blob/main/LICENSE) file for the full text.
197+
CodeSafe is released under the terms of the **MIT License (Modified)**. Please see the [LICENSE](https://github.com/infinitode/codesafe/blob/main/LICENSE?utm_source=gemini) file for the full text.
129198

130199
**Modified License Clause**
131200

132-
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.
201+
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.

‎codesafe/__init__.py‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,41 @@
99
__all__ = ['safe_eval', 'EvaluationTimeoutError', 'UnsafeExpressionError', 'encrypt_to_file', 'encrypt', 'decrypt', 'run', 'decrypt_to_file']
1010

1111
# Pre-filtered builtins to speed up safe_eval
12-
_BASE_BUILTINS = dict(builtins.__dict__)
12+
# Only include truly safe builtins - exclude exec, eval, compile, __import__, etc.
13+
_SAFE_BUILTIN_NAMES = {
14+
# Types
15+
'int', 'float', 'complex', 'str', 'bytes', 'bytearray', 'list', 'tuple',
16+
'range', 'set', 'frozenset', 'dict', 'bool', 'object',
17+
# Functions
18+
'abs', 'all', 'any', 'bin', 'chr', 'dir', 'divmod', 'enumerate',
19+
'format', 'hex', 'id', 'isinstance', 'issubclass', 'iter', 'len',
20+
'max', 'min', 'oct', 'ord', 'pow', 'repr', 'reversed', 'round',
21+
'sorted', 'sum', 'type', 'zip',
22+
# Exceptions (safe to expose)
23+
'Exception', 'BaseException', 'ArithmeticError', 'AssertionError',
24+
'AttributeError', 'BlockingIOError', 'BrokenPipeError', 'BufferError',
25+
'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError',
26+
'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError',
27+
'DeprecationWarning', 'EOFError', 'EnvironmentError', 'FileExistsError',
28+
'FileNotFoundError', 'FloatingPointError', 'FutureWarning',
29+
'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning',
30+
'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError',
31+
'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError',
32+
'ModuleNotFoundError', 'NameError', 'NotADirectoryError',
33+
'NotImplementedError', 'OSError', 'OverflowError',
34+
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
35+
'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError',
36+
'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError',
37+
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError',
38+
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
39+
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
40+
'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',
41+
'ZeroDivisionError',
42+
# Constants
43+
'True', 'False', 'None',
44+
}
45+
46+
_BASE_BUILTINS = {name: getattr(builtins, name) for name in _SAFE_BUILTIN_NAMES if hasattr(builtins, name)}
1347
_FILE_FUNCS = {'open'}
1448
_NETWORK_FUNCS = {
1549
'socket', 'requests', 'urllib', 'http.client', 'http.server',
@@ -150,10 +184,24 @@ def _check_ast(parsed_expr, restricted_imports, allowed_function_calls, allow_at
150184
raise UnsafeExpressionError(f"Use of '{alias.name}' is restricted.")
151185
raise UnsafeExpressionError("Imports are not allowed in expressions.")
152186

153-
# Prevent function calls except for whitelisted ones
187+
# Prevent ALL function calls except for whitelisted ones
188+
# This includes calls via ast.Name (e.g., exec()), ast.Attribute (e.g., obj.method()),
189+
# ast.Subscript (e.g., __builtins__['exec']()), and any other call target
154190
if isinstance(node, ast.Call):
155-
if isinstance(node.func, ast.Name) and node.func.id not in allowed_function_calls:
156-
raise UnsafeExpressionError(f"Function call to '{node.func.id}' is not allowed.")
191+
# Only allow calls where the function is a simple Name that's in the allowlist
192+
# OR a safe builtin function
193+
if isinstance(node.func, ast.Name):
194+
if node.func.id in allowed_function_calls or node.func.id in _SAFE_BUILTIN_NAMES:
195+
continue # This call is allowed
196+
# Also allow method calls on objects when attributes are allowed
197+
# (e.g., 'hello'.upper()) - these are ast.Attribute calls
198+
if isinstance(node.func, ast.Attribute) and allow_attributes:
199+
# Check it's not a dunder method
200+
if node.func.attr.startswith('__') and node.func.attr in blocked_attrs:
201+
raise UnsafeExpressionError(f"Access to dunder attribute '{node.func.attr}' is not allowed.")
202+
continue # Method call is allowed
203+
# All other calls are rejected (including subscript, attribute without allow_attributes, lambda, etc.)
204+
raise UnsafeExpressionError(f"Function call is not allowed.")
157205

158206
# Prevent attribute access (e.g., accessing os.system or other potentially harmful attributes)
159207
if isinstance(node, ast.Attribute) and not allow_attributes:

0 commit comments

Comments
 (0)