Sooua
登录
返回文章列表
Claude Code··5 分钟阅读

安全加固与沙箱配置

graph LR

目标:配置安全策略,使用沙箱隔离,防止 AI 操作带来的风险
预计时间:35 分钟
对应官方文档:SecuritySandboxingSandbox Environments


安全威胁模型

AI 代理的风险

风险示例防护措施
数据泄露AI 上传代码到外部网络隔离、DLP
权限提升AI 修改系统文件沙箱、权限控制
供应链攻击AI 安装恶意包包管理审查
意外破坏AI 删除生产数据备份、只读模式
提示注入恶意输入诱导 AI输入验证

安全威胁模型图


沙箱选项对比

方案隔离级别复杂度适用场景
内置 Bash 沙箱进程级日常开发
Dev Container容器级团队统一环境
Docker容器级自定义环境
VM / 云沙箱系统级高安全要求

内置沙箱配置

默认限制

# Claude Code 内置沙箱默认限制:
- 不能访问 $HOME 以外的目录(项目目录除外)
- 不能修改系统文件
- 网络访问受限
- 环境变量隔离

自定义沙箱规则

# .claude/sandbox.yaml
sandbox:
  # 文件系统
  filesystem:
    allowed_paths:
      - ./src
      - ./tests
      - /tmp/claude-work
    denied_paths:
      - ./secrets/
      - ~/.ssh/
      - /etc/
    
  # 网络
  network:
    mode: restricted
    allowed_hosts:
      - pypi.org
      - npmjs.org
      - github.com
    denied_hosts:
      - "*"
    
  # 命令
  commands:
    allowed:
      - python
      - pytest
      - black
      - git
    denied:
      - rm -rf /
      - curl *
      - wget *
    require_confirmation:
      - pip install *
      - npm install *
      - docker *

Dev Container 配置

创建配置

// .devcontainer/devcontainer.json
{
  "name": "Secure Claude Environment",
  "image": "mcr.microsoft.com/devcontainers/python:3.11",
  
  "features": {
    "ghcr.io/devcontainers/features/docker-in-docker:2": {}
  },
  
  "customizations": {
    "vscode": {
      "extensions": ["anthropic.claude-code"]
    }
  },
  
  "postCreateCommand": "pip install -r requirements.txt",
  
  "remoteUser": "vscode",
  
  // 安全加固
  "runArgs": [
    "--cap-drop=ALL",
    "--security-opt=no-new-privileges"
  ],
  
  // 挂载限制
  "mounts": [
    "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=cached"
  ]
}

使用

# VS Code 自动检测并启动 Dev Container
# 或手动启动
devcontainer up --workspace-folder .
 
# 在容器内运行 Claude Code
claude

安全策略最佳实践

1. 最小权限原则

# 创建专用用户(不要 root)
useradd -m claude-worker
su - claude-worker
 
# 限制目录权限
chmod 700 /home/claude-worker/projects
chmod 500 /home/claude-worker/.claude

2. 网络隔离

# 使用网络命名空间
sudo unshare --net --pid --fork --mount-proc /bin/bash
 
# 或使用 Firejail
firejail --net=none --private=. claude

3. 命令审计

# 记录所有执行的命令
export PROMPT_COMMAND='history -a'
export HISTFILE=/var/log/claude-commands.log
 
# 实时监控
tail -f /var/log/claude-commands.log | grep -E "(rm|curl|wget|pip|npm)"

4. 备份策略

# 自动备份(pre-session)
#!/bin/bash
# .claude/hooks/session-start.sh
BACKUP_DIR="/backups/claude/$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
git bundle create "$BACKUP_DIR/repo.bundle" --all

安全插件

安装安全审查插件

claude plugin install security-guidance

配置安全规则

# .claude/security-rules.yaml
rules:
  - id: no-hardcoded-secrets
    pattern: '(password|secret|key|token)\s*=\s*["\'][^"\']+["\']'
    severity: error
    message: "禁止硬编码敏感信息"
    
  - id: no-sql-injection
    pattern: 'execute\s*\(\s*["\'].*%s'
    severity: error
    message: "可能存在 SQL 注入风险"
    
  - id: check-dependency-vulnerabilities
    command: "safety check"
    severity: warning
    
  - id: scan-for-secrets
    command: "git-secrets --scan"
    severity: error

应急响应

发现异常时

# 1. 立即停止所有 Claude 进程
killall claude
 
# 2. 检查修改了哪些文件
git status
git diff
 
# 3. 回滚到安全状态
git reset --hard HEAD
 
# 4. 审查日志
cat ~/.claude/logs/latest.log | grep -i "error\|warning\|denied"
 
# 5. 报告安全团队
# 保存相关日志和 diff

生产级安全加固方案

Docker Compose 完整配置

# docker-compose.security.yml
version: '3.8'
 
services:
  claude-secure:
    image: anthropic/claude-code:latest
    container_name: claude-sandbox
    
    # 安全选项
    security_opt:
      - no-new-privileges:true
      - seccomp:./seccomp-claude.json
    
    cap_drop:
      - ALL
    cap_add:
      - CHOWN
      - SETGID
      - SETUID
    
    # 只读根文件系统
    read_only: true
    
    # 临时文件系统
    tmpfs:
      - /tmp:noexec,nosuid,size=100m
      - /home/claude/.cache:size=50m
    
    # 网络隔离
    networks:
      - claude-isolated
    
    # 资源限制
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G
        reservations:
          cpus: '0.5'
          memory: 512M
    
    # 健康检查
    healthcheck:
      test: ["CMD", "claude", "--version"]
      interval: 30s
      timeout: 10s
      retries: 3
    
    volumes:
      # 只读挂载项目代码
      - ./project:/workspace:ro
      # 可写挂载(限制范围)
      - ./workspace:/workspace/output:rw
      # 配置文件
      - ./security/claude-sandbox.yaml:/etc/claude/config.yaml:ro
 
networks:
  claude-isolated:
    driver: bridge
    internal: true  # 无外网访问

Seccomp 配置文件

// seccomp-claude.json
{
  "defaultAction": "SCMP_ACT_ERRNO",
  "architectures": ["SCMP_ARCH_X86_64", "SCMP_ARCH_X86"],
  "syscalls": [
    {
      "names": [
        "accept", "bind", "clone", "close", "connect",
        "execve", "exit", "exit_group", "fcntl", "fork",
        "fstat", "getpid", "getrandom", "ioctl", "mmap",
        "munmap", "open", "openat", "poll", "read",
        "recvfrom", "sendto", "socket", "wait4", "write"
      ],
      "action": "SCMP_ACT_ALLOW"
    },
    {
      "names": ["chroot", "mount", "umount", "pivot_root"],
      "action": "SCMP_ACT_KILL"
    }
  ]
}

下一步

07. CI/CD 集成:GitHub Actions / GitLab

分享

评论

登录 后参与讨论。

加载中…

相关文章