首页 > 解决方案 > AWS ELB Apache 获取客户端 IP,避免 X-Forwarded-For 欺骗

问题描述

从 apache 文档(https://httpd.apace.org/docs/2.4/mod/mod_remoteip.html)我们在我们的服务器上实现了以下任务:

RemoteIPHeader X-Forwarded-For

获取客户端的 IP 而不是 ELB 的 IP。但是,我们没有注意到 ELB 还将所有其他X-Forwarded-For值附加到该字符串的左侧。因此,这不是获取客户端 IP 的安全方式。

我们已经使用LogFormatwith\"%{X-Forwarded-For}i\"来验证传入的值是否符合文档记录。

192.168.0.0, 10.0.0.0

如果192.168.0.0标头被传递并且10.0.0.0是客户端的请求机器,将会发生什么。没有标头的标准请求是:

10.0.0.0

有没有办法提取最右边的IP?我在想类似的东西,

RemoteIPHeader ('(?:\d{1,3}[.]){3}\d{1,3}$', X-Forwarded-For,)[0]

但无法在 apache 中找到一个函数来配置它。我可以在 PHP 中执行此操作,但是我的日志中都会记录错误的 IP。

我试过了:

SetEnvIf X-Forwarded-For '((?:\d{1,3}[.]){3}\d{1,3})$' ip_is=$1
RemoteIPHeader %{ip_is}

但这没有影响。

更新:

Apache 配置运行:

LogFormat "%{%Y-%m-%d %H:%M:%S}t %a %u %A %p %m %U %q %>s \"%{User-agent}i\" %T/%D \"%{X-Forwarded-For}i\"" w3c_extended
CustomLog /var/log/httpd/example.com/access.log w3c_extended

我目前收到:

2021-02-27 14:29:06 10.0.21.150 - 10.0.20.222 443 GET /IPtest.php ?v=1 200 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" 0/2822 "73.149.97.219"

或者

2021-02-27 14:29:06 10.0.21.150 - 10.0.20.222 443 GET /IPtest.php ?v=1 200 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" 0/2822 "10.0.21.150, 73.149.97.219"

我需要73.149.97.219在这两种情况下捕获。

标签: amazon-web-servicesapacheapache2amazon-elbx-forwarded-for

解决方案


我正在使用 apache 2.4 和 remoteIP 进行测试

RemoteIPHeader x-forwarded-for

您还需要告诉您的 apache 您的负载均衡器(反向代理)的内部 IP 地址是什么。没有可靠的简单方法来确定内部 IP,它可以通过“任何”RFC1918(私有)IP 地址,因此您需要添加这 3 个子网。

RemoteIPTrustedProxy 10.0.0.0/8
RemoteIPTrustedProxy 172.16.0.0/12
RemoteIPTrustedProxy 192.168.0.0/16

然后使用 %a 作为 logFormat

LogFromat %a

我已经测试过

RemoteIPTrustedProxy 127.0.0.1
LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

用 curl 测试

curl 127.0.0.1/so 
127.0.0.1 - - [27/Feb/2021:15:02:38 +0100] "GET /so/ HTTP/1.1" 200 167 "-" "curl/7.52.1"

curl 127.0.0.1/so/ -H "x-forwarded-for:  1.2.3.4"
1.2.3.4 - - [27/Feb/2021:15:04:06 +0100] "GET /so/ HTTP/1.1" 200 167 "-" "curl/7.52.1"

curl 127.0.0.1/so/ -H "x-forwarded-for:  8.5.4.1, 1.2.3.4"
1.2.3.4 - - [27/Feb/2021:15:04:31 +0100] "GET /so/ HTTP/1.1" 200 167 "-" "curl/7.52.1"

推荐阅读