Truly independent web browser
LibMedia+LibWeb: Use checked arithmetic for byte parsing
Zaggy1024ee09d19b7148
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/Reader.cpp b/Libraries/LibMedia/Containers/ISOBMFF/Reader.cppindex d442971f218..c4c08248e7a 100644--- a/Libraries/LibMedia/Containers/ISOBMFF/Reader.cpp+++ b/Libraries/LibMedia/Containers/ISOBMFF/Reader.cpp@@ -770,7 +770,7 @@ DecoderErrorOr<FixedArray<u8>> Reader::parse_elementary_stream_descriptor_box(Stif (streamer.position() >= end || TRY(streamer.read<u8>()) != DECODER_SPECIFIC_INFO_TAG)return FixedArray<u8> {};auto size = TRY(read_descriptor_size(streamer));- if (streamer.position() + size > end)+ if (streamer.position() > end || size > end - streamer.position())return DecoderError::corrupted("DecoderSpecificInfo extends past the end of its box"sv);return streamer.read_bytes(size);}diff --git a/Libraries/LibMedia/Containers/Matroska/Reader.cpp b/Libraries/LibMedia/Containers/Matroska/Reader.cppindex 87dd8a86514..1c8bb22e2d0 100644--- a/Libraries/LibMedia/Containers/Matroska/Reader.cpp+++ b/Libraries/LibMedia/Containers/Matroska/Reader.cpp@@ -5,6 +5,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/Checked.h>#include <AK/Debug.h>#include <AK/Function.h>#include <AK/GenericShorthands.h>@@ -853,7 +854,11 @@ DecoderErrorOr<Block> Reader::parse_simple_block(Streamer& streamer, AK::DuratioBlock block;auto content_size = TRY(streamer.read_variable_size_integer());- auto content_end = streamer.position() + content_size;+ Checked<size_t> checked_content_end = streamer.position();+ checked_content_end += content_size;+ if (checked_content_end.has_overflow())+ return DecoderError::corrupted("SimpleBlock extends past the representable size"sv);+ auto content_end = checked_content_end.value();block.set_track_number(TRY(streamer.read_variable_size_integer()));@@ -897,7 +902,11 @@ DecoderErrorOr<Block> Reader::parse_block_group(Streamer& streamer, AK::Durationreturn DecoderError::with_description(DecoderErrorCategory::Corrupted, "Block group contained multiple blocks"sv);auto content_size = TRY(streamer.read_variable_size_integer());- auto content_end = streamer.position() + content_size;+ Checked<size_t> checked_content_end = streamer.position();+ checked_content_end += content_size;+ if (checked_content_end.has_overflow())+ return DecoderError::corrupted("Block extends past the representable size"sv);+ auto content_end = checked_content_end.value();block.set_track_number(TRY(streamer.read_variable_size_integer()));timestamp_offset = TRY(streamer.read_i16());diff --git a/Libraries/LibMedia/Containers/Matroska/SampleIterator.cpp b/Libraries/LibMedia/Containers/Matroska/SampleIterator.cppindex 15347277c26..980e492e82d 100644--- a/Libraries/LibMedia/Containers/Matroska/SampleIterator.cpp+++ b/Libraries/LibMedia/Containers/Matroska/SampleIterator.cpp@@ -5,6 +5,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/Checked.h>#include <AK/Debug.h>#include <LibMedia/Containers/Matroska/ElementIDs.h>#include <LibMedia/Containers/Matroska/Reader.h>@@ -177,7 +178,11 @@ DecoderErrorOr<void> SampleIterator::seek_to_cue_point(TrackCuePoint const& cue_m_position = streamer.position();m_last_timestamp = m_current_cluster->timestamp();} else {- m_position = streamer.position() + cue_position.block_offset();+ Checked<size_t> block_position = streamer.position();+ block_position += cue_position.block_offset();+ if (block_position.has_overflow())+ return DecoderError::corrupted("Cue point's block offset extends past the representable size"sv);+ m_position = block_position.value();m_last_timestamp = cue_point.timestamp;}return {};diff --git a/Libraries/LibMedia/Containers/Matroska/Streamer.cpp b/Libraries/LibMedia/Containers/Matroska/Streamer.cppindex 953749f5da3..ece0c7df882 100644--- a/Libraries/LibMedia/Containers/Matroska/Streamer.cpp+++ b/Libraries/LibMedia/Containers/Matroska/Streamer.cpp@@ -5,6 +5,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/Checked.h>#include <AK/IntegralMath.h>#include <AK/String.h>#include <AK/Utf8View.h>@@ -187,8 +188,11 @@ DecoderErrorOr<void> Streamer::read_unknown_element()if (!element_size.has_value())return DecoderError::corrupted("Cannot skip past an element with an unknown size"sv);dbgln_if(MATROSKA_TRACE_DEBUG, "Skipping unknown element of size {}.", element_size.value());- TRY(m_stream_cursor->seek(element_size.value(), AK::SeekMode::FromCurrentPosition));- return {};+ Checked<size_t> element_end = position();+ element_end += element_size.value();+ if (element_end.has_overflow())+ return DecoderError::corrupted("Element extends past the representable size"sv);+ return seek_to_position(element_end.value());}size_t Streamer::position() const@@ -198,7 +202,7 @@ size_t Streamer::position() constDecoderErrorOr<void> Streamer::seek_to_position(size_t position){- return m_stream_cursor->seek(position, AK::SeekMode::SetPosition);+ return m_stream_cursor->seek_to_position(position);}}diff --git a/Libraries/LibMedia/IncrementallyPopulatedStream.cpp b/Libraries/LibMedia/IncrementallyPopulatedStream.cppindex 11309d15769..fe58cb424a4 100644--- a/Libraries/LibMedia/IncrementallyPopulatedStream.cpp+++ b/Libraries/LibMedia/IncrementallyPopulatedStream.cpp@@ -5,7 +5,10 @@*/#include <AK/AnyOf.h>+#include <AK/Checked.h>+#include <AK/Math.h>#include <AK/RefPtr.h>+#include <AK/SaturatingMath.h>#include <LibCore/EventLoop.h>#include <LibMedia/IncrementallyPopulatedStream.h>@@ -62,7 +65,14 @@ void IncrementallyPopulatedStream::add_chunk_at(u64 offset, ReadonlyBytes data)MutexLocker locker { m_mutex };- if (m_closed && offset + data.size() > m_expected_size.value()) {+ Checked<u64> checked_new_chunk_end = offset;+ checked_new_chunk_end += data.size();+ if (checked_new_chunk_end.has_overflow()) {+ dbgln("IncrementallyPopulatedStream: Ignoring {} bytes at {} that would end past the representable size", data.size(), offset);+ return;+ }++ if (m_closed && checked_new_chunk_end.value() > m_expected_size.value()) {auto stream_end = m_expected_size.value();auto dropped_start = max(offset, stream_end);dbgln("IncrementallyPopulatedStream: Ignoring {} bytes at {} appended past the end of the closed stream at {}", offset + data.size() - dropped_start, dropped_start, stream_end);@@ -301,7 +311,7 @@ bool IncrementallyPopulatedStream::check_if_data_is_available_or_begin_request_wauto data_is_available = m_closed;if (chunk) {VERIFY(position >= chunk->offset());- u64 end = position + length;+ u64 end = saturating_add(position, length);if (m_closed && end > m_expected_size.value())end = m_expected_size.value();data_is_available = end <= chunk->end();@@ -337,7 +347,7 @@ size_t IncrementallyPopulatedStream::read_from_chunks_while_locked(u64 position,return 0;VERIFY(position >= chunk.offset());- auto end = position + bytes.size();+ auto end = saturating_add(position, static_cast<u64>(bytes.size()));auto copy_size = bytes.size();if (end > chunk.end()) {end = chunk.end();@@ -420,20 +430,26 @@ void IncrementallyPopulatedStream::Cursor::set_blocked_change_handler(ReadBlockeDecoderErrorOr<void> IncrementallyPopulatedStream::Cursor::seek(i64 offset, AK::SeekMode mode){+ Checked<i64> position;switch (mode) {case AK::SeekMode::SetPosition:- m_position = offset;+ position = offset;break;case AK::SeekMode::FromCurrentPosition:- m_position += offset;+ position = static_cast<i64>(m_position);+ position += offset;break;case AK::SeekMode::FromEndPosition:- m_position = this->blocking_size() + offset;+ position = AK::clamp_to<i64>(this->blocking_size());+ position += offset;break;default:VERIFY_NOT_REACHED();}+ if (position.has_overflow() || position.value() < 0)+ return DecoderError::corrupted("Seek target lies outside the stream"sv);+ m_position = static_cast<size_t>(position.value());return {};}diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cppindex 2a960d5c406..700c8a312e1 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp@@ -1919,6 +1919,16 @@ Optional<Utf16String> HTMLMediaElement::verify_response_or_get_failure_reason(GCreturn Utf16String::formatted("Failed to extract values from Content-Range: {}", internal_response->header_list()->get("Content-Range"sv));auto const& content_range = maybe_content_range.get<HTTP::HeaderList::ContentRangeValues>();++ // AD-HOC: The server chooses where its bytes land in the resource, so hold it to the range that was asked for.+ // Otherwise a response could place bytes anywhere, including past the end of the representable resource.+ if (content_range.last_byte_pos < content_range.first_byte_pos)+ return Utf16String::formatted("Content-Range ends before it begins: {}", internal_response->header_list()->get("Content-Range"sv));+ if (content_range.complete_length.has_value() && content_range.last_byte_pos >= content_range.complete_length.value())+ return Utf16String::formatted("Content-Range extends past the complete length: {}", internal_response->header_list()->get("Content-Range"sv));+ if (content_range.first_byte_pos != byte_range.get<UntilEnd>().first)+ return Utf16String::formatted("Content-Range does not begin at the requested byte {}: {}", byte_range.get<UntilEnd>().first, internal_response->header_list()->get("Content-Range"sv));+m_remote_fetch_data->offset = content_range.first_byte_pos;if (content_range.complete_length.has_value())m_remote_fetch_data->stream->set_expected_size(content_range.complete_length.value());diff --git a/Tests/LibMedia/TestIncrementallyPopulatedStream.cpp b/Tests/LibMedia/TestIncrementallyPopulatedStream.cppindex 017ab3ff639..f9d72c376d2 100644--- a/Tests/LibMedia/TestIncrementallyPopulatedStream.cpp+++ b/Tests/LibMedia/TestIncrementallyPopulatedStream.cpp@@ -1071,3 +1071,35 @@ TEST_CASE(a_read_after_idle_is_withdrawn_asks_for_data_when_none_has_arrived)stream->add_chunk_at(0, data.bytes());MUST(thread->join());}++TEST_CASE(chunk_ending_past_the_representable_size_is_ignored)+{+ auto stream = Media::IncrementallyPopulatedStream::create_empty();+ stream->set_expected_size(NumericLimits<u64>::max());+ auto data = make_test_data(2);++ stream->add_chunk_at(NumericLimits<u64>::max() - 1, data.bytes());+ EXPECT(stream->availability().byte_ranges.is_empty());++ stream->add_chunk_at(NumericLimits<u64>::max() - 2, data.bytes());+ auto byte_ranges = stream->availability().byte_ranges;+ EXPECT_EQ(byte_ranges.size(), 1u);+ EXPECT_EQ(byte_ranges[0].start, NumericLimits<u64>::max() - 2);+ EXPECT_EQ(byte_ranges[0].end, NumericLimits<u64>::max());+}++TEST_CASE(cursor_rejects_seeks_outside_the_stream)+{+ auto data = make_test_data(10);+ auto stream = Media::IncrementallyPopulatedStream::create_from_data(data.bytes());+ auto cursor = stream->create_cursor();++ EXPECT(cursor->seek(-1, AK::SeekMode::SetPosition).is_error());+ EXPECT(cursor->seek(-1, AK::SeekMode::FromCurrentPosition).is_error());+ EXPECT(cursor->seek(NumericLimits<i64>::max(), AK::SeekMode::FromEndPosition).is_error());+ EXPECT_EQ(cursor->position(), 0u);++ EXPECT(!cursor->seek(5, AK::SeekMode::SetPosition).is_error());+ EXPECT(!cursor->seek(-2, AK::SeekMode::FromEndPosition).is_error());+ EXPECT_EQ(cursor->position(), 8u);+}diff --git a/Tests/LibMedia/TestParseMatroska.cpp b/Tests/LibMedia/TestParseMatroska.cppindex 4d8efcbb8c4..5e5c8f6da6c 100644--- a/Tests/LibMedia/TestParseMatroska.cpp+++ b/Tests/LibMedia/TestParseMatroska.cpp@@ -1138,6 +1138,28 @@ TEST_CASE(color_element_overrides_the_codec_private_configuration_record)EXPECT(track.video_data().cicp.transfer_characteristics() == Media::TransferCharacteristics::BT709);}+TEST_CASE(simple_block_extending_past_the_representable_size_is_corrupted)+{+ // A SimpleBlock placed as high as a cursor can be seeked, whose declared size reaches past that.+ auto stream = Media::IncrementallyPopulatedStream::create_empty();+ stream->set_expected_size(NumericLimits<u64>::max());+ auto block_position = static_cast<u64>(NumericLimits<i64>::max()) - 8;+ Array<u8, 8> simple_block { 0x88, 0x81, 0x00, 0x00, 0x80, 0x11, 0x22, 0x33 };+ stream->add_chunk_at(block_position, simple_block);++ auto cursor = stream->create_cursor();+ cursor->set_is_blocking(false);+ Media::Matroska::Streamer streamer { cursor };+ MUST(streamer.seek_to_position(block_position));++ auto result = Media::Matroska::Reader::parse_simple_block(streamer, AK::Duration::zero(), 1'000'000, {});+ EXPECT(result.is_error());+ EXPECT_EQ(result.error().category(), Media::DecoderErrorCategory::Corrupted);++ // Nothing in the stream lies past what a cursor can address.+ EXPECT(streamer.seek_to_position(NumericLimits<u64>::max() - 8).is_error());+}+TEST_CASE(unknown_track_type_values_are_invalid){EXPECT_EQ(Media::Matroska::TrackEntry::track_type_from_element_value(33), Media::Matroska::TrackEntry::TrackType::Metadata);