Home · Developers · Guides · Tool Sandboxing System

Security

Tool Sandboxing System

Sandboxed tool execution

Overview

The Tool Sandboxing System provides secure execution environments for Nova Coder tools with multiple isolation levels, resource limits, and violation tracking. This system enhances security by isolating tool execution and preventing potential system damage from malicious or buggy tools.

Location

  • File: novacoder/tools/sandboxing.py
  • Components: ToolSandbox, SandboxManager, SandboxLevel, ResourceLimits, SandboxViolation

Key Features

Multi-Level Isolation

The system provides four isolation levels for different security requirements:

  • NONE: No isolation - full system access (for trusted tools)
  • BASIC: Basic import restrictions and resource monitoring
  • STRICT: Full isolation with resource limits and access controls
  • PARANOID: Maximum isolation with strict security policies

Resource Limits

Configurable resource limits for sandboxed execution:

  • Memory Limits: Maximum memory usage in MB
  • CPU Limits: Maximum CPU percentage usage
  • Execution Time: Maximum execution time in seconds
  • File Descriptors: Maximum number of open file descriptors
  • Network Connections: Maximum number of network connections
  • Module Restrictions: Allowed/blocked Python modules
  • Path Restrictions: Allowed/blocked file system paths
  • Network Control: Allow/deny network access
  • File Access Control: Allow/deny file read/write operations

Violation Tracking

Automatic detection and tracking of sandbox violations:

  • Memory limit violations
  • CPU limit violations
  • Time limit violations
  • File access violations
  • Network access violations
  • Import restriction violations
  • System call violations

Components

SandboxLevel

Enum defining isolation levels:

class SandboxLevel(Enum):
    NONE = "none"
    BASIC = "basic"
    STRICT = "strict"
    PARANOID = "paranoid"

ResourceLimits

Dataclass for resource limit configuration:

@dataclass
class ResourceLimits:
    max_memory_mb: Optional[int] = None
    max_cpu_percent: Optional[float] = None
    max_execution_time: Optional[float] = None
    max_file_descriptors: Optional[int] = None
    max_network_connections: Optional[int] = None
    allowed_modules: Optional[Set[str]] = None
    blocked_modules: Optional[Set[str]] = None
    allowed_paths: Optional[Set[str]] = None
    blocked_paths: Optional[Set[str]] = None
    allow_network: bool = True
    allow_file_write: bool = True
    allow_file_read: bool = True

ToolSandbox

Main sandbox execution class with methods:

  • execute_tool(tool, **kwargs): Execute a tool within the sandbox
  • get_violations(): Get all recorded violations
  • clear_violations(): Clear all recorded violations
  • get_active_executions(): Get currently active executions

SandboxManager

Manager for multiple tool sandboxes:

  • create_sandbox(tool_name, level, limits): Create a sandbox for a specific tool
  • get_sandbox(tool_name): Get sandbox for a tool
  • remove_sandbox(tool_name): Remove sandbox for a tool
  • get_all_violations(): Get all violations from all sandboxes
  • get_statistics(): Get sandbox statistics

Usage Example

Basic Sandboxing

from novacoder.tools import SandboxLevel, ResourceLimits, ToolSandbox
from novacoder.tools.filesystem import ReadFileTool

# Create a sandbox with strict isolation
limits = ResourceLimits(
    max_memory_mb=512,
    max_cpu_percent=50.0,
    max_execution_time=30.0,
    allow_network=False,
    allow_file_write=False
)

sandbox = ToolSandbox(level=SandboxLevel.STRICT, limits=limits)

# Execute a tool within the sandbox
tool = ReadFileTool()
result = sandbox.execute_tool(tool, path='/path/to/file.txt')

print(f"Success: {result.success}")
print(f"Output: {result.output}")
print(f"Violations: {len(result.violations)}")
print(f"Execution time: {result.execution_time:.3f}s")
print(f"Memory used: {result.memory_used_mb:.2f}MB")

Sandbox Manager

from novacoder.tools import SandboxManager, SandboxLevel, get_sandbox_manager

# Get the global sandbox manager
manager = get_sandbox_manager()

# Create sandboxes for different tools
manager.create_sandbox('read_file', level=SandboxLevel.BASIC)
manager.create_sandbox('shell', level=SandboxLevel.PARANOID)

# Get sandbox statistics
stats = manager.get_statistics()
print(f"Total sandboxes: {stats['total_sandboxes']}")
print(f"Total violations: {stats['total_violations']}")
print(f"Active executions: {stats['active_executions']}")

Custom Resource Limits

from novacoder.tools import ResourceLimits, SandboxLevel

# Create custom resource limits for a specific tool
limits = ResourceLimits(
    max_memory_mb=1024,  # 1GB memory limit
    max_cpu_percent=75.0,  # 75% CPU limit
    max_execution_time=60.0,  # 60 second timeout
    max_file_descriptors=100,
    allowed_modules={'os', 'sys', 'json'},  # Only allow specific modules
    blocked_modules={'subprocess', 'eval'},  # Block dangerous modules
    allow_network=False,  # Disable network access
    allow_file_write=False,  # Read-only file access
)

sandbox = ToolSandbox(level=SandboxLevel.STRICT, limits=limits)

Registry Pattern

The sandbox system uses a global manager pattern:

from novacoder.tools import get_sandbox_manager, set_sandbox_manager

# Get the global manager (singleton)
manager = get_sandbox_manager()

# Set a custom manager if needed
custom_manager = SandboxManager(default_level=SandboxLevel.PARANOID)
set_sandbox_manager(custom_manager)

Best Practices

  1. Choose Appropriate Isolation Level

    • Use NONE only for trusted, internal tools
    • Use BASIC for tools that need monitoring but aren't dangerous
    • Use STRICT for most user-executable tools
    • Use PARANOID for tools with high security requirements
  2. Set Reasonable Resource Limits

    • Memory limits should be based on expected tool usage
    • CPU limits prevent tools from monopolizing system resources
    • Execution time limits prevent hanging tools
    • File descriptor limits prevent resource exhaustion
  3. Monitor Violations

    • Regularly check violation logs for security issues
    • Use violation patterns to identify problematic tools
    • Adjust resource limits based on violation patterns
  4. Use Sandbox Manager

    • Create dedicated sandboxes for different tool categories
    • Use the manager for centralized sandbox management
    • Track statistics to optimize sandbox configuration

CI/CD Integration

# In CI/CD pipelines, use strict sandboxing for all tool execution
from novacoder.tools import SandboxLevel, ResourceLimits, get_sandbox_manager

ci_limits = ResourceLimits(
    max_memory_mb=2048,
    max_execution_time=300.0,  # 5 minutes
    allow_network=False
)

manager = get_sandbox_manager()
manager.create_sandbox('ci_tool', level=SandboxLevel.STRICT, limits=ci_limits)

Troubleshooting

Common Issues

Tool execution fails with "Execution time limit exceeded"

  • Increase max_execution_time in ResourceLimits
  • Check if tool is actually hanging or just slow
  • Consider optimizing the tool implementation

Tool fails with "Memory limit exceeded"

  • Increase max_memory_mb in ResourceLimits
  • Check for memory leaks in tool implementation
  • Consider processing data in chunks

Module import violations

  • Add required modules to allowed_modules in ResourceLimits
  • Check if module is actually needed for tool functionality
  • Consider alternative implementations that don't require restricted modules

File access violations

  • Add required paths to allowed_paths in ResourceLimits
  • Check if file access is actually necessary
  • Consider using temporary directories for file operations

Security Considerations

  1. Always use sandboxing for untrusted tools
  2. Use PARANOID level for tools with system access
  3. Disable network access for tools that don't need it
  4. Restrict file system access to minimum required paths
  5. Monitor violation logs for security incidents
  6. Regularly audit sandbox configurations

Performance Optimization

  1. Use BASIC level for performance-critical tools
  2. Adjust resource limits based on actual usage patterns
  3. Reuse sandbox instances for repeated tool execution
  4. Monitor sandbox overhead and adjust accordingly
  5. Use violation data to optimize resource limits

Development Instructions

Adding New Isolation Levels

class SandboxLevel(Enum):
    NONE = "none"
    BASIC = "basic"
    STRICT = "strict"
    PARANOID = "paranoid"
    CUSTOM = "custom"  # Add new level

Adding New Violation Types

class SandboxViolationType(Enum):
    MEMORY_LIMIT = "memory_limit"
    CPU_LIMIT = "cpu_limit"
    TIME_LIMIT = "time_limit"
    FILE_ACCESS = "file_access"
    NETWORK_ACCESS = "network_access"
    IMPORT_RESTRICTION = "import_restriction"
    SYSTEM_CALL = "system_call"
    CUSTOM_VIOLATION = "custom_violation"  # Add new type

See Also

Source: wiki/tool-sandboxing.md · rendered 2026-11-10