# Bash Sandbox

> Learn how CodeBuddy Code's sandboxed Bash tool provides file system and network isolation for safer, more autonomous agent execution.

## Overview

CodeBuddy Code features native sandbox capabilities that provide a more secure environment for agent execution while reducing constant permission prompts. Instead of requiring permission for every bash command, the sandbox creates predefined boundaries that allow CodeBuddy Code to work more freely with reduced risk.

The sandboxed Bash tool uses operating system-level primitives to enforce file system and network isolation.

## Why Sandbox Matters

Traditional permission-based security requires continuous user approval for bash command execution. While this provides control, it can lead to:

* **Approval Fatigue**: Repeatedly clicking "approve" may cause users to pay less attention to what they're approving
* **Reduced Productivity**: Constant interruptions slow down development workflows
* **Limited Autonomy**: CodeBuddy Code cannot work efficiently while waiting for approvals

Sandbox addresses these challenges by:

1. **Defining Clear Boundaries**: Explicitly specifying which directories and network hosts CodeBuddy Code can access
2. **Reducing Permission Prompts**: Safe commands within the sandbox don't require approval
3. **Maintaining Security**: Attempts to access resources outside the sandbox trigger immediate notifications
4. **Enabling Autonomy**: CodeBuddy Code can run more independently within defined limits

<Warning>
  Effective sandboxing requires **both** file system and network isolation. Without network isolation, a compromised agent could exfiltrate sensitive files (like SSH keys). Without file system isolation, a compromised agent could backdoor system resources to gain network access. When configuring sandbox, it's important to ensure your configuration settings don't create bypasses in these systems.
</Warning>

## How It Works

### File System Isolation

The sandboxed Bash tool restricts file system access to specific directories:

* **Default Write Behavior**: Read-write access to current working directory and its subdirectories
* **Default Read Behavior**: Read access to the entire computer, except certain denied directories
* **Blocked Access**: Cannot modify files outside the current working directory without explicit permission
* **Configurable**: Define custom allowed and denied paths through settings

### Network Isolation

Network access is controlled through a proxy server running outside the sandbox:

* **Domain Restrictions**: Only approved domains can be accessed
* **User Confirmation**: New domain requests trigger permission prompts
* **Custom Proxy Support**: Advanced users can implement custom rules for outbound traffic
* **Comprehensive Coverage**: Restrictions apply to all scripts, programs, and subprocesses spawned by commands

### OS-Level Enforcement

The sandboxed Bash tool leverages operating system security primitives:

* **Linux**: Uses [bubblewrap](https://github.com/containers/bubblewrap) for isolation
* **macOS**: Uses Seatbelt for sandbox enforcement

These OS-level restrictions ensure all subprocesses spawned by CodeBuddy Code commands inherit the same security boundaries.

## Getting Started

### Enabling Sandbox

You can enable the sandbox by running the `/sandbox` slash command:

```
> /sandbox
```

This activates the sandboxed Bash tool with default settings, allowing access to the current working directory while blocking access to sensitive system locations.

### Configuring Sandbox

Customize sandbox behavior through the `settings.json` file. See [Settings](settings.md#bash-sandbox-settings) for complete configuration reference.

<Tip>
  Not all commands work out of the box with sandboxing. Here are some notes that may help you get the most out of sandboxing:

  * Many CLI tools need access to certain hosts. When you use these tools, they will request permission to access certain hosts. Granting permission will allow them to access these hosts now and in the future, enabling them to execute safely within the sandbox.
  * `watchman` is incompatible with running in the sandbox. If you're running `jest`, consider using `jest --no-watchman`
  * `docker` is incompatible with running in the sandbox. Consider specifying `docker` in `excludedCommands` to force it to run outside the sandbox.
</Tip>

<Note>
  CodeBuddy Code includes an intentional escape hatch mechanism that allows running commands outside the sandbox when necessary. When a command fails due to sandbox restrictions (like network connectivity issues or incompatible tools), CodeBuddy is prompted to analyze the failure and may retry the command using the `dangerouslyDisableSandbox` parameter. Commands using this parameter go through the normal CodeBuddy Code permission flow, requiring user permission to execute. This allows CodeBuddy Code to handle edge cases where certain tools or network operations cannot run within sandbox constraints.

  You can disable this escape hatch by setting `"allowUnsandboxedCommands": false` in your [sandbox settings](settings.md#bash-sandbox-settings). When disabled, the `dangerouslyDisableSandbox` parameter is completely ignored, and all commands must run in the sandbox or be explicitly listed in `excludedCommands`.
</Note>

## Sandbox Auto-Approval

In AcceptEdits permission mode, CodeBuddy Code provides sandbox auto-approval functionality to further reduce permission prompts:

### How It Works

When sandbox auto-approval is enabled, Bash commands that meet all of the following conditions will be automatically approved for execution without user confirmation:

1. **Currently in AcceptEdits permission mode**
2. **Sandbox is enabled** (`sandbox.enabled = true`)
3. **Auto-approval configuration is on** (`sandbox.autoAllowBashIfSandboxed = true`)
4. **Command will run in sandbox** (not in `excludedCommands` list)
5. **Not using dangerouslyDisableSandbox parameter**

### Configuration Example

Enable sandbox auto-approval in `.codebuddy/settings.json`:

```json
{
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": true,
    "excludedCommands": ["git", "docker"]
  }
}
```

### Usage Scenarios

**Auto-approved** (no user confirmation needed):
```bash
# In AcceptEdits mode, these commands are auto-approved
npm test
npm run build
ls -la
grep "pattern" file.txt
```

**Requires approval** (the following situations still require user confirmation):
```bash
# 1. Excluded commands (in excludedCommands)
git push

# 2. Commands explicitly disabling sandbox
# (using dangerouslyDisableSandbox parameter)

# 3. All commands in non-AcceptEdits mode
```

### Security Guarantees

Sandbox auto-approval improves efficiency while maintaining security:

* ✅ **Only within sandbox environment**: Only sandboxed commands can be auto-approved
* ✅ **File system isolation**: Commands can only access allowed directories
* ✅ **Network isolation**: Commands can only access approved domains
* ✅ **Configurable boundaries**: Exclude high-risk commands via `excludedCommands`
* ✅ **Security first**: Any configuration errors or anomalies fall back to requiring user approval

### Best Practices

1. **Use cautiously**: Only enable auto-approval when you understand sandbox limitations
2. **Exclude high-risk commands**: Add dangerous operations like `git push`, `rm -rf` to `excludedCommands`
3. **Review regularly**: Check logs to see which commands are being auto-approved
4. **Use in combination**: Use together with IAM permission rules for defense in depth

## Sandbox Auto-Approval

In AcceptEdits permission mode, CodeBuddy Code provides sandbox auto-approval functionality to further reduce permission prompts:

### How It Works

When sandbox auto-approval is enabled, Bash commands that meet all of the following conditions will be automatically approved for execution without user confirmation:

1. **Currently in AcceptEdits permission mode**
2. **Sandbox is enabled** (`sandbox.enabled = true`)
3. **Auto-approval configuration is on** (`sandbox.autoAllowBashIfSandboxed = true`)
4. **Command will run in sandbox** (not in `excludedCommands` list)
5. **Not using dangerouslyDisableSandbox parameter**

### Configuration Example

Enable sandbox auto-approval in `.codebuddy/settings.json`:

```json
{
  "sandbox": {
    "enabled": true,
    "autoAllowBashIfSandboxed": true,
    "excludedCommands": ["git", "docker"]
  }
}
```

### Usage Scenarios

**Auto-approved** (no user confirmation needed):
```bash
# In AcceptEdits mode, these commands are auto-approved
npm test
npm run build
ls -la
grep "pattern" file.txt
```

**Requires approval** (the following situations still require user confirmation):
```bash
# 1. Excluded commands (in excludedCommands)
git push

# 2. Commands explicitly disabling sandbox
# (using dangerouslyDisableSandbox parameter)

# 3. All commands in non-AcceptEdits mode
```

### Security Guarantees

Sandbox auto-approval improves efficiency while maintaining security:

* ✅ **Only within sandbox environment**: Only sandboxed commands can be auto-approved
* ✅ **File system isolation**: Commands can only access allowed directories
* ✅ **Network isolation**: Commands can only access approved domains
* ✅ **Configurable boundaries**: Exclude high-risk commands via `excludedCommands`
* ✅ **Security first**: Any configuration errors or anomalies fall back to requiring user approval

### Best Practices

1. **Use cautiously**: Only enable auto-approval when you understand sandbox limitations
2. **Exclude high-risk commands**: Add dangerous operations like `git push`, `rm -rf` to `excludedCommands`
3. **Review regularly**: Check logs to see which commands are being auto-approved
4. **Use in combination**: Use together with IAM permission rules for defense in depth

## Security Benefits

### Protection Against Prompt Injection

Even if an attacker successfully manipulates CodeBuddy Code's behavior through prompt injection, the sandbox ensures your system remains secure:

**File System Protection:**

* Cannot modify critical configuration files like `~/.bashrc`
* Cannot modify system-level files in `/bin/`
* Cannot modify CodeBuddy configuration files (`settings.json`, `settings.local.json`), preventing sandbox escape through hook injection
* Cannot read files denied in [CodeBuddy permission settings](iam.md#configuring-permissions)

**Network Protection:**

* Cannot exfiltrate data to attacker-controlled servers
* Cannot download malicious scripts from unauthorized domains
* Cannot make unexpected API calls to unapproved services
* Cannot contact any domain not explicitly allowed

**Monitoring and Control:**

* All attempts to access outside the sandbox are blocked at the OS level
* You receive immediate notification when boundaries are tested
* You can choose to deny, allow once, or permanently update configuration

### Configuration File Protection

The sandbox blocks writes to CodeBuddy configuration files by default to prevent sandbox escape attacks. An attacker could use prompt injection to make the Agent write to `settings.json`, injecting malicious `SessionStart` hooks that execute malicious commands with host privileges the next time the user starts CodeBuddy.

The following configuration files are write-protected in the sandbox:

* `~/.codebuddy/settings.json` - User global settings
* `~/.codebuddy/settings.local.json` - User local settings
* `.codebuddy/settings.json` - Project shared settings
* `.codebuddy/settings.local.json` - Project local settings

This protection applies to both Bash commands and file editing tools (Write, Edit, MultiEdit), ensuring the sandbox's `denyWrite` rules are uniformly enforced across all tools.

### Reduced Attack Surface

The sandbox limits potential damage from:

* **Malicious Dependencies**: NPM packages or other dependencies with harmful code
* **Compromised Scripts**: Build scripts or tools with security vulnerabilities
* **Social Engineering**: Attacks that trick users into running dangerous commands
* **Prompt Injection**: Attacks that trick CodeBuddy into running dangerous commands

### Transparent Operation

When CodeBuddy Code attempts to access network resources outside the sandbox:

1. The operation is blocked at the OS level
2. You receive immediate notification
3. You can choose to:
   * Deny the request
   * Allow once
   * Update sandbox configuration to allow permanently

## Security Limitations

* **Network Sandbox Limitations**: The network filtering system works by restricting which domains a process is allowed to connect to. It does not inspect traffic going through the proxy, and users are responsible for ensuring they only allow trusted domains in their policy.

<Warning>
  Users should be aware of the risks of allowing broad domain names (like `github.com`) which could allow data exfiltration. Additionally, in some cases it may be possible to bypass network filtering through [domain fronting](https://en.wikipedia.org/wiki/Domain_fronting).
</Warning>

* **Privilege Escalation via Unix Sockets**: The `allowUnixSockets` configuration may inadvertently grant access to powerful system services which could lead to sandbox bypasses. For example, if using it to allow access to `/var/run/docker.sock`, this would effectively grant access to the host system by leveraging the docker socket. Users are encouraged to carefully consider any unix sockets they allow through the sandbox.
* **File System Privilege Escalation**: Overly broad file system write permissions could enable privilege escalation attacks. Allowing writes to directories containing executables in `$PATH`, system configuration directories, or user shell configuration files (`.bashrc`, `.zshrc`) could lead to code execution in a different security context when those files are accessed by other users or system processes.
* **Linux Sandbox Strength**: The Linux implementation provides strong file system and network isolation but includes an `enableWeakerNestedSandbox` mode to work in Docker environments without privileged namespaces. This option significantly weakens security and should only be used where additional isolation is enforced by other means.

## Advanced Usage

### Custom Proxy Configuration

For organizations requiring advanced network security, you can implement custom proxies to:

* Decrypt and inspect HTTPS traffic
* Apply custom filtering rules
* Log all network requests
* Integrate with existing security infrastructure

```json
{
  "sandbox": {
    "network": {
      "httpProxyPort": 8080,
      "socksProxyPort": 8081
    }
  }
}
```

### Integration with Existing Security Tools

The sandboxed Bash tool works alongside:

* **IAM Policies**: Use with [permission settings](iam.md) for defense in depth
* **Development Containers**: Use with devcontainers for additional isolation
* **Enterprise Policies**: Enforce sandbox configuration through [managed settings](settings.md#settings-priority)

## Best Practices

1. **Start Restrictive**: Begin with minimal permissions, expand as needed
2. **Monitor Logs**: Review sandbox violation attempts to understand CodeBuddy Code's needs
3. **Use Environment-Specific Configuration**: Different sandbox rules for development and production environments
4. **Combine with Permissions**: Use sandbox together with IAM policies for comprehensive security
5. **Test Configuration**: Verify your sandbox settings don't block legitimate workflows
6. **Use Auto-Approval Cautiously**: Only enable `autoAllowBashIfSandboxed` when you fully understand sandbox limitations

## Open Source

The sandbox runtime is available as an open source npm package for your own agent projects. This enables the broader AI agent community to build safer, more reliable autonomous systems. This can also be used to sandbox other programs you may wish to run. For example, to sandbox an MCP server, you could run:

```bash
npx @anthropic-ai/sandbox-runtime <command-to-sandbox>
```

For implementation details and source code, visit the [GitHub repository](https://github.com/anthropic-experimental/sandbox-runtime).

## Limitations

* **Performance Overhead**: Minimal, but some file system operations may be slightly slower
* **Compatibility**: Some tools requiring specific system access patterns may need configuration adjustments, or may even need to run outside the sandbox
* **Platform Support**: Currently supports Linux and macOS; Windows support planned

## Related Documentation

* [Security](security.md) - Comprehensive security features and best practices
* [IAM](iam.md) - Permission configuration and access control
* [Settings](settings.md) - Complete configuration reference

---

*Let CodeBuddy Code work more autonomously in a secure sandbox 🛡️*
