From 63f8779e49664d5e95fae8d42d04c8e373162b3c Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Sat, 30 Jan 2021 12:22:01 -0500 Subject: [PATCH] fix(security): prevent command injection in FileResponse#read_body Also add general test coverage for FileResponse#read_body Related to https://github.com/sparklemotion/mechanize/security/advisories/GHSA-qrqm-fpv6-6r8g --- lib/mechanize/file_response.rb | 2 +- test/test_mechanize_file_response.rb | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/mechanize/file_response.rb b/lib/mechanize/file_response.rb index 195cf167..8b44883e 100644 --- a/lib/mechanize/file_response.rb +++ b/lib/mechanize/file_response.rb @@ -15,7 +15,7 @@ def read_body if directory? yield dir_body else - open @file_path, 'rb' do |io| + ::File.open(@file_path, 'rb') do |io| yield io.read end end diff --git a/test/test_mechanize_file_response.rb b/test/test_mechanize_file_response.rb index 05e08ea8..1f77837f 100644 --- a/test/test_mechanize_file_response.rb +++ b/test/test_mechanize_file_response.rb @@ -1,7 +1,6 @@ require 'mechanize/test_case' class TestMechanizeFileResponse < Mechanize::TestCase - def test_content_type Tempfile.open %w[pi .nothtml] do |tempfile| res = Mechanize::FileResponse.new tempfile.path @@ -19,5 +18,24 @@ def test_content_type end end -end + def test_read_body + Tempfile.open %w[pi .html] do |tempfile| + tempfile.write("asdfasdfasdf") + tempfile.close + res = Mechanize::FileResponse.new(tempfile.path) + res.read_body do |input| + assert_equal("asdfasdfasdf", input) + end + end + end + + def test_read_body_does_not_allow_command_injection + in_tmpdir do + FileUtils.touch('| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'') + res = Mechanize::FileResponse.new('| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'') + res.read_body { |_| } + refute_operator(File, :exist?, "vul.txt") + end + end +end