From 4c0b634caec3850a7fd8dddf9e2634796aec7edd Mon Sep 17 00:00:00 2001 From: Kush Fanikiso Date: Fri, 25 Oct 2019 18:12:17 +0000 Subject: [PATCH] Handle null byte when serving static files --- lib/sinatra/base.rb | 15 +++++++++------ test/static_test.rb | 6 ++++++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index dc538a634a..0ab77a0d96 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -1057,13 +1057,16 @@ def route_missing # Attempt to serve static files from public directory. Throws :halt when # a matching file is found, returns nil otherwise. def static!(options = {}) - return if (public_dir = settings.public_folder).nil? - path = File.expand_path("#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" ) - return unless File.file?(path) - - env['sinatra.static_file'] = path + public_dir = settings.public_folder + return if public_dir.nil? + path = "#{public_dir}#{URI_INSTANCE.unescape(request.path_info)}" + return unless valid_path?(path) + expanded_path = File.expand_path(path) + return unless File.file?(expanded_path) + + env['sinatra.static_file'] = expanded_path cache_control(*settings.static_cache_control) if settings.static_cache_control? - send_file path, options.merge(:disposition => nil) + send_file expanded_path, options.merge(:disposition => nil) end # Run the block with 'throw :halt' support and apply result to the response. diff --git a/test/static_test.rb b/test/static_test.rb index e8408b14e4..1ebd4e74b2 100644 --- a/test/static_test.rb +++ b/test/static_test.rb @@ -59,6 +59,12 @@ class StaticTest < Minitest::Test assert not_found? end + it 'passes to the next handler when the path contains null bytes' do + @app.set :public_folder, "\0" + get "/" + assert not_found? + end + it 'passes to the next handler when the static option is disabled' do @app.set :static, false get "/#{File.basename(__FILE__)}"