负载均衡后Apache服务器:按IP针对指定URI关闭ModSecurity规则
问题:负载均衡后指定IP访问特定POST URI绕过ModSecurity规则
需求
服务器位于负载均衡器后方,需实现:当指定IP(123.123.123.123)向特定URI(/api/hello-world开头路径)发送POST请求时,绕过指定的ModSecurity规则(移除规则ID 942230、980130)。
现有规则问题
当前规则允许任意IP访问目标URI,无法实现精准的IP+URI+请求方法控制:
SecRule REQUEST_URI "/api/hello-world.*" \ "phase:1,id:2000,log,allow,ctl:ruleRemoveById=942230,ctl:ruleRemoveById=980130" SecRule REQUEST_HEADERS:X-Forwarded-For "@contains 123.123.123.123" \ "id:2001"
失败尝试的规则
示例1(未生效)
# Rule to identify allowed client IP and target URI SecRule REQUEST_HEADERS:X-Forwarded-For "^123\.123\.123\.123$" "phase:1,id:20008,t:none,setvar:tx.allowed_ip=1" SecRule REQUEST_URI "/api/hello-world.*" "phase:1,id:20009,t:none,setvar:tx.target_uri=1" # Rule to apply ctl actions if allowed IP and target URI match SecRule TX:allowed_ip "@eq 1" "phase:2,id:20010,ctl:ruleRemoveById=942230,ctl:ruleRemoveById=980130,chain" SecRule TX:target_uri "@eq 1" "t:none,id:20010"
问题:链式规则中ID重复(20010),且未限定POST请求方法,逻辑不完整。
示例2(服务器无法启动)
# Rule to identify allowed client IP SecRule REQUEST_HEADERS:X-Forwarded-For "^123\.123\.123\.123$" "phase:1,id:20008,t:none,setvar:tx.allowed_ip=1,skipAfter:END_ALLOWED_IP" # Rule to identify target URI SecRule REQUEST_URI "/api/hello-world.*" "phase:2,id:20009,t:none,setvar:tx.target_uri=1,skipAfter:END_TARGET_URI" # Rule to apply ctl actions if allowed IP and target URI match SecRule TX:allowed_ip "@eq 1" "phase:2,id:20010,chain,skipAfter:END_CHAIN" SecRule TX:target_uri "@eq 1" "t:none,ctl:ruleRemoveById=942230,ctl:ruleRemoveById=980130" SecRule TX:target_uri "!@eq 1" "t:none, id:20011"
问题:链式规则串联了3个条件(chain仅支持串联2个规则),且skipAfter标签未定义,导致语法错误。
示例3(服务器无法启动)
ecRule REQUEST_HEADERS:X-Forwarded-For "^123\.123\.123\.123$$" "phase:1,id:20008,t:none,setvar:tx.allowed_ip=1" SecRule REQUEST_URI "/api/hello-world.*" "phase:1,id:20009,t:none,setvar:tx.target_uri=1" # Rule to apply ctl actions if allowed IP and target URI match SecRule TX:allowed_ip "@eq 1" "phase:2,id:20010,ctl:ruleRemoveById=942230,ctl:ruleRemoveById=980130,chain" SecRule TX:target_uri "@eq 1" "t:none,id:20011"
问题:第一条规则拼写错误(ecRule应为SecRule),正则表达式多了一个$,语法错误导致服务器启动失败。
正确解决方案
通过链式规则同时匹配IP、URI和请求方法,在请求头阶段(phase:1)提前移除目标规则,确保后续阶段不再触发:
# 允许指定IP向特定URI发送POST请求时,绕过指定ModSecurity规则 SecRule REQUEST_HEADERS:X-Forwarded-For "^123\.123\.123\.123$" \ "phase:1,id:20012,chain,ctl:ruleRemoveById=942230,ctl:ruleRemoveById=980130,log,msg:'Allowed specified IP to access target URI via POST'" SecRule REQUEST_URI "^/api/hello-world.*$" "t:none" SecRule REQUEST_METHOD "@streq POST" "t:none"
规则说明
phase:1:在请求头阶段执行,提前移除规则,避免后续阶段触发拦截chain:串联三个匹配条件,需同时满足才执行ctl动作- 匹配条件:
X-Forwarded-For严格匹配指定IP(^和$避免部分匹配)REQUEST_URI匹配目标路径REQUEST_METHOD为POST
ctl:ruleRemoveById:移除指定的ModSecurity规则IDlog:记录匹配日志,便于后续排查
内容的提问来源于stack exchange,提问作者louie anderson
相关产品推荐
相关产品推荐

