AI Code Interpreter 与代码沙箱深度实战 - 12. 安全与权限控制
本文是 AI Code Interpreter 与代码沙箱深度实战 的分章阅读版。
12. 安全与权限控制
12.1 多层防御
┌─────────────────────────────────────────────────┐
│ L1: 静态代码分析 (Code Analyzer) │
│ - 检测危险模式 (rm -rf, os.system) │
│ - AST 解析,识别危险 API │
├─────────────────────────────────────────────────┤
│ L2: 配额限制 │
│ - 每用户/天 次数限制 │
│ - CPU/内存/磁盘配额 │
├─────────────────────────────────────────────────┤
│ L3: 沙箱隔离 │
│ - 容器/MicroVM 物理隔离 │
│ - 系统调用过滤 (seccomp) │
├─────────────────────────────────────────────────┤
│ L4: 网络隔离 │
│ - 默认禁网 │
│ - 白名单访问 │
├─────────────────────────────────────────────────┤
│ L5: 输出过滤 │
│ - 检测敏感信息泄露 │
│ - 文件大小限制 │
├─────────────────────────────────────────────────┤
│ L6: 审计与告警 │
│ - 全量日志 │
│ - 异常行为告警 │
└─────────────────────────────────────────────────┘
12.2 代码静态分析
@Component
public class CodeAnalyzer {
private static final List<Pattern> DANGEROUS_PATTERNS = List.of(
Pattern.compile("(?i)\\bos\\.system\\s*\\("),
Pattern.compile("(?i)\\bsubprocess\\.[Pp]open\\s*\\("),
Pattern.compile("(?i)\\brm\\s+-rf?\\s+/"),
Pattern.compile("(?i):\\(\\)\\s*\\{\\s*:\\|:&\\s*\\};:"), // fork bomb
Pattern.compile("(?i)/dev/(tcp|udp)/"),
Pattern.compile("(?i)curl\\s+.*\\|\\s*sh"),
Pattern.compile("(?i)wget\\s+.*\\|\\s*sh"),
Pattern.compile("(?i)\\beval\\s*\\("),
Pattern.compile("(?i)__import__\\s*\\("),
Pattern.compile("(?i)\\bctypes\\.CDLL\\s*\\(")
);
public StaticAnalysisResult analyze(String code) {
List<String> violations = DANGEROUS_PATTERNS.stream()
.filter(p -> p.matcher(code).find())
.map(Pattern::pattern)
.toList();
if (!violations.isEmpty()) {
return StaticAnalysisResult.blocked("dangerous_pattern", violations);
}
// AST 分析 (深度检测)
try {
ASTAnalysisResult astResult = analyzeAST(code);
if (astResult.hasDanger()) {
return StaticAnalysisResult.blocked("ast_analysis", astResult.dangers());
}
} catch (Exception ignored) {
// AST 解析失败:不阻断 (沙箱兜底)
}
return StaticAnalysisResult.passed();
}
}
12.3 网络白名单
@Component
public class NetworkPolicyEnforcer {
private static final List<String> ALLOWED_DOMAINS = List.of(
"pypi.org",
"files.pythonhosted.org",
"registry.npmjs.org"
);
public String buildIptablesRules() {
// 在容器启动时配置 iptables
// 允许出站到白名单域名,其他全部拒绝
return """
# 默认拒绝 OUTPUT
iptables -P OUTPUT DROP
# 允许已建立的连接
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 允许 DNS
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
# 允许白名单域名(需要预解析 IP)
iptables -A OUTPUT -d <pypi_ip> -p tcp --dport 443 -j ACCEPT
# 拒绝其他所有
iptables -A OUTPUT -j REJECT
""";
}
}
12.4 用户配额
@Service
public class QuotaService {
private final RedisTemplate<String, String> redis;
public boolean checkQuota(String userId, ExecutionRequest req) {
String dayKey = "quota:" + userId + ":" + LocalDate.now();
// 检查每日次数
Long count = redis.opsForValue().increment(dayKey + ":count");
if (count == 1) {
redis.expire(dayKey + ":count", Duration.ofDays(1));
}
if (count > 100) return false;
// 检查每日 CPU 时间
Long cpuSec = redis.opsForValue().increment(
dayKey + ":cpu",
req.config().timeout().toSeconds()
);
if (cpuSec > 1800) return false; // 30 分钟/天
return true;
}
}
相关页面