Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only follow symlinks within configured static file handler directory #545

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions spec/static_file_handler_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,34 @@ describe Kemal::StaticFileHandler do
response = handle HTTP::Request.new("GET", "/dir/index.html")
response.headers["Access-Control-Allow-Origin"].should eq("*")
end

it "should not follow symlinks outside of the configured directory" do
tempfile = File.tempfile("symlink", "txt")
symlink_path = "#{__DIR__}/static/dir/symlink.txt"
File.write tempfile.path, "my_super_secret"
begin
File.symlink(tempfile.path, symlink_path)

response = handle HTTP::Request.new("GET", "/dir/symlink.txt")
response.body.should_not contain("my_super_secret")
response.status_code.should eq(404)
ensure
File.delete symlink_path
tempfile.delete
end
end

it "should follow symlinks inside of the configured directory" do
symlink_path = "#{__DIR__}/static/dir/symlink.txt"
begin
File.symlink("#{__DIR__}/static/dir/test.txt", symlink_path)

response = handle HTTP::Request.new("GET", "/dir/symlink.txt")
response.status_code.should eq(200)
response.body.should eq(File.read("#{__DIR__}/static/dir/test.txt"))
ensure
File.delete symlink_path
end
end

end
7 changes: 7 additions & 0 deletions src/kemal/static_file_handler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ module Kemal
end

file_path = File.join(@public_dir, expanded_path)

# prevent symlinks out of the public dir
if File.symlink?(file_path) && !File.real_path(file_path).starts_with?(@public_dir)
context.response.status_code = 404
return
end

is_dir = Dir.exists? file_path

if request_path != expanded_path
Expand Down