如何在 HAProxy 中验证 HMAC



是否可以在HAProxy中检查HMAC有效性?理想情况下,如果 HMAC 有效,我想设置一个 acl,以便我可以在规则中使用它。

我们的 Ubuntu 18.04 构建服务器(运行 Jenkins(位于防火墙后面,只有特定的 IP 范围被列入白名单。

我们有一个 HAProxy (1.8( 实例接收所有入站请求并路由到相应的后端服务。

问题是SonarCloud已经将其Webhook从一组定义的IP地址更改为使用HMAC来验证真实性。这意味着网络钩子会被防火墙阻止,除非我们向所有互联网流量开放它。

https://sonarcloud.io/documentation/project-administration/webhooks/#securing-your-webhooks

如果我们可以通过HAProxy来验证HMAC,那么我们可以向所有流量开放服务器,并使用HAProxy来验证这些请求(以及其他现有的IP白名单范围(。

感谢Michael提供HAProxy/Lua集成的指针。我的解决方案在这里注明以供参考。

创建了以下 Lua 脚本 (hmac_validate.lua(:

hmac = require('openssl.hmac')
local function tohex(s)
return (string.gsub(s, ".", function (c)
return string.format("%.2x", string.byte(c))
end))
end -- tohex
function validate_sonar_hmac(txn, hmac_header_key, hmac_secret)
local payload = txn.req:dup() -- take a copy of the request content
local body = string.sub(payload,string.find(payload,"rnrn")+4) -- strip off the headers
local signature = txn.sf:req_fhdr(hmac_header_key) -- get the HMAC signature sent on the request
-- calculate hmac from body & secret
local sc_hmac = hmac.new(hmac_secret, "sha256")
local calculated_signature = tohex(sc_hmac:final(body))
local signatures_match = calculated_signature == signature
if not signatures_match then
core.Alert("Sonar Cloud HMAC signature mismatch - received '"..signature.."' but calculated '"..calculated_signature.."'")
end
txn:set_var("req.sonar_request_valid", signatures_match)
end;
core.register_action("validate-sonar-hmac", {"http-req"}, validate_sonar_hmac, 2)

HA 代理配置已更改以添加以下行:

global
lua-load /etc/haproxy/hmac_validate.lua
frontend
acl sonarcloud hdr(X-Sonar-Webhook-HMAC-SHA256) -m found
http-request lua.validate-sonar-hmac X-Sonar-Webhook-HMAC-SHA256 {{ sonarcloud_hmac_secret }} if sonarcloud
http-request deny if sonarcloud !{ var(req.sonar_request_valid) -m bool }

HAProxy本身不做HMAC,但它可以使用HAProxy的Lua集成来完成。

一种方法是找到一个可以执行所需HMAC风格的Lua库,然后在Lua中编写HAProxy转换器以获取适当的输入并计算摘要进行比较。

我曾经在Lua 5.x中使用HAProxy 1.6实现了类似的东西,其中客户端发送了一个使用HMAC-SHA1签名的URL,并且代理成功检查了它的有效性。

不幸的是,我不再有权访问该代码,但我编写了这个 HAProxy 转换器来在 Lua 中进行 utf-8 感知 URL 转义(百分比编码(......我在这里提到它,因为它是一个完整的工作示例,介绍了使用 Lua 扩展 HAProxy 功能的一种方法,包括使用它所需的 Lua 代码和 HAProxy 配置,因此它可以帮助您找到解决方案。

最新更新