sandbox.mdx 9.2 KB

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