Claude Code 安全優先開發
如何確保您的 Claude Code 工作流程產生安全的程式碼。從 security-auditor agent 到 PreToolUse hooks 和自動化審計。
AI 輔助開發帶來一個重要問題:如何確保 Claude 編寫的程式碼是安全的?
答案不是避免使用 AI 輔助,而是使用 Claude Code 的官方工具將安全性融入您的工作流程:security-auditor agent、PreToolUse hooks 和 permission settings。
本指南涵蓋如何使用官方功能配置 Claude Code 進行安全意識開發。
官方安全工具
security-auditor Agent
根據 Claude Code 文件,security-auditor 是專門用於漏洞檢測的專用 agent:
Task({
subagent_type: "security-auditor",
model: "sonnet", // or "opus" for critical code
prompt: `
Audit the authentication module for security vulnerabilities.
Check for:
- OWASP Top 10 vulnerabilities
- Hardcoded secrets
- SQL injection patterns
- XSS vulnerabilities
- Authentication bypass risks
`
})
何時使用 security-auditor:
| 場景 | 模型 | 原因 |
|---|---|---|
| 認證/支付變更 | Sonnet/Opus | 關鍵程式碼 |
| 新 API 端點 | Sonnet | 輸入驗證 |
| 檔案上傳處理 | Sonnet | 清理處理 |
| 外部 API 整合 | Sonnet | 資料暴露 |
自動安全執行的 Hooks
根據官方 hooks 文件,hooks 可以在無需手動介入的情況下自動執行安全政策。
PreToolUse Hook - 阻擋危險操作
在 .claude/settings.json 中配置:
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "prompt",
"prompt": "If the command contains destructive operations (rm -rf, DROP TABLE, git push --force), return 'ask' for user confirmation. Otherwise return 'approve'."
}]
}]
}
}
可用的 hook 事件:
| 事件 | 時機 | 安全用途 |
|---|---|---|
PreToolUse | 工具執行前 | 阻擋危險指令 |
PostToolUse | 工具執行後 | 審計檔案變更 |
Stop | Agent 考慮停止時 | 驗證安全審查 |
SessionStart | 會話開始時 | 載入安全上下文 |
Stop Hook - 驗證安全審查
{
"hooks": {
"Stop": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "If code in auth/, payment/, or admin/ was modified, verify security-auditor was run. If not, block and explain."
}]
}]
}
}
Permission Settings
根據 Claude Code 文件,使用 settings.json 進行存取控制:
{
"permissions": {
"allow": [
"Read",
"Write",
"Edit",
"Bash(npm run:*)",
"Bash(git:*)"
],
"deny": [
"Read(.env)",
"Read(.env.*)",
"Read(secrets/**)",
"Read(**/*credentials*)",
"Bash(*rm -rf*)",
"Bash(*DROP*)"
]
}
}
權限模式語法:
Bash(npm run:*)- 允許所有 npm run 指令Read(.env)- 拒絕讀取 .env 檔案Read(secrets/**)- 拒絕讀取 secrets/ 中的任何內容Bash(*DROP*)- 拒絕包含 DROP 的指令
安全挑戰
當 Claude 編寫程式碼時,存在幾個風險:
- 從訓練資料複製的不安全模式
- 缺少輸入驗證
- 洩露資訊的不當錯誤處理
- 硬編碼的憑證或密鑰
- SQL injection、XSS 和其他漏洞
解決方案:使用 agents 和 hooks 將您的安全需求程式碼化,讓 Claude 自動遵循。
建立安全優先的 CLAUDE.md
安全章節範本
# Security Requirements
## Non-Negotiables
These rules cannot be overridden for any reason:
1. **No Secrets in Code**
- Never hardcode credentials, API keys, or tokens
- Use environment variables for all secrets
- Reference secrets through secure config management
2. **Input Validation**
- All user inputs must be validated
- Use allowlist validation over blocklist
- Validate on both client and server
3. **Output Encoding**
- Encode all outputs for the context (HTML, URL, JS)
- Use framework-provided escaping mechanisms
- Never concatenate raw user input into responses
4. **Authentication & Authorization**
- All endpoints must verify authentication
- Check authorization before every action
- Use principle of least privilege
5. **Data Protection**
- Encrypt sensitive data at rest and in transit
- Minimize data collection and retention
- Log access to sensitive data
## Security Review Requirements
These types of changes require explicit security review:
- Authentication/authorization logic
- Payment processing
- Personal data handling
- API endpoint creation
- Database queries
- File uploads
- Email sending
- External API calls
輸入驗證標準
# Input Validation Standards
## Validation Library
Use Zod for all runtime validation:
\`\`\`typescript
import { z } from 'zod';
// Define schema
const UserSchema = z.object({
email: z.string().email(),
age: z.number().min(0).max(150),
name: z.string().min(1).max(100),
});
// Validate
const result = UserSchema.safeParse(input);
if (!result.success) {
throw new ValidationError(result.error);
}
\`\`\`
## Validation Rules
- String inputs: Define max length
- Numeric inputs: Define valid range
- Email: Use proper email validation
- URLs: Validate protocol and domain
- IDs: Validate format (UUID, numeric, etc.)
- Arrays: Validate length and item types
- Objects: Validate required fields
安全編碼模式
# Secure Coding Patterns
## Database Queries
ALWAYS use parameterized queries:
\`\`\`typescript
// NEVER do this
const query = \`SELECT * FROM users WHERE email = '\${email}'\`;
// ALWAYS do this
const user = await db.user.findUnique({
where: { email }, // Prisma handles parameterization
});
\`\`\`
## Error Handling
Never expose internal details:
\`\`\`typescript
// NEVER do this
catch (error) {
return res.status(500).json({ error: error.message });
}
// ALWAYS do this
catch (error) {
console.error('Internal error:', error); // Log full error
return res.status(500).json({ error: 'An error occurred' }); // Generic message
}
\`\`\`
## Authentication Checks
Always verify auth at the start:
\`\`\`typescript
export async function handler(req, res) {
// First: Authenticate
const user = await getAuthenticatedUser(req);
if (!user) {
return res.status(401).json({ error: 'Unauthorized' });
}
// Second: Authorize
if (!user.canAccessResource(resourceId)) {
return res.status(403).json({ error: 'Forbidden' });
}
// Then: Proceed with logic
// ...
}
\`\`\`
安全的 Agent 委派
配置 Claude 對敏感變更自動進行安全審查:
# Agent Delegation Rules
## Automatic Security Review
These changes automatically trigger security-auditor agent:
- Files in: auth/, payment/, admin/
- Functions containing: password, token, secret, key, credential
- Operations: user creation, permission changes, data deletion
- External calls: API integrations, webhooks, email
## Security Agent Configuration
When security-auditor runs, it checks for:
- OWASP Top 10 vulnerabilities
- Hardcoded secrets
- Missing authentication
- SQL injection patterns
- XSS vulnerabilities
- Insecure direct object references
- Missing rate limiting
- Insufficient logging
使用 Task Tool 實作
// Automatic security review for auth changes
Task({
subagent_type: "security-auditor",
model: "sonnet",
prompt: `
Review changes to auth/ directory.
Check for OWASP Top 10 vulnerabilities:
1. Injection
2. Broken authentication
3. Sensitive data exposure
4. XML external entities
5. Broken access control
6. Security misconfiguration
7. Cross-site scripting
8. Insecure deserialization
9. Using components with known vulnerabilities
10. Insufficient logging
Report findings with severity levels.
`
})
安全工作流程模式
模式 1:實作前審查
在編寫安全敏感程式碼之前:
Task({
subagent_type: "security-auditor",
model: "sonnet",
prompt: `
Planning to implement password reset functionality.
Review security considerations:
1. What vulnerabilities should I address?
2. What OWASP vulnerabilities are relevant?
3. What's the secure implementation pattern?
4. What tests should I write?
`
})
模式 2:帶有防護機制的實作
使用自動 hooks 進行實作:
{
"hooks": {
"PostToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "If the written file is in auth/, payment/, or admin/ directories, trigger a security scan and report any issues found."
}]
}]
}
}
模式 3:實作後審計
實作完成後:
Task({
subagent_type: "security-auditor",
model: "opus", // Use Opus for critical security review
prompt: `
Comprehensive security audit of password reset feature.
Check for:
- Token generation entropy
- Timing attacks in token comparison
- Rate limiting bypass
- User enumeration
- Session fixation after reset
- Proper invalidation of old sessions
Provide findings categorized by severity:
- Critical
- High
- Medium
- Low
`
})
常見漏洞與預防
SQL Injection
有漏洞的:
const query = `SELECT * FROM users WHERE id = ${userId}`;
安全的:
const user = await prisma.user.findUnique({ where: { id: userId } });
Hook 保護:
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "If the code contains string concatenation with SQL keywords (SELECT, INSERT, UPDATE, DELETE), return 'block' with warning about SQL injection. Otherwise 'approve'."
}]
}]
}
}
Cross-Site Scripting (XSS)
有漏洞的:
<div dangerouslySetInnerHTML={{ __html: userContent }} />
安全的:
<div>{userContent}</div> // React auto-escapes
CLAUDE.md 規則:
## XSS Prevention
- Never use dangerouslySetInnerHTML without sanitization
- Use DOMPurify for HTML content that must be rendered
- Escape all dynamic content in non-React contexts
認證繞過
有漏洞的:
if (user.role === 'admin') {
// Allow action
}
安全的:
if (await authService.hasPermission(user.id, 'admin:action')) {
// Allow action
}
敏感資料暴露
有漏洞的:
return res.json({ user }); // Includes password hash!
安全的:
return res.json({ user: sanitizeUser(user) });
持續安全的 Hooks
預提交安全檢查
{
"hooks": {
"Stop": [{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "npm run security-scan",
"onFailure": "block"
}]
}]
}
}
自動密鑰檢測
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "Scan the code for potential secrets: API keys, passwords, tokens, private keys. If found, return 'block' with the line numbers. Otherwise 'approve'."
}]
}]
}
}
檔案存取控制
{
"permissions": {
"deny": [
"Read(.env*)",
"Read(**/secrets/**)",
"Read(**/*credential*)",
"Read(**/*.pem)",
"Read(**/*.key)",
"Write(.env*)",
"Edit(.env*)"
]
}
}
使用 test-runner 進行安全測試
自動化安全測試套件
// Launch parallel security tests
Task({
subagent_type: "test-runner",
model: "haiku",
prompt: "Run all security-related tests in tests/security/"
})
Task({
subagent_type: "security-auditor",
model: "sonnet",
prompt: "Verify test coverage for authentication edge cases"
})
安全測試範例
describe('Password Reset Security', () => {
it('rejects invalid tokens', async () => {
const response = await request(app)
.post('/api/auth/reset-password')
.send({ token: 'invalid', password: 'newpassword' });
expect(response.status).toBe(400);
expect(response.body).not.toContain('token');
});
it('prevents timing attacks on token validation', async () => {
// Use constant-time comparison
const times = [];
for (let i = 0; i < 100; i++) {
const start = performance.now();
await validateToken(`token${i}`);
times.push(performance.now() - start);
}
// Variance should be minimal
expect(standardDeviation(times)).toBeLessThan(5);
});
it('rate limits reset requests', async () => {
const email = '[email protected]';
// First 3 requests succeed
for (let i = 0; i < 3; i++) {
const response = await request(app)
.post('/api/auth/forgot-password')
.send({ email });
expect(response.status).toBe(200);
}
// 4th request is rate limited
const response = await request(app)
.post('/api/auth/forgot-password')
.send({ email });
expect(response.status).toBe(429);
});
});
安全審計檢查清單
在任何部署之前:
## Pre-Deployment Security Checklist
### Authentication
- [ ] All endpoints require authentication (except public ones)
- [ ] Tokens expire appropriately
- [ ] Password requirements enforced
- [ ] Account lockout after failed attempts
### Authorization
- [ ] Permission checks on all protected actions
- [ ] No privilege escalation paths
- [ ] Admin functions properly protected
### Data Protection
- [ ] Sensitive data encrypted at rest
- [ ] HTTPS enforced
- [ ] No secrets in code or logs
- [ ] PII handling compliant
### Input/Output
- [ ] All inputs validated
- [ ] All outputs properly encoded
- [ ] File uploads validated and sanitized
- [ ] No SQL injection vulnerabilities
### Logging & Monitoring
- [ ] Security events logged
- [ ] Logs don't contain sensitive data
- [ ] Alerting configured for anomalies
企業安全功能
Claude Code 透過四層配置層級支援企業安全需求:
企業層(Managed Settings)
// /etc/claude-code/settings.json (IT managed)
{
"permissions": {
"deny": [
"Bash(*curl*)",
"Bash(*wget*)",
"Read(/etc/**)",
"Write(/etc/**)"
]
},
"mcpServers": {
"allowlist": ["filesystem", "memory"]
}
}
審計日誌配置
## Audit Requirements
Log these events to secure audit system:
- Authentication attempts (success/failure)
- Authorization decisions
- Data access (especially sensitive data)
- Configuration changes
- API calls to external services
合規整合
## Compliance Requirements
- PCI DSS: No card data in logs, encrypt at rest
- GDPR: Data minimization, right to deletion
- HIPAA: PHI access controls and audit trails
- SOC 2: Change management documentation
安全的模型選擇
| 任務 | 推薦模型 | 原因 |
|---|---|---|
| 快速安全掃描 | Haiku 4.5 | 快速模式匹配 |
| 程式碼審查 | Sonnet 4.5 | 平衡的分析 |
| 安全審計 | Sonnet 4.5 | 徹底審查 |
| 關鍵安全 | Opus 4.5 | 最高智能 |
快速模型切換(v2.0.65+):在提示時按 Option+P(macOS)或 Alt+P(Windows/Linux)。
開始行動
今天:
- 在 CLAUDE.md 中添加 security-auditor 委派規則
- 為敏感檔案配置權限拒絕
- 為危險指令添加一個 PreToolUse hook
本週:
- 實作用於安全驗證的 Stop hook
- 添加安全測試套件
- 對關鍵模組執行 security-auditor
本月:
- 部署預提交安全 hooks
- 在 CI/CD 中整合安全掃描
- 培訓團隊進行安全優先開發
安全是一段旅程,而非終點。透過 Claude Code 的 agents 和 hooks,您可以自動化安全最佳實踐。