问题:如何在像nginx这样的代理后面时在rails日志中记录真实的客户端IP

问题

我在两台服务器上安装了带有机架 1.4.5 的导轨 3.2.15。第一个服务器是服务静态资产的 nginx 代理。第二台服务器是为 rails 应用程序服务的独角兽。

在 Railsproduction.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。

我们的设置

HTTP 标头X-Forwarded-ForX-Real-IP在 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

requestActionDispatch::Request的一个实例。它继承了Rack::Request,它定义了如何计算 IP 地址:

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 中编写了一个小 Rack 中间件:

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::Requesttrusted_proxy?方法?

已编辑:添加 nginx 配置和 HTTP 请求捕获

zoz100036:

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/时,rails 服务器上的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: */*

Rails 日志/home/deployer/site/current/log/production.log(Remote IPrequest.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 推送或取消移动到列表中。

只有一种方法可以确定哪个字段具有正确的值以及如何保持正确的值,那就是潜入那里并查看。你显然已经这样做了。现在,只需使用 Rack 中间件用正确的值覆盖env['REMOTE_ADDR']。让您没有编写的任何代码记录或处理错误的 IP 地址是没有意义的,就像现在发生的那样。

(这是 Ruby,你也可以修改 Rack::Request,当然......)

对于说明不同程度的异国情调设置可能会在尝试找到客户的真实 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。 (请注意,在我写这篇文章时,它们也没有解决,而且它们已经存在了很长时间。)

Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐