Skip to content

Commit

Permalink
Change ActionDispatch::RemoteIp to not use HTTP_X_FORWARDED_FOR w…
Browse files Browse the repository at this point in the history
…hen `REMOTE_ADDR` is not a trusted proxy

As pointed out in the documentation, using `RemoteIp` while accessible without a reverse proxy opens you to IP
spoofing. Returning `REMOTE_ADDR` when that is not considered a trusted proxy should make that less likely.
  • Loading branch information
ClearlyClaire committed Apr 19, 2024
1 parent adf0c73 commit e403810
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions actionpack/lib/action_dispatch/middleware/remote_ip.rb
Expand Up @@ -164,7 +164,7 @@ def calculate_ip

# If every single IP option is in the trusted list, return the IP that's
# furthest away
filter_proxies(ips + [remote_addr]).first || ips.last || remote_addr
filter_proxies([remote_addr] + ips).first || ips.last || remote_addr
end

# Memoizes the value returned by #calculate_ip and returns it for
Expand All @@ -191,7 +191,7 @@ def ips_from(header) # :doc:

def filter_proxies(ips) # :doc:
ips.reject do |ip|
@proxies.any? { |proxy| proxy === ip }
ip.blank? || @proxies.any? { |proxy| proxy === ip }
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions actionpack/test/dispatch/request_test.rb
Expand Up @@ -74,7 +74,7 @@ class RequestIP < BaseRequestTest

request = stub_request "REMOTE_ADDR" => "1.2.3.4",
"HTTP_X_FORWARDED_FOR" => "3.4.5.6"
assert_equal "3.4.5.6", request.remote_ip
assert_equal "1.2.3.4", request.remote_ip

request = stub_request "REMOTE_ADDR" => "127.0.0.1",
"HTTP_X_FORWARDED_FOR" => "3.4.5.6"
Expand Down Expand Up @@ -155,7 +155,7 @@ class RequestIP < BaseRequestTest

request = stub_request "REMOTE_ADDR" => "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"HTTP_X_FORWARDED_FOR" => "fe80:0000:0000:0000:0202:b3ff:fe1e:8329"
assert_equal "fe80:0000:0000:0000:0202:b3ff:fe1e:8329", request.remote_ip
assert_equal "2001:0db8:85a3:0000:0000:8a2e:0370:7334", request.remote_ip

request = stub_request "REMOTE_ADDR" => "::1",
"HTTP_X_FORWARDED_FOR" => "fe80:0000:0000:0000:0202:b3ff:fe1e:8329"
Expand Down

0 comments on commit e403810

Please sign in to comment.