>问题
我在两台服务器上设置了带有机架 1.4.5 的 rails 3.2.15。第一个服务器是服务于静态资产的nginx代理。第二台服务器是服务于rails应用程序的独角兽。
在 Rails production.log
中,我总是看到 nginx IP 地址 (10.0.10.150( 而不是我的客户端 IP 地址 (10.0.10.62(:
Started GET "/" for 10.0.10.150 at 2013-11-21 13:51:05 +0000
我想在日志中拥有真实的客户端 IP。
我们的设置
X-Forwarded-For
和X-Real-IP
的HTTP标头在nginx中设置正确,我已经通过在config/environments/production.rb
中设置config.action_dispatch.trusted_proxies = /^127.0.0.1$/
10.0.10.62
定义为不受信任的代理地址,这要归功于另一个答案。我可以检查它是否正常工作,因为我将它们记录在应用程序控制器中:
在app/controllers/application_controller.rb
:
class ApplicationController < ActionController::Base
before_filter :log_ips
def log_ips
logger.info("request.ip = #{request.ip} and request.remote_ip = #{request.remote_ip}")
end
end
在production.log
:
request.ip = 10.0.10.150 and request.remote_ip = 10.0.10.62
调查
在调查时,我看到Rails::Rack::Logger
负责记录IP地址:
def started_request_message(request)
'Started %s "%s" for %s at %s' % [
request.request_method,
request.filtered_path,
request.ip,
Time.now.to_default_s ]
end
request
是ActionDispatch::Request
的一个实例。它继承了定义如何计算 IP 地址的Rack::Request
:
def trusted_proxy?(ip)
ip =~ /^127.0.0.1$|^(10|172.(1[6-9]|2[0-9]|30|31)|192.168).|^::1$|^fd[0-9a-f]{2}:.+|^localhost$/i
end
def ip
remote_addrs = @env['REMOTE_ADDR'] ? @env['REMOTE_ADDR'].split(/[,s]+/) : []
remote_addrs.reject! { |addr| trusted_proxy?(addr) }
return remote_addrs.first if remote_addrs.any?
forwarded_ips = @env['HTTP_X_FORWARDED_FOR'] ? @env['HTTP_X_FORWARDED_FOR'].strip.split(/[,s]+/) : []
if client_ip = @env['HTTP_CLIENT_IP']
# If forwarded_ips doesn't include the client_ip, it might be an
# ip spoofing attempt, so we ignore HTTP_CLIENT_IP
return client_ip if forwarded_ips.include?(client_ip)
end
return forwarded_ips.reject { |ip| trusted_proxy?(ip) }.last || @env["REMOTE_ADDR"]
end
转发的 IP 地址使用 trusted_proxy?
进行过滤。因为我们的nginx服务器使用的是公共IP地址而不是私有IP地址,所以Rack::Request#ip
认为它不是代理,而是尝试进行某些IP欺骗的真实客户端IP。这就是为什么我在日志中看到nginx IP地址的原因。
在日志摘录中,客户端和服务器的 IP 地址为 10.0.10.x,因为我正在使用虚拟机来重现我们的生产环境。
我们目前的解决方案
为了规避这种行为,我写了一个位于app/middleware/remote_ip_logger.rb中的小机架中间件:
class RemoteIpLogger
def initialize(app)
@app = app
end
def call(env)
remote_ip = env["action_dispatch.remote_ip"]
Rails.logger.info "Remote IP: #{remote_ip}" if remote_ip
@app.call(env)
end
end
我把它插入到ActionDispatch::RemoteIp
中间件之后
config.middleware.insert_after ActionDispatch::RemoteIp, "RemoteIpLogger"
这样我就可以在日志中看到真实的客户端 IP:
Started GET "/" for 10.0.10.150 at 2013-11-21 13:59:06 +0000
Remote IP: 10.0.10.62
我对这个解决方案感到有点不舒服。 nginx+unicorn是Rails应用程序的常见设置。如果我必须自己记录客户端IP,这意味着我错过了一些东西。是因为 Nginx 服务器在与 rails 服务器通信时使用公共 IP 地址吗?有没有办法自定义Rack::Request
trusted_proxy?
方法?
已编辑:添加nginx配置和HTTP请求捕获
/etc/nginx/sites-enabled/site.example.com.conf
:
server {
server_name site.example.com;
listen 80;
location ^~ /assets/ {
root /home/deployer/site/shared;
expires 30d;
}
location / {
root /home/deployer/site/current/public;
try_files $uri @proxy;
}
location @proxy {
access_log /var/log/nginx/site.access.log combined_proxy;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_read_timeout 300;
proxy_pass http://rails.example.com:8080;
}
}
Nginx服务器10.0.10.150
.Rails 服务器10.0.10.190
。我的机器10.0.10.62
从我的机器执行curl http://10.0.10.150/
时,轨道服务器上的tcpdump port 8080 -i eth0 -Aq -s 0
显示以下请求HTTP标头:
GET / HTTP/1.0
X-Forwarded-For: 10.0.10.62
X-Forwarded-Proto: http
Host: 10.0.10.150
Connection: close
User-Agent: curl/7.29.0
Accept: */*
轨道日志/home/deployer/site/current/log/production.log
(通过自定义代码添加远程 IP 和 request.ip 行(:
Started GET "/" for 10.0.10.150 at 2013-11-22 08:01:17 +0000
Remote IP: 10.0.10.62
Processing by Devise::RegistrationsController#new as */*
request.ip = 10.0.10.150 and request.remote_ip = 10.0.10.62
Rendered devise/shared/_links.erb (0.1ms)
Rendered devise/registrations/new.html.erb within layouts/application (2.3ms)
Rendered layouts/_landing.html.erb (1.5ms)
Completed 200 OK in 8.9ms (Views: 7.5ms | ActiveRecord: 0.0ms)
在我看来,你目前的方法是唯一理智的方法。唯一缺少的步骤是覆盖 env
中的 IP 地址。
典型的REMOTE_ADDR很少拥有正确的IP,如果你有任意数量的代理和负载均衡器层,或者没有 - 你在这方面并不是独一无二的。每个都可能添加或更改与远程 IP 相关的标头。而且,您不能假设这些字段中的每一个都必须对应于单个IP地址。有些人会将 IP 推送或取消移动到列表。
只有一种方法可以确定哪个字段具有正确的值以及如何保存,那就是潜入其中并查看。你显然已经这样做了。现在,只需使用机架中间件用正确的值覆盖env['REMOTE_ADDR']
即可。让你没有编写的任何一段代码记录或处理错误的IP地址是没有意义的,就像现在发生的那样。
(这是 Ruby,你也可以猴子补丁 Rack::请求,当然...
有关丰富多彩的阅读,说明异国情调的设置可能会在多大程度上破坏查找客户真实IP地址的尝试,例如,请参阅WordPress对此进行的无休止的讨论:
- https://core.trac.wordpress.org/ticket/9235
- https://core.trac.wordpress.org/ticket/4198
- https://core.trac.wordpress.org/ticket/4602
它是PHP,但所提出的观点的要点同样适用于Ruby。(请注意,在我写这篇文章时,它们也没有解决,而且它们已经存在了很长时间。
这似乎为我做了一个技巧。 (在nginx配置中设置(
proxy_set_header CLIENT_IP $remote_addr;
我遇到了同样的问题,我们的网络客户端的一部分在我们的专用网络上访问我们的 rails 应用程序(Rails 4.2.7(,我们得到了错误的 IP 报告。所以,我想我会添加对我们有用的东西来解决问题。
我发现 Rails 问题 5223 提供了比像问题那样双重记录 IP 更好的解决方法。因此,我们打补丁 Rack 以从受信任代理列表中删除专用网络,如下所示:
module Rack
class Request
def trusted_proxy?(ip)
ip =~ /^127.0.0.1$/
end
end
end
这解决了控制器记录错误的 IP,另一半修复以确保正确处理request.remote_ip
。为此,请将以下内容添加到您的 config/environment/production.rb 中:
config.action_dispatch.trusted_proxies = [IPAddr.new('127.0.0.1')]
我面临着同样的问题。为了解决这个问题,我参考了您的实现,就在config/application.rb
修复了它的行下方。
config.middleware.insert_before Rails::Rack::Logger, 'RemoteIpLogger'
无需编写额外的记录器,您将在第一行本身中看到实际的客户端IP。
Started GET "/" for 10.0.10.62 at 2013-11-22 08:01:17 +0000
而在appmiddlewareremote_ip_logger.rb
.我的HTTP_X_FORWARDED_FOR
有一个IP列表,第一个是实际客户的IP。
class RemoteIpLogger
def initialize(app)
@app = app
end
def call(env)
if env["HTTP_X_FORWARDED_FOR"]
remote_ip = env["HTTP_X_FORWARDED_FOR"].split(",")[0]
env['REMOTE_ADDR'] = env["action_dispatch.remote_ip"] = env["HTTP_X_FORWARDED_FOR"] = remote_ip
@app.call(env)
else
@app.call(env)
end
end
end
简短而简单:
request.remote_ip