简介:本文详解如何利用开源工具ModSecurity与Nginx,在10分钟内完成轻量级WAF的部署,涵盖规则配置、攻击拦截及性能优化全流程,提供可落地的安全防护方案。
Web应用防火墙(WAF)作为抵御SQL注入、XSS、CSRF等OWASP Top 10威胁的关键防线,传统部署需采购商业产品(如F5、Imperva)或等待云服务商配置,耗时数小时至数天。本文提出的10分钟方案基于开源组件ModSecurity(核心规则引擎)与Nginx(反向代理),通过预编译规则集实现即插即用,适合初创团队快速验证安全需求或中小型企业的轻量级防护。
| 组件 | 版本要求 | 作用 |
|---|---|---|
| Nginx | ≥1.18.0 | 反向代理与流量转发 |
| ModSecurity | 3.0.5+ | 规则引擎与攻击检测 |
| OWASP CRS | 4.0/dev | 开源规则集(覆盖90%常见攻击) |
# Ubuntu示例sudo apt updatesudo apt install -y libnginx-mod-http-modsecurity nginx# CentOS示例sudo yum install -y epel-releasesudo yum install -y mod_security nginx
启用ModSecurity模块:
# 在nginx.conf的http块中添加load_module modules/ngx_http_modsecurity_module.so;
下载OWASP CRS规则集:
git clone https://github.com/coreruleset/coreruleset.git /etc/nginx/modsec/
创建基础配置文件/etc/nginx/modsec/main.conf:
SecRuleEngine OnSecDebugLog /var/log/nginx/modsec_debug.logSecAuditEngine RelevantOnlySecAuditLog /var/log/nginx/modsec_audit.logInclude /etc/nginx/modsec/crs-setup.confInclude /etc/nginx/modsec/rules/*.conf
修改Nginx站点配置:
server {listen 80;server_name example.com;ModSecurityEnabled on;ModSecurityConfig /etc/nginx/modsec/main.conf;location / {proxy_pass http://backend;}}
关键规则优化示例(禁用误报率高的规则):
# 在main.conf中添加SecRuleRemoveById 920350 # 禁用特定SQL注入规则SecRuleUpdateTargetById 941100 "!ARGS:token" # 排除token参数检测
重启Nginx服务:
sudo systemctl restart nginx
攻击模拟测试:
```bash
curl “http://example.com/?id=1‘ OR ‘1’=’1”
curl “http://example.com/?q=“
3. 检查日志验证拦截:```bashtail -f /var/log/nginx/modsec_audit.log | grep "Blocked"
SecPcreMatchLimit参数(默认1000)watch -n 1 “grep ‘Blocked’ /var/log/nginx/modsec_audit.log | wc -l”
2. 告警规则示例(Prometheus配置):```yaml- alert: WAFHighAttackRateexpr: increase(modsec_blocked_requests[5m]) > 100labels:severity: criticalannotations:summary: "WAF拦截量突增"
示例:阻止特定User-Agent的爬虫:
SecRule REQUEST_HEADERS:User-Agent "@rx (BadBot/1.0|ScraperBot)" \"id:999999,phase:1,block,msg:'Malicious Bot Detected'"
| 问题现象 | 排查步骤 |
|---|---|
| 502 Bad Gateway | 检查modsec_audit.log是否有规则导致合法请求被拦截 |
| 高CPU占用 | 使用top -H查看nginx worker进程,调整SecResponseBodyAccess Off |
| 规则未生效 | 确认SecRuleEngine On且配置文件路径正确 |
本方案通过开源组件实现了10分钟内的WAF快速部署,适合作为安全防护的起点。长期来看,建议:
git pull origin main)对于日均请求量超过100万的大型应用,可考虑将ModSecurity升级为商业版(如ModSecurity for Enterprise),或迁移至云服务商的托管WAF服务以获得更好的横向扩展能力。