From 3501854b78dc8ffb70be270ead73bbbaf3e26184 Mon Sep 17 00:00:00 2001 From: Lawrence Pit Date: Thu, 3 Jun 2010 14:52:55 +1000 Subject: [PATCH] Fail asap in case of IP spoofing detection. --- .../lib/action_dispatch/middleware/remote_ip.rb | 16 ++++++++++++---- actionpack/test/dispatch/request_test.rb | 7 ++++--- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb index c7d710b..a0ff830 100644 --- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb +++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb @@ -16,10 +16,12 @@ module ActionDispatch end end - def to_s - return remote_addrs.first if remote_addrs.any? + def forwarded_ips + @forwarded_ips ||= @env['HTTP_X_FORWARDED_FOR'] ? @env['HTTP_X_FORWARDED_FOR'].strip.split(/[,\s]+/) : [] + end - forwarded_ips = @env['HTTP_X_FORWARDED_FOR'] ? @env['HTTP_X_FORWARDED_FOR'].strip.split(/[,\s]+/) : [] + def ip + return remote_addrs.first if remote_addrs.any? if client_ip = @env['HTTP_CLIENT_IP'] if @check_ip_spoofing && !forwarded_ips.include?(client_ip) @@ -33,6 +35,10 @@ module ActionDispatch return forwarded_ips.reject { |ip| ip =~ @trusted_proxies }.last || @env["REMOTE_ADDR"] end + + def to_s + @to_s ||= ip + end end def initialize(app, check_ip_spoofing = true, trusted_proxies = nil) @@ -44,7 +50,9 @@ module ActionDispatch end def call(env) - env["action_dispatch.remote_ip"] = RemoteIpGetter.new(env, @check_ip_spoofing, @trusted_proxies) + remote_ip = RemoteIpGetter.new(env, @check_ip_spoofing, @trusted_proxies) + remote_ip = remote_ip.to_s if @check_ip_spoofing + env["action_dispatch.remote_ip"] = remote_ip @app.call(env) end end diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index e5ee412..0454737 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -2,7 +2,9 @@ require 'abstract_unit' class RequestTest < ActiveSupport::TestCase test "remote ip" do + request = stub_request 'REMOTE_ADDR' => '1.2.3.4' + assert request.env["action_dispatch.remote_ip"].is_a?(String) assert_equal '1.2.3.4', request.remote_ip request = stub_request 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6' @@ -40,10 +42,9 @@ class RequestTest < ActiveSupport::TestCase request = stub_request 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4' assert_equal '3.4.5.6', request.remote_ip - request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', - 'HTTP_CLIENT_IP' => '2.2.2.2' e = assert_raise(ActionDispatch::RemoteIp::IpSpoofAttackError) { - request.remote_ip + request = stub_request 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', + 'HTTP_CLIENT_IP' => '2.2.2.2' } assert_match /IP spoofing attack/, e.message assert_match /HTTP_X_FORWARDED_FOR="1.1.1.1"/, e.message -- 1.7.0