Claude Code 最精密的子系统之一。每个工具执行前都经过多层安全审查。
一、安全设计第一性原理
核心矛盾:
- AI Agent 需要 自主执行 文件编辑、命令运行(否则效率太低)
- 但用户需要 控制权 和 安全保障(AI 可能犯错或执行危险操作)
解决方案:分层权限模型 + 智能分类器 + 用户确认
二、权限模式 (PermissionMode)
type PermissionMode = | 'default' | 'auto' | 'bypass' | 'plan'
|
模式详情
| 模式 |
读操作 |
写操作 |
命令执行 |
适用场景 |
| default |
自动允许 |
逐个询问 |
逐个询问 |
日常使用 |
| auto |
自动允许 |
分类器判断 |
分类器判断 |
信任 AI 的场景 |
| bypass |
自动允许 |
自动允许 |
自动允许 |
测试/CI 环境 |
| plan |
自动允许 |
禁止 |
只读命令 |
先规划后执行 |
三、权限检查完整流程
工具请求 (如 BashTool: "npm install lodash") │ ▼ [1] 工具级验证 ── tool.validateInput(input) │ 输入格式/范围检查 ▼ [2] 权限规则匹配 ── matchPermissionRules() │ ├─ alwaysAllowRules: 匹配 → 直接通过 ✅ ├─ alwaysDenyRules: 匹配 → 直接拒绝 ❌ └─ alwaysAskRules: 匹配 → 强制询问用户 ❓ │ ▼ (未匹配任何规则) [3] 权限模式判断 │ ├─ mode === 'bypass' → 直接通过 ✅ ├─ mode === 'plan' → 拒绝写操作 ❌ ├─ mode === 'default' → 询问用户 ❓ └─ mode === 'auto' → 进入分类器 │ ▼ [4] 分类器判断 (auto 模式) │ ── bashClassifier / yoloClassifier │ ├─ 安全 → 自动允许 ✅ ├─ 危险 → 拒绝 ❌ └─ 不确定 → 询问用户 ❓ │ ▼ [5] 用户确认对话框 │ ├─ Allow (允许本次) ├─ Always Allow (添加到 allow 规则) ├─ Deny (拒绝本次) └─ Always Deny (添加到 deny 规则)
|
四、权限规则系统
4.1 规则来源 (PermissionRuleSource)
type PermissionRuleSource = | 'user' | 'project' | 'enterprise' | 'plugin'
|
优先级:enterprise > project > user > plugin
4.2 规则格式
{ "permissions": { "allow": [ "Bash(npm *)", "Bash(git *)", "FileEdit(**/src/**)", "FileRead" ], "deny": [ "Bash(rm -rf *)", "Bash(sudo *)", "FileEdit(**/node_modules/**)" ] } }
|
4.3 通配符匹配算法
function matchWildcardPattern(pattern: string, command: string): boolean {
}
function permissionRuleExtractPrefix(rule: string): string { }
|
5.1 Bash 命令解析
function parseForSecurity(command: string): SecurityAnalysis { }
|
5.2 危险命令模式
const DANGEROUS_PATTERNS = [ /rm\s+(-[a-zA-Z]*r[a-zA-Z]*f|rf)\s/, /rm\s+-[a-zA-Z]*f[a-zA-Z]*r\s/,
/sudo\s/, /chmod\s+777/, /chown\s+root/,
/curl.*\|\s*(ba)?sh/, /wget.*\|\s*(ba)?sh/,
/>\s*\/etc\//, />\s*\/dev\//,
/curl\s+.*-d\s+@/, ];
|
5.3 Auto 模式分类器
function classifyBashCommand(command: string, context): ClassifierResult { return { decision: 'allow' | 'deny' | 'ask', reason: string, confidence: number, }; }
|
六、ToolPermissionContext — 权限上下文
type ToolPermissionContext = DeepImmutable<{ mode: PermissionMode; additionalWorkingDirectories: Map<string, AdditionalWorkingDirectory>; alwaysAllowRules: ToolPermissionRulesBySource; alwaysDenyRules: ToolPermissionRulesBySource; alwaysAskRules: ToolPermissionRulesBySource; isBypassPermissionsModeAvailable: boolean; isAutoModeAvailable?: boolean; strippedDangerousRules?: ToolPermissionRulesBySource; shouldAvoidPermissionPrompts?: boolean; awaitAutomatedChecksBeforeDialog?: boolean; prePlanMode?: PermissionMode; }>;
|
为什么用 DeepImmutable?
权限上下文是 不可变的。修改权限必须通过 PermissionUpdate 创建新的上下文对象。这防止了:
- 工具执行期间偷偷修改自己的权限
- Race condition 导致的权限泄露
- 回滚操作不一致
七、路径验证
function isPathWithinAllowedDirectories( path: string, cwd: string, additionalDirs: Map<string, AdditionalWorkingDirectory> ): boolean { const resolved = resolve(cwd, path);
if (resolved.startsWith(cwd)) return true;
for (const [dir] of additionalDirs) { if (resolved.startsWith(dir)) return true; }
return false; }
|
Symlink 攻击防护
const realPath = realpathSync(path); if (!realPath.startsWith(allowedDir)) { throw new Error('Symlink escape detected'); }
|
八、拒绝追踪
type DenialTrackingState = { denials: Array<{ toolName: string; input: unknown; reason: string; timestamp: number; }>; };
|
系统追踪所有被拒绝的操作,用于:
- 在自动压缩时保留拒绝信息(告诉 LLM “这个操作被拒绝过”)
- 分析模式(如果同一操作被反复拒绝,可能 LLM 策略有问题)
- 安全审计日志
九、沙箱执行
class SandboxManager { static async execute(command: string, options): Promise<ExecResult> { } }
function shouldUseSandbox(command: string, context): boolean { }
|
十、权限持久化
type PermissionUpdate = { tool: string; rule: string; behavior: 'allow' | 'deny'; destination: 'session' | 'project' | 'user'; };
async function persistPermissionUpdate(update: PermissionUpdate) { if (update.destination === 'project') { await updateProjectSettings(update); } else if (update.destination === 'user') { await updateGlobalSettings(update); } else { applyToCurrentContext(update); } }
|
十一、安全设计总结
Enterprise Policy (最高优先级) │ ▼ Project Rules (.claude/) │ ▼ User Rules (~/.claude/) │ ▼ Permission Mode (default/auto/plan/bypass) │ ▼ ┌───────┴───────┐ │ │ Classifier Rule Matcher (ML/规则) (通配符匹配) │ │ └───────┬───────┘ │ ▼ User Confirmation (权限对话框) │ ▼ Sandbox / Direct Execution
|
核心原则:
- Defense in Depth — 多层防御,任何一层都能阻止危险操作
- Least Privilege — 默认拒绝,需要显式授权
- Fail Safe — 不确定时询问用户,而不是自动允许
- Auditability — 所有操作和决策都有日志