简体   繁体   中英

Rack and trusted IPs

I'm not a Rack expert, so I didn't understand one thing that appeared on Rack 1.4 source code :

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

```

trusted_proxy? seems to return if the address belongs to a local network (or even my own computer).

Does it rejects trusted_ips with forwarded_ips because it seems that I'm forging an IP doing a request from outside when I'm inside a network ?

The trusted_proxy? returns true if it's trusted, and yes, it appears that it only returns true if it's a local address - something with 10.xxx or 172.xxx, the loopback address (127.0.0.1), or localhost , etc.

Below that, it has remote_addrs.reject! which takes a collection, and removes from that collection anything that is true in the block. Imagine you have a collection of IP addresses (a mix of local and remote) - what that block does is take that list of IP addresses and rejects any that return true through the trusted_proxy? method, therefore all you have left over are the remote addresses.

To say it another way, it takes a list of IP addresses and rejects the local ones, leaving you with only remote IPs.

The forwarded_ips are picked up based on the info in the header, HTTP_X_FORWARDED_FOR , etc.

Finally, the block that starts with if client_ip returns true if the list of forwarded_ips includes the client_ip , and false otherwise.

Overall, and I'm guessing a bit on this last part, but I think the purpose of the ip method is to ultimately return the IP address of the connection, or something, if and only if it's a trusted IP that doesn't otherwise appear to be a spoofing attempt. Like I said I'm not really sure on that, but the ip method appears to be acting as a series of filters on the input to give you back something useful within the scope of the purpose of that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM