Agent Code Sandboxing
Agents that execute code must do so in a sandboxed environment to prevent security breaches.
Task
Implement CodeSandbox that:
- Validates code statically for dangerous patterns before execution.
- Executes Python code in a restricted globals environment.
- Enforces time and memory limits.
- Logs all execution attempts.
Constraints
- Block:
os.system,subprocess,__import__,eval,exec,open, file I/O. - Execution timeout: configurable, default 5s.
- Return structured result with success, output, error, and execution time.
Examples
Example 1:
Input:
sb = CodeSandbox(SandboxConstraints())
sb.validate_code('import os; os.system("rm -rf /")')Output:
['Blocked pattern: os.system', 'Blocked pattern: import']Explanation: Both patterns are in the blocked list.
Starter Code
import subprocess
import resource
from typing import Dict, Any, List
class SandboxConstraints:
def __init__(self):
self.allowed_modules: List[str] = []
self.blocked_patterns: List[str] = ['os.system', 'subprocess', '__import__', 'eval', 'exec']
self.max_execution_time: float = 5.0 # seconds
self.max_memory_mb: int = 128
self.allow_network: bool = False
class CodeSandbox:
def __init__(self, constraints: SandboxConstraints):
self.constraints = constraints
self.execution_log: list = []
def validate_code(self, code: str) -> List[str]:
# TODO: Static analysis - return list of violations
pass
def execute(self, code: str, timeout: float = None) -> Dict:
# TODO: Execute in restricted environment
# Return: {'success': bool, 'output': str, 'error': str, 'time': float}
pass
def _build_restricted_globals(self) -> Dict:
# TODO: Build safe globals dict
pass
Python3
ReadyLines: 1Characters: 0
Ready