mirror of
https://github.com/affaan-m/everything-claude-code.git
synced 2026-04-17 23:53:30 +08:00
docs: Add Chinese (zh-CN) translations for all documentation
* docs: add Chinese versions docs * update --------- Co-authored-by: neo <neo.dowithless@gmail.com>
This commit is contained in:
526
docs/zh-CN/skills/security-review/SKILL.md
Normal file
526
docs/zh-CN/skills/security-review/SKILL.md
Normal file
@@ -0,0 +1,526 @@
|
||||
---
|
||||
name: security-review
|
||||
description: Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment/sensitive features. Provides comprehensive security checklist and patterns.
|
||||
---
|
||||
|
||||
# 安全审查技能
|
||||
|
||||
此技能确保所有代码遵循安全最佳实践,并识别潜在漏洞。
|
||||
|
||||
## 何时激活
|
||||
|
||||
* 实现身份验证或授权时
|
||||
* 处理用户输入或文件上传时
|
||||
* 创建新的 API 端点时
|
||||
* 处理密钥或凭据时
|
||||
* 实现支付功能时
|
||||
* 存储或传输敏感数据时
|
||||
* 集成第三方 API 时
|
||||
|
||||
## 安全检查清单
|
||||
|
||||
### 1. 密钥管理
|
||||
|
||||
#### ❌ 绝对不要这样做
|
||||
|
||||
```typescript
|
||||
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
|
||||
const dbPassword = "password123" // In source code
|
||||
```
|
||||
|
||||
#### ✅ 始终这样做
|
||||
|
||||
```typescript
|
||||
const apiKey = process.env.OPENAI_API_KEY
|
||||
const dbUrl = process.env.DATABASE_URL
|
||||
|
||||
// Verify secrets exist
|
||||
if (!apiKey) {
|
||||
throw new Error('OPENAI_API_KEY not configured')
|
||||
}
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 没有硬编码的 API 密钥、令牌或密码
|
||||
* \[ ] 所有密钥都存储在环境变量中
|
||||
* \[ ] `.env` 文件在 .gitignore 中
|
||||
* \[ ] git 历史记录中没有密钥
|
||||
* \[ ] 生产环境密钥存储在托管平台中(Vercel, Railway)
|
||||
|
||||
### 2. 输入验证
|
||||
|
||||
#### 始终验证用户输入
|
||||
|
||||
```typescript
|
||||
import { z } from 'zod'
|
||||
|
||||
// Define validation schema
|
||||
const CreateUserSchema = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().min(1).max(100),
|
||||
age: z.number().int().min(0).max(150)
|
||||
})
|
||||
|
||||
// Validate before processing
|
||||
export async function createUser(input: unknown) {
|
||||
try {
|
||||
const validated = CreateUserSchema.parse(input)
|
||||
return await db.users.create(validated)
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return { success: false, errors: error.errors }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 文件上传验证
|
||||
|
||||
```typescript
|
||||
function validateFileUpload(file: File) {
|
||||
// Size check (5MB max)
|
||||
const maxSize = 5 * 1024 * 1024
|
||||
if (file.size > maxSize) {
|
||||
throw new Error('File too large (max 5MB)')
|
||||
}
|
||||
|
||||
// Type check
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
throw new Error('Invalid file type')
|
||||
}
|
||||
|
||||
// Extension check
|
||||
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
|
||||
const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0]
|
||||
if (!extension || !allowedExtensions.includes(extension)) {
|
||||
throw new Error('Invalid file extension')
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 所有用户输入都使用模式进行了验证
|
||||
* \[ ] 文件上传受到限制(大小、类型、扩展名)
|
||||
* \[ ] 查询中没有直接使用用户输入
|
||||
* \[ ] 使用白名单验证(而非黑名单)
|
||||
* \[ ] 错误消息不会泄露敏感信息
|
||||
|
||||
### 3. SQL 注入防护
|
||||
|
||||
#### ❌ 绝对不要拼接 SQL
|
||||
|
||||
```typescript
|
||||
// DANGEROUS - SQL Injection vulnerability
|
||||
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
|
||||
await db.query(query)
|
||||
```
|
||||
|
||||
#### ✅ 始终使用参数化查询
|
||||
|
||||
```typescript
|
||||
// Safe - parameterized query
|
||||
const { data } = await supabase
|
||||
.from('users')
|
||||
.select('*')
|
||||
.eq('email', userEmail)
|
||||
|
||||
// Or with raw SQL
|
||||
await db.query(
|
||||
'SELECT * FROM users WHERE email = $1',
|
||||
[userEmail]
|
||||
)
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 所有数据库查询都使用参数化查询
|
||||
* \[ ] SQL 中没有字符串拼接
|
||||
* \[ ] 正确使用 ORM/查询构建器
|
||||
* \[ ] Supabase 查询已正确清理
|
||||
|
||||
### 4. 身份验证与授权
|
||||
|
||||
#### JWT 令牌处理
|
||||
|
||||
```typescript
|
||||
// ❌ WRONG: localStorage (vulnerable to XSS)
|
||||
localStorage.setItem('token', token)
|
||||
|
||||
// ✅ CORRECT: httpOnly cookies
|
||||
res.setHeader('Set-Cookie',
|
||||
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)
|
||||
```
|
||||
|
||||
#### 授权检查
|
||||
|
||||
```typescript
|
||||
export async function deleteUser(userId: string, requesterId: string) {
|
||||
// ALWAYS verify authorization first
|
||||
const requester = await db.users.findUnique({
|
||||
where: { id: requesterId }
|
||||
})
|
||||
|
||||
if (requester.role !== 'admin') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
// Proceed with deletion
|
||||
await db.users.delete({ where: { id: userId } })
|
||||
}
|
||||
```
|
||||
|
||||
#### 行级安全(Supabase)
|
||||
|
||||
```sql
|
||||
-- Enable RLS on all tables
|
||||
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Users can only view their own data
|
||||
CREATE POLICY "Users view own data"
|
||||
ON users FOR SELECT
|
||||
USING (auth.uid() = id);
|
||||
|
||||
-- Users can only update their own data
|
||||
CREATE POLICY "Users update own data"
|
||||
ON users FOR UPDATE
|
||||
USING (auth.uid() = id);
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 令牌存储在 httpOnly cookie 中(而非 localStorage)
|
||||
* \[ ] 执行敏感操作前进行授权检查
|
||||
* \[ ] Supabase 中启用了行级安全
|
||||
* \[ ] 实现了基于角色的访问控制
|
||||
* \[ ] 会话管理安全
|
||||
|
||||
### 5. XSS 防护
|
||||
|
||||
#### 清理 HTML
|
||||
|
||||
```typescript
|
||||
import DOMPurify from 'isomorphic-dompurify'
|
||||
|
||||
// ALWAYS sanitize user-provided HTML
|
||||
function renderUserContent(html: string) {
|
||||
const clean = DOMPurify.sanitize(html, {
|
||||
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
|
||||
ALLOWED_ATTR: []
|
||||
})
|
||||
return <div dangerouslySetInnerHTML={{ __html: clean }} />
|
||||
}
|
||||
```
|
||||
|
||||
#### 内容安全策略
|
||||
|
||||
```typescript
|
||||
// next.config.js
|
||||
const securityHeaders = [
|
||||
{
|
||||
key: 'Content-Security-Policy',
|
||||
value: `
|
||||
default-src 'self';
|
||||
script-src 'self' 'unsafe-eval' 'unsafe-inline';
|
||||
style-src 'self' 'unsafe-inline';
|
||||
img-src 'self' data: https:;
|
||||
font-src 'self';
|
||||
connect-src 'self' https://api.example.com;
|
||||
`.replace(/\s{2,}/g, ' ').trim()
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 用户提供的 HTML 已被清理
|
||||
* \[ ] 已配置 CSP 头部
|
||||
* \[ ] 没有渲染未经验证的动态内容
|
||||
* \[ ] 使用了 React 内置的 XSS 防护
|
||||
|
||||
### 6. CSRF 防护
|
||||
|
||||
#### CSRF 令牌
|
||||
|
||||
```typescript
|
||||
import { csrf } from '@/lib/csrf'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const token = request.headers.get('X-CSRF-Token')
|
||||
|
||||
if (!csrf.verify(token)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid CSRF token' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
// Process request
|
||||
}
|
||||
```
|
||||
|
||||
#### SameSite Cookie
|
||||
|
||||
```typescript
|
||||
res.setHeader('Set-Cookie',
|
||||
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 状态变更操作上使用了 CSRF 令牌
|
||||
* \[ ] 所有 Cookie 都设置了 SameSite=Strict
|
||||
* \[ ] 实现了双重提交 Cookie 模式
|
||||
|
||||
### 7. 速率限制
|
||||
|
||||
#### API 速率限制
|
||||
|
||||
```typescript
|
||||
import rateLimit from 'express-rate-limit'
|
||||
|
||||
const limiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: 100, // 100 requests per window
|
||||
message: 'Too many requests'
|
||||
})
|
||||
|
||||
// Apply to routes
|
||||
app.use('/api/', limiter)
|
||||
```
|
||||
|
||||
#### 昂贵操作
|
||||
|
||||
```typescript
|
||||
// Aggressive rate limiting for searches
|
||||
const searchLimiter = rateLimit({
|
||||
windowMs: 60 * 1000, // 1 minute
|
||||
max: 10, // 10 requests per minute
|
||||
message: 'Too many search requests'
|
||||
})
|
||||
|
||||
app.use('/api/search', searchLimiter)
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 所有 API 端点都实施了速率限制
|
||||
* \[ ] 对昂贵操作有更严格的限制
|
||||
* \[ ] 基于 IP 的速率限制
|
||||
* \[ ] 基于用户的速率限制(已认证)
|
||||
|
||||
### 8. 敏感数据泄露
|
||||
|
||||
#### 日志记录
|
||||
|
||||
```typescript
|
||||
// ❌ WRONG: Logging sensitive data
|
||||
console.log('User login:', { email, password })
|
||||
console.log('Payment:', { cardNumber, cvv })
|
||||
|
||||
// ✅ CORRECT: Redact sensitive data
|
||||
console.log('User login:', { email, userId })
|
||||
console.log('Payment:', { last4: card.last4, userId })
|
||||
```
|
||||
|
||||
#### 错误消息
|
||||
|
||||
```typescript
|
||||
// ❌ WRONG: Exposing internal details
|
||||
catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, stack: error.stack },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
// ✅ CORRECT: Generic error messages
|
||||
catch (error) {
|
||||
console.error('Internal error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'An error occurred. Please try again.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 日志中没有密码、令牌或密钥
|
||||
* \[ ] 对用户显示通用错误消息
|
||||
* \[ ] 详细错误信息仅在服务器日志中
|
||||
* \[ ] 没有向用户暴露堆栈跟踪
|
||||
|
||||
### 9. 区块链安全(Solana)
|
||||
|
||||
#### 钱包验证
|
||||
|
||||
```typescript
|
||||
import { verify } from '@solana/web3.js'
|
||||
|
||||
async function verifyWalletOwnership(
|
||||
publicKey: string,
|
||||
signature: string,
|
||||
message: string
|
||||
) {
|
||||
try {
|
||||
const isValid = verify(
|
||||
Buffer.from(message),
|
||||
Buffer.from(signature, 'base64'),
|
||||
Buffer.from(publicKey, 'base64')
|
||||
)
|
||||
return isValid
|
||||
} catch (error) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 交易验证
|
||||
|
||||
```typescript
|
||||
async function verifyTransaction(transaction: Transaction) {
|
||||
// Verify recipient
|
||||
if (transaction.to !== expectedRecipient) {
|
||||
throw new Error('Invalid recipient')
|
||||
}
|
||||
|
||||
// Verify amount
|
||||
if (transaction.amount > maxAmount) {
|
||||
throw new Error('Amount exceeds limit')
|
||||
}
|
||||
|
||||
// Verify user has sufficient balance
|
||||
const balance = await getBalance(transaction.from)
|
||||
if (balance < transaction.amount) {
|
||||
throw new Error('Insufficient balance')
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 已验证钱包签名
|
||||
* \[ ] 已验证交易详情
|
||||
* \[ ] 交易前检查余额
|
||||
* \[ ] 没有盲签名交易
|
||||
|
||||
### 10. 依赖项安全
|
||||
|
||||
#### 定期更新
|
||||
|
||||
```bash
|
||||
# Check for vulnerabilities
|
||||
npm audit
|
||||
|
||||
# Fix automatically fixable issues
|
||||
npm audit fix
|
||||
|
||||
# Update dependencies
|
||||
npm update
|
||||
|
||||
# Check for outdated packages
|
||||
npm outdated
|
||||
```
|
||||
|
||||
#### 锁定文件
|
||||
|
||||
```bash
|
||||
# ALWAYS commit lock files
|
||||
git add package-lock.json
|
||||
|
||||
# Use in CI/CD for reproducible builds
|
||||
npm ci # Instead of npm install
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 依赖项是最新的
|
||||
* \[ ] 没有已知漏洞(npm audit 检查通过)
|
||||
* \[ ] 提交了锁定文件
|
||||
* \[ ] GitHub 上启用了 Dependabot
|
||||
* \[ ] 定期进行安全更新
|
||||
|
||||
## 安全测试
|
||||
|
||||
### 自动化安全测试
|
||||
|
||||
```typescript
|
||||
// Test authentication
|
||||
test('requires authentication', async () => {
|
||||
const response = await fetch('/api/protected')
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
// Test authorization
|
||||
test('requires admin role', async () => {
|
||||
const response = await fetch('/api/admin', {
|
||||
headers: { Authorization: `Bearer ${userToken}` }
|
||||
})
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
// Test input validation
|
||||
test('rejects invalid input', async () => {
|
||||
const response = await fetch('/api/users', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email: 'not-an-email' })
|
||||
})
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
// Test rate limiting
|
||||
test('enforces rate limits', async () => {
|
||||
const requests = Array(101).fill(null).map(() =>
|
||||
fetch('/api/endpoint')
|
||||
)
|
||||
|
||||
const responses = await Promise.all(requests)
|
||||
const tooManyRequests = responses.filter(r => r.status === 429)
|
||||
|
||||
expect(tooManyRequests.length).toBeGreaterThan(0)
|
||||
})
|
||||
```
|
||||
|
||||
## 部署前安全检查清单
|
||||
|
||||
在任何生产环境部署前:
|
||||
|
||||
* \[ ] **密钥**:没有硬编码的密钥,全部在环境变量中
|
||||
* \[ ] **输入验证**:所有用户输入都已验证
|
||||
* \[ ] **SQL 注入**:所有查询都已参数化
|
||||
* \[ ] **XSS**:用户内容已被清理
|
||||
* \[ ] **CSRF**:已启用防护
|
||||
* \[ ] **身份验证**:正确处理令牌
|
||||
* \[ ] **授权**:已实施角色检查
|
||||
* \[ ] **速率限制**:所有端点都已启用
|
||||
* \[ ] **HTTPS**:在生产环境中强制执行
|
||||
* \[ ] **安全头部**:已配置 CSP、X-Frame-Options
|
||||
* \[ ] **错误处理**:错误中不包含敏感数据
|
||||
* \[ ] **日志记录**:日志中不包含敏感数据
|
||||
* \[ ] **依赖项**:已更新,无漏洞
|
||||
* \[ ] **行级安全**:Supabase 中已启用
|
||||
* \[ ] **CORS**:已正确配置
|
||||
* \[ ] **文件上传**:已验证(大小、类型)
|
||||
* \[ ] **钱包签名**:已验证(如果涉及区块链)
|
||||
|
||||
## 资源
|
||||
|
||||
* [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
* [Next.js 安全](https://nextjs.org/docs/security)
|
||||
* [Supabase 安全](https://supabase.com/docs/guides/auth)
|
||||
* [Web 安全学院](https://portswigger.net/web-security)
|
||||
|
||||
***
|
||||
|
||||
**请记住**:安全不是可选项。一个漏洞就可能危及整个平台。如有疑问,请谨慎行事。
|
||||
@@ -0,0 +1,361 @@
|
||||
| name | description |
|
||||
|------|-------------|
|
||||
| cloud-infrastructure-security | 在部署到云平台、配置基础设施、管理IAM策略、设置日志记录/监控或实现CI/CD流水线时使用此技能。提供符合最佳实践的云安全检查清单。 |
|
||||
|
||||
# 云与基础设施安全技能
|
||||
|
||||
此技能确保云基础设施、CI/CD流水线和部署配置遵循安全最佳实践并符合行业标准。
|
||||
|
||||
## 何时激活
|
||||
|
||||
* 将应用程序部署到云平台(AWS、Vercel、Railway、Cloudflare)
|
||||
* 配置IAM角色和权限
|
||||
* 设置CI/CD流水线
|
||||
* 实施基础设施即代码(Terraform、CloudFormation)
|
||||
* 配置日志记录和监控
|
||||
* 在云环境中管理密钥
|
||||
* 设置CDN和边缘安全
|
||||
* 实施灾难恢复和备份策略
|
||||
|
||||
## 云安全检查清单
|
||||
|
||||
### 1. IAM 与访问控制
|
||||
|
||||
#### 最小权限原则
|
||||
|
||||
```yaml
|
||||
# ✅ CORRECT: Minimal permissions
|
||||
iam_role:
|
||||
permissions:
|
||||
- s3:GetObject # Only read access
|
||||
- s3:ListBucket
|
||||
resources:
|
||||
- arn:aws:s3:::my-bucket/* # Specific bucket only
|
||||
|
||||
# ❌ WRONG: Overly broad permissions
|
||||
iam_role:
|
||||
permissions:
|
||||
- s3:* # All S3 actions
|
||||
resources:
|
||||
- "*" # All resources
|
||||
```
|
||||
|
||||
#### 多因素认证 (MFA)
|
||||
|
||||
```bash
|
||||
# ALWAYS enable MFA for root/admin accounts
|
||||
aws iam enable-mfa-device \
|
||||
--user-name admin \
|
||||
--serial-number arn:aws:iam::123456789:mfa/admin \
|
||||
--authentication-code1 123456 \
|
||||
--authentication-code2 789012
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 生产环境中未使用根账户
|
||||
* \[ ] 所有特权账户已启用MFA
|
||||
* \[ ] 服务账户使用角色,而非长期凭证
|
||||
* \[ ] IAM策略遵循最小权限原则
|
||||
* \[ ] 定期进行访问审查
|
||||
* \[ ] 未使用的凭证已轮换或移除
|
||||
|
||||
### 2. 密钥管理
|
||||
|
||||
#### 云密钥管理器
|
||||
|
||||
```typescript
|
||||
// ✅ CORRECT: Use cloud secrets manager
|
||||
import { SecretsManager } from '@aws-sdk/client-secrets-manager';
|
||||
|
||||
const client = new SecretsManager({ region: 'us-east-1' });
|
||||
const secret = await client.getSecretValue({ SecretId: 'prod/api-key' });
|
||||
const apiKey = JSON.parse(secret.SecretString).key;
|
||||
|
||||
// ❌ WRONG: Hardcoded or in environment variables only
|
||||
const apiKey = process.env.API_KEY; // Not rotated, not audited
|
||||
```
|
||||
|
||||
#### 密钥轮换
|
||||
|
||||
```bash
|
||||
# Set up automatic rotation for database credentials
|
||||
aws secretsmanager rotate-secret \
|
||||
--secret-id prod/db-password \
|
||||
--rotation-lambda-arn arn:aws:lambda:region:account:function:rotate \
|
||||
--rotation-rules AutomaticallyAfterDays=30
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 所有密钥存储在云密钥管理器(AWS Secrets Manager、Vercel Secrets)中
|
||||
* \[ ] 数据库凭证已启用自动轮换
|
||||
* \[ ] API密钥至少每季度轮换一次
|
||||
* \[ ] 代码、日志或错误消息中没有密钥
|
||||
* \[ ] 密钥访问已启用审计日志记录
|
||||
|
||||
### 3. 网络安全
|
||||
|
||||
#### VPC 和防火墙配置
|
||||
|
||||
```terraform
|
||||
# ✅ CORRECT: Restricted security group
|
||||
resource "aws_security_group" "app" {
|
||||
name = "app-sg"
|
||||
|
||||
ingress {
|
||||
from_port = 443
|
||||
to_port = 443
|
||||
protocol = "tcp"
|
||||
cidr_blocks = ["10.0.0.0/16"] # Internal VPC only
|
||||
}
|
||||
|
||||
egress {
|
||||
from_port = 443
|
||||
to_port = 443
|
||||
protocol = "tcp"
|
||||
cidr_blocks = ["0.0.0.0/0"] # Only HTTPS outbound
|
||||
}
|
||||
}
|
||||
|
||||
# ❌ WRONG: Open to the internet
|
||||
resource "aws_security_group" "bad" {
|
||||
ingress {
|
||||
from_port = 0
|
||||
to_port = 65535
|
||||
protocol = "tcp"
|
||||
cidr_blocks = ["0.0.0.0/0"] # All ports, all IPs!
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 数据库未公开访问
|
||||
* \[ ] SSH/RDP端口仅限VPN/堡垒机访问
|
||||
* \[ ] 安全组遵循最小权限原则
|
||||
* \[ ] 网络ACL已配置
|
||||
* \[ ] VPC流日志已启用
|
||||
|
||||
### 4. 日志记录与监控
|
||||
|
||||
#### CloudWatch/日志记录配置
|
||||
|
||||
```typescript
|
||||
// ✅ CORRECT: Comprehensive logging
|
||||
import { CloudWatchLogsClient, CreateLogStreamCommand } from '@aws-sdk/client-cloudwatch-logs';
|
||||
|
||||
const logSecurityEvent = async (event: SecurityEvent) => {
|
||||
await cloudwatch.putLogEvents({
|
||||
logGroupName: '/aws/security/events',
|
||||
logStreamName: 'authentication',
|
||||
logEvents: [{
|
||||
timestamp: Date.now(),
|
||||
message: JSON.stringify({
|
||||
type: event.type,
|
||||
userId: event.userId,
|
||||
ip: event.ip,
|
||||
result: event.result,
|
||||
// Never log sensitive data
|
||||
})
|
||||
}]
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 所有服务已启用CloudWatch/日志记录
|
||||
* \[ ] 失败的身份验证尝试已记录
|
||||
* \[ ] 管理员操作已审计
|
||||
* \[ ] 日志保留期已配置(合规要求90天以上)
|
||||
* \[ ] 为可疑活动配置了警报
|
||||
* \[ ] 日志已集中存储且防篡改
|
||||
|
||||
### 5. CI/CD 流水线安全
|
||||
|
||||
#### 安全流水线配置
|
||||
|
||||
```yaml
|
||||
# ✅ CORRECT: Secure GitHub Actions workflow
|
||||
name: Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read # Minimal permissions
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# Scan for secrets
|
||||
- name: Secret scanning
|
||||
uses: trufflesecurity/trufflehog@main
|
||||
|
||||
# Dependency audit
|
||||
- name: Audit dependencies
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
# Use OIDC, not long-lived tokens
|
||||
- name: Configure AWS credentials
|
||||
uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
role-to-assume: arn:aws:iam::123456789:role/GitHubActionsRole
|
||||
aws-region: us-east-1
|
||||
```
|
||||
|
||||
#### 供应链安全
|
||||
|
||||
```json
|
||||
// package.json - Use lock files and integrity checks
|
||||
{
|
||||
"scripts": {
|
||||
"install": "npm ci", // Use ci for reproducible builds
|
||||
"audit": "npm audit --audit-level=moderate",
|
||||
"check": "npm outdated"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 使用OIDC而非长期凭证
|
||||
* \[ ] 流水线中进行密钥扫描
|
||||
* \[ ] 依赖项漏洞扫描
|
||||
* \[ ] 容器镜像扫描(如适用)
|
||||
* \[ ] 分支保护规则已强制执行
|
||||
* \[ ] 合并前需要代码审查
|
||||
* \[ ] 已强制执行签名提交
|
||||
|
||||
### 6. Cloudflare 与 CDN 安全
|
||||
|
||||
#### Cloudflare 安全配置
|
||||
|
||||
```typescript
|
||||
// ✅ CORRECT: Cloudflare Workers with security headers
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const response = await fetch(request);
|
||||
|
||||
// Add security headers
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set('X-Frame-Options', 'DENY');
|
||||
headers.set('X-Content-Type-Options', 'nosniff');
|
||||
headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
headers.set('Permissions-Policy', 'geolocation=(), microphone=()');
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
headers
|
||||
});
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
#### WAF 规则
|
||||
|
||||
```bash
|
||||
# Enable Cloudflare WAF managed rules
|
||||
# - OWASP Core Ruleset
|
||||
# - Cloudflare Managed Ruleset
|
||||
# - Rate limiting rules
|
||||
# - Bot protection
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] WAF已启用并配置OWASP规则
|
||||
* \[ ] 已配置速率限制
|
||||
* \[ ] 机器人防护已激活
|
||||
* \[ ] DDoS防护已启用
|
||||
* \[ ] 安全标头已配置
|
||||
* \[ ] SSL/TLS严格模式已启用
|
||||
|
||||
### 7. 备份与灾难恢复
|
||||
|
||||
#### 自动化备份
|
||||
|
||||
```terraform
|
||||
# ✅ CORRECT: Automated RDS backups
|
||||
resource "aws_db_instance" "main" {
|
||||
allocated_storage = 20
|
||||
engine = "postgres"
|
||||
|
||||
backup_retention_period = 30 # 30 days retention
|
||||
backup_window = "03:00-04:00"
|
||||
maintenance_window = "mon:04:00-mon:05:00"
|
||||
|
||||
enabled_cloudwatch_logs_exports = ["postgresql"]
|
||||
|
||||
deletion_protection = true # Prevent accidental deletion
|
||||
}
|
||||
```
|
||||
|
||||
#### 验证步骤
|
||||
|
||||
* \[ ] 已配置自动化每日备份
|
||||
* \[ ] 备份保留期符合合规要求
|
||||
* \[ ] 已启用时间点恢复
|
||||
* \[ ] 每季度执行备份测试
|
||||
* \[ ] 灾难恢复计划已记录
|
||||
* \[ ] RPO和RTO已定义并经过测试
|
||||
|
||||
## 部署前云安全检查清单
|
||||
|
||||
在任何生产云部署之前:
|
||||
|
||||
* \[ ] **IAM**:未使用根账户,已启用MFA,最小权限策略
|
||||
* \[ ] **密钥**:所有密钥都在云密钥管理器中并已配置轮换
|
||||
* \[ ] **网络**:安全组受限,无公开数据库
|
||||
* \[ ] **日志记录**:已启用CloudWatch/日志记录并配置保留期
|
||||
* \[ ] **监控**:为异常情况配置了警报
|
||||
* \[ ] **CI/CD**:OIDC身份验证,密钥扫描,依赖项审计
|
||||
* \[ ] **CDN/WAF**:Cloudflare WAF已启用并配置OWASP规则
|
||||
* \[ ] **加密**:静态和传输中的数据均已加密
|
||||
* \[ ] **备份**:自动化备份并已测试恢复
|
||||
* \[ ] **合规性**:满足GDPR/HIPAA要求(如适用)
|
||||
* \[ ] **文档**:基础设施已记录,已创建操作手册
|
||||
* \[ ] **事件响应**:已制定安全事件计划
|
||||
|
||||
## 常见云安全配置错误
|
||||
|
||||
### S3 存储桶暴露
|
||||
|
||||
```bash
|
||||
# ❌ WRONG: Public bucket
|
||||
aws s3api put-bucket-acl --bucket my-bucket --acl public-read
|
||||
|
||||
# ✅ CORRECT: Private bucket with specific access
|
||||
aws s3api put-bucket-acl --bucket my-bucket --acl private
|
||||
aws s3api put-bucket-policy --bucket my-bucket --policy file://policy.json
|
||||
```
|
||||
|
||||
### RDS 公开访问
|
||||
|
||||
```terraform
|
||||
# ❌ WRONG
|
||||
resource "aws_db_instance" "bad" {
|
||||
publicly_accessible = true # NEVER do this!
|
||||
}
|
||||
|
||||
# ✅ CORRECT
|
||||
resource "aws_db_instance" "good" {
|
||||
publicly_accessible = false
|
||||
vpc_security_group_ids = [aws_security_group.db.id]
|
||||
}
|
||||
```
|
||||
|
||||
## 资源
|
||||
|
||||
* [AWS 安全最佳实践](https://aws.amazon.com/security/best-practices/)
|
||||
* [CIS AWS 基础基准](https://www.cisecurity.org/benchmark/amazon_web_services)
|
||||
* [Cloudflare 安全文档](https://developers.cloudflare.com/security/)
|
||||
* [OWASP 云安全](https://owasp.org/www-project-cloud-security/)
|
||||
* [Terraform 安全最佳实践](https://www.terraform.io/docs/cloud/guides/recommended-practices/)
|
||||
|
||||
**请记住**:云配置错误是数据泄露的主要原因。一个暴露的S3存储桶或一个权限过大的IAM策略就可能危及整个基础设施。始终遵循最小权限原则和深度防御策略。
|
||||
Reference in New Issue
Block a user