为什么 iptables 不能使用 x-forwarded-for 进行字符串匹配?

问题描述 投票:0回答:2

我有一个在 Cloudflare 后面的 Ubuntu 上使用 Apache 运行的网络服务器。我想阻止用户使用网络服务器的 iptables。这里我想实现 iptables 的字符串匹配功能并断开连接。这是我的规则,但不起作用:

iptables -I INPUT -m string --string "x-forwarded-for: 216.244.66.205" --algo bm --to 65535 -j DROP

添加此规则后,客户端仍然能够访问服务器。

我知道 Cloudflare 客户端 IP 的特定标头是 cf-connecting-ip。我可以用这个来阻止客户端。这是有效的规则:

iptables -I INPUT -m string --string "cf-connecting-ip: 216.244.66.205" --algo bm --to 65535 -j DROP

从 Cloudflare 到 Web 服务器的流量是 HTTP(端口 80)。

我有一个负载均衡器 (haproxy),一些域通过它而不是 Cloudflare 运行。这就是为什么我想使用 XFF,因为 cf-connecting-ip 特定于 Cloudflare,而两者都支持 XFF。

我可以看到 Cloudflare 正确附加了 cf-connecting-ip 和 XFF 标头。这是多个请求中 tcpdump 的输出:

tcpdump -A -s 65535 'tcp port 80' | grep 216.244.66.205
x-forwarded-for: 216.244.66.205
cf-connecting-ip: 216.244.66.205
x-forwarded-for: 216.244.66.205
cf-connecting-ip: 216.244.66.205
x-forwarded-for: 216.244.66.205
cf-connecting-ip: 216.244.66.205
x-forwarded-for: 216.244.66.205
cf-connecting-ip: 216.244.66.205

不知何故,iptables 能够检测到字符串 cf-connecting-ip 但不能检测到 x-forwarded-for

如有任何帮助,我们将不胜感激。

apache ubuntu networking cloudflare iptables
2个回答
0
投票

HTTP 标头位于应用程序层,而 IPTables 在 TCP/IP 堆栈的较低位置工作。您要过滤的数据对 IPTables 不可见。

对于 Cloudflare 背后的网站,您应该将 IPTables 配置为仅允许 Cloudflare IP 地址通过,并使用 Cloudflare 防火墙阻止客户端 IP 地址。


0
投票

回答自己的问题,希望可以帮助别人。

该问题是由于字母大小写(上+下)引起的。

所以,我只是在 iptables 规则中添加了一个额外的选项,即

--icase
,它忽略大小写(不区分大小写的匹配)。

现在命令如下,它适用于:cloudflare 和我自己的基于 haproxy 的负载均衡器:

iptables -I INPUT -m string --string "x-forwarded-for: 216.244.66.205" --algo bm --to 65535 --icase -j DROP
© www.soinside.com 2019 - 2024. All rights reserved.