Closed Bug 2049393 Opened 5 months ago Closed 4 months ago

Heap-buffer-overflow write in [@ BufferList::WriteBytes] via Pickle::AlignInt integer wrap

Categories

(Core :: IPC, defect)

defect

Tracking

()

RESOLVED FIXED
154 Branch
Tracking Status
firefox-esr115 --- wontfix
firefox-esr140 154+ fixed
firefox-esr153 154+ fixed
firefox152 --- wontfix
firefox153 --- wontfix
firefox154 + fixed

People

(Reporter: bugmon, Assigned: jld)

Details

(5 keywords, Whiteboard: [adv-main154+r][adv-esr153.1+r][adv-esr140.14+r])

Attachments

(5 files, 3 external files)

Pickle::ConstantAligner::align takes a signed int parameter but is invoked throughout pickle.cc with uint32_t arguments. For inputs in {0xFFFFFFFD, 0xFFFFFFFE, 0xFFFFFFFF} the expression (bytes + (alignment-1)) wraps in unsigned arithmetic to {0,1,2} and the masked result is 0, so AlignInt returns 0 instead of a value ≥ input. This silently defeats the MOZ_RELEASE_ASSERT(new_size >= header_->payload_size) overflow guard in Pickle::BeginWrite.

In Pickle::WriteBytesZeroCopy (the path used by ParamTraits<mozilla::ipc::ByteBuf>::Write), AlignInt(capacity)=0 is passed as the new segment capacity to BufferList::WriteBytesZeroCopy, producing a Segment with mSize=0xFFFFFFFD and mCapacity=0 (the mSize<=mCapacity invariant is only MOZ_ASSERT'd). EndWrite then computes padding = AlignInt(0xFFFFFFFD) - 0xFFFFFFFD = 0 - 0xFFFFFFFD = 3 (uint32 wrap) and BufferList::WriteBytes/AllocateBytes computes remaining capacity as mCapacity - mSize, which underflows size_t to a huge value, returning mData + 0xFFFFFFFD as the write target. memcpy then writes 3 padding bytes one-past-the-end of the honestly-allocated 0xFFFFFFFD-byte buffer. Every subsequent write to the Pickle (the next IPDL parameter or sentinel) lands at mData + 4GiB because the corrupted segment continues to claim near-unbounded remaining capacity.

The sole production caller of Pickle::WriteBytesZeroCopy is ParamTraits<ByteBuf>::Write, which truncates the size_t mCapacity to uint32_t. Any process that serializes a ByteBuf whose capacity (or its low 32 bits) lands in 0xFFFFFFFD..0xFFFFFFFF triggers this overflow in the sending process. ByteBufs of content-influenced size are serialized by WebGPU (WebGPUChild::SendSerializedMessages), CrossProcessPaint recordings, WebRender display-list builders and the MOZ_DEFINE_RUST_PARAMTRAITS macro.

Build Info

Affected Code

File: ipc/chromium/src/base/pickle.h, line 250-261

template <uint32_t alignment>
struct ConstantAligner {
  static uint32_t align(int bytes) {
    static_assert((alignment & (alignment - 1)) == 0,
                  "alignment must be a power of two");
    return (bytes + (alignment - 1)) & ~static_cast<uint32_t>(alignment - 1);
    // bytes is implicitly converted int->uint32_t; for bytes=0xFFFFFFFD,
    // 0xFFFFFFFD + 3 wraps to 0 -> result 0
  }
};
static uint32_t AlignInt(int bytes) {
  return ConstantAligner<sizeof(memberAlignmentType)>::align(bytes);
}

File: ipc/chromium/src/base/pickle.cc, line 356-381

void Pickle::BeginWrite(uint32_t length) {
  uint32_t offset = AlignInt(header_->payload_size);
  uint32_t padding = (header_size_ + offset) % sizeof(memberAlignmentType);
  uint32_t new_size = offset + padding + AlignInt(length);   // AlignInt(0xFFFFFFFD)=0
  MOZ_RELEASE_ASSERT(new_size >= header_->payload_size);     // 4 >= 4 -> passes, guard defeated
  ...
  header_->payload_size = new_size;
}

void Pickle::EndWrite(uint32_t length) {
  uint32_t padding = AlignInt(length) - length;              // 0 - 0xFFFFFFFD -> 3
  WritePadding(buffers_, padding);                           // OOB memcpy
}

File: ipc/chromium/src/base/pickle.cc, line 437-462

bool Pickle::WriteBytesZeroCopy(void* data, uint32_t data_len,
                                uint32_t capacity) {
  BeginWrite(data_len);

  uint32_t new_capacity = AlignInt(capacity);               // 0xFFFFFFFD -> 0
#ifndef MOZ_MEMORY
  if (new_capacity > capacity) {                            // 0 > 0xFFFFFFFD -> false, no realloc
    data = realloc(data, new_capacity);
  }
#endif

  MOZ_ALWAYS_TRUE(buffers_.WriteBytesZeroCopy(reinterpret_cast<char*>(data),
                                              data_len, new_capacity));
  // appends Segment{mData=data, mSize=0xFFFFFFFD, mCapacity=0}
  // (aSize <= aCapacity is only MOZ_ASSERT in BufferList)

  EndWrite(data_len);
  return true;
}

File: mfbt/BufferList.h, line 454-470

char* BufferList<AllocPolicy>::AllocateBytes(size_t aMaxSize, size_t* aSize) {
  ...
  if (!mSegments.empty()) {
    Segment& lastSegment = mSegments.back();

    size_t capacity = lastSegment.mCapacity - lastSegment.mSize;
    // 0 - 0xFFFFFFFD underflows size_t -> ~0xFFFFFFFF00000003
    if (capacity) {
      size_t size = std::min(aMaxSize, capacity);            // = aMaxSize (3)
      char* data = lastSegment.mData + lastSegment.mSize;    // mData + 0xFFFFFFFD (OOB)
      lastSegment.mSize += size;
      mSize += size;
      *aSize = size;
      return data;                                           // -> memcpy writes OOB

File: ipc/glue/ByteBufUtils.h, line 25-38

static void Write(MessageWriter* aWriter, paramType&& aParam) {
  mozilla::CheckedInt<uint32_t> length = aParam.mLen;
  MOZ_RELEASE_ASSERT(length.isValid());
  WriteParam(aWriter, length.value());
  // mCapacity (size_t) silently truncates to uint32_t here
  aWriter->WriteBytesZeroCopy(aParam.mData, length.value(), aParam.mCapacity);
  aParam.mData = nullptr;
  aParam.mCapacity = 0;
  aParam.mLen = 0;
}

AlignInt's signed-int parameter causes a wrap to 0 for inputs ≥ 0xFFFFFFFD. WriteBytesZeroCopy then installs a BufferList segment with mSize > mCapacity, and EndWrite's padding write plus all later WriteBytes calls land out-of-bounds because AllocateBytes underflows mCapacity - mSize.

Exploit Chain

  1. A code path in the sending process constructs a mozilla::ipc::ByteBuf whose mLen == mCapacity is 0xFFFFFFFD, 0xFFFFFFFE or 0xFFFFFFFF (e.g. via ByteBuf::Allocate or the WebGPU/CrossProcessPaint/WebRender ByteBuf constructors with content-influenced size).
  2. The ByteBuf is serialized into an IPC::Message via ParamTraits<ByteBuf>::Write, which calls MessageWriter::WriteBytesZeroCopy(data, len, capacity) with capacity in the wrap window.
  3. Pickle::WriteBytesZeroCopy calls BeginWrite(len): AlignInt(len) wraps to 0 so new_size does not grow and MOZ_RELEASE_ASSERT(new_size >= payload_size) passes — the overflow guard is bypassed.
  4. AlignInt(capacity) also wraps to 0 and is passed as the segment capacity to BufferList::WriteBytesZeroCopy, which appends a Segment with mSize=len (≈4GiB) and mCapacity=0; the mSize<=mCapacity invariant is debug-only.
  5. EndWrite(len) computes padding = AlignInt(len) - len = 0 - len = 3 (uint32 wrap) and calls BufferList::WriteBytes(kBytePaddingData, 3).
  6. BufferList::AllocateBytes underflows mCapacity - mSize to a huge size_t and returns mData + len; memcpy writes 3 bytes of 0xea immediately past the end of the 0xFFFFFFFD-byte allocation (heap-buffer-overflow WRITE).
  7. Every subsequent write to this Pickle (the IPDL sentinel that follows the ByteBuf, the next parameter, the message footer) is placed in the same corrupted segment at mData + 4GiB and beyond, producing additional out-of-bounds writes of partly attacker-influenced data in the sending process's heap.

Steps to Reproduce

  1. Apply the provided patch (adds FuzzingFunctions.testPickleAlignWrap which builds a ByteBuf identical to ByteBuf::Allocate(n) and serializes it via the real ParamTraits<ByteBuf>::Write into a local IPC::Message).
  2. Build Firefox with the ASAN fuzzing mozconfig (--enable-address-sanitizer --enable-fuzzing).
  3. Set pref fuzzing.enabled=true.
  4. Load test.html which calls FuzzingFunctions.testPickleAlignWrap(100) (clean control) then FuzzingFunctions.testPickleAlignWrap(0xFFFFFFFD).
  5. Observe ASAN heap-buffer-overflow WRITE of size 3 in BufferList::WriteBytes ← WritePadding ← Pickle::EndWrite ← Pickle::WriteBytesZeroCopy ← ParamTraits<ByteBuf>::Write.

Security Impact

  • Severity: Moderate
  • Attacker capability: Out-of-bounds heap write in the process serializing the ByteBuf: 3 bytes of fixed padding (0xea) immediately past a ~4GiB allocation, followed by additional out-of-bounds writes of subsequent IPDL fields (sentinels, next parameters, footer) at mData + 4GiB. The corrupted BufferList segment claims effectively unbounded remaining capacity, so all later writes to the message land out-of-bounds. This is a memory-corruption primitive in whichever process performs the send (content for WebGPU/WebRender/CrossProcessPaint).
  • Preconditions: The sending process must construct and serialize a mozilla::ipc::ByteBuf whose mCapacity (truncated to uint32_t) is exactly 0xFFFFFFFD, 0xFFFFFFFE or 0xFFFFFFFF — a 3-byte window at ~4GiB — and the ~4GiB malloc must succeed. No end-to-end web-content trigger producing a ByteBuf of that exact size is demonstrated; the harness exercises the unmodified ParamTraits<ByteBuf>::Write path directly with a validly-allocated ByteBuf (allocation == mLen == mCapacity, identical to ByteBuf::Allocate). Reproduction uses a fuzzing build with fuzzing.enabled=true to expose the FuzzingFunctions hook.

ASAN Report

==26054==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7486c70337fd at pc 0x57ae3c4e947e bp 0x7ffdeaf3ed70 sp 0x7ffdeaf3e530
WRITE of size 3 at 0x7486c70337fd thread T0 (WebCOOP+COEP Co)
    #0 0x57ae3c4e947d in __asan_memcpy _asan_rtl_:3
    #1 0x7486eea61d41 in mozilla::BufferList<InfallibleAllocPolicy>::WriteBytes(char const*, unsigned long) /firefox/obj-firefox-asan/dist/include/mozilla/BufferList.h:446:5
    #2 0x7486eea51e72 in WritePadding(mozilla::BufferList<InfallibleAllocPolicy>&, unsigned int) /firefox/ipc/chromium/src/base/pickle.cc:352:5
    #3 0x7486eea52ef6 in Pickle::EndWrite(unsigned int) /firefox/ipc/chromium/src/base/pickle.cc:380:3
    #4 0x7486eea52ef6 in Pickle::WriteBytesZeroCopy(void*, unsigned int, unsigned int) /firefox/ipc/chromium/src/base/pickle.cc:460:3
    #5 0x7486f21dd3dc in IPC::MessageWriter::WriteBytesZeroCopy(void*, unsigned int, unsigned int) /firefox/ipc/chromium/src/chrome/common/ipc_message_utils.h:112:21
    #6 0x7486f21dd3dc in IPC::ParamTraits<mozilla::ipc::ByteBuf>::Write(IPC::MessageWriter*, mozilla::ipc::ByteBuf&&) /firefox/obj-firefox-asan/dist/include/mozilla/ipc/ByteBufUtils.h:34:14
    #7 0x7486f21dd3dc in void IPC::WriteParam<mozilla::ipc::ByteBuf>(IPC::MessageWriter*, mozilla::ipc::ByteBuf&&) /firefox/ipc/chromium/src/chrome/common/ipc_message_utils.h:477:3
    #8 0x7486f21dd3dc in mozilla::dom::FuzzingFunctions::TestPickleAlignWrap(mozilla::dom::GlobalObject const&, unsigned int) /firefox/dom/base/FuzzingFunctions.cpp:45:3
    #9 0x7486f44ba374 in mozilla::dom::FuzzingFunctions_Binding::testPickleAlignWrap(JSContext*, unsigned int, JS::Value*) /firefox/obj-firefox-asan/dom/bindings/./FuzzingFunctionsBinding.cpp:335:3
    ...

0x7486c70337fd is located 0 bytes after 4294967293-byte region [0x7485c7033800,0x7486c70337fd)
allocated by thread T0 (WebCOOP+COEP Co) here:
    #0 0x57ae3c4eb734 in __interceptor_malloc _asan_rtl_:3
    #1 0x7486f21dd318 in mozilla::dom::FuzzingFunctions::TestPickleAlignWrap(mozilla::dom::GlobalObject const&, unsigned int) /firefox/dom/base/FuzzingFunctions.cpp:34:28

SUMMARY: AddressSanitizer: heap-buffer-overflow (/firefox/obj-firefox-asan/dist/bin/firefox+0x17747d)
==26054==ABORTING
Attached file trace.jsonl —
Attached file test.html —
Attached file prefs.js —
Attached patch fix.patch — — Splinter Review
Attached file crash_stack.txt —
Group: core-security → dom-core-security

In reply to comment #0:

No end-to-end web-content trigger producing a ByteBuf of that exact size is demonstrated

I'm slightly worried that there might be a way to do this that Clauditor didn't spot. It did cite a number of places where ByteBufs of partially-content-controlled size are serialized, and I assume if there was an obvious way to use them to exploit this then it mostly likely would have, but that's no guarantee.

The patch looks reasonable at a glance, although I have to wonder if there are any other related overflows in this code.

The severity field is not set for this bug.
:jld, could you have a look please?

For more information, please visit BugBot documentation.

Flags: needinfo?(jld)

I looked at this a little more. It's a linear overwrite past the end of a 4GB allocation, which should mean that it immediately runs into a guard page (at least with mozjemalloc) and isn't exploitable. That might be enough to demote this further to sec-low (although it seems to have already been reduced one level from sec-high because Clauditor couldn't find a Web API that would expose it to an attacker).

On the other hand, this code worries me a little; the exploit involves integer overflow/underflow or unexpected truncation in several places.

Assignee: nobody → jld
Severity: -- → S3
Flags: needinfo?(jld)
Attached file (secure) —

I don't think any of this is exploitable, but:

  • Add a bunch of overflow checks.
  • Remove a couple of checks that are now superfluous.
  • Widen some arguments to size_t to avoid silent truncation.
Group: dom-core-security → core-security-release
Status: UNCONFIRMED → RESOLVED
Closed: 4 months ago
Resolution: --- → FIXED
Target Milestone: --- → 154 Branch

Please add uplift requests for ESR140 and ESR153

Flags: needinfo?(jld)
QA Whiteboard: [sec] [qa-triage-done-c155/b154]
Attached file (secure) —

I don't think any of this is exploitable, but:

  • Add a bunch of overflow checks.
  • Remove a couple of checks that are now superfluous.
  • Widen some arguments to size_t to avoid silent truncation.

I ran some perf tests on CI and didn't see any obvious regressions.

Original Revision: https://phabricator.services.mozilla.com/D312391

Attachment #9619536 - Flags: approval-mozilla-esr140?

firefox-esr140 Uplift Approval Request

  • User impact if declined/Reason for urgency: While the security impact isn't especially high (I believe that exploitation is blocked by mitigations within the malloc implementation, so I'm not entirely lying in the commit message), the risk is low and I'm a little worried there might be some situation I'm not thinking of where it really would be exploitable.
  • 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: Just adds some bounds/overflow checks and removes some potential integer truncation, i.e. normal operation shouldn't change unless it was already unsafe/wrong; has had time to bake on nightly/beta, and hasn't been flagged for perf regressions as far as I know. The patch appears to crossport cleanly.
  • String changes made/needed?: none
  • Is Android affected?: yes
Attached file (secure) —

I don't think any of this is exploitable, but:

  • Add a bunch of overflow checks.
  • Remove a couple of checks that are now superfluous.
  • Widen some arguments to size_t to avoid silent truncation.

I ran some perf tests on CI and didn't see any obvious regressions.

Original Revision: https://phabricator.services.mozilla.com/D312391

Attachment #9619537 - Flags: approval-mozilla-esr153?

firefox-esr153 Uplift Approval Request

  • User impact if declined/Reason for urgency: While the security impact isn't especially high (I believe that exploitation is blocked by mitigations within the malloc implementation, so I'm not entirely lying in the commit message), the risk is low and I'm a little worried there might be some situation I'm not thinking of where it really would be exploitable.
  • 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: Just adds some bounds/overflow checks and removes some potential integer truncation, i.e. normal operation shouldn't change unless it was already unsafe/wrong; has had time to bake on nightly/beta, and hasn't been flagged for perf regressions as far as I know. The patch appears to crossport cleanly.
  • String changes made/needed?: none
  • Is Android affected?: yes
Attachment #9619537 - Flags: approval-mozilla-esr153? → approval-mozilla-esr153+
Attachment #9619536 - Flags: approval-mozilla-esr140? → approval-mozilla-esr140+
Flags: needinfo?(jld)
Whiteboard: [adv-main154+r][adv-esr53.1+r][adv-esr140.14+r]
Whiteboard: [adv-main154+r][adv-esr53.1+r][adv-esr140.14+r] → [adv-main154+r][adv-esr153.1+r][adv-esr140.14+r]
Group: core-security-release
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: