Skip to content

Commit

Permalink
moved the trusted_proxy regex into a separate method to allow overrid…
Browse files Browse the repository at this point in the history
…ing, added ipv6 loopback and private address ranges to the default regex

Signed-off-by: Konstantin Haase <konstantin.mailinglists@googlemail.com>
  • Loading branch information
martoche authored and rkh committed Oct 1, 2011
1 parent 250cde1 commit a9fae37
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
12 changes: 6 additions & 6 deletions lib/rack/request.rb
Expand Up @@ -305,13 +305,13 @@ def accept_encoding
end
end

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}:.+/i
end

def ip
# Copied from https://github.com/rails/rails/blob/master/actionpack/lib/
# action_dispatch/middleware/remote_ip.rb
trusted_proxies = /(^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.)/i

remote_addrs = @env['REMOTE_ADDR'] ? @env['REMOTE_ADDR'].split(/[,\s]+/) : []
remote_addrs.reject! { |addr| addr =~ trusted_proxies }
remote_addrs.reject! { |addr| trusted_proxy?(addr) }

return remote_addrs.first if remote_addrs.any?

Expand All @@ -323,7 +323,7 @@ def ip
return client_ip if forwarded_ips.include?(client_ip)
end

return forwarded_ips.reject { |ip| ip =~ trusted_proxies }.last || @env["REMOTE_ADDR"]
return forwarded_ips.reject { |ip| trusted_proxy?(ip) }.last || @env["REMOTE_ADDR"]
end

protected
Expand Down
12 changes: 12 additions & 0 deletions test/spec_request.rb
Expand Up @@ -811,6 +811,18 @@
res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4'
res.body.should.equal '3.4.5.6'

res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '::1,2620:0:1c00:0:812c:9583:754b:ca11'
res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11'

res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '2620:0:1c00:0:812c:9583:754b:ca11,::1'
res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11'

res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'fd5b:982e:9130:247f:0000:0000:0000:0000,2620:0:1c00:0:812c:9583:754b:ca11'
res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11'

res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '2620:0:1c00:0:812c:9583:754b:ca11,fd5b:982e:9130:247f:0000:0000:0000:0000'
res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11'

res = mock.get '/',
'HTTP_X_FORWARDED_FOR' => '1.1.1.1, 127.0.0.1',
'HTTP_CLIENT_IP' => '1.1.1.1'
Expand Down

0 comments on commit a9fae37

Please sign in to comment.