Secure Sandbox
A high-security Python sandbox library for safely executing untrusted third-party code (such as AI-generated code)
Core Features
1. Gas Mechanism - Prevent CPU DoS Attacks
- ✅ Automatically inject Gas checks in every loop and function call
- ✅ Immediately throw
GasLimitExceededexception when Gas quota is exhausted - ✅ Effectively defend against infinite loops and resource exhaustion attacks
2. AST Whitelist Validation
- ✅ Strict AST node whitelist mechanism
- ✅ Reject dangerous AST nodes (Import, Async, Yield, etc.)
- ✅ Block dangerous operations at compile time
3. Attribute Access Interception
- ✅ All attribute accesses are rewritten to
__sandbox_getattr__ - ✅ Strict attribute blacklist (40+ dangerous attributes like
__class__,__subclasses__) - ✅ Prevent sandbox escape via reflection chains
4. Import Whitelist Control
- ✅ Configurable module import whitelist
- ✅ Default allows safe modules (math, json, datetime, etc.)
- ✅ Reject dangerous modules (os, sys, subprocess, etc.)
5. Fully Configurable
- ✅ All security policies can be customized
- ✅ Gas quota, AST whitelist, attribute blacklist, module whitelist all configurable
- ✅ Support flexible security level adjustments
Installation
pip install secure-sandbox
Quick Start
Basic Usage
from secure_sandbox import safe_execute
# Execute safe code
code = """
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(f"Factorial of 5: {factorial(5)}")
"""
result = safe_execute(code, max_gas=100)
print(f"Remaining Gas: {result['remaining_gas']}")
Prevent Infinite Loops
from secure_sandbox import SecureSandbox, GasLimitExceeded
malicious_code = """
i = 0
while True:
i += 1
"""
sandbox = SecureSandbox()
try:
sandbox.safe_execute(malicious_code, max_gas=50)
except GasLimitExceeded as e:
print(f"Successfully intercepted infinite loop: {e}")
Prevent Sandbox Escape
from secure_sandbox import SecureSandbox, SandboxSecurityError
escape_code = """
result = [].__class__.__base__.__subclasses__()
"""
sandbox = SecureSandbox()
try:
sandbox.safe_execute(escape_code, max_gas=100)
except SandboxSecurityError as e:
print(f"Successfully intercepted escape attack: {e}")
Use Module Imports
from secure_sandbox import safe_execute
code = """
import math
result = math.sqrt(16)
print(f"sqrt(16) = {result}")
from json import dumps
json_str = dumps({"name": "Alice", "age": 25})
print(json_str)
"""
result = safe_execute(code, max_gas=100)
Security Interception Demo
See comprehensive attack interception examples:
python examples/security_interception.py
This demonstrates how Secure Sandbox blocks 20 types of attacks:
- ✅ Infinite loops (Gas mechanism)
- ✅ Reflection chain escapes (class, globals, code)
- ✅ Import attacks (os, sys, subprocess)
- ✅ Dynamic execution (eval, exec, compile)
- ✅ Exception handling escapes
- ✅ Context manager attacks
- ✅ Private attribute access
- ✅ Internal attribute attacks (dict, mro, subclasses)
All attacks are successfully intercepted with 100% block rate!
Advanced Configuration
Custom Security Policy
from secure_sandbox import SecureSandbox, SecurityConfig
# Create custom configuration
config = SecurityConfig(
# Gas configuration
max_gas=5000, # Maximum Gas quota
max_recursion_depth=50, # Maximum recursion depth
# Import configuration
allow_imports=True, # Allow imports
allowed_modules={'math', 'json'}, # Only allow these modules
# AST node configuration (optional)
ast_whitelist={'For', 'While', 'FunctionDef', ...}, # Custom AST whitelist
ast_blacklist={'Import', 'Try', ...}, # Custom AST blacklist
# Attribute access configuration
allow_dunder_access=False, # Disallow magic methods
allow_private_attrs=False, # Disallow private attributes
dangerous_attributes={'__class__', '__globals__', ...}, # Custom dangerous attributes
safe_attributes={'append', 'upper', ...}, # Custom safe attributes
# Feature switches
allow_comprehensions=True, # Allow comprehensions
allow_lambdas=True, # Allow Lambda
allow_classes=False, # Disallow class definitions
)
sandbox = SecureSandbox(config)
result = sandbox.safe_execute(code, max_gas=100)
Add Custom Modules to Whitelist
from secure_sandbox import SecurityConfig, DEFAULT_ALLOWED_MODULES
# Extend default module whitelist
custom_modules = DEFAULT_ALLOWED_MODULES.copy()
custom_modules.update({
'numpy', # Add numpy
'pandas', # Add pandas
})
config = SecurityConfig(
allowed_modules=custom_modules
)
Configuration Details
SecurityConfig Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
max_gas |
int | 10000 | Maximum Gas quota to prevent infinite loops |
max_recursion_depth |
int | 100 | Maximum recursion depth |
allow_imports |
bool | True | Whether to allow module imports |
allowed_modules |
Set[str] | DEFAULT_ALLOWED_MODULES | Module import whitelist |
ast_whitelist |
Set[str] | AST_WHITELIST | Allowed AST node whitelist |
ast_blacklist |
Set[str] | AST_BLACKLIST | Forbidden AST node blacklist |
allow_dunder_access |
bool | False | Whether to allow magic method access |
allow_private_attrs |
bool | False | Whether to allow private attribute access |
dangerous_attributes |
Set[str] | DANGEROUS_ATTRIBUTES | Dangerous attribute blacklist |
safe_attributes |
Set[str] | SAFE_ATTRIBUTES | Safe attribute whitelist |
allow_comprehensions |
bool | True | Whether to allow comprehensions |
allow_lambdas |
bool | True | Whether to allow Lambda expressions |
allow_classes |
bool | True | Whether to allow class definitions |
Default Allowed Modules
math - Mathematical operations
json - JSON processing
datetime - Date and time
collections - Advanced data structures
itertools - Iterator tools
functools - Function tools
operator - Operator functions
typing - Type hints
decimal - High-precision math
fractions - Fraction operations
statistics - Statistical functions
array - Arrays
copy - Copy tools
re - Regular expressions
random - Random numbers
API Documentation
safe_execute(code_str, max_gas, config)
Convenience function for quick code execution
Parameters:
code_str(str): Code string to executemax_gas(int): Maximum Gas quota, default 10000config(SecurityConfig, optional): Security configuration
Returns:
{
'success': True, # Execution success
'locals': {...}, # Local variables dictionary
'remaining_gas': 9999, # Remaining Gas
'total_checks': 100, # Total check count
}
Exceptions:
GasLimitExceeded: Gas quota exhaustedSandboxSecurityError: Security violationASTValidationError: AST validation failed
Comparison with Traditional Solutions
| Feature | RestrictedPython | Secure Sandbox |
|---|---|---|
| CPU DoS Defense | ❌ None | ✅ Gas mechanism |
| Sandbox Escape Defense | ⚠️ Limited | ✅ Strict interception |
| Import Control | ❌ None | ✅ Whitelist mechanism |
| Configurability | ⚠️ Basic | ✅ Fully configurable |
| Performance Overhead | Low | Medium (10-15%) |
Security Best Practices
- Set reasonable Gas quota: Based on code complexity, recommend 100-1000
- Limit imported modules: Only allow necessary modules
- Monitor execution results: Check remaining_gas and exception logs
- Regular audit: Check if whitelist needs updating
- Add timeout mechanism: Combine with signal or threading for dual protection
Known Limitations
- Performance overhead: Gas checks add ~10-15% overhead
- Feature limitations: Cannot import dangerous modules or use certain advanced features
- Reflection limitations: Normal reflection operations are also restricted
Contributing
Issues and Pull Requests are welcome!
Development environment setup:
git clone https://github.com/yourname/secure-sandbox.git
cd secure-sandbox
pip install -e ".[dev]"
pytest tests/
License
MIT License
Author
Python Security Architect
Version History
- v0.0.1 - Initial version
- Implemented Gas mechanism
- Implemented AST whitelist validation
- Implemented attribute access interception
- Implemented Import whitelist control
- Fully configurable security policies
- Complete test suite
Metadata
Release files for secure-sandbox 0.0.1
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 |
|---|---|---|---|---|
| secure_sandbox-0.0.1.tar.gz | 38.6 kB | With provenance | Details for secure_sandbox-0.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| secure_sandbox-0.0.1-py3-none-any.whl | Python 3 | none | any | Details for secure_sandbox-0.0.1-py3-none-any.whl |
Total release size: 56.3 kB
Release files / secure_sandbox-0.0.1.tar.gz
| Download URL | secure_sandbox-0.0.1.tar.gz |
|---|---|
| Size | 38.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e83fbd4fa92964874fa712704bf6dc1e0054b77950c5b8edcc788ea28e969af7
|
|
BLAKE2b-256 checksum How to use checksums |
14a12842a913ee259f12c5df0b50629c186b1178d678b62a098a2313cfac3203
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
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 Jun 5, 2026.
Transparency logRelease files / secure_sandbox-0.0.1-py3-none-any.whl
| Download URL | secure_sandbox-0.0.1-py3-none-any.whl |
|---|---|
| Size | 17.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5cd6cb22c0cd6f51bab35fe5083b7c5d25d378fc02f3773fe517e0b561f12916
|
|
BLAKE2b-256 checksum How to use checksums |
a0dcd3d9110bebf2a39130638731f0b14daf8a49e08d7b26cdc17666a1003fb2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
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 Jun 5, 2026.
Transparency logSecurity for secure-sandbox 0.0.1
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 secure_sandbox-0.0.1.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 Jun 5, 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.