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)
Tracking
()
| 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:
mStoppedistrue(shutdown calledStop()on the listener before the media-threadAllocate/Startcompleted)sHasMainThreadShutdownistrue(set byMediaManager::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
- Web content calls
navigator.mediaDevices.getUserMedia({video: ...})and obtains a videoMediaStreamTrack. - Content rapidly calls
track.clone()in a loop. Each clone →DeviceListener::Clone→MediaEngineRemoteVideoSource::CreateFromallocates a new source on the main thread, then posts an asyncInvokeAsyncto the media thread toAllocate+Initialize(which callsStart→StartCapture). - Content calls
window.close()while cloneInvokeAsynctasks are still in flight. MediaManager::Shutdown()runs on the main thread: callsStop()on all knownDeviceListeners (clone listeners havemAllocated == false, so no deviceStopis dispatched — onlymStopped = trueis set), then setssHasMainThreadShutdown = true, then entersSpinEventLoopUntil.- On the media thread, a pending clone task runs
Allocate→SetTrack→Start→StartCapture, which callsCamerasChild::StartCapture(..., this)→AddCallback(captureId, this)storing the rawFrameRelay*inmCallbacks. Source is nowkStarted; parent process begins pushing frames. - The
InvokeAsyncpromise resolves; the THEN handler is queued on the main thread. SpinEventLoopUntilprocesses the THEN handler.mStopped && !sHasMainThreadShutdown→true && false→Stop/Deallocatenot dispatched.- The THEN lambda destructs, dropping the last
RefPtr<DeviceListener>→~DeviceListener→~DeviceState→~LocalMediaDevice→MediaEngineSource::Release()→ refcount 0 →MediaEngineRemoteVideoSourcefreed. - A
DeliverFrameIPC message arrives on the Cameras IPC thread (T18).RecvDeliverFramelooks up the stream ID inmCallbacks, retrieves the danglingFrameRelay*, and invokescb->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.disabledandmedia.getusermedia.camera.fake.forceprefs 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().
| Reporter | ||
Comment 1•8 months ago
|
||
| Reporter | ||
Comment 2•8 months ago
|
||
| Reporter | ||
Comment 3•8 months ago
|
||
| Reporter | ||
Comment 4•8 months ago
|
||
Updated•8 months ago
|
Updated•8 months ago
|
Updated•8 months ago
|
Updated•8 months ago
|
Comment 6•8 months ago
|
||
Comment 7•8 months ago
|
||
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:
-
MediaManager.cpp (primary fix): when the Clone THEN-handler finds
mStoppedduring shutdown, dispatchStop()/Deallocate()directly tomMediaThreadinstead of skipping it. This follows the existing pattern atMediaManager::Shutdown()line ~3920.TaskQueue::DispatchLockedaccepts dispatches while draining, and the backend-shutdown task queued beforeBeginShutdown()keeps the queue running past the point where these handlers fire. -
MediaEngineRemoteVideoSource destructor (backstop): if
mState == kStartedat destruction, call the newcamera::RemoveCallbackIfExists(mCaptureId)— a mutex-protected list removal, no IPC.mCallbackMutexserializes withRecvDeliverFrame, so if a frame is mid-delivery on the IPC thread, the destructor blocks until it completes (object still fully valid). Lock order matchesGetChildAndCall→StartCapture→AddCallback. This guarantees no UAF even if the task queue is already drained or any future code path drops the ref withoutStop().
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.
| Reporter | ||
Comment 8•8 months ago
|
||
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
Updated•8 months ago
|
| Assignee | ||
Updated•7 months ago
|
Updated•7 months ago
|
Updated•7 months ago
|
Comment 10•7 months ago
|
||
The severity field is not set for this bug.
:jib, could you have a look please?
For more information, please visit BugBot documentation.
| Assignee | ||
Comment 11•7 months ago
|
||
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
| Assignee | ||
Comment 12•7 months ago
|
||
| Assignee | ||
Updated•7 months ago
|
Updated•7 months ago
|
| Assignee | ||
Comment 13•7 months ago
|
||
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
Updated•7 months ago
|
Comment 15•7 months ago
|
||
Comment 16•7 months ago
|
||
Comment 17•7 months ago
|
||
The patch landed in nightly and beta is affected.
:jib, is this bug important enough to require an uplift?
- If yes, please nominate the patch for beta approval.
- See https://wiki.mozilla.org/Release_Management/Requesting_an_Uplift for documentation on how to request an uplift.
- If no, please set
status-firefox151towontfix.
For more information, please visit BugBot documentation.
Comment 18•7 months ago
|
||
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
| Assignee | ||
Comment 19•7 months ago
|
||
Original Revision: https://phabricator.services.mozilla.com/D295365
Updated•7 months ago
|
| Reporter | ||
Comment 20•7 months ago
|
||
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.
Updated•7 months ago
|
Updated•7 months ago
|
Updated•7 months ago
|
Comment 21•7 months ago
|
||
| uplift | ||
Comment 22•7 months ago
|
||
Probably worth a Release uplift request at this point too.
Comment 23•7 months ago
|
||
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
| Assignee | ||
Comment 24•7 months ago
|
||
Original Revision: https://phabricator.services.mozilla.com/D295365
| Assignee | ||
Updated•7 months ago
|
Updated•7 months ago
|
Updated•7 months ago
|
Comment 25•7 months ago
|
||
| 150.0.2 uplift | ||
Updated•7 months ago
|
Updated•7 months ago
|
Updated•3 months ago
|
Description
•