> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch32-security-model/32.3-sandbox-mechanism.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 32.3 Sandbox Mechanism

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~280k tokens, Output \~9k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

When an AI Agent is given "tool capabilities" such as executing commands and reading/writing files, a core question emerges: how much damage can an Agent cause if it's hijacked by a prompt injection attack? OpenClaw's sandbox system answers this question through Docker container isolation—restricting tool execution in non-main sessions to a controlled container environment, so even if the Agent behaves abnormally, it cannot access the host machine.

***

## 32.3.1 Sandbox Design: Docker Isolation for Non-Main Sessions (`src/agents/sandbox.ts`)

### Sandbox Modes

Sandbox behavior is controlled by the `agents.defaults.sandbox.mode` configuration, with three modes:

| Mode         | Behavior                                                                                  |
| ------------ | ----------------------------------------------------------------------------------------- |
| `"off"`      | Default. No sandbox used; all commands execute on the host                                |
| `"non-main"` | Non-main sessions use sandbox. Main session (Bot owner's CLI interaction) is unrestricted |
| `"all"`      | All sessions execute in sandbox, including main session                                   |

`"non-main"` is the recommended production configuration—it allows the Bot owner to retain full host access while isolating sessions from channels (WhatsApp, Telegram, etc.) into containers.

### Sandbox Scope

`scope` determines the container lifecycle granularity:

```typescript
// src/agents/sandbox/types.ts

export type SandboxScope = "session" | "agent" | "shared";
```

| Scope       | Container Granularity             | Use Case                                                 |
| ----------- | --------------------------------- | -------------------------------------------------------- |
| `"session"` | One container per session         | Strongest isolation; sessions are completely independent |
| `"agent"`   | One container per Agent (default) | Multiple sessions of the same Agent share a container    |
| `"shared"`  | All Agents share one container    | Most resource-efficient                                  |

***

## 32.3.2 Sandbox Configuration Resolution (`src/agents/sandbox/`)

### Two-Layer Configuration Merging

Sandbox configuration supports a two-layer structure with global defaults and Agent-level overrides. The `resolveSandboxConfigForAgent` function merges both layers:

```typescript
// src/agents/sandbox/config.ts (simplified)

export function resolveSandboxConfigForAgent(cfg?: OpenClawConfig, agentId?: string): SandboxConfig {
  const globalSandbox = cfg?.agents?.defaults?.sandbox;    // Global default
  const agentSandbox = resolveAgentConfig(cfg, agentId)?.sandbox;  // Agent level

  const scope = resolveSandboxScope({
    scope: agentSandbox?.scope ?? globalSandbox?.scope,
  });

  return {
    mode: agentSandbox?.mode ?? globalSandbox?.mode ?? "off",
    scope,
    workspaceAccess: agentSandbox?.workspaceAccess ?? globalSandbox?.workspaceAccess ?? "none",
    workspaceRoot: agentSandbox?.workspaceRoot ?? globalSandbox?.workspaceRoot ?? DEFAULT_ROOT,
    docker: resolveSandboxDockerConfig({ scope, globalDocker: ..., agentDocker: ... }),
    browser: resolveSandboxBrowserConfig({ scope, globalBrowser: ..., agentBrowser: ... }),
    tools: resolveSandboxToolPolicyForAgent(cfg, agentId),
    prune: resolveSandboxPruneConfig({ scope, globalPrune: ..., agentPrune: ... }),
  };
}
```

### Docker Configuration Security Defaults

`resolveSandboxDockerConfig` applies a series of security hardening defaults:

```typescript
// src/agents/sandbox/config.ts (simplified)

export function resolveSandboxDockerConfig(params): SandboxDockerConfig {
  return {
    image: agentDocker?.image ?? globalDocker?.image ?? "openclaw-sandbox:bookworm-slim",
    readOnlyRoot: agentDocker?.readOnlyRoot ?? globalDocker?.readOnlyRoot ?? true,
    tmpfs: agentDocker?.tmpfs ?? globalDocker?.tmpfs ?? ["/tmp", "/var/tmp", "/run"],
    network: agentDocker?.network ?? globalDocker?.network ?? "none",    // No network!
    capDrop: agentDocker?.capDrop ?? globalDocker?.capDrop ?? ["ALL"],   // Drop all capabilities!
    env: { LANG: "C.UTF-8", ...globalDocker?.env, ...agentDocker?.env },
    // ... resource limits (pids, memory, cpu, ulimits)
  };
}
```

| Default                               | Security Implication                                                                |
| ------------------------------------- | ----------------------------------------------------------------------------------- |
| `readOnlyRoot: true`                  | Root filesystem is read-only, preventing system file modification                   |
| `tmpfs: ["/tmp", "/var/tmp", "/run"]` | Temporary directories use in-memory filesystem, cleared when container is destroyed |
| `network: "none"`                     | Completely disable network access, preventing data exfiltration                     |
| `capDrop: ["ALL"]`                    | Drop all Linux capabilities, principle of least privilege                           |

> **Sidebar**: **Linux Capabilities** is a fine-grained privilege separation mechanism that divides traditional root superuser privileges into 40+ independent capabilities (such as `CAP_NET_ADMIN` for network management, `CAP_SYS_PTRACE` for process debugging, etc.). `--cap-drop ALL` drops all capabilities, making processes in the container have almost no privileged operations even if running as root. This is a standard best practice for Docker security hardening.

***

## 32.3.3 Sandbox Path Management (`src/agents/sandbox-paths.ts`)

### Path Traversal Prevention

One of the most critical security issues in sandbox environments is **path traversal attacks**—the Agent might attempt to access files outside the sandbox root directory through paths like `../../etc/passwd`. The `resolveSandboxPath` function performs strict path validation:

```typescript
// src/agents/sandbox-paths.ts

export function resolveSandboxPath(params: {
  filePath: string;
  cwd: string;
  root: string;
}): { resolved: string; relative: string } {
  const resolved = resolveToCwd(params.filePath, params.cwd);
  const rootResolved = path.resolve(params.root);
  const relative = path.relative(rootResolved, resolved);

  // Check if path escapes sandbox root
  if (relative.startsWith("..") || path.isAbsolute(relative)) {
    throw new Error(`Path escapes sandbox root (${rootResolved}): ${params.filePath}`);
  }

  return { resolved, relative };
}
```

### Symlink Protection

Even if a path doesn't escape at the string level, attackers can still bypass through **symbolic links (symlinks)**—creating a symlink inside the sandbox pointing to an external directory. The `assertNoSymlink` function checks each component of the path layer by layer:

```typescript
// src/agents/sandbox-paths.ts

async function assertNoSymlink(relative: string, root: string) {
  const parts = relative.split(path.sep).filter(Boolean);
  let current = root;
  for (const part of parts) {
    current = path.join(current, part);
    try {
      const stat = await fs.lstat(current);
      if (stat.isSymbolicLink()) {
        throw new Error(`Symlink not allowed in sandbox path: ${current}`);
      }
    } catch (err) {
      if ((err as { code?: string }).code === "ENOENT") {
        return;  // Path doesn't exist → no threat
      }
      throw err;
    }
  }
}
```

> **Sidebar**: **TOCTOU (Time-of-check to Time-of-use)** is a common class of security vulnerabilities—there is a time window between checking file attributes and actually using the file, during which an attacker can replace a normal file with a symlink. OpenClaw mitigates this risk by using `lstat` (stat that doesn't follow symlinks) instead of `stat`, but complete TOCTOU protection typically requires operating system-level support (such as Linux's `openat` system call with the `O_NOFOLLOW` flag).

### Unicode Space Normalization

The `expandPath` function also handles an easily overlooked attack vector—Unicode non-breaking spaces and other special whitespace characters:

```typescript
const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;

function normalizeUnicodeSpaces(str: string): string {
  return str.replace(UNICODE_SPACES, " ");
}
```

This prevents attackers from constructing paths using special whitespace characters that appear legitimate but actually point to different locations.

***

## 32.3.4 Docker Sandbox Containers

### Container Creation Parameters

`buildSandboxCreateArgs` builds the complete parameter list for the `docker create` command. In addition to the security defaults mentioned earlier, there's a critical security flag:

```typescript
// src/agents/sandbox/docker.ts (simplified)

export function buildSandboxCreateArgs(params) {
  const args = ["create", "--name", params.name];

  // Labels (for management and identification)
  args.push("--label", "openclaw.sandbox=1");
  args.push("--label", `openclaw.sessionKey=${params.scopeKey}`);

  // Security hardening
  if (params.cfg.readOnlyRoot) args.push("--read-only");
  for (const entry of params.cfg.tmpfs) args.push("--tmpfs", entry);
  if (params.cfg.network) args.push("--network", params.cfg.network);
  for (const cap of params.cfg.capDrop) args.push("--cap-drop", cap);
  args.push("--security-opt", "no-new-privileges");  // Critical!

  // Resource limits
  if (params.cfg.pidsLimit > 0) args.push("--pids-limit", String(params.cfg.pidsLimit));
  if (params.cfg.memory) args.push("--memory", params.cfg.memory);
  if (params.cfg.cpus > 0) args.push("--cpus", String(params.cfg.cpus));

  // Optional security configuration
  if (params.cfg.seccompProfile) args.push("--security-opt", `seccomp=${...}`);
  if (params.cfg.apparmorProfile) args.push("--security-opt", `apparmor=${...}`);

  return args;
}
```

> **Sidebar**: `--security-opt no-new-privileges` is the Linux kernel's `PR_SET_NO_NEW_PRIVS` flag. It ensures that processes in the container (and their child processes) cannot acquire new privileges through mechanisms like `setuid` and `setgid`. Even if a setuid-root executable exists in the container, attackers cannot exploit it to escalate privileges. This is one of the most important yet most easily forgotten options in Docker security hardening.

### Container Lifecycle Management

`ensureSandboxContainer` manages the complete container lifecycle—creation, reuse, and configuration drift detection:

```typescript
// src/agents/sandbox/docker.ts (simplified)

export async function ensureSandboxContainer(params) {
  const containerName = `${prefix}${slug}`.slice(0, 63);

  // 1. Compute configuration hash
  const expectedHash = computeSandboxConfigHash({ docker, workspaceAccess, workspaceDir });

  // 2. Check if container already exists
  const state = await dockerContainerState(containerName);

  if (state.exists) {
    // 3. Configuration drift detection
    const currentHash = await readContainerConfigHash(containerName);
    if (currentHash !== expectedHash) {
      if (isRecentlyUsed) {
        // In use → only warn, don't break
        log("Sandbox config changed. Recreate to apply.");
      } else {
        // Idle → auto-destroy and rebuild
        await execDocker(["rm", "-f", containerName]);
        // Subsequent logic will create new container
      }
    }
  }

  if (!state.exists) {
    // 4. Create new container
    await createSandboxContainer({ name: containerName, cfg, workspaceDir, ... });
  } else if (!state.running) {
    // 5. Container exists but stopped → restart
    await execDocker(["start", containerName]);
  }

  // 6. Update registry
  await updateRegistry({ containerName, sessionKey, lastUsedAtMs: Date.now() });
  return containerName;
}
```

**Configuration drift detection** is an important security feature—when users modify sandbox configuration (such as changing from `network: "none"` to `network: "bridge"`), old containers might still be running with the old configuration. The system detects this situation through configuration hash comparison: idle containers are automatically rebuilt, active containers issue a warning.

### Workspace Mounting

When a container is created, the workspace directory is mounted into the container. The mounting method depends on the `workspaceAccess` configuration:

| workspaceAccess | Mount Method                                 | Description                     |
| --------------- | -------------------------------------------- | ------------------------------- |
| `"none"`        | Sandbox independent directory → `/workspace` | Agent cannot access host files  |
| `"ro"`          | Host workspace → `/workspace:ro`             | Read-only access to host files  |
| `"rw"`          | Host workspace → `/workspace`                | Read-write access to host files |

***

## 32.3.5 Tool Whitelist / Blacklist

### Sandbox Tool Policy

Not all tools should be available in the sandbox environment. `resolveSandboxToolPolicyForAgent` resolves tool policies with three levels of priority:

```typescript
// src/agents/sandbox/tool-policy.ts (simplified)

export function resolveSandboxToolPolicyForAgent(cfg?, agentId?): SandboxToolPolicyResolved {
  // Priority: Agent level > Global > Default
  const deny  = agentDeny  ?? globalDeny  ?? [...DEFAULT_TOOL_DENY];
  const allow = agentAllow ?? globalAllow ?? [...DEFAULT_TOOL_ALLOW];

  // image tool is always allowed by default (needed for multimodal)
  if (!deny.includes("image") && !allow.includes("image")) {
    allow.push("image");
  }

  return { allow: expandToolGroups(allow), deny: expandToolGroups(deny), sources };
}
```

### Default Policy

```typescript
// src/agents/sandbox/constants.ts

// Tools allowed by default
const DEFAULT_TOOL_ALLOW = [
  "exec", "process",     // Command execution
  "read", "write", "edit", "apply_patch",  // File operations
  "image",               // Image processing
  "sessions_list", "sessions_history",     // Session viewing
  "sessions_send", "sessions_spawn",       // Session operations
  "session_status",      // Session status
];

// Tools denied by default
const DEFAULT_TOOL_DENY = [
  "browser",  // Browser control (bypasses network isolation)
  "canvas",   // Canvas (may expose host resources)
  "nodes",    // Node management
  "cron",     // Scheduled tasks
  "gateway",  // Gateway management
  // All channel IDs (prevent sending messages from sandbox)
  ...CHANNEL_IDS,
];
```

### Wildcard Matching

Tool names support wildcard pattern matching:

```typescript
// src/agents/sandbox/tool-policy.ts

function compilePattern(pattern: string): CompiledPattern {
  const normalized = pattern.trim().toLowerCase();
  if (normalized === "*") return { kind: "all" };          // Match everything
  if (!normalized.includes("*")) return { kind: "exact", value: normalized };
  // Convert to regex
  const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return { kind: "regex", value: new RegExp(`^${escaped.replaceAll("\\*", ".*")}$`) };
}

export function isToolAllowed(policy: SandboxToolPolicy, name: string) {
  const normalized = name.trim().toLowerCase();
  // 1. Check blacklist first — blacklist takes priority
  if (matchesAny(normalized, deny)) return false;
  // 2. Then check whitelist — empty whitelist = allow all
  if (allow.length === 0) return true;
  return matchesAny(normalized, allow);
}
```

The **deny-first** strategy ensures security—even if a tool is in the whitelist, it will be rejected if it also appears in the blacklist.

***

## Summary of This Section

1. **Three Sandbox Modes**: `off` (disabled), `non-main` (recommended, isolates external sessions only), `all` (isolates all sessions).
2. **Three Scopes**: `session` (strongest isolation), `agent` (default, shared within Agent), `shared` (globally shared).
3. **Security Defaults**: Read-only root filesystem, no network, drop all Linux capabilities, prevent privilege escalation.
4. **Path Safety**: Path traversal detection + symlink checking + Unicode space normalization, preventing multiple path traversal attacks.
5. **Configuration Drift Detection**: Detect container-configuration inconsistency through configuration hash comparison; idle containers auto-rebuild.
6. **Tool Policy**: Three-level priority (Agent level > Global > Default), blacklist takes priority over whitelist.
7. **Default Deny**: Sensitive tools like browser, channel sending, and Gateway management are disabled by default in sandbox.
