Created
March 10, 2017 21:31
-
-
Save rdp/ec8d8d7152988f496f951a2f0d65a320 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Determines originating IP address. REMOTE_ADDR is the standard | |
# but will fail if the user is behind a proxy. HTTP_CLIENT_IP and/or | |
# HTTP_X_FORWARDED_FOR are set by proxies so check for these if | |
# REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma- | |
# delimited list in the case of multiple chained proxies; the last | |
# address which is not trusted is the originating IP. | |
def remote_ip | |
remote_addr_list = @env['REMOTE_ADDR'] && @env['REMOTE_ADDR'].scan(/[^,\s]+/) | |
unless remote_addr_list.blank? | |
not_trusted_addrs = remote_addr_list.reject {|addr| addr =~ TRUSTED_PROXIES} | |
return not_trusted_addrs.first unless not_trusted_addrs.empty? | |
end | |
remote_ips = @env['HTTP_X_FORWARDED_FOR'] && @env['HTTP_X_FORWARDED_FOR'].split(',') | |
if @env.include? 'HTTP_CLIENT_IP' | |
if ActionController::Base.ip_spoofing_check && remote_ips && !remote_ips.include?(@env['HTTP_CLIENT_IP']) | |
# We don't know which came from the proxy, and which from the user | |
raise ActionControllerError.new(<<EOM) | |
IP spoofing attack?! | |
HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect} | |
HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect} | |
EOM | |
end | |
return @env['HTTP_CLIENT_IP'] | |
end | |
if remote_ips | |
while remote_ips.size > 1 && TRUSTED_PROXIES =~ remote_ips.last.strip | |
remote_ips.pop | |
end | |
return remote_ips.last.strip | |
end | |
@env['REMOTE_ADDR'] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment