Web 應用防火牆
Vibe Prompt
「幫我寫 OWASP ModSecurity Core Rule Set (CRS) 設定檔,防護 SQL Injection 與 XSS。」
ModSecurity 安裝
# Nginx + ModSecurity
docker run -p 80:80 -p 443:443 \
-v ./modsec.conf:/etc/nginx/modsec/modsec.conf \
owasp/modsecurity-crs:nginx
CRS 規則
# 啟用 CRS
Include /etc/modsecurity.d/owasp-crs/crs-setup.conf
Include /etc/modsecurity.d/owasp-crs/rules/*.conf
# SQL Injection 偵測
SecRule ARGS "@detectSQLi" \
"id:942100,phase:2,deny,status:403,
msg:'SQL Injection Detected'"
# XSS 偵測
SecRule ARGS "@detectXSS" \
"id:941100,phase:2,deny,status:403,
msg:'XSS Detected'"
# 限制請求體大小
SecRequestBodyLimit 1048576
Cloudflare WAF
# Cloudflare 防火牆規則(儀表板設定)
- 規則: 阻擋 SQL Injection
- 規則: 阻擋 XSS
- 規則: 阻擋已知攻擊者 IP
- 速率限制: 每 IP 每分鐘 100 次
- 瀏覽器完整性檢查: 開啟
CDN + WAF 架構
使用者 → Cloudflare CDN (DDoS 防護 + WAF) → Nginx (ModSecurity) → 應用
↓
阻擋惡意流量
關鍵要點
WAF (Web Application Firewall)
| 比較 | Cloud WAF (AWS WAF) | 自管 WAF (ModSecurity) | |:----:|:-------------------:|:----------------------:| | 部署方式 | 託管服務 | 自行安裝在 Nginx/Apache | | 維護工作 | AWS 負責更新規則 | 自行維護規則庫 | | 費用 | 按規則與請求數計費 | 免費(開源) | | 效能影響 | 無(邊緣節點處理) | 需配合 Nginx 設定 | | 規則來源 | AWS Managed Rules | OWASP CRS (Core Rule Set) |
ModSecurity 設定範例
# Nginx + ModSecurity
server {
listen 443 ssl;
server_name example.com;
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
CRS (Core Rule Set) 規則分類
| 規則編號 | 攻擊類型 | |:--------:|---------| | 920xxx | 協定強制 | | 921xxx | 協定攻擊 | | 930xxx | 檔案包含攻擊 | | 931xxx | 跨站腳本 (XSS) | | 942xxx | SQL Injection | | 943xxx | 命令注入 | | 944xxx | 遠端檔案包含 |
WAF:應用層的防火牆
WAF 是部署在 Web 伺服器前面的防火牆,檢查所有 HTTP 流量,阻擋惡意請求。
部署方式
| 方式 | 適合 | |:----|:----| | 雲端 WAF(AWS WAF) | AWS 用戶 | | 反向代理 WAF(Nginx + ModSecurity) | 自建伺服器 | | 硬體 WAF(F5、Imperva) | 大型企業 |
ModSecurity + OWASP CRS
server {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/crs-setup.conf;
location / {
proxy_pass http://localhost:3000;
}
}
OWASP CRS 包含了防護 SQL Injection、XSS、Path Traversal 的規則。
課程總結
這堂網路安全課從網路分割、WebGoat 實戰到 WAF 部署——涵蓋了從網路層到應用層的安全防護。