ModSecurity+Coraza:开源WAF部署与规则编写指南
为什么商业WAF不是唯一选择?
企业WAF市场被Imperva、F5、Cloudflare三大厂商瓜分,年费动辄上万美元。对于中小企业和独立开发者来说,这笔开销实在不小。更关键的是,商业WAF往往是"黑盒"——你看不到规则逻辑,遇到误报只能开工单等厂商处理。
开源WAF生态在2024年已经非常成熟。ModSecurity作为老牌开源WAF,被Nginx、Apache原生支持;Coraza是ModSecurity的Go语言重写,兼容OWASP CRS规则集,性能更好、部署更灵活;国产的雷池(SafeLine)则提供了开箱即用的可视化界面。
本文将手把手教你搭建一套企业级开源WAF方案,从安装到规则编写全覆盖。
付费WAF定价对比
先看看主流商业WAF的价格区间:
| 工具 | 月费/年费估算 | 部署方式 | 核心卖点 |
|---|---|---|---|
| Imperva WAF | $10,000+/年 | 云/混合 | 行业标杆,DDoS防护 |
| F5 Advanced WAF | $15,000+/年 | 硬件/虚拟 | ADC集成,深度包检测 |
| Cloudflare Enterprise | $5,000+/月 | 纯云 | CDN集成,全球节点 |
| AWS WAF | $3+/WebACL/月 + $0.60/百万请求 | 云 | 原生AWS集成 |
| 阿里云WAF | ¥9,800+/年 | 云 | 国内合规,中文支持 |
对于一个中等流量的Web应用,年花费通常在$5,000-$20,000之间。而开源方案的硬件成本可以控制在$500/年以内(一台小型云服务器)。
开源WAF方案全景
| 方案 | 语言 | Nginx支持 | OWASP CRS | 可视化界面 | 适合场景 |
|---|---|---|---|---|---|
| ModSecurity v3 | C++ | ✅ 原生模块 | ✅ | ❌ | Nginx/Apache生产环境 |
| Coraza WAF | Go | ✅ ModSec兼容 | ✅ | ❌ | Go生态/云原生 |
| NAXSI | C | ✅ Nginx模块 | ❌ 自有规则 | ❌ | 轻量Nginx防护 |
| SafeLine(雷池) | Go | ✅ 反向代理 | ✅ | ✅ | 快速上手/可视化需求 |
实战一:ModSecurity + Nginx 部署
安装依赖
# Ubuntu/Debian
sudo apt update
sudo apt install -y git gcc make libpcre3-dev libssl-dev libcurl4-openssl-dev libyajl-dev libgeoip-dev liblmdb-dev libpcre++-dev libxml2-dev
# CentOS/RHEL
sudo yum install -y git gcc make pcre-devel openssl-devel libcurl-devel yajl-devel GeoIP-devel lmdb-devel pcre++-devel libxml2-devel
编译ModSecurity v3
cd /tmp
git clone --depth 1 -b v3/master --single-branch https://github.com/owasp-modsecurity/ModSecurity.git
cd ModSecurity
git submodule init
git submodule update
./build.sh
./configure
make -j$(nproc)
sudo make install
编译Nginx ModSecurity模块
cd /tmp
git clone --depth 1 https://github.com/owasp-modsecurity/ModSecurity-nginx.git
# 下载对应版本的Nginx源码
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar xzf nginx-1.24.0.tar.gz
cd nginx-1.24.0
# 编译动态模块(假设Nginx已安装)
./configure --with-compat --add-dynamic-module=../ModSecurity-nginx
make modules
sudo cp objs/ngx_http_modsecurity_module.so /usr/share/nginx/modules/
配置Nginx + ModSecurity
编辑 /etc/nginx/nginx.conf:
load_module modules/ngx_http_modsecurity_module.so;
http {
# 启用ModSecurity引擎
modsecurity on;
modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
}
配置 /etc/nginx/modsecurity/modsecurity.conf:
# 基本配置
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess Off
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
# 临时文件和日志
SecTmpDir /tmp/modsecurity
SecDataDir /tmp/modsecurity
SecAuditLog /var/log/modsecurity/audit.log
SecAuditLogType Serial
SecAuditLogParts ABCDEFHZ
# 默认动作
SecDefaultAction "phase:1,deny,log,status:403"
# 包含OWASP CRS规则
Include /etc/nginx/modsecurity/crs-setup.conf
Include /etc/nginx/modsecurity/rules/*.conf
安装OWASP Core Rule Set (CRS)
cd /tmp
git clone https://github.com/coreruleset/coreruleset.git
cd coreruleset
sudo mkdir -p /etc/nginx/modsecurity/rules
sudo cp crs-setup.conf.example /etc/nginx/modsecurity/crs-setup.conf
sudo cp rules/*.conf /etc/nginx/modsecurity/rules/
# 创建SecRule默认包含文件
echo 'SecAction "id:900000, phase:1, nolog, pass, t:none, set:tx.blocking_paranoia_level=1"' | sudo tee /etc/nginx/modsecurity/crs-setup.conf
sudo nginx -t && sudo systemctl reload nginx
实战二:Coraza WAF部署
Coraza是ModSecurity的Go重写,兼容ModSecurity配置语法和OWASP CRS。
安装Coraza
# Go安装(如果未安装)
wget https://go.dev/dl/go1.22.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.0.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
# 安装Coraza Caddy模块(推荐方式)
# Coraza官方推荐与Caddy Web Server集成
xcaddy build --with github.com/corazawaf/coraza-caddy/v2
# 或作为Go库使用
go get github.com/corazawaf/coraza/v3
Coraza配置示例
创建 coraza.conf:
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess On
SecResponseBodyMimeType text/plain text/html text/xml application/json
SecTmpDir /tmp/coraza
SecDataDir /tmp/coraza
# 自定义规则:拦截SQL注入
SecRule ARGS "@rx (?i)(union\s+select|insert\s+into|drop\s+table|delete\s+from)" "id:1001,phase:2,deny,status:403,log,msg:'SQL Injection Attack Detected'"
# 自定义规则:拦截XSS攻击
SecRule ARGS "@rx <script[^>]*>.*?</script>" "id:1002,phase:2,deny,status:403,log,msg:'XSS Attack Detected'"
# 自定义规则:拦截路径遍历
SecRule ARGS "@rx \.\./" "id:1003,phase:2,deny,status:403,log,msg:'Path Traversal Attack Detected'"
# 自定义规则:限制请求频率(需配合外部工具)
SecRule REQUEST_URI "@streq /login" "id:1004,phase:1,deny,status:429,log,msg:'Rate limit exceeded'"
Coraza作为独立WAF代理
// main.go - Coraza独立WAF代理
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"github.com/corazawaf/coraza/v3"
)
func main() {
// 初始化Coraza WAF
waf, err := coraza.NewWAF(coraza.NewWAFConfig().
WithDirectives(`
SecRuleEngine On
SecRequestBodyAccess On
SecRule ARGS "@rx (?i)(union\s+select|<script)" "id:1001,phase:2,deny,status:403"
`))
if err != nil {
log.Fatal(err)
}
// 反向代理到后端服务
target, _ := url.Parse("http://127.0.0.1:8080")
proxy := httputil.NewSingleHostReverseProxy(target)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tx := waf.NewTransaction()
defer tx.Close()
// 处理请求头
if it := tx.ProcessRequestHeaders(r); it != nil {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// 转发到后端
proxy.ServeHTTP(w, r)
})
log.Println("WAF running on :9090")
log.Fatal(http.ListenAndServe(":9090", nil))
}
实战三:SafeLine(雷池)快速部署
雷池是长亭科技开源的WAF,提供Web管理界面,适合快速上手:
# 一键安装
bash -c "$(curl -fsSLk https://waf.chaitin.com/release/latest/setup.sh)"
# 或使用Docker
git clone https://github.com/chaitin/SafeLine.git
cd SafeLine
docker compose up -d
# 访问管理界面
# 默认地址: https://your-ip:9443
# 默认账号: admin
# 默认密码: 随机生成,查看安装日志
WAF规则编写进阶
OWASP CRS调优
# /etc/nginx/modsecurity/crs-setup.conf
# 降低误报:排除静态资源
SecRule REQUEST_URI "@rx \.(css|js|jpg|png|gif|ico|svg|woff2?)$" "id:9001,phase:1,pass,nolog,ctl:ruleEngine=Off"
# 调整检测级别(1-4,越高越严格)
SecAction "id:900000,phase:1,nolog,pass,t:none, set:tx.blocking_paranoia_level=2"
# 排除特定规则ID(误报处理)
SecRuleRemoveById 941100 941130 942100
# 白名单特定IP
SecRule REMOTE_ADDR "@ipMatch 192.168.1.0/24,10.0.0.0/8" "id:9002,phase:1,pass,nolog,ctl:ruleEngine=Off"
自定义规则:拦截Web Shell
# 检测PHP Web Shell
SecRule REQUEST_URI "@rx \.php$" "id:2001,phase:1,chain,deny,status:403,log,msg:'PHP WebShell Detected'"
SecRule ARGS|ARGS_NAMES|REQUEST_BODY "@rx (eval\s*\(|base64_decode\s*\(|system\s*\(|passthru\s*\(|shell_exec\s*\(|exec\s*\(|popen\s*\()" "t:none,t:urlDecodeUni"
自定义规则:CC攻击防护
# 基于IP的简易CC防护(需配合持久化计数器)
SecAction "id:3001,phase:1,initcol:ip=%{REMOTE_ADDR},pass,nolog"
SecRule REQUEST_URI "@streq /api/login" "id:3002,phase:1,chain,pass,setvar:ip.request_count=+1"
SecRule &ip.request_count "@ge 10" "id:3003,phase:1,deny,status:429,log,msg:'CC Attack Rate Limit'"
统一监控:日志分析
# 实时监控ModSecurity告警
tail -f /var/log/modsecurity/audit.log | grep --color=always -E '\[id "[0-9]+"\]|\[msg ".*"\]|\[severity ".*"\]'
# 统计Top规则触发
grep -oP 'id "\K[0-9]+' /var/log/modsecurity/audit.log | sort | uniq -c | sort -rn | head -20
# 统计攻击来源IP
grep -oP 'client "\K[0-9.]+' /var/log/modsecurity/audit.log | sort | uniq -c | sort -rn | head -20
# 使用GoAccess分析WAF日志
goaccess /var/log/modsecurity/audit.log --log-format=COMBINED -o waf_report.html
生产环境最佳实践
- 先用检测模式:
SecRuleEngine DetectionOnly,观察一段时间再切换到拦截模式 - 定期更新CRS规则:
cd coreruleset && git pull - 建立误报反馈流程:收集误报,逐步调优规则白名单
- 多层防护:WAF + Rate Limiting + IP黑名单 + CDN
- 备份规则配置:所有规则纳入Git版本控制
总结
开源WAF不是"穷人替代品",而是真正可控、可定制的安全方案。ModSecurity成熟稳定,Coraza性能优异,雷池开箱即用。三者各有适用场景,组合使用可以覆盖从小型网站到企业级应用的WAF需求。
关键建议:先用雷池(SafeLine)快速搭建可视化WAF熟悉概念,再深入ModSecurity/Coraza做定制化规则开发。OWASP CRS作为规则基线,结合业务特点进行调优,误报率可以控制在5%以下。
每年省下数万美元的WAF授权费,投入在规则优化和安全运营上,这才是安全团队的正确投资方向。
评论