Skip to content

Commit

Permalink
Do not allow file type spoofing if the header bytes are not recognized
Browse files Browse the repository at this point in the history
  • Loading branch information
Zach Gardner authored and mshibuya committed Apr 30, 2019
1 parent 817b4b7 commit 22b3ce9
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/carrierwave/sanitized_file.rb
Expand Up @@ -341,7 +341,7 @@ def existing_content_type
end

def mime_magic_content_type
MimeMagic.by_magic(File.open(path)).try(:type) if path
MimeMagic.by_magic(File.open(path)).try(:type) || 'invalid/invalid' if path
rescue Errno::ENOENT
nil
end
Expand Down
4 changes: 4 additions & 0 deletions spec/fixtures/spoof.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions spec/sanitized_file_spec.rb
Expand Up @@ -230,6 +230,7 @@

it "handles Mime::Type object" do
file = File.open(file_path('sponsored.doc'))
file.stub(:content_type) { 'application/msword' }

sanitized_file = CarrierWave::SanitizedFile.new(file)
allow(sanitized_file).to receive(:file).and_return(file)
Expand All @@ -253,6 +254,17 @@
expect(sanitized_file.content_type).to eq("application/zip")
end

it "does not allow spoofing of the mime type if the mime type is not detectable" do
file = File.open(file_path('spoof.png'))

sanitized_file = CarrierWave::SanitizedFile.new(file)

lambda { sanitized_file.content_type }.should_not raise_error

sanitized_file.content_type.should_not == 'image/png'
sanitized_file.content_type.should == 'invalid/invalid'
end

it "does not raise an error if the path is not present" do
sanitized_file = CarrierWave::SanitizedFile.new(nil)

Expand Down
4 changes: 3 additions & 1 deletion spec/spec_helper.rb
Expand Up @@ -66,7 +66,9 @@ def stub_stringio(filename, mime_type=nil, fake_name=nil)
end

def stub_file(filename, mime_type=nil, fake_name=nil)
File.open(file_path(filename))
f = File.open(file_path(filename))
f.stub(:content_type) { mime_type } if mime_type
return f
end
end

Expand Down
1 change: 1 addition & 0 deletions spec/uploader/proxy_spec.rb
Expand Up @@ -65,6 +65,7 @@
end

context "when the file has been cached" do
let(:test_file_name) { 'landscape.jpg' }
before { uploader.cache!(test_file) }

it { is_expected.to eq('image/jpeg') }
Expand Down

0 comments on commit 22b3ce9

Please sign in to comment.