ModSecurity自定义Lua规则无法捕获REQUEST_HEADERS问题排查
ModSecurity 3.0.9 + Nginx 1.23.4中Lua脚本无法获取REQUEST_HEADERS的问题
问题场景
- 环境配置:ModSecurity 3.0.9 搭配 Nginx 1.23.4,使用Lua 5.3编写自定义规则脚本
- 规则配置:
SecRuleScript "/path/to/lua/script.lua" "id:1,phase:3,deny" - Lua脚本代码:
local headers = m.getvars("REQUEST_HEADERS") - 异常现象:
- 执行
curl请求时返回curl: (52) Empty reply from server - Nginx错误日志显示worker进程崩溃,报错信息:
terminate called after throwing an instance of 'std::invalid_argument' what(): Variable not found. - 切换规则的phase(1/2/3)无效果,但指定单个请求头(如
local user_agent= m.getvars("REQUEST_HEADERS:User-Agent"))可正常获取值
- 执行
问题原因
ModSecurity的Lua API中,m.getvars()方法不支持直接传入集合类变量名(如REQUEST_HEADERS),该方法仅能处理单个变量或带明确字段名/索引的变量项。直接传入集合名会触发底层C++异常,导致Nginx worker进程崩溃。
解决方案
要获取所有请求头,需通过数字索引遍历REQUEST_HEADERS集合,示例脚本如下:
local headers = {} local index = 0 -- 遍历所有请求头项 while true do local header_item = m.getvar("REQUEST_HEADERS:" .. index) if header_item == nil then break end -- 将头信息存入table,key为头名称,value为对应值 headers[header_item.name] = header_item.value index = index + 1 end -- 此处可添加对headers的业务处理逻辑
注意事项
- 集合类变量(如
REQUEST_HEADERS、REQUEST_ARGS)均需通过数字索引或具体字段名访问,不能直接作为m.getvars()的参数 - 避免触发未捕获的底层异常,否则会直接导致Nginx worker进程终止,返回空响应
内容的提问来源于stack exchange,提问作者Udi Aharon
相关产品推荐
相关产品推荐

