Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails 4, how do I configure a list of trusted proxies for RemoteIp?

My application logs the ip address of each user that logs in, but I've noticed that it's logging the IP address of our load balancer instead of the actual client ip. Researching the issue, I believe it's because our load balancers use publically routable ip addresses, and Rails is ignoring the X-Forwarded-For header assuming it's been spoofed. The solution appears to be to 'whitelist' the range of ip's used by our load balancers.

My question is, exactly how do I do that, for rails 4.1.x? Here's what I have now in config/environments/production.rb:

config.action_dispatch.custom_proxies = %r{
  ^100\.30 | # production environment load balancers
  ^200\.40 | # dev environment load balancers
}x

I tried to format it like the TRUSTED_PROXIES in remote_ip.rb, but maybe it should be a string or an array, or a differently formatted regex? Any help on the details are much appreciated. Bonus upvote if you can suggest an integration test that would catch this configuration breaking in a future version of rails. :-)

UPDATE

I've tried multiple ways to update this, and had slightly more success using config.action_dispatch.trusted_proxies. This keeps my load balancers from getting logged, but leaves all IP addresses logged as '127.0.0.1', whether they're internal or external. In logs/unicorn.log, the ip addresses are coming in as [external address, 10.* address, load balancer address], so I know the problem is at the rack or rails layer, not earlier in apache or nginx. I've also tried to replace the TRUSTED_PROXIES constant with a list that does NOT include the 10.* range (because internal users have that range), but to no apparent effect.

At this point, it looks like Rails 4.1.x is broken for any application that has real users coming from non-public IP addresses, or any application hosted in a network environment that has a load balancer with an external IP address.

like image 216
sockmonk Avatar asked Jan 08 '15 17:01

sockmonk


1 Answers

As of Rails 4.2 you have to define the proxies in a different way:

config.action_dispatch.trusted_proxies = %w(100.30.0.0/16 200.40.0.0/16).
  map { |proxy| IPAddr.new(proxy) }

See https://github.com/rails/rails/issues/5223#issuecomment-199082324

like image 193
peterfication Avatar answered Oct 21 '22 06:10

peterfication