From 83c32fb543f72732509a943523f9c7a25a44c07b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 10 Oct 2014 16:00:03 -0700 Subject: [PATCH] FileHandler should not be called for files outside the root FileHandler#matches? should return false for files that are outside the "root" path. Conflicts: actionpack/lib/action_dispatch/middleware/static.rb Conflicts: actionpack/lib/action_dispatch/middleware/static.rb actionpack/test/dispatch/static_test.rb --- actionpack/lib/action_dispatch/middleware/static.rb | 21 ++++++++++++++++++++- actionpack/test/dispatch/static_test.rb | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index a8d1765..7f11170 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -12,7 +12,7 @@ module ActionDispatch def match?(path) path = path.dup - full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(unescape_path(path))) + full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(clean_path_info(unescape_path(path)))) paths = "#{full_path}#{ext}" matches = Dir[paths] @@ -42,6 +42,25 @@ module ActionDispatch path.force_encoding('binary') if path.respond_to? :force_encoding path.gsub(/[*?{}\[\]]/, "\\\\\\&") end + + private + + PATH_SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact) + + def clean_path_info(path_info) + parts = path_info.split PATH_SEPS + + clean = [] + + parts.each do |part| + next if part.empty? || part == '.' + part == '..' ? clean.pop : clean << part + end + + clean.unshift '/' if parts.empty? || parts.first.empty? + + ::File.join(*clean) + end end class Static diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb index 856746c..a035abd 100644 --- a/actionpack/test/dispatch/static_test.rb +++ b/actionpack/test/dispatch/static_test.rb @@ -140,10 +140,28 @@ class StaticTest < ActiveSupport::TestCase [200, {"Content-Type" => "text/plain"}, ["Hello, World!"]] } App = ActionDispatch::Static.new(DummyApp, "#{FIXTURE_LOAD_PATH}/public", "public, max-age=60") + Root = "#{FIXTURE_LOAD_PATH}/public" def setup @app = App + @root = Root end include StaticTests + + def test_custom_handler_called_when_file_is_outside_root + filename = 'shared.html.erb' + assert File.exist?(File.join(@root, '..', filename)) + env = { + "REQUEST_METHOD"=>"GET", + "REQUEST_PATH"=>"/..%2F#{filename}", + "PATH_INFO"=>"/..%2F#{filename}", + "REQUEST_URI"=>"/..%2F#{filename}", + "HTTP_VERSION"=>"HTTP/1.1", + "SERVER_NAME"=>"localhost", + "SERVER_PORT"=>"8080", + "QUERY_STRING"=>"" + } + assert_equal(DummyApp.call(nil), @app.call(env)) + end end -- 1.9.3 (Apple Git-50)