From aae0b13514a1a0caf93b1cf233733c50e679069a Mon Sep 17 00:00:00 2001 From: Katsuhiko YOSHIDA Date: Sat, 20 Jul 2019 11:03:40 +0900 Subject: [PATCH] fix(security): prevent command injection in CookieJar Related to https://github.com/sparklemotion/mechanize/security/advisories/GHSA-qrqm-fpv6-6r8g --- lib/mechanize/cookie_jar.rb | 4 ++-- test/test_mechanize_cookie_jar.rb | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/mechanize/cookie_jar.rb b/lib/mechanize/cookie_jar.rb index c8d462d7..c60e279e 100644 --- a/lib/mechanize/cookie_jar.rb +++ b/lib/mechanize/cookie_jar.rb @@ -65,7 +65,7 @@ def dump_cookiestxt(io) class CookieJar < ::HTTP::CookieJar def save(output, *options) output.respond_to?(:write) or - return open(output, 'w') { |io| save(io, *options) } + return ::File.open(output, 'w') { |io| save(io, *options) } opthash = { :format => :yaml, @@ -119,7 +119,7 @@ def save(output, *options) def load(input, *options) input.respond_to?(:write) or - return open(input, 'r') { |io| load(io, *options) } + return ::File.open(input, 'r') { |io| load(io, *options) } opthash = { :format => :yaml, diff --git a/test/test_mechanize_cookie_jar.rb b/test/test_mechanize_cookie_jar.rb index ce705c14..96f01aef 100644 --- a/test/test_mechanize_cookie_jar.rb +++ b/test/test_mechanize_cookie_jar.rb @@ -1,4 +1,5 @@ require 'mechanize/test_case' +require 'fileutils' class TestMechanizeCookieJar < Mechanize::TestCase @@ -500,6 +501,35 @@ def test_save_and_read_cookiestxt_with_session_cookies assert_equal(0, @jar.cookies(url).length) end + def test_prevent_command_injection_when_saving + url = URI 'http://rubygems.org/' + path = '| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'' + + @jar.add(url, Mechanize::Cookie.new(cookie_values)) + + in_tmpdir do + @jar.save_as(path, :cookiestxt) + assert_equal(false, File.exist?('vul.txt')) + end + end + + def test_prevent_command_injection_when_loading + url = URI 'http://rubygems.org/' + path = '| ruby -rfileutils -e \'FileUtils.touch("vul.txt")\'' + + @jar.add(url, Mechanize::Cookie.new(cookie_values)) + + in_tmpdir do + @jar.save_as("cookies.txt", :cookiestxt) + @jar.clear! + + assert_raises Errno::ENOENT do + @jar.load(path, :cookiestxt) + end + assert_equal(false, File.exist?('vul.txt')) + end + end + def test_save_and_read_expired_cookies url = URI 'http://rubygems.org/'