Closed Bug 2027247 Opened 8 months ago Closed 7 months ago

Heap buffer over-read in [@ MediaCacheStream::ReadPartialBlock] via int32 truncation of server-controlled Content-Range offset

Categories

(Core :: Audio/Video, defect, P2)

defect

Tracking

()

RESOLVED FIXED
152 Branch
Tracking Status
firefox-esr115 --- wontfix
firefox-esr140 151+ fixed
firefox149 --- wontfix
firefox150 --- wontfix
firefox151 + fixed
firefox152 + fixed

People

(Reporter: bugmon, Assigned: kinetik)

Details

(5 keywords, Whiteboard: [prefs-checked][adv-main151+r][adv-esr140.11+r])

Attachments

(7 files, 4 external files)

Summary

Heap buffer over-read (7 bytes past end of a 32768-byte allocation) in MediaCacheStream::ReadPartialBlock. Root cause is a missing range check in ChannelMediaResource::OnStartRequest, which accepts an arbitrarily large Content-Range start offset from a remote HTTP server and forwards it to MediaCacheStream::NotifyDataStarted without invoking IsOffsetAllowed. The out-of-range offset (2^47) poisons mChannelOffset; subsequent calls to OffsetToBlockIndexUnchecked truncate int32_t(2^47 / 32768) = int32_t(2^32) = 0, causing block-index aliasing that spuriously passes the guard at line 2435, followed by signed-to-unsigned underflow in the Span length calculation at line 2444.

Affected Code

File: dom/media/ChannelMediaResource.cpp, line 228 — missing validation:

      if (gotRangeHeader) {
        startOffset = rangeStart;   // <-- server-controlled, unbounded
        ...
      }
  ...
  mCacheStream.NotifyDataStarted(mLoadID, startOffset, seekable, length);  // line 274

rangeStart is parsed from the server's Content-Range: bytes START-END/TOTAL header as a raw int64_t. Nothing validates it against IsOffsetAllowed (offset < 2^46). All downstream consumers of mChannelOffset assume this invariant holds — the entire file uses OffsetToBlockIndexUnchecked and OffsetInBlock, which only MOZ_ASSERT the range (debug-only, compiled out in release).

File: dom/media/MediaCache.cpp, line 877-881 — the truncating conversion:

static int32_t OffsetToBlockIndexUnchecked(int64_t aOffset) {
  MOZ_ASSERT(IsOffsetAllowed(aOffset));          // debug-only
  return int32_t(aOffset / MediaCache::BLOCK_SIZE);  // int64 -> int32 truncation
}

With aOffset = 2^47 + 32768, the division yields 2^32 + 1; the int32_t cast truncates to 1.

File: dom/media/MediaCache.cpp, lines 2431-2449 — the broken guard and underflow:

uint32_t MediaCacheStream::ReadPartialBlock(AutoLock&, int64_t aOffset,
                                            Span<char> aBuffer) {
  MOZ_ASSERT(IsOffsetAllowed(aOffset));

  if (OffsetToBlockIndexUnchecked(mChannelOffset) !=   // int32_t(2^32+1) = 1
          OffsetToBlockIndexUnchecked(aOffset) ||       // int32_t(1)      = 1 -> match!
      aOffset >= mChannelOffset) {                      // 65535 < 2^47+32768 -> false
    return 0;
  }
  // Guard bypassed due to aliasing.

  auto source = Span<const uint8_t>(
      mPartialBlockBuffer.get() + OffsetInBlock(aOffset),           // buf + 32767
      OffsetInBlock(mChannelOffset) - OffsetInBlock(aOffset));      // 0 - 32767 = -32767
      //                    ^ (2^47+32768) % 32768 = 0      ^ 65535 % 32768 = 32767
      // -32767 as int32_t is implicitly converted to size_t in Span ctor -> ~18 EB
  uint32_t bytesToRead = std::min(aBuffer.Length(), source.Length());  // min(8, huge) = 8
  memcpy(aBuffer.Elements(), source.Elements(), bytesToRead);
  // memcpy(dst, mPartialBlockBuffer + 32767, 8) -> reads offsets [32767..32774]
  // Buffer is 32768 bytes -> 7 bytes OOB read into heap redzone.
  return bytesToRead;
}

Correct Pattern

// In ChannelMediaResource::OnStartRequest, after line 227:
if (gotRangeHeader) {
  if (rangeStart < 0 ||
      rangeStart >= (int64_t(INT32_MAX) + 1) * MediaCache::BLOCK_SIZE) {
    // Server sent an offset the media cache cannot represent.
    mCacheStream.NotifyDataEnded(mLoadID, NS_ERROR_FAILURE);
    CloseChannel();
    return NS_OK;
  }
  startOffset = rangeStart;
  ...
}

Alternatively (defense-in-depth), clamp the offset in MediaCacheStream::NotifyDataStartedInternal, and/or use OffsetToBlockIndex (the checked variant, line 885) instead of OffsetToBlockIndexUnchecked for mChannelOffset in ReadPartialBlock.

Exploit Chain

  1. Victim loads a page containing <video src="https://attacker.com/x.mp4" preload=auto>. This is a standard, no-privilege web content scenario — the attacker only needs to control an HTTP server referenced by a <video> element.
  2. Firefox opens an HTTP channel to attacker.com. HTMLMediaElement::InitializeDecoderForChannel constructs a ChannelMediaResource, which allocates the 32768-byte mPartialBlockBuffer in MediaCacheStream::MediaCacheStream.
  3. The server responds HTTP/1.1 206 Partial Content with Content-Range: bytes 140737488355328-140737488388095/140737488388096 (start = 2^47) and Content-Type: video/mp4, followed by exactly 32768 bytes containing a minimal fragmented-MP4 init segment (ftyp + moov with mvex/trex) and a free box whose size field is crafted to place the next box header at file offset 65535.
  4. ChannelMediaResource::OnStartRequest calls ParseContentRangeHeader, extracts rangeStart = 2^47, assigns startOffset = rangeStart (line 228), and calls mCacheStream.NotifyDataStarted(mLoadID, 2^47, ...) (line 274). This sets mChannelOffset = 2^47 on the cache thread.
  5. 32768 bytes arrive and are written into the cache at the aliased block index 0 (OffsetToBlockIndexUnchecked(2^47) = int32_t(2^32) = 0). After ingestion, mChannelOffset = 2^47 + 32768.
  6. MP4Demuxer::Init runs on a media supervisor thread, constructs MP4TrackDemuxer, which calls EnsureUpToDateIndex → MoofParser::RebuildFragmentedIndex. This path uses ResourceStream::CachedReadAt → MediaCacheStream::ReadFromCache directly, bypassing the MediaResourceIndex 8192-byte alignment layer that would otherwise mask the odd offset.
  7. The MP4 box parser in Box::Box walks boxes sequentially. The crafted free box (size = 64848) causes Box::Next() to request an 8-byte header read at file offset 65535. aOffset = 65535 is within IsOffsetAllowed range, so the assertion in ReadPartialBlock passes.
  8. ReadFromCache: ReadBlockFromCache for block 1 returns 0 (no cache entry), so it falls through to ReadPartialBlock(lock, 65535, Span{buf, 8}).
  9. In ReadPartialBlock: the guard compares OffsetToBlockIndexUnchecked(2^47+32768) = 1 vs OffsetToBlockIndexUnchecked(65535) = 1 → equal. 65535 >= 2^47+32768 → false. Guard passes.
  10. Span length = OffsetInBlock(2^47+32768) - OffsetInBlock(65535) = 0 - 32767 = -32767 (int32_t) → implicit size_t conversion → 18446744073709518849.
  11. bytesToRead = min(8, 18446744073709518849) = 8. memcpy(dst, mPartialBlockBuffer + 32767, 8) reads 7 bytes past the end of the 32768-byte heap allocation.

Steps to Reproduce

  1. Start a malicious HTTP server on 127.0.0.1:38475 that returns 206 Partial Content with Content-Range: bytes 140737488355328-140737488388095/140737488388096 and a 32768-byte body containing a fragmented-MP4 init segment followed by a free box sized to make the next box header land at offset 65535. The server must stall after sending the body to keep the channel open and mPartialBlockBuffer populated.
  2. Prefs: {"media.autoplay.default": 0, "media.autoplay.blocking_policy": 0, "browser.opaqueResponseBlocking": false, "browser.opaqueResponseBlocking.javascriptValidator": false}. (In a real attack with the video served same-origin, the ORB prefs are unnecessary.)
  3. Load an HTML page containing <video src="http://127.0.0.1:38475/x.mp4" crossorigin="anonymous" preload="auto" autoplay muted>.

Security Impact

Severity: sec-moderate to sec-high (heap buffer over-read).

Attacker capability: A remote web server can read up to BLOCK_SIZE - 1 = 32767 bytes past the end of a 32768-byte heap allocation in the content process. The server controls OffsetInBlock(aOffset) (via the MP4 box layout that steers the demuxer's read offset) and thus controls both the OOB start offset (mPartialBlockBuffer + k for any k in [1, 32767]) and the Span::Length() side of the min(). The destination buffer size (aBuffer.Length()) limits bytesToRead on this particular Box.cpp path to 8 bytes per call, but the parser loops on Box::Next(), allowing repeated 8-byte reads at attacker-chosen intra-block offsets. Other callers of ReadFromCache may supply larger buffers.

The leaked bytes are interpreted as an MP4 box header (4-byte big-endian size + 4-byte FourCC type). If the OOB data forms a plausible box header, parsing continues and the values influence subsequent behavior (next read offset = current + leaked size). This provides a constrained oracle: the attacker can probe heap memory adjacent to mPartialBlockBuffer and infer byte values through timing/error side channels or through which follow-on requests Firefox issues. Combined with heap grooming to place sensitive data (e.g., ASLR pointers) in the 32768-byte size class adjacent slot, this is a viable infoleak primitive for defeating ASLR as part of a larger exploit chain.

Preconditions: Victim visits a page that loads a <video>/<audio> element from an attacker-controlled (or MITM'd / compromised-CDN) HTTP endpoint. No user interaction beyond page load is required (preload="auto" triggers the demuxer automatically).

Suggested Fix

Validate the server-supplied range start against IsOffsetAllowed before accepting it. In ChannelMediaResource::OnStartRequest:

--- a/dom/media/ChannelMediaResource.cpp
+++ b/dom/media/ChannelMediaResource.cpp
@@ -224,6 +224,15 @@ nsresult ChannelMediaResource::OnStartRequest(nsIRequest* aRequest,
       // We received 'Content-Range', so the server accepts range requests.
       bool gotRangeHeader = NS_SUCCEEDED(rv);
 
       if (gotRangeHeader) {
+        // Reject offsets the media cache cannot safely represent. The cache
+        // uses int32_t block indices (BLOCK_SIZE = 32768), so the hard limit
+        // is 2^46 bytes. Offsets at or beyond this cause int32 truncation in
+        // OffsetToBlockIndexUnchecked() and memory-safety violations downstream.
+        if (rangeStart < 0 ||
+            rangeStart >= (int64_t(INT32_MAX) + 1) * MediaCache::BLOCK_SIZE) {
+          mCacheStream.NotifyDataEnded(mLoadID, NS_ERROR_UNEXPECTED);
+          CloseChannel();
+          return NS_OK;
+        }
         startOffset = rangeStart;

Additionally, consider hardening ReadPartialBlock with a runtime (not just MOZ_ASSERT) check on mChannelOffset, since a poisoned mChannelOffset affects many code paths throughout MediaCache.cpp (e.g., NotifyDataReceived at line 2056, GetCachedDataEndInternal at line 2353).

Attached file test.html —
Attached file prefs.json —
Attached file evil_server.py —
Attached file crash_stack.txt —
Attached file REPRODUCTION.md —
Attached file prefs.js —
Group: core-security → media-core-security
Whiteboard: [prefs-checked]

Prefs: supported config. ORB prefs are unneeded when the video is served same-origin (normal attack scenario); preload="auto" triggers demuxer init independently of autoplay policy. sec-moderate looks correct for a content-process over-read with a constrained exfiltration oracle.

Crash reproduced locally (ASAN heap-buffer-overflow READ at MediaCache.cpp:2448). Attached patch validates the server-supplied Content-Range start offset in ChannelMediaResource::OnStartRequest before it reaches the cache. IsOffsetAllowed is hoisted to a public constexpr on MediaCacheStream so there is a single definition of the limit; the file-local helper in MediaCache.cpp delegates to it. Error handling follows the existing NotifyNetworkError + CloseChannel pattern already in that function.

With the patch applied, the evil server delivers the poisoned 206 response (Content-Range: bytes 140737488355328-…) and Firefox cleanly rejects the load — no ASAN report.

This is the analysis tool's suggested fix. Feel welcome to adopt it as a starting point and evolve it as needed to meet our coding standards.

Unable to reproduce bug 2027247 using build mozilla-central 20260328200338-8e941630524a. Without a baseline, bugmon is unable to analyze this bug.
Removing bugmon keyword as no further action possible. Please review the bug and re-add the keyword for further analysis.

Keywords: bugmon
Assignee: nobody → kinetik
Severity: -- → S2
Status: UNCONFIRMED → ASSIGNED
Ever confirmed: true
OS: Unspecified → All
Priority: -- → P2
Hardware: Unspecified → All
Attached file (secure) —
Group: media-core-security → core-security-release
Status: ASSIGNED → RESOLVED
Closed: 7 months ago
Resolution: --- → FIXED
Target Milestone: --- → 152 Branch

Please add uplift requests for beta and ESR140

Attached file (secure) —
Attachment #9572644 - Flags: approval-mozilla-beta?
Attached file (secure) —
Attachment #9572646 - Flags: approval-mozilla-esr140?

Uplifts prepared.

Flags: needinfo?(kinetik)

firefox-beta Uplift Approval Request

  • User impact if declined/Reason for urgency: Potential security issue.
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Simple fix, enforces range limits at appropriate abstraction level.
  • String changes made/needed?: N/A
  • Is Android affected?: yes

firefox-esr140 Uplift Approval Request

  • User impact if declined/Reason for urgency: Potential security issue.
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Simple fix, enforces range limits at appropriate abstraction level.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attachment #9572644 - Flags: approval-mozilla-beta? → approval-mozilla-beta+
Attachment #9572646 - Flags: approval-mozilla-esr140? → approval-mozilla-esr140+
QA Whiteboard: [sec] [qa-triage-done-c152/b151]
Whiteboard: [prefs-checked] → [prefs-checked][adv-main151+r][adv-main151+r][adv-esr115.36+r][adv-esr115.36+r][adv-esr140.11+r][adv-esr140.11+r]
Whiteboard: [prefs-checked][adv-main151+r][adv-main151+r][adv-esr115.36+r][adv-esr115.36+r][adv-esr140.11+r][adv-esr140.11+r] → [prefs-checked][adv-main151+r][adv-esr140.11+r]
Group: core-security-release
Attachment #9570442 - Attachment description: (secure) → Bug 2027247 - Test invalid content-range edge case. r?#media-playback-reviewers
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: