mirror of
https://github.com/sweetwisdom/everything-claude-code-zh.git
synced 2026-03-22 14:40:14 +00:00
fix: restore missing files (package.json etc) and fix sync script logic
This commit is contained in:
494
docs/zh-TW/skills/security-review/SKILL.md
Normal file
494
docs/zh-TW/skills/security-review/SKILL.md
Normal file
@@ -0,0 +1,494 @@
|
||||
---
|
||||
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" // 寫死的密鑰
|
||||
const dbPassword = "password123" // 在原始碼中
|
||||
```
|
||||
|
||||
#### ✅ 總是這樣做
|
||||
```typescript
|
||||
const apiKey = process.env.OPENAI_API_KEY
|
||||
const dbUrl = process.env.DATABASE_URL
|
||||
|
||||
// 驗證密鑰存在
|
||||
if (!apiKey) {
|
||||
throw new Error('OPENAI_API_KEY not configured')
|
||||
}
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] 無寫死的 API 金鑰、Token 或密碼
|
||||
- [ ] 所有密鑰在環境變數中
|
||||
- [ ] `.env.local` 在 .gitignore 中
|
||||
- [ ] git 歷史中無密鑰
|
||||
- [ ] 生產密鑰在託管平台(Vercel、Railway)中
|
||||
|
||||
### 2. 輸入驗證
|
||||
|
||||
#### 總是驗證使用者輸入
|
||||
```typescript
|
||||
import { z } from 'zod'
|
||||
|
||||
// 定義驗證 schema
|
||||
const CreateUserSchema = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().min(1).max(100),
|
||||
age: z.number().int().min(0).max(150)
|
||||
})
|
||||
|
||||
// 處理前驗證
|
||||
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) {
|
||||
// 大小檢查(最大 5MB)
|
||||
const maxSize = 5 * 1024 * 1024
|
||||
if (file.size > maxSize) {
|
||||
throw new Error('File too large (max 5MB)')
|
||||
}
|
||||
|
||||
// 類型檢查
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
throw new Error('Invalid file type')
|
||||
}
|
||||
|
||||
// 副檔名檢查
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] 所有使用者輸入以 schema 驗證
|
||||
- [ ] 檔案上傳受限(大小、類型、副檔名)
|
||||
- [ ] 查詢中不直接使用使用者輸入
|
||||
- [ ] 白名單驗證(非黑名單)
|
||||
- [ ] 錯誤訊息不洩露敏感資訊
|
||||
|
||||
### 3. SQL 注入預防
|
||||
|
||||
#### ❌ 絕不串接 SQL
|
||||
```typescript
|
||||
// 危險 - SQL 注入漏洞
|
||||
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
|
||||
await db.query(query)
|
||||
```
|
||||
|
||||
#### ✅ 總是使用參數化查詢
|
||||
```typescript
|
||||
// 安全 - 參數化查詢
|
||||
const { data } = await supabase
|
||||
.from('users')
|
||||
.select('*')
|
||||
.eq('email', userEmail)
|
||||
|
||||
// 或使用原始 SQL
|
||||
await db.query(
|
||||
'SELECT * FROM users WHERE email = $1',
|
||||
[userEmail]
|
||||
)
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] 所有資料庫查詢使用參數化查詢
|
||||
- [ ] SQL 中無字串串接
|
||||
- [ ] ORM/查詢建構器正確使用
|
||||
- [ ] Supabase 查詢正確淨化
|
||||
|
||||
### 4. 認證與授權
|
||||
|
||||
#### JWT Token 處理
|
||||
```typescript
|
||||
// ❌ 錯誤:localStorage(易受 XSS 攻擊)
|
||||
localStorage.setItem('token', token)
|
||||
|
||||
// ✅ 正確:httpOnly cookies
|
||||
res.setHeader('Set-Cookie',
|
||||
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)
|
||||
```
|
||||
|
||||
#### 授權檢查
|
||||
```typescript
|
||||
export async function deleteUser(userId: string, requesterId: string) {
|
||||
// 總是先驗證授權
|
||||
const requester = await db.users.findUnique({
|
||||
where: { id: requesterId }
|
||||
})
|
||||
|
||||
if (requester.role !== 'admin') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Unauthorized' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
// 繼續刪除
|
||||
await db.users.delete({ where: { id: userId } })
|
||||
}
|
||||
```
|
||||
|
||||
#### Row Level Security(Supabase)
|
||||
```sql
|
||||
-- 在所有表格上啟用 RLS
|
||||
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- 使用者只能查看自己的資料
|
||||
CREATE POLICY "Users view own data"
|
||||
ON users FOR SELECT
|
||||
USING (auth.uid() = id);
|
||||
|
||||
-- 使用者只能更新自己的資料
|
||||
CREATE POLICY "Users update own data"
|
||||
ON users FOR UPDATE
|
||||
USING (auth.uid() = id);
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] Token 儲存在 httpOnly cookies(非 localStorage)
|
||||
- [ ] 敏感操作前有授權檢查
|
||||
- [ ] Supabase 已啟用 Row Level Security
|
||||
- [ ] 已實作基於角色的存取控制
|
||||
- [ ] 工作階段管理安全
|
||||
|
||||
### 5. XSS 預防
|
||||
|
||||
#### 淨化 HTML
|
||||
```typescript
|
||||
import DOMPurify from 'isomorphic-dompurify'
|
||||
|
||||
// 總是淨化使用者提供的 HTML
|
||||
function renderUserContent(html: string) {
|
||||
const clean = DOMPurify.sanitize(html, {
|
||||
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
|
||||
ALLOWED_ATTR: []
|
||||
})
|
||||
return <div dangerouslySetInnerHTML={{ __html: clean }} />
|
||||
}
|
||||
```
|
||||
|
||||
#### Content Security Policy
|
||||
```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 headers 已設定
|
||||
- [ ] 無未驗證的動態內容渲染
|
||||
- [ ] 使用 React 內建 XSS 保護
|
||||
|
||||
### 6. CSRF 保護
|
||||
|
||||
#### CSRF Tokens
|
||||
```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 }
|
||||
)
|
||||
}
|
||||
|
||||
// 處理請求
|
||||
}
|
||||
```
|
||||
|
||||
#### SameSite Cookies
|
||||
```typescript
|
||||
res.setHeader('Set-Cookie',
|
||||
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] 狀態變更操作有 CSRF tokens
|
||||
- [ ] 所有 cookies 設定 SameSite=Strict
|
||||
- [ ] 已實作 Double-submit cookie 模式
|
||||
|
||||
### 7. 速率限制
|
||||
|
||||
#### API 速率限制
|
||||
```typescript
|
||||
import rateLimit from 'express-rate-limit'
|
||||
|
||||
const limiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 分鐘
|
||||
max: 100, // 每視窗 100 個請求
|
||||
message: 'Too many requests'
|
||||
})
|
||||
|
||||
// 套用到路由
|
||||
app.use('/api/', limiter)
|
||||
```
|
||||
|
||||
#### 昂貴操作
|
||||
```typescript
|
||||
// 搜尋的積極速率限制
|
||||
const searchLimiter = rateLimit({
|
||||
windowMs: 60 * 1000, // 1 分鐘
|
||||
max: 10, // 每分鐘 10 個請求
|
||||
message: 'Too many search requests'
|
||||
})
|
||||
|
||||
app.use('/api/search', searchLimiter)
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] 所有 API 端點有速率限制
|
||||
- [ ] 昂貴操作有更嚴格限制
|
||||
- [ ] 基於 IP 的速率限制
|
||||
- [ ] 基於使用者的速率限制(已認證)
|
||||
|
||||
### 8. 敏感資料暴露
|
||||
|
||||
#### 日誌記錄
|
||||
```typescript
|
||||
// ❌ 錯誤:記錄敏感資料
|
||||
console.log('User login:', { email, password })
|
||||
console.log('Payment:', { cardNumber, cvv })
|
||||
|
||||
// ✅ 正確:遮蔽敏感資料
|
||||
console.log('User login:', { email, userId })
|
||||
console.log('Payment:', { last4: card.last4, userId })
|
||||
```
|
||||
|
||||
#### 錯誤訊息
|
||||
```typescript
|
||||
// ❌ 錯誤:暴露內部細節
|
||||
catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error.message, stack: error.stack },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
// ✅ 正確:通用錯誤訊息
|
||||
catch (error) {
|
||||
console.error('Internal error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'An error occurred. Please try again.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] 日誌中無密碼、token 或密鑰
|
||||
- [ ] 使用者收到通用錯誤訊息
|
||||
- [ ] 詳細錯誤只在伺服器日誌
|
||||
- [ ] 不向使用者暴露堆疊追蹤
|
||||
|
||||
### 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) {
|
||||
// 驗證收款人
|
||||
if (transaction.to !== expectedRecipient) {
|
||||
throw new Error('Invalid recipient')
|
||||
}
|
||||
|
||||
// 驗證金額
|
||||
if (transaction.amount > maxAmount) {
|
||||
throw new Error('Amount exceeds limit')
|
||||
}
|
||||
|
||||
// 驗證使用者有足夠餘額
|
||||
const balance = await getBalance(transaction.from)
|
||||
if (balance < transaction.amount) {
|
||||
throw new Error('Insufficient balance')
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] 錢包簽章已驗證
|
||||
- [ ] 交易詳情已驗證
|
||||
- [ ] 交易前有餘額檢查
|
||||
- [ ] 無盲目交易簽署
|
||||
|
||||
### 10. 依賴安全
|
||||
|
||||
#### 定期更新
|
||||
```bash
|
||||
# 檢查漏洞
|
||||
npm audit
|
||||
|
||||
# 自動修復可修復的問題
|
||||
npm audit fix
|
||||
|
||||
# 更新依賴
|
||||
npm update
|
||||
|
||||
# 檢查過時套件
|
||||
npm outdated
|
||||
```
|
||||
|
||||
#### Lock 檔案
|
||||
```bash
|
||||
# 總是 commit lock 檔案
|
||||
git add package-lock.json
|
||||
|
||||
# 在 CI/CD 中使用以獲得可重現的建置
|
||||
npm ci # 而非 npm install
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
- [ ] 依賴保持最新
|
||||
- [ ] 無已知漏洞(npm audit 乾淨)
|
||||
- [ ] Lock 檔案已 commit
|
||||
- [ ] GitHub 上已啟用 Dependabot
|
||||
- [ ] 定期安全更新
|
||||
|
||||
## 安全測試
|
||||
|
||||
### 自動化安全測試
|
||||
```typescript
|
||||
// 測試認證
|
||||
test('requires authentication', async () => {
|
||||
const response = await fetch('/api/protected')
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
// 測試授權
|
||||
test('requires admin role', async () => {
|
||||
const response = await fetch('/api/admin', {
|
||||
headers: { Authorization: `Bearer ${userToken}` }
|
||||
})
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
// 測試輸入驗證
|
||||
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('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**:保護已啟用
|
||||
- [ ] **認證**:正確的 token 處理
|
||||
- [ ] **授權**:角色檢查已就位
|
||||
- [ ] **速率限制**:所有端點已啟用
|
||||
- [ ] **HTTPS**:生產環境強制使用
|
||||
- [ ] **安全標頭**:CSP、X-Frame-Options 已設定
|
||||
- [ ] **錯誤處理**:錯誤中無敏感資料
|
||||
- [ ] **日誌記錄**:無敏感資料被記錄
|
||||
- [ ] **依賴**:最新,無漏洞
|
||||
- [ ] **Row Level Security**:Supabase 已啟用
|
||||
- [ ] **CORS**:正確設定
|
||||
- [ ] **檔案上傳**:已驗證(大小、類型)
|
||||
- [ ] **錢包簽章**:已驗證(如果是區塊鏈)
|
||||
|
||||
## 資源
|
||||
|
||||
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
- [Next.js Security](https://nextjs.org/docs/security)
|
||||
- [Supabase Security](https://supabase.com/docs/guides/auth)
|
||||
- [Web Security Academy](https://portswigger.net/web-security)
|
||||
|
||||
---
|
||||
|
||||
**記住**:安全性不是可選的。一個漏洞可能危及整個平台。有疑慮時,選擇謹慎的做法。
|
||||
@@ -0,0 +1,361 @@
|
||||
| name | description |
|
||||
|------|-------------|
|
||||
| cloud-infrastructure-security | Use this skill when deploying to cloud platforms, configuring infrastructure, managing IAM policies, setting up logging/monitoring, or implementing CI/CD pipelines. Provides cloud security checklist aligned with best practices. |
|
||||
|
||||
# 雲端與基礎設施安全技能
|
||||
|
||||
此技能確保雲端基礎設施、CI/CD 管線和部署設定遵循安全最佳實務並符合業界標準。
|
||||
|
||||
## 何時啟用
|
||||
|
||||
- 部署應用程式到雲端平台(AWS、Vercel、Railway、Cloudflare)
|
||||
- 設定 IAM 角色和權限
|
||||
- 設置 CI/CD 管線
|
||||
- 實作基礎設施即程式碼(Terraform、CloudFormation)
|
||||
- 設定日誌和監控
|
||||
- 在雲端環境管理密鑰
|
||||
- 設置 CDN 和邊緣安全
|
||||
- 實作災難復原和備份策略
|
||||
|
||||
## 雲端安全檢查清單
|
||||
|
||||
### 1. IAM 與存取控制
|
||||
|
||||
#### 最小權限原則
|
||||
|
||||
```yaml
|
||||
# ✅ 正確:最小權限
|
||||
iam_role:
|
||||
permissions:
|
||||
- s3:GetObject # 只有讀取存取
|
||||
- s3:ListBucket
|
||||
resources:
|
||||
- arn:aws:s3:::my-bucket/* # 只有特定 bucket
|
||||
|
||||
# ❌ 錯誤:過於廣泛的權限
|
||||
iam_role:
|
||||
permissions:
|
||||
- s3:* # 所有 S3 動作
|
||||
resources:
|
||||
- "*" # 所有資源
|
||||
```
|
||||
|
||||
#### 多因素認證(MFA)
|
||||
|
||||
```bash
|
||||
# 總是為 root/admin 帳戶啟用 MFA
|
||||
aws iam enable-mfa-device \
|
||||
--user-name admin \
|
||||
--serial-number arn:aws:iam::123456789:mfa/admin \
|
||||
--authentication-code1 123456 \
|
||||
--authentication-code2 789012
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
|
||||
- [ ] 生產環境不使用 root 帳戶
|
||||
- [ ] 所有特權帳戶啟用 MFA
|
||||
- [ ] 服務帳戶使用角色,非長期憑證
|
||||
- [ ] IAM 政策遵循最小權限
|
||||
- [ ] 定期進行存取審查
|
||||
- [ ] 未使用憑證已輪換或移除
|
||||
|
||||
### 2. 密鑰管理
|
||||
|
||||
#### 雲端密鑰管理器
|
||||
|
||||
```typescript
|
||||
// ✅ 正確:使用雲端密鑰管理器
|
||||
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;
|
||||
|
||||
// ❌ 錯誤:寫死或只在環境變數
|
||||
const apiKey = process.env.API_KEY; // 未輪換、未稽核
|
||||
```
|
||||
|
||||
#### 密鑰輪換
|
||||
|
||||
```bash
|
||||
# 為資料庫憑證設定自動輪換
|
||||
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
|
||||
# ✅ 正確:限制的安全群組
|
||||
resource "aws_security_group" "app" {
|
||||
name = "app-sg"
|
||||
|
||||
ingress {
|
||||
from_port = 443
|
||||
to_port = 443
|
||||
protocol = "tcp"
|
||||
cidr_blocks = ["10.0.0.0/16"] # 只有內部 VPC
|
||||
}
|
||||
|
||||
egress {
|
||||
from_port = 443
|
||||
to_port = 443
|
||||
protocol = "tcp"
|
||||
cidr_blocks = ["0.0.0.0/0"] # 只有 HTTPS 輸出
|
||||
}
|
||||
}
|
||||
|
||||
# ❌ 錯誤:對網際網路開放
|
||||
resource "aws_security_group" "bad" {
|
||||
ingress {
|
||||
from_port = 0
|
||||
to_port = 65535
|
||||
protocol = "tcp"
|
||||
cidr_blocks = ["0.0.0.0/0"] # 所有埠、所有 IP!
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
|
||||
- [ ] 資料庫不可公開存取
|
||||
- [ ] SSH/RDP 埠限制為 VPN/堡壘機
|
||||
- [ ] 安全群組遵循最小權限
|
||||
- [ ] 網路 ACL 已設定
|
||||
- [ ] VPC 流量日誌已啟用
|
||||
|
||||
### 4. 日誌與監控
|
||||
|
||||
#### CloudWatch/日誌設定
|
||||
|
||||
```typescript
|
||||
// ✅ 正確:全面日誌記錄
|
||||
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,
|
||||
// 永遠不要記錄敏感資料
|
||||
})
|
||||
}]
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
|
||||
- [ ] 所有服務啟用 CloudWatch/日誌記錄
|
||||
- [ ] 失敗的認證嘗試被記錄
|
||||
- [ ] 管理員動作被稽核
|
||||
- [ ] 日誌保留已設定(合規需 90+ 天)
|
||||
- [ ] 可疑活動設定警報
|
||||
- [ ] 日誌集中化且防篡改
|
||||
|
||||
### 5. CI/CD 管線安全
|
||||
|
||||
#### 安全管線設定
|
||||
|
||||
```yaml
|
||||
# ✅ 正確:安全的 GitHub Actions 工作流程
|
||||
name: Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read # 最小權限
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# 掃描密鑰
|
||||
- name: Secret scanning
|
||||
uses: trufflesecurity/trufflehog@main
|
||||
|
||||
# 依賴稽核
|
||||
- name: Audit dependencies
|
||||
run: npm audit --audit-level=high
|
||||
|
||||
# 使用 OIDC,非長期 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 - 使用 lock 檔案和完整性檢查
|
||||
{
|
||||
"scripts": {
|
||||
"install": "npm ci", // 使用 ci 以獲得可重現建置
|
||||
"audit": "npm audit --audit-level=moderate",
|
||||
"check": "npm outdated"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
|
||||
- [ ] 使用 OIDC 而非長期憑證
|
||||
- [ ] 管線中的密鑰掃描
|
||||
- [ ] 依賴漏洞掃描
|
||||
- [ ] 容器映像掃描(如適用)
|
||||
- [ ] 強制執行分支保護規則
|
||||
- [ ] 合併前需要程式碼審查
|
||||
- [ ] 強制執行簽署 commits
|
||||
|
||||
### 6. Cloudflare 與 CDN 安全
|
||||
|
||||
#### Cloudflare 安全設定
|
||||
|
||||
```typescript
|
||||
// ✅ 正確:帶安全標頭的 Cloudflare Workers
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const response = await fetch(request);
|
||||
|
||||
// 新增安全標頭
|
||||
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
|
||||
# 啟用 Cloudflare WAF 管理規則
|
||||
# - OWASP 核心規則集
|
||||
# - Cloudflare 管理規則集
|
||||
# - 速率限制規則
|
||||
# - Bot 保護
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
|
||||
- [ ] WAF 啟用 OWASP 規則
|
||||
- [ ] 速率限制已設定
|
||||
- [ ] Bot 保護啟用
|
||||
- [ ] DDoS 保護啟用
|
||||
- [ ] 安全標頭已設定
|
||||
- [ ] SSL/TLS 嚴格模式啟用
|
||||
|
||||
### 7. 備份與災難復原
|
||||
|
||||
#### 自動備份
|
||||
|
||||
```terraform
|
||||
# ✅ 正確:自動 RDS 備份
|
||||
resource "aws_db_instance" "main" {
|
||||
allocated_storage = 20
|
||||
engine = "postgres"
|
||||
|
||||
backup_retention_period = 30 # 30 天保留
|
||||
backup_window = "03:00-04:00"
|
||||
maintenance_window = "mon:04:00-mon:05:00"
|
||||
|
||||
enabled_cloudwatch_logs_exports = ["postgresql"]
|
||||
|
||||
deletion_protection = true # 防止意外刪除
|
||||
}
|
||||
```
|
||||
|
||||
#### 驗證步驟
|
||||
|
||||
- [ ] 已設定自動每日備份
|
||||
- [ ] 備份保留符合合規要求
|
||||
- [ ] 已啟用時間點復原
|
||||
- [ ] 每季執行備份測試
|
||||
- [ ] 災難復原計畫已記錄
|
||||
- [ ] RPO 和 RTO 已定義並測試
|
||||
|
||||
## 部署前雲端安全檢查清單
|
||||
|
||||
任何生產雲端部署前:
|
||||
|
||||
- [ ] **IAM**:不使用 root 帳戶、啟用 MFA、最小權限政策
|
||||
- [ ] **密鑰**:所有密鑰在雲端密鑰管理器並有輪換
|
||||
- [ ] **網路**:安全群組受限、無公開資料庫
|
||||
- [ ] **日誌**:CloudWatch/日誌啟用並有保留
|
||||
- [ ] **監控**:異常設定警報
|
||||
- [ ] **CI/CD**:OIDC 認證、密鑰掃描、依賴稽核
|
||||
- [ ] **CDN/WAF**:Cloudflare WAF 啟用 OWASP 規則
|
||||
- [ ] **加密**:資料靜態和傳輸中加密
|
||||
- [ ] **備份**:自動備份並測試復原
|
||||
- [ ] **合規**:符合 GDPR/HIPAA 要求(如適用)
|
||||
- [ ] **文件**:基礎設施已記錄、建立操作手冊
|
||||
- [ ] **事件回應**:安全事件計畫就位
|
||||
|
||||
## 常見雲端安全錯誤設定
|
||||
|
||||
### S3 Bucket 暴露
|
||||
|
||||
```bash
|
||||
# ❌ 錯誤:公開 bucket
|
||||
aws s3api put-bucket-acl --bucket my-bucket --acl public-read
|
||||
|
||||
# ✅ 正確:私有 bucket 並有特定存取
|
||||
aws s3api put-bucket-acl --bucket my-bucket --acl private
|
||||
aws s3api put-bucket-policy --bucket my-bucket --policy file://policy.json
|
||||
```
|
||||
|
||||
### RDS 公開存取
|
||||
|
||||
```terraform
|
||||
# ❌ 錯誤
|
||||
resource "aws_db_instance" "bad" {
|
||||
publicly_accessible = true # 絕不這樣做!
|
||||
}
|
||||
|
||||
# ✅ 正確
|
||||
resource "aws_db_instance" "good" {
|
||||
publicly_accessible = false
|
||||
vpc_security_group_ids = [aws_security_group.db.id]
|
||||
}
|
||||
```
|
||||
|
||||
## 資源
|
||||
|
||||
- [AWS Security Best Practices](https://aws.amazon.com/security/best-practices/)
|
||||
- [CIS AWS Foundations Benchmark](https://www.cisecurity.org/benchmark/amazon_web_services)
|
||||
- [Cloudflare Security Documentation](https://developers.cloudflare.com/security/)
|
||||
- [OWASP Cloud Security](https://owasp.org/www-project-cloud-security/)
|
||||
- [Terraform Security Best Practices](https://www.terraform.io/docs/cloud/guides/recommended-practices/)
|
||||
|
||||
**記住**:雲端錯誤設定是資料外洩的主要原因。單一暴露的 S3 bucket 或過於寬鬆的 IAM 政策可能危及你的整個基礎設施。總是遵循最小權限原則和深度防禦。
|
||||
Reference in New Issue
Block a user