高安全性Python沙箱库 - 用于安全执行不可信代码
Project description
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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file secure_sandbox-0.0.1.tar.gz.
File metadata
- Download URL: secure_sandbox-0.0.1.tar.gz
- Upload date:
- Size: 38.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e83fbd4fa92964874fa712704bf6dc1e0054b77950c5b8edcc788ea28e969af7
|
|
| MD5 |
1cfecb4c093fffaf0afc0a8791aac83e
|
|
| BLAKE2b-256 |
14a12842a913ee259f12c5df0b50629c186b1178d678b62a098a2313cfac3203
|
Provenance
The following attestation bundles were made for secure_sandbox-0.0.1.tar.gz:
Publisher:
python-publish.yml on dotnet-7/secure-sandbox
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
secure_sandbox-0.0.1.tar.gz -
Subject digest:
e83fbd4fa92964874fa712704bf6dc1e0054b77950c5b8edcc788ea28e969af7 - Sigstore transparency entry: 1730979922
- Sigstore integration time:
-
Permalink:
dotnet-7/secure-sandbox@dc3b5d517adecbae4fd00e07dfadbfd198e4a962 -
Branch / Tag:
refs/tags/v0.0.1 - Owner: https://github.com/dotnet-7
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@dc3b5d517adecbae4fd00e07dfadbfd198e4a962 -
Trigger Event:
release
-
Statement type:
File details
Details for the file secure_sandbox-0.0.1-py3-none-any.whl.
File metadata
- Download URL: secure_sandbox-0.0.1-py3-none-any.whl
- Upload date:
- Size: 17.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5cd6cb22c0cd6f51bab35fe5083b7c5d25d378fc02f3773fe517e0b561f12916
|
|
| MD5 |
77b18ec01dc934bec5b32e5ce1ac2e5c
|
|
| BLAKE2b-256 |
a0dcd3d9110bebf2a39130638731f0b14daf8a49e08d7b26cdc17666a1003fb2
|
Provenance
The following attestation bundles were made for secure_sandbox-0.0.1-py3-none-any.whl:
Publisher:
python-publish.yml on dotnet-7/secure-sandbox
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
secure_sandbox-0.0.1-py3-none-any.whl -
Subject digest:
5cd6cb22c0cd6f51bab35fe5083b7c5d25d378fc02f3773fe517e0b561f12916 - Sigstore transparency entry: 1730979934
- Sigstore integration time:
-
Permalink:
dotnet-7/secure-sandbox@dc3b5d517adecbae4fd00e07dfadbfd198e4a962 -
Branch / Tag:
refs/tags/v0.0.1 - Owner: https://github.com/dotnet-7
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@dc3b5d517adecbae4fd00e07dfadbfd198e4a962 -
Trigger Event:
release
-
Statement type: