Sandbox Execution

Host-side command filtering with SandboxExecutor — and when to use real OS or container isolation instead

Sandbox Execution

SandboxExecutor (praisonai_code.cli.features.sandbox_executor) checks command text against deny lists and runs the command on the host as the current user — it is a guard rail against mistakes, not isolation and not a security boundary.

Overview

Each SandboxExecutor run applies:

  • Command deny-list filtering — refuses blocked commands (rm, sudo, shells like sh/bash, etc.) and dangerous patterns
  • shell=False and minimal environment — runs directly without a shell and passes a reduced env
  • Resource limits — wall-clock timeout, CPU-time and file-size limits (plus memory limit on Linux)
  • Network tool deny-list — refuses common network tools (curl, wget, nc, ssh, python, node, etc.) in network_isolated mode (does not create a network namespace)
  • Temporary working directory — runs in a temporary directory in strict mode (settings a host subprocess cannot enforce, such as non-empty allowed_hosts, raise an error instead of silently pretending)

Quick Start

bash
# Real OS-level containment for the coding agent
PRAISON_SHELL=sandboxed praisonai code
python
# Host-side command filter from Python
from praisonai.cli.features import SandboxExecutorHandler

handler = SandboxExecutorHandler()
handler.initialize(mode="basic")
print(handler.execute("echo hello").stdout)

!Sandbox Execution

Filter Modes

Mode names are kept for backward compatibility; every mode runs the command on the host.

Disabled (Default)

No filtering. Commands run directly.

Basic

Deny-listed commands, patterns, and paths are refused with resource limits:

python
handler.initialize(mode="basic")

Applied checks:

  • 512 MB memory limit (Linux), 60 s CPU/timeout limit
  • Blocks dangerous commands (rm, rmdir, mv, dd, sudo, sh, bash, etc.) and blocked paths
  • Network tools allowed

Strict

Adds network tools to the deny list and runs in a temporary working directory on the host:

python
handler.initialize(mode="strict")

Applied checks:

  • 256 MB memory limit (Linux), 30 s CPU/timeout limit, max 5 processes
  • Blocks dangerous commands plus network tools (curl, wget, nc, netcat, ssh, scp)
  • Runs in a temporary working directory (host filesystem still exists — not a container or chroot)

Network Isolated

Same as basic, plus refuses commands in NETWORK_COMMANDS (curl, wget, nc, ssh, scp, python, python3, node, ruby, perl, openssl, etc.). Passing a non-empty allowed_hosts raises an error because a host subprocess cannot enforce host-level firewalling.

python
handler.initialize(mode="network_isolated")

Applied checks:

  • 512 MB memory limit (Linux), 60 s CPU/timeout limit
  • Blocks dangerous commands and NETWORK_COMMANDS on the command line (no kernel network namespace)

Python API

Basic Usage

python
from praisonai.cli.features import SandboxExecutorHandler

# Initialize with a mode
handler = SandboxExecutorHandler()
sandbox = handler.initialize(mode="basic")

# Execute a command
result = handler.execute("echo 'Hello, World!'")

print(f"Success: {result.success}")
print(f"Output: {result.stdout}")
print(f"Was sandboxed: {result.was_sandboxed}")

Execution Result

python
result = handler.execute("ls -la")

# Result properties
print(f"Success: {result.success}")
print(f"Exit code: {result.exit_code}")
print(f"Stdout: {result.stdout}")
print(f"Stderr: {result.stderr}")
print(f"Duration: {result.duration_ms}ms")
print(f"Sandboxed: {result.was_sandboxed}")
print(f"Violations: {result.policy_violations}")

Command Validation

python
# Validate before executing
violations = handler.validate_command("rm -rf /")

if violations:
    print("Command blocked:")
    for v in violations:
        print(f"  - {v}")
else:
    result = handler.execute("rm -rf /")

Custom Policy

python
from praisonai.cli.features.sandbox_executor import (
    SandboxPolicy,
    SandboxMode,
    SubprocessSandbox
)

# Create custom policy
policy = SandboxPolicy(
    mode=SandboxMode.BASIC,
    max_memory_mb=1024,
    max_cpu_seconds=120,
    max_file_size_mb=50,
    max_processes=20,
    allow_network=True,
    blocked_commands={"rm", "sudo", "chmod"},
    blocked_paths={"/etc", "/var", "/usr"}
)

# Use custom policy
sandbox = SubprocessSandbox(policy=policy)
result = sandbox.execute("my_command")

Blocked Commands

By default, these commands are blocked:

CommandReason
rmFile deletion
rmdirDirectory deletion
mvFile moving (can overwrite)
ddDisk operations
mkfsFilesystem creation
fdiskDisk partitioning
sudoPrivilege escalation
suUser switching
chmodPermission changes
chownOwnership changes
killProcess termination
pkillProcess termination

Strict Mode Additional Blocks

CommandReason
curlNetwork access
wgetNetwork access
nc / netcatNetwork access
sshRemote access
scpRemote file transfer

Dangerous Patterns

These patterns are always blocked:

python
# Recursive force delete
"rm -rf /"  # Blocked

# Device file access
"> /dev/sda"  # Blocked

# Shell piping
"cat file | sh"  # Blocked
"cat file | bash"  # Blocked

# Command substitution
"$(dangerous_command)"  # Blocked
"`dangerous_command`"  # Blocked

Path Restrictions

Blocked Paths (Strict Mode)

python
blocked_paths = {
    "/etc",      # System configuration
    "/var",      # Variable data
    "/usr",      # User programs
    "/bin",      # Essential binaries
    "/sbin",     # System binaries
    "/root",     # Root home
    "/home",     # User homes
    "/sys",      # Kernel interface
    "/proc"      # Process information
}

Allowed Paths

python
# Configure allowed paths
policy = SandboxPolicy(
    mode=SandboxMode.STRICT,
    allowed_paths={
        "/tmp",
        "/path/to/project",
        "/path/to/data"
    }
)

Resource Limits

Memory Limit

python
policy = SandboxPolicy(
    max_memory_mb=256  # 256MB limit
)

CPU Time Limit

python
policy = SandboxPolicy(
    max_cpu_seconds=30  # 30 second timeout
)

Process Limit

python
policy = SandboxPolicy(
    max_processes=5  # Max 5 child processes
)

Integration with Autonomy Modes

Sandbox works with autonomy modes:

python
from praisonai.cli.features import (
    SandboxExecutorHandler,
    AutonomyModeHandler
)

# Set up autonomy
autonomy = AutonomyModeHandler()
autonomy.initialize(mode="auto_edit")

# Set up sandbox
sandbox = SandboxExecutorHandler()
sandbox.initialize(mode="basic")

# Commands go through both:
# 1. Autonomy check (approval if needed)
# 2. Sandbox validation
# 3. Sandboxed execution

Error Handling

Timeout

python
result = sandbox.execute("sleep 100", timeout=5)

if not result.success:
    if "timed out" in result.stderr.lower():
        print("Command timed out")

Policy Violation

python
result = sandbox.execute("rm -rf /")

if result.policy_violations:
    print("Command blocked by policy:")
    for violation in result.policy_violations:
        print(f"  - {violation}")

Execution Error

python
result = sandbox.execute("nonexistent_command")

if not result.success:
    print(f"Error: {result.stderr}")
    print(f"Exit code: {result.exit_code}")

Best Practices

When to Use Sandbox

ScenarioRecommended Mode
Running user-provided codestrict
AI-generated shell commandsbasic
Processing untrusted datastrict
Local file operationsbasic
Network-sensitive tasksnetwork-isolated
Trusted automationdisabled

Security Tips

  1. Start with strict – Relax restrictions as needed
  2. Review violations – Check what’s being blocked
  3. Use network isolation – When network isn’t needed
  4. Set timeouts – Prevent runaway processes
  5. Limit resources – Prevent resource exhaustion

Environment Variables

bash
# Default sandbox mode
export PRAISONAI_SANDBOX_MODE=basic

# Disable sandbox entirely (not recommended)
export PRAISONAI_DISABLE_SANDBOX=false

# Custom timeout
export PRAISONAI_SANDBOX_TIMEOUT=60

CLI Flags

The legacy --sandbox off|basic|strict flag only prints a not-enforced warning; it does not use this executor. For containment from the CLI:

bash
PRAISON_SHELL=sandboxed praisonai code

Troubleshooting

Command Unexpectedly Blocked

python
# Check what's being blocked
violations = handler.validate_command("my_command")
print(violations)

# Adjust policy if needed
policy = SandboxPolicy(
    mode=SandboxMode.BASIC,
    blocked_commands={"rm", "sudo"}  # Reduced list
)

Timeout Too Short

python
# Increase timeout
result = handler.execute("long_running_command", timeout=300)

# Or in policy
policy = SandboxPolicy(max_cpu_seconds=300)

Path Access Denied

python
# Add to allowed paths
policy = SandboxPolicy(
    allowed_paths={"/path/to/needed/directory"}
)

Related Features