sandbox.mdx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. ---
  2. title: "沙箱机制 - 权限之外的第二道防线"
  3. description: "深入 Claude Code 沙箱机制:文件系统隔离、网络限制和资源约束,即使命令通过权限审批,沙箱仍可限制其行为范围。"
  4. keywords: ["沙箱", "sandbox", "文件隔离", "安全沙箱", "命令隔离"]
  5. ---
  6. ## 权限之外的第二道防线
  7. 权限系统决定"这条命令能不能执行",沙箱决定"执行时能做到什么程度"。
  8. 即使一条命令通过了权限审批,沙箱仍然可以限制它的行为。两者构成纵深防御的两层:
  9. - **权限层**(应用级):在工具调用前检查,决定是否弹窗审批
  10. - **沙箱层**(OS 级):在进程级别强制约束,即使 AI 生成了恶意命令也无法突破
  11. ## 执行链路:从用户输入到沙箱包裹
  12. 一条 Bash 命令的完整执行路径如下:
  13. ```
  14. 用户输入 → BashTool.call()
  15. → shouldUseSandbox(input) ─── 是否需要沙箱?
  16. → Shell.exec(command, { shouldUseSandbox })
  17. → SandboxManager.wrapWithSandbox(command)
  18. → spawn(wrapped_command) ─── 实际进程创建
  19. ```
  20. 关键判定发生在 `shouldUseSandbox()`(`src/tools/BashTool/shouldUseSandbox.ts`),它执行以下检查:
  21. 1. **全局开关**:`SandboxManager.isSandboxingEnabled()` — 检查平台支持 + 依赖完整性 + 用户设置
  22. 2. **显式跳过**:如果 `dangerouslyDisableSandbox: true` 且策略允许(`allowUnsandboxedCommands`),则不走沙箱
  23. 3. **排除列表**:用户可在 `settings.json` 中配置 `sandbox.excludedCommands`,匹配的命令跳过沙箱
  24. 4. **默认行为**:以上条件都不满足时,**进入沙箱**
  25. ## `shouldUseSandbox()` 判定逻辑详解
  26. ```typescript
  27. // src/tools/BashTool/shouldUseSandbox.ts
  28. function shouldUseSandbox(input: Partial<SandboxInput>): boolean {
  29. // 1. 全局未启用 → 直接跳过
  30. if (!SandboxManager.isSandboxingEnabled()) return false
  31. // 2. 显式禁用 + 策略允许 → 跳过
  32. if (input.dangerouslyDisableSandbox &&
  33. SandboxManager.areUnsandboxedCommandsAllowed()) return false
  34. // 3. 无命令 → 跳过
  35. if (!input.command) return false
  36. // 4. 匹配排除列表 → 跳过
  37. if (containsExcludedCommand(input.command)) return false
  38. // 5. 其他情况 → 必须沙箱化
  39. return true
  40. }
  41. ```
  42. `containsExcludedCommand()` 的匹配机制值得注意——它不只是简单的前缀匹配,而是支持三种模式:
  43. | 模式 | 示例 | 匹配行为 |
  44. |------|------|----------|
  45. | **精确匹配** | `npm run lint` | 完全相等 |
  46. | **前缀匹配** | `npm run test:*` | 前缀 + 空格或完全相等 |
  47. | **通配符** | `docker*` | 使用 `matchWildcardPattern` |
  48. 对于复合命令(如 `docker ps && curl evil.com`),系统会先拆分为子命令,逐一检查。还会迭代剥离环境变量前缀(`FOO=bar bazel ...`)和包装命令(`timeout 30 bazel ...`),直到不动点——防止通过嵌套包装绕过。
  49. ## 沙箱的配置模型
  50. 沙箱配置来自 `settings.json` 中的 `sandbox` 字段(`src/entrypoints/sandboxTypes.ts`):
  51. ```jsonc
  52. {
  53. "sandbox": {
  54. "enabled": true, // 主开关
  55. "autoAllowBashIfSandboxed": true, // 沙箱中的命令自动允许(跳过审批)
  56. "allowUnsandboxedCommands": true, // 是否允许 dangerouslyDisableSandbox
  57. "failIfUnavailable": false, // 沙箱依赖缺失时是否报错退出
  58. "network": {
  59. "allowedDomains": ["github.com"], // 网络白名单
  60. "deniedDomains": [], // 网络黑名单
  61. "allowLocalBinding": true, // 允许 localhost 绑定
  62. "httpProxyPort": 8888 // HTTP 代理端口(MITM)
  63. },
  64. "filesystem": {
  65. "allowWrite": ["~/projects"], // 额外可写路径
  66. "denyWrite": ["~/.ssh"], // 禁止写入路径
  67. "denyRead": [], // 禁止读取路径
  68. "allowRead": [] // 在 denyRead 中重新放行
  69. },
  70. "excludedCommands": ["docker", "npm:*"] // 不走沙箱的命令
  71. }
  72. }
  73. ```
  74. `SandboxSettingsSchema` 定义了完整的 Zod 验证规则,包含一些未公开的设置如 `enabledPlatforms`(限制沙箱只在特定平台生效)。
  75. ## 平台实现差异
  76. ### macOS:sandbox-exec(Seatbelt)
  77. macOS 使用 Apple 的 Seatbelt 沙箱(`sandbox-exec` 命令),这是 macOS 原生的进程隔离机制。
  78. 执行流程:
  79. 1. `SandboxManager.wrapWithSandbox()` 调用 `@anthropic-ai/sandbox-runtime` 的 `BaseSandboxManager`
  80. 2. 运行时生成 Seatbelt profile(基于配置中的网络/文件系统规则)
  81. 3. 通过 `sandbox-exec -p <profile> -- <command>` 包裹原始命令
  82. 4. Seatbelt 在内核级别强制执行约束
  83. 网络隔离的实现方式:
  84. - 通过代理端口拦截 HTTP/HTTPS 请求
  85. - 域名白名单/黑名单在代理层过滤
  86. - Unix socket 可单独配置允许路径
  87. ### Linux:bubblewrap(bwrap)+ seccomp
  88. Linux 使用 `bubblewrap`(bwrap)创建命名空间隔离,配合 seccomp 过滤系统调用:
  89. 依赖项(`apt install`):
  90. | 包 | 作用 |
  91. |----|------|
  92. | `bubblewrap` | 创建 mount/PID/network 命名空间 |
  93. | `socat` | 网络代理(HTTP/SOCKS) |
  94. | `libseccomp` / seccomp filter | 过滤 Unix socket 系统调用 |
  95. bwrap 的实现差异:
  96. - **不支持 glob 路径模式**(macOS 的 Seatbelt 支持)— Linux 上带 glob 的权限规则会触发警告
  97. - 执行后会在当前目录留下 0 字节的 mount-point 文件(如 `.bashrc`),需要 `cleanupAfterCommand()` 清理
  98. - seccomp 无法按路径过滤 Unix socket(只能全允许或全拒绝),与 macOS 的按路径放行形成差异
  99. ### 平台支持矩阵
  100. | 特性 | macOS | Linux | WSL |
  101. |------|-------|-------|-----|
  102. | 沙箱引擎 | sandbox-exec (Seatbelt) | bubblewrap + seccomp | 仅 WSL2 |
  103. | 文件 glob | ✅ 完整支持 | ⚠️ 仅 `/**` 后缀 | 同 Linux |
  104. | 网络 Unix socket 按路径 | ✅ | ❌ | ❌ |
  105. | 依赖检查 | ripgrep | bwrap + socat + ripgrep + seccomp | 同 Linux |
  106. ## 沙箱初始化流程
  107. ```
  108. REPL/SDK 启动
  109. → main.tsx → init.ts
  110. → SandboxManager.initialize(sandboxAskCallback)
  111. → detectWorktreeMainRepoPath() // 检测 git worktree,放行主仓库 .git
  112. → convertToSandboxRuntimeConfig() // 构建 SandboxRuntimeConfig
  113. → BaseSandboxManager.initialize() // 启动底层运行时
  114. → settingsChangeDetector.subscribe() // 订阅设置变更,动态更新配置
  115. ```
  116. `convertToSandboxRuntimeConfig()`(`src/utils/sandbox/sandbox-adapter.ts`)完成从用户设置到运行时配置的转换:
  117. 1. **网络规则**:从 `WebFetch(domain:...)` 权限规则提取域名 → `allowedDomains`
  118. 2. **文件系统规则**:从 `Edit(...)` / `Read(...)` 权限规则提取路径 → `allowWrite` / `denyWrite` / `denyRead`
  119. 3. **安全加固**:
  120. - 自动将项目目录加入 `allowWrite`
  121. - 自动将 `settings.json` 路径加入 `denyWrite`(防止沙箱逃逸)
  122. - 自动将 `.claude/skills` 加入 `denyWrite`(防止技能注入)
  123. - 检测 bare git repo 攻击向量,对 `HEAD`/`objects`/`refs` 做保护
  124. ## `dangerouslyDisableSandbox` 的设计权衡
  125. 这个参数的命名本身就传达了设计意图——它不是"关闭沙箱",而是"**危险地禁用沙箱**"。
  126. 双重保险机制:
  127. 1. **调用侧**:模型在 BashTool 的 `inputSchema` 中可以设置 `dangerouslyDisableSandbox: true`
  128. 2. **策略侧**:管理员可通过 `allowUnsandboxedCommands: false` 完全禁止此参数(企业部署场景)
  129. ```typescript
  130. // 即使 AI 请求了 dangerouslyDisableSandbox,策略层仍可覆盖
  131. if (input.dangerouslyDisableSandbox &&
  132. SandboxManager.areUnsandboxedCommandsAllowed()) {
  133. return false // 只有策略允许时才真正跳过沙箱
  134. }
  135. ```
  136. `autoAllowBashIfSandboxed` 进一步补充了这个模型:当启用时,**在沙箱中的命令自动获得执行许可**,无需逐条审批。这基于一个信任假设——如果 OS 级沙箱已经限制了命令的能力,那么应用层的逐条审批就变得多余。
  137. ## 沙箱违规处理
  138. 当命令尝试违反沙箱约束时:
  139. 1. 运行时捕获违规事件(文件/网络访问被拒绝)
  140. 2. `SandboxManager.annotateStderrWithSandboxFailures()` 在输出中注入 `<sandbox_violations>` 标签
  141. 3. UI 层通过 `removeSandboxViolationTags()` 清理显示
  142. 4. 违规事件通过 `SandboxViolationStore` 持久化,可用于审计
  143. ## 完整执行链路示例
  144. 以 `npm install` 为例:
  145. ```
  146. 1. 用户在 REPL 中输入 → Claude 决定调用 BashTool
  147. 2. BashTool.validateInput() → 通过
  148. 3. BashTool.checkPermissions() → 检查权限规则
  149. ├── autoAllowBashIfSandboxed = true 且沙箱可用 → 自动允许
  150. └── 否则 → 弹窗请用户确认
  151. 4. BashTool.call() → runShellCommand()
  152. 5. shouldUseSandbox({ command: "npm install" })
  153. ├── SandboxManager.isSandboxingEnabled() → true
  154. ├── dangerouslyDisableSandbox → undefined
  155. └── containsExcludedCommand() → false(除非用户配置了排除 npm)
  156. → 结果: true,需要沙箱
  157. 6. Shell.exec() → SandboxManager.wrapWithSandbox("npm install")
  158. ├── macOS: sandbox-exec -p <generated-profile> -- bash -c 'npm install'
  159. └── Linux: bwrap ... bash -c 'npm install'
  160. 7. spawn(wrapped_command) → 子进程在沙箱内执行
  161. 8. 执行完成 → SandboxManager.cleanupAfterCommand()
  162. ├── 清理 bwrap 残留文件(Linux)
  163. └── scrubBareGitRepoFiles()(安全清理)
  164. 9. 结果返回给 Claude → 展示给用户
  165. ```