用途
AC Security Sandbox 为自主代码执行提供纵深防御(defense-in-depth)安全能力。当自动化流程或 AI 智能体需要执行 shell 命令时,该沙箱用于校验命令、配置权限、管理允许列表,并确保执行过程安全可控。
主要能力
该工具提供三层安全防护:
- 操作系统级沙箱:提供隔离的执行环境,可配置隔离级别(如 strict)与网络访问策略(如 restricted)。
- 文件系统权限:限制路径访问,通过 allow 与 deny 规则控制读写编辑范围。例如允许读写编辑项目目录(./),拒绝读取系统文件(/etc/)、拒绝写入系统目录(/usr/**)以及拒绝破坏性命令。
- 命令允许列表:仅允许预先批准的命令执行。内置允许列表涵盖文件查看(ls、cat、head、tail、wc、grep、find)、文件操作(cp、mv、mkdir、chmod、touch)、Node.js(npm、node、npx、yarn、pnpm)、Python(python、python3、pip、pip3)、版本控制(git)、进程管理(ps、lsof、sleep、pkill)、构建工具(make、cmake、cargo、go)以及测试工具(jest、pytest、vitest、playwright)。
此外还包含命令校验与提取机制:可从复杂命令字符串中提取基础命令,处理管道(|)、链式(&&、||)和分号(;)。例如 "npm install && npm test" 提取为 ["npm", "npm"],"cat file.txt | grep error" 提取为 ["cat", "grep"]。
使用方式
校验命令:
from scripts.security_sandbox import SecuritySandbox
sandbox = SecuritySandbox(project_dir)
is_safe, reason = sandbox.validate_command("npm install")
if is_safe:
# Execute command
pass
else:
print(f"Blocked: {reason}")
配置允许列表:
sandbox.configure_allowlist([
"ls", "cat", "head", "tail",
"npm", "node", "python",
"git", "grep"
])
启用沙箱模式:
sandbox_config = {
"enabled": True,
"isolation": "strict",
"network": "restricted"
}
配置文件系统权限:
permissions = {
"allow": [
"Read(./**)",
"Write(./**)",
"Edit(./**)",
],
"deny": [
"Read(/etc/**)",
"Write(/usr/**)",
"Bash(rm -rf /)",
]
}
Pre-Tool-Use 钩子:
async def bash_security_hook(input_data, tool_use_id, context):
command = input_data.get("tool_input", {}).get("command", "")
commands = extract_commands(command)
for cmd in commands:
if cmd not in ALLOWED_COMMANDS:
return {
"decision": "block",
"reason": f"Command '{cmd}' not in allowlist"
}
return {}
常用操作:初始化沙箱(await sandbox.initialize(),加载配置并设置钩子)、校验命令(validate_command)、校验路径(validate_path,可指定 operation="write")、注册钩子(create_pre_tool_hook)、添加自定义命令(add_allowed_command)、查看审计日志(get_audit_log(limit=100))。
配置文件(.claude/security-config.json)可设置 sandbox 的 enabled 与 isolation、permissions 的文件系统读写与拒绝路径、网络允许与拒绝列表,以及 allowlist 的命令与自定义项。
阻止的命令模式
始终阻止的危险模式包括:递归删除根目录(rm -rf /)、直接磁盘写入(dd if=)、格式化文件系统(mkfs)、fork 炸弹、过度宽松权限(chmod 777)、管道到 shell(curl | bash、wget | sh)。上下文相关命令(如 rm、mv、cp)仅在项目目录内允许。
审计日志
所有安全决策都会记录到 .claude/security-audit.jsonl,包含时间戳、动作(ALLOW/BLOCK)、命令与原因。
最佳实践
建议从最小允许列表开始,按需添加命令,定期审查审计日志,使用项目相对路径。不应允许 sudo 命令、系统路径写入,不应在生产环境禁用沙箱,也不应忽略被阻止命令的日志。
集成与脚本
集成点包括 ac-session-manager(提供安全钩子)、ac-build-runner(校验构建命令)、ac-coder-agent(限制智能体命令)、ac-config-manager(加载安全配置)。相关脚本有 scripts/security_sandbox.py(核心 SecuritySandbox)、scripts/command_validator.py(命令校验)、scripts/path_validator.py(路径校验)、scripts/audit_logger.py(安全审计日志)。参考资料包括 references/ALLOWLIST.md、references/PATTERNS.md、references/AUDIT.md。
适用场景与限制
适用于需要让 AI 智能体或自动化流程执行 shell 命令、但必须限制其权限范围的开发场景,尤其是自主编码环境。限制方面:资料未提供具体的平台兼容性、性能数据或收费信息。