apisix上修复cors漏洞
背景
CORS漏洞
CORS跨域资源共享漏洞与JSONP劫持漏洞类似,都是程序员在解决跨域问题中进行了错误的配置。攻击者可以利用Web应用对用户请求数据包的Origin头校验不严格,诱骗受害者访问攻击者制作好的恶意网站,从而跨域获取受害者的敏感数据,包括转账记录、交易记录、个人身份证号信息、订单信息等等。
修复建议
1.Access-Control-Allow-Origin中指定的来源只能是受信任的站点,避免使用Access-Control-Allow-Origin:*,避免使用Access-Control-Allow-Origin: null,否则攻击者可以伪造来源请求实现跨域资源窃取。
2.严格校验“Origin”值,校验的正则表达式一定要编写完善,避免出现绕过的情况。
3.减少“Access-Control-Allow-Methods”所允许的请求方法。
4.除了正确配置CORS之外,Web服务器还应继续对敏感数进行保护,例如身份验证和会话管理等。
apisix修复代码
function()
local core = require("apisix.core")
-- 配置允许的源(支持完整域名和通配符)
local allowed_origins = {
"https://xxx.abc.cn",
"http://xxx.xxx.xxx.xxx:80",
"http://xxx.xxx.xxx.xxx:3432"
}
-- 1. 获取请求的 Origin 头
local origin = core.request.header(ctx, "Origin")
-- 2. 如果没有 Origin 头则放行(可根据需要改为阻止)
if not origin then
core.log.warn("Request with missing Origin header")
return true
end
-- 3. 检查是否在允许列表中
local allowed = false
for _, pattern in ipairs(allowed_origins) do
-- 将模式转换为 Lua 模式匹配:
-- 转义特殊字符,替换 * 为 .*,确保完整匹配
local regex = "^" .. pattern:gsub("([%-%.%+%[%]%(%)%$%^%%])", "%%%1")
:gsub("%*", ".*")
:gsub("%?", ".") .. "$"
if origin:match(regex) then
allowed = true
break
end
end
-- 4. 未通过检查的处理
if not allowed then
core.log.warn("Blocked origin: ", origin)
return core.response.exit(403, {
error = "Forbidden",
message = "Origin not allowed"
----received_origin = origin,
----allowed_origins = allowed_origins
})
end
-- 5. 通过检查后可以添加验证头(可选)
--core.response.set_header("X-Origin-Validated", "true")
return true
end
配置截图


浙公网安备 33010602011771号