class ActionDispatch::RemoteIp::GetIp
def calculate_ip
take the list of IPs, remove known and trusted proxies, and then take
In order to find the first address that is (probably) accurate, we
it could also have been set by the client maliciously.
while the first IP in the list is likely to be the "originating" IP,
As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
set the Client-Ip header instead, so we check that too.
proxies, that header may contain a list of IPs. Other proxy services
request will be put in an X-Forwarded-For header. If there are multiple
server like HAProxy or Nginx, the IP address that made the original
Ruby process, on e.g. Heroku. When the request is proxied by another
REMOTE_ADDR will be correct if the request is made directly against the
request.
likely to be the address of the actual remote client making this
Sort through the various IP address headers, looking for the IP most
def calculate_ip # Set by the Rack web server, this is a single value. remote_addr = ips_from('REMOTE_ADDR').last # Could be a CSV list and/or repeated headers that were concatenated. client_ips = ips_from('HTTP_CLIENT_IP').reverse forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR').reverse # +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set. # If they are both set, it means that this request passed through two # proxies with incompatible IP header conventions, and there is no way # for us to determine which header is the right one after the fact. # Since we have no idea, we give up and explode. should_check_ip = @check_ip && client_ips.last && forwarded_ips.last if should_check_ip && !forwarded_ips.include?(client_ips.last) # We don't know which came from the proxy, and which from the user raise IpSpoofAttackError, "IP spoofing attack?! " + "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect} " + "HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}" end # We assume these things about the IP headers: # # - X-Forwarded-For will be a list of IPs, one per proxy, or blank # - Client-Ip is propagated from the outermost proxy, or is blank # - REMOTE_ADDR will be the IP that made the request to Rack ips = [forwarded_ips, client_ips, remote_addr].flatten.compact # If every single IP option is in the trusted list, just return REMOTE_ADDR filter_proxies(ips).first || remote_addr end