简介:本文通过分步教学,结合开源工具ModSecurity与Nginx,演示如何在10分钟内完成WAF核心功能部署,涵盖规则配置、攻击拦截测试及性能优化策略,帮助开发者快速构建基础安全防护体系。
Web应用防火墙(WAF)是抵御SQL注入、XSS跨站脚本、CC攻击等常见Web威胁的关键防线。传统商业WAF部署周期长、成本高,而开源方案通过模块化设计可实现快速集成。本文以ModSecurity+Nginx组合为例,提供一套10分钟内可完成的轻量级WAF部署方案,适用于中小型项目初期安全防护。
ngx_http_modsecurity_module模块集成WAF
# Ubuntu示例sudo apt updatesudo apt install -y libmodsecurity3 modsecurity-crs nginx# 验证安装modsecurity -v # 应输出3.x版本号
修改Nginx主配置文件/etc/nginx/nginx.conf,在http块中添加:
load_module modules/ngx_http_modsecurity_module.so; # 确保模块路径正确http {modsecurity on;modsecurity_rules_file /etc/nginx/modsec/main.conf;}
创建规则目录并加载CRS规则集:
sudo mkdir -p /etc/nginx/modsecsudo wget https://raw.githubusercontent.com/coreruleset/coreruleset/v3.4/dev/crs-setup.conf.example -O /etc/nginx/modsec/crs-setup.confsudo wget -O /etc/nginx/modsec/rules.conf https://raw.githubusercontent.com/coreruleset/coreruleset/v3.4/dev/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf
主规则文件/etc/nginx/modsec/main.conf配置示例:
Include /etc/nginx/modsec/crs-setup.confInclude /etc/nginx/modsec/rules.confSecRuleEngine OnSecDebugLog /var/log/nginx/modsec_debug.logSecDebugLevel 3
关键参数说明:
SecRuleEngine:设置为DetectionOnly可先进入监控模式SecAuditEngine:启用审计日志(RelevantOnly模式减少日志量)SecDefaultAction:默认拦截动作(建议初期设为"phase:2,log,auditlog,deny,status:403")性能优化技巧:
SecRule REMOVE_REQUEST_BODY "@rx \.(jpg|png|css|js)$" "id:'999998',phase:1,nolog,pass"
SecPcreMatchLimit 1000
curl -I http://localhost# 应返回HTTP 200且无WAF拦截标识
curl "http://localhost/?id=1' OR '1'='1"# 预期返回403 Forbidden,日志记录攻击特征
检查/var/log/nginx/error.log,应包含类似以下条目:
ModSecurity: Warning. Matched "Operator `Rx' with parameter `(?i:(?:\b(?:a(?:lter(?:\s+table)?|n(?:d|si)|s(?:c|sert)|d(?:min|d)|ggregate|v(?:g|rage)?)|c(?:all|reate(?:\s+(?:f(?:unction|ulltext(?:\s+index)?)|i(?:ndex|nsert)|procedure|table)|har(?:acter)?)|ast)|d(?:e(?:clare|lete)|rop(?:\s+table)?)|i(?:nsert|n(?:ner|to))|t(?:runcate(?:\s+table)?|able)|u(?:pdate|nion)|x(?:p(?:lain|ort)|or)))|b(?:egin|in(?:ary|d)|o(?:olean|t)|it(?:map)?)|c(?:ase|heck(?:point)?|ol(?:late|umn)|omment|on(?:n(?:ect|ection)|straint)|ur(?:rent_date|sor)|heck)|d(?:e(?:fault|sc)|i(?:stinct|sable)|ouble|o(?:main|ne)|ate(?:format)?)|e(?:lse(?:if)?|nd|x(?:ists|plain)|rror)|f(?:etch|or(?:eign|m)|ull|unction)|g(?:lobal|o(?:to|up)|rant)|i(?:f|n(?:ner|to)|s(?:null|olation|numeric)|n(?:dex|ter)|n(?:t|out)|mmediate)|k(?:ey|ill)|l(?:imit|o(?:cal|ck)|eft)|m(?:atch(?:ed)?|erge|odify|sg)|n(?:ational|atural|char(?:acter)?|ew|o(?:t|w)|ull)|o(?:f|n(?:line|ly)|ut(?:er)?|pt(?:ion|imized)|rder)|p(?:recision|rimary|rint|ublic)|r(?:e(?:fer(?:ences|ence)|lease|strict|turn)|ow(?:id|num)|ight)|s(?:e(?:lect|nsitive|ssion(?:_user)?|t)|mallint|t(?:art|op)|h(?:utdown|ow)|ome|igned|y(?:sdate|stem_user)|ql)|t(?:able|hen|ime(?:stamp)?|inyint|ext)|u(?:nion|nsigned|pdate|se(?:r)?)|v(?:alues|ariable|iew)|w(?:hen|here|ith)|x(?:or)|y(?:ear)\b)' against variable `ARGS:id' (Variable `ARGS:id' Value: `1' OR '1'='1') ..."
使用SecRuleRemoveById排除误报规则:
SecRuleRemoveById 942100 # 排除特定SQLi检测规则
自定义白名单规则(示例:允许特定IP的测试请求):
SecRule REMOTE_ADDR "@ipMatch 192.168.1.100" "id:'999999',phase:1,nolog,allow"
stap -e 'probe nginx.modsec.request_processing { printf("%s\n", execname()) }'监控规则处理耗时GoAccess分析WAF日志:
goaccess /var/log/nginx/access.log -a --log-format=COMBINED
容器化部署示例(Dockerfile核心片段):
FROM nginx:alpineRUN apk add --no-cache libmodsecurity modsecurity-crsCOPY modsec-config /etc/nginx/modsec
负载均衡场景建议:
location /waf-health { return 200; }modsecurity -c /etc/nginx/modsec/main.conf -tSecResponseBodyAccess为Off(若无需响应体检查)
SecRule REQUEST_HEADERS:Content-Type "@rx ^multipart/form-data" "id:'999997',phase:1,nolog,pass"
#!/bin/bashcd /etc/nginx/modsecwget -O rules.conf https://raw.githubusercontent.com/coreruleset/coreruleset/v3.4/dev/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.confnginx -s reload
本文提供的10分钟方案适用于项目初期快速验证安全需求,但生产环境需考虑:
wrk工具进行并发测试)对于日均请求量超过10万的系统,建议评估商业WAF解决方案或基于Envoy的现代WAF架构。开发者可通过持续优化规则集(如采用机器学习辅助的异常检测),在防护效果与系统性能间取得平衡。