Closed Bug 2027154 Opened 8 months ago Closed 7 months ago

Heap-use-after-free in [@ camera::CamerasChild::RecvDeliverFrame] via dangling FrameRelay callback when DeviceListener::Clone skips Stop during shutdown

Categories

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

defect

Tracking

()

VERIFIED FIXED
152 Branch
Tracking Status
firefox-esr115 --- unaffected
firefox-esr140 --- unaffected
firefox150 --- fixed
firefox151 + fixed
firefox152 + verified

People

(Reporter: bugmon, Assigned: jib)

References

(Regression)

Details

(7 keywords, Whiteboard: [prefs-checked][bugmon:bisected,confirmed][pp3][adv-main150.0.2+r])

Attachments

(6 files, 3 external files)

Summary

Heap use-after-free in the content process. DeviceListener::Clone's THEN-handler at dom/media/MediaManager.cpp:4556 skips dispatching Stop()/Deallocate() when sHasMainThreadShutdown is true. This leaves the MediaEngineRemoteVideoSource in kStarted state with its raw FrameRelay* pointer still registered in CamerasChild::mCallbacks. When the lambda's captured RefPtrs are destroyed, the source is freed, but a video frame arriving on the Cameras IPC thread dereferences the dangling pointer and performs a virtual call through its freed vtable.

Regression from the fix for Bug 2009260 (commit e49de7d105, landed 2026-03-24), which added && !sHasMainThreadShutdown to avoid a MOZ_CRASH in MediaManager::Dispatch — converting a safe abort into an exploitable UAF.

Affected Code

File: dom/media/MediaManager.cpp, line 4556

->Then(
    GetMainThreadSerialEventTarget(), __func__,
    [listener, device,
     trackSource](GenericPromise::ResolveOrRejectValue&& aValue) {
      if (aValue.IsReject()) {
        ...
        listener->Stop();
        return;
      }
      listener->mDeviceState->mAllocated = true;
      if (listener->mDeviceState->mStopped && !sHasMainThreadShutdown) {  // <-- BUG
        MediaManager::Dispatch(NS_NewRunnableFunction(
            "DeviceListener::Clone::Stop",
            [device = listener->mDeviceState->mDevice]() {
              device->Stop();
              device->Deallocate();
            }));
      }
    });

When this handler runs during MediaManager::Shutdown()'s SpinEventLoopUntil:

  • mStopped is true (shutdown called Stop() on the listener before the media-thread Allocate/Start completed)
  • sHasMainThreadShutdown is true (set by MediaManager::Shutdown())
  • The condition evaluates to true && !true → false → Stop()/Deallocate() are never dispatched

The lambda then destructs, releasing the last RefPtr references to the DeviceListener → DeviceState → LocalMediaDevice → MediaEngineRemoteVideoSource. The source is freed with mState == kStarted and its raw this pointer still in CamerasChild::mCallbacks (added by StartCapture → CamerasChild::AddCallback). Only Stop() → StopCapture → RemoveCallback removes it — and that path was skipped.

File: dom/media/systemservices/CamerasChild.cpp, line 515

mozilla::ipc::IPCResult CamerasChild::RecvDeliverFrame(
    const int& aCaptureId, nsTArray<int>&& aStreamIds,
    mozilla::ipc::Shmem&& aShmem, const VideoFrameProperties& aProps) {
  MutexAutoLock lock(mCallbackMutex);
  for (const int& streamId : aStreamIds) {
    if (auto* cb = Callback(streamId)) {
      unsigned char* image = aShmem.get<unsigned char>();
      cb->DeliverFrame(image, aProps);   // <-- UAF: virtual call via freed vtable
    }
    ...

cb is a raw FrameRelay* retrieved from mCallbacks. DeliverFrame is virtual. The 8-byte read at offset 16 in the freed 1592-byte allocation is the FrameRelay subobject's vtable pointer (second base in class MediaEngineRemoteVideoSource : public MediaEngineSource, public camera::FrameRelay).

Correct Pattern

listener->mDeviceState->mAllocated = true;
if (listener->mDeviceState->mStopped) {
  // Device was started on the media thread but the listener was stopped
  // (e.g. by shutdown) before we got here. We MUST call Stop/Deallocate
  // to remove the raw FrameRelay* from CamerasChild::mCallbacks, even if
  // MediaManager is shutting down. Dispatch directly to the media task
  // queue to avoid MediaManager::Dispatch's shutdown MOZ_CRASH.
  RefPtr<LocalMediaDevice> dev = listener->mDeviceState->mDevice;
  if (sHasMainThreadShutdown) {
    if (nsCOMPtr<nsISerialEventTarget> mediaThread =
            MediaManager::GetMessageLoop()) {
      mediaThread->Dispatch(NS_NewRunnableFunction(
          "DeviceListener::Clone::StopShutdown",
          [dev]() { dev->Stop(); dev->Deallocate(); }));
    }
  } else {
    MediaManager::Dispatch(NS_NewRunnableFunction(
        "DeviceListener::Clone::Stop",
        [dev]() { dev->Stop(); dev->Deallocate(); }));
  }
}

Alternatively, ~MediaEngineRemoteVideoSource should defensively call CamerasChild::RemoveCallback if mState == kStarted, or CamerasChild should hold weak/refcounted references instead of raw pointers.

Exploit Chain

  1. Web content calls navigator.mediaDevices.getUserMedia({video: ...}) and obtains a video MediaStreamTrack.
  2. Content rapidly calls track.clone() in a loop. Each clone → DeviceListener::Clone → MediaEngineRemoteVideoSource::CreateFrom allocates a new source on the main thread, then posts an async InvokeAsync to the media thread to Allocate + Initialize (which calls Start → StartCapture).
  3. Content calls window.close() while clone InvokeAsync tasks are still in flight.
  4. MediaManager::Shutdown() runs on the main thread: calls Stop() on all known DeviceListeners (clone listeners have mAllocated == false, so no device Stop is dispatched — only mStopped = true is set), then sets sHasMainThreadShutdown = true, then enters SpinEventLoopUntil.
  5. On the media thread, a pending clone task runs Allocate → SetTrack → Start → StartCapture, which calls CamerasChild::StartCapture(..., this) → AddCallback(captureId, this) storing the raw FrameRelay* in mCallbacks. Source is now kStarted; parent process begins pushing frames.
  6. The InvokeAsync promise resolves; the THEN handler is queued on the main thread.
  7. SpinEventLoopUntil processes the THEN handler. mStopped && !sHasMainThreadShutdown → true && false → Stop/Deallocate not dispatched.
  8. The THEN lambda destructs, dropping the last RefPtr<DeviceListener> → ~DeviceListener → ~DeviceState → ~LocalMediaDevice → MediaEngineSource::Release() → refcount 0 → MediaEngineRemoteVideoSource freed.
  9. A DeliverFrame IPC message arrives on the Cameras IPC thread (T18). RecvDeliverFrame looks up the stream ID in mCallbacks, retrieves the dangling FrameRelay*, and invokes cb->DeliverFrame(image, aProps) — virtual call through freed vtable. UAF.

Steps to Reproduce

Set the following prefs (enables fake camera backend and bypasses the permission prompt):

{
  "media.getusermedia.camera.fake.force": true,
  "media.navigator.permission.disabled": true,
  "media.navigator.streams.fake": false
}

Load the testcase. This is a shutdown race; the testcase creates 300 clones and calls window.close() to maximize the window. In testing it reproduced on the first attempt, but may occasionally require a few runs.

Security Impact

Severity: High (sec-high)

Attacker capability: Use-after-free with virtual-call dispatch through a freed vtable pointer, triggerable from unprivileged web content in the content process. If the attacker can reallocate the freed 1592-byte heap slot with controlled data between step 8 and step 9 (the IPC thread is racing the main thread, giving a spray window), they control the vtable pointer and achieve arbitrary code execution in the content process.

Preconditions:

  • Camera permission must be granted (or use the fake camera backend). The media.navigator.permission.disabled and media.getusermedia.camera.fake.force prefs used in the testcase simulate a user who has granted camera access. On a real system, the user must accept the camera permission prompt once.
  • No other configuration or user interaction required beyond loading the page.

Fresh regression: Introduced by commit e49de7d105 landed 2026-03-24.

Suggested Fix

The Stop()/Deallocate() call is load-bearing for memory safety — it is the only path that calls CamerasChild::RemoveCallback. It cannot be skipped just because MediaManager::Dispatch would MOZ_CRASH. Two options:

Option A (targeted): Dispatch directly to the media task queue when sHasMainThreadShutdown is set, bypassing MediaManager::Dispatch's shutdown check. MediaManager::Shutdown() already joins on the media task queue via mMediaThread->BeginShutdown(), so this is safe to dispatch into.

Option B (defense-in-depth): Make ~MediaEngineRemoteVideoSource call camera::GetChildAndCall(&CamerasChild::StopCapture, mCapEngine, mCaptureId) if mState == kStarted. This ensures the raw callback is always removed before the object is freed, regardless of whether the caller properly called Stop().

// In MediaEngineRemoteVideoSource.cpp, ~MediaEngineRemoteVideoSource():
MediaEngineRemoteVideoSource::~MediaEngineRemoteVideoSource() {
  if (mState == kStarted) {
    // Defensive: ensure our raw FrameRelay* is removed from
    // CamerasChild::mCallbacks even if Stop() was never called.
    // This prevents UAF in RecvDeliverFrame.
    camera::GetChildAndCall(&camera::CamerasChild::StopCapture,
                            mCapEngine, mCaptureId);
  }
  mFirstFramePromiseHolder.RejectIfExists(NS_ERROR_ABORT, __func__);
}

Option B is preferable as it also protects against any other future path that might drop the last reference without calling Stop().

Attached file test.html —
Attached file prefs.json —
Attached file crash_stack.txt —
Attached file prefs.js —
Group: core-security → dom-core-security
Component: General → Audio/Video
Component: Audio/Video → WebRTC: Audio/Video
Whiteboard: [prefs-checked]

Prefs: supported configuration. media.navigator.permission.disabled + media.getusermedia.camera.fake.force just simulate a user with a webcam who clicked Allow on the standard camera prompt — the crashing code is the production MediaEngineRemoteVideoSource/CamerasChild pipeline used with real hardware. media.navigator.streams.fake=false is already the default.

sec-high is correct — heap UAF with virtual dispatch through a freed vtable pointer, triggered from web content with a normal browsing precondition.

Patch: reproduced 1/1 on ASAN trunk; 0/3 crashes after fix. Two parts:

  1. MediaManager.cpp (primary fix): when the Clone THEN-handler finds mStopped during shutdown, dispatch Stop()/Deallocate() directly to mMediaThread instead of skipping it. This follows the existing pattern at MediaManager::Shutdown() line ~3920. TaskQueue::DispatchLocked accepts dispatches while draining, and the backend-shutdown task queued before BeginShutdown() keeps the queue running past the point where these handlers fire.

  2. MediaEngineRemoteVideoSource destructor (backstop): if mState == kStarted at destruction, call the new camera::RemoveCallbackIfExists(mCaptureId) — a mutex-protected list removal, no IPC. mCallbackMutex serializes with RecvDeliverFrame, so if a frame is mid-delivery on the IPC thread, the destructor blocks until it completes (object still fully valid). Lock order matches GetChildAndCall→StartCapture→AddCallback. This guarantees no UAF even if the task queue is already drained or any future code path drops the ref without Stop().

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.

Verified bug as reproducible on mozilla-central 20260329205327-086d14f42154.
The bug appears to have been introduced in the following build range:

Start: c65d5e2208afa704c3da0803bdb5250247dd603d (20250928173911)
End: c65d5e2208afa704c3da0803bdb5250247dd603d (20250928211743)
Pushlog: https://hg.mozilla.org/integration/autoland/pushloghtml?fromchange=c65d5e2208afa704c3da0803bdb5250247dd603d&tochange=c65d5e2208afa704c3da0803bdb5250247dd603d

Keywords: regression
Whiteboard: [prefs-checked] → [prefs-checked][bugmon:bisected,confirmed]
Whiteboard: [prefs-checked][bugmon:bisected,confirmed] → [prefs-checked][bugmon:bisected,confirmed][pp3]
Assignee: nobody → jib
Group: dom-core-security → media-core-security
Status: UNCONFIRMED → NEW
Ever confirmed: true

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

For more information, please visit BugBot documentation.

Flags: needinfo?(jib)
Attached file test_v2.html —

I was unable to reproduce on my mac using the original POC, but with this version which 10x-es the loops, it reproduces reliably for me.

Also, JS can only window.close() windows it has opened, so running the bugzilla attachment won't close the content process, so I used a https://jan-ivar.github.io/dummy/opener.html helper to open localhost:8000/test.html

Flags: needinfo?(jib)
Attached file (secure) —
Regressed by: 2009260

Comment on attachment 9571757 [details]
(secure)

Security Approval Request

  • How easily could an exploit be constructed based on the patch?: Not easily
  • Do comments in the patch, the check-in comment, or tests included in the patch paint a bulls-eye on the security problem?: No
  • Which branches (beta, release, and/or ESR) are affected by this flaw, and do the release status flags reflect this affected/unaffected state correctly?: beta, release, yes
  • If not all supported branches, which bug introduced the flaw?: Bug 2009260
  • Do you have backports for the affected branches?: No
  • If not, how different, hard to create, and risky will they be?: trivial
  • How likely is this patch to cause regressions; how much testing does it need?: Regression unlikely (and isolated to shutdown path). Tested locally.
  • Is the patch ready to land after security approval is given?: Yes
  • Is Android affected?: Yes
Attachment #9571757 - Flags: sec-approval?
Duplicate of this bug: 2033497
Attachment #9571757 - Flags: sec-approval? → sec-approval+
Group: media-core-security → core-security-release
Status: NEW → RESOLVED
Closed: 7 months ago
Resolution: --- → FIXED
Target Milestone: --- → 152 Branch

The patch landed in nightly and beta is affected.
:jib, is this bug important enough to require an uplift?

For more information, please visit BugBot documentation.

Flags: needinfo?(jib)

firefox-beta Uplift Approval Request

  • User impact if declined/Reason for urgency: sec-high - uaf read in content process behind camera permission
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing: verified locally per comment 11
  • Risk associated with taking this patch: low
  • Explanation of risk level: modifications are contained to active camera cleanup in content process shutdown path
  • String changes made/needed?: none
  • Is Android affected?: yes
Attachment #9572956 - Flags: approval-mozilla-beta?

Verified bug as fixed on rev mozilla-central 20260423082823-2a5398c41a2c.
Removing bugmon keyword as no further action possible. Please review the bug and re-add the keyword for further analysis.

Status: RESOLVED → VERIFIED
Keywords: bugmon
Flags: needinfo?(jib)
Attachment #9572956 - Flags: approval-mozilla-beta? → approval-mozilla-beta+

Probably worth a Release uplift request at this point too.

Flags: needinfo?(jib)

firefox-release Uplift Approval Request

  • User impact if declined/Reason for urgency: sec-high - uaf read in content process behind camera permission
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing: verified locally per comment 11
  • Risk associated with taking this patch: low
  • Explanation of risk level: modifications are contained to active camera cleanup in content process shutdown path
  • String changes made/needed?: none
  • Is Android affected?: yes
Attachment #9575097 - Flags: approval-mozilla-release?
Flags: needinfo?(jib)
Attachment #9575097 - Flags: approval-mozilla-release? → approval-mozilla-release+
Whiteboard: [prefs-checked][bugmon:bisected,confirmed][pp3] → [prefs-checked][bugmon:bisected,confirmed][pp3][adv-main150.0.2+r]
QA Whiteboard: [sec] [qa-triage-done-c152/b151]
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: