问题描述
从 apache 文档 (https://httpd.apace.org/docs/2.4/mod/mod_remoteip.html),我们在我们的服务器上实现了以下分配:
RemoteIPHeader X-Forwarded-For
获取客户端的 IP 而不是 ELB 的 IP。但是,我们没有注意到 ELB 还将所有其他 X-Forwarded-For
值附加到该字符串的左侧。因此,这不是获取客户端 IP 的安全方式。
我们使用 LogFormat
和 \"%{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})$' 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
。
解决方法
我正在使用 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"