diff --git a/app.rb b/app.rb index 208b51c..9635174 100644 --- a/app.rb +++ b/app.rb @@ -173,12 +173,19 @@ module Maptool "#{request.base_url}/auth/callback" end + # Zip-bomb guard: the entries' *declared* uncompressed sizes are summed + # before anything is extracted, and rubyzip itself (validate_entry_sizes, + # on by default) raises Zip::EntrySizeError if an entry inflates past + # what it declared — so a lying header can't sneak past this either. + MAX_ZIP_UNCOMPRESSED = 500 * 1024 * 1024 + def save_zip_entries(folder:, io:) paths = [] Zip::File.open_buffer(io) do |zip| - zip.each do |entry| - next unless entry.file? && GpxStore::TRACK_EXTENSIONS.any? { |ext| entry.name.downcase.end_with?(ext) } + entries = zip.select { |entry| entry.file? && GpxStore::TRACK_EXTENSIONS.any? { |ext| entry.name.downcase.end_with?(ext) } } + halt 413, json(error: "zip contents too large") if entries.sum(&:size) > MAX_ZIP_UNCOMPRESSED + entries.each do |entry| paths << GPX_STORE.save(folder: folder, filename: File.basename(entry.name), io: StringIO.new(entry.get_input_stream.read)) end end diff --git a/test/test_app.rb b/test/test_app.rb index 69f0f2c..cf52c62 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -198,6 +198,20 @@ class AppTest < Minitest::Test refute_includes names, "readme.txt" end + def test_zip_whose_contents_exceed_the_size_limit_is_rejected_before_saving_anything + zip_bytes = build_zip("big.gpx" => "x" * 2048) + original = Maptool::App::MAX_ZIP_UNCOMPRESSED + Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED) + Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, 1024) + response = post_file("/api/gpx", filename: "bomb.zip", content: zip_bytes, content_type: "application/zip", env: logged_in_env) + + assert_equal 413, response.status + assert_empty json_body(request.get("/api/gpx/tree"))["children"] + ensure + Maptool::App.send(:remove_const, :MAX_ZIP_UNCOMPRESSED) + Maptool::App.const_set(:MAX_ZIP_UNCOMPRESSED, original) + end + def test_corrupt_zip_is_rejected response = post_file("/api/gpx", filename: "bad.zip", content: "not a zip", content_type: "application/zip", env: logged_in_env) assert_equal 400, response.status