Closed Bug 2025940 Opened 8 months ago Closed 7 months ago

Heap-use-after-free in [@ CanonicalQuotaObject::LockedMaybeUpdateSize] via self-eviction of OriginInfo under quota pressure

Categories

(Core :: Storage: Quota Manager, defect)

defect

Tracking

()

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

People

(Reporter: bugmon, Assigned: hsingh)

Details

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

Attachments

(4 files, 3 external files)

Summary

Heap-use-after-free in the Firefox parent process. When an IndexedDB write exceeds the temporary storage limit, CanonicalQuotaObject::LockedMaybeUpdateSize triggers origin eviction. If the eviction selects the currently writing origin, LockedRemoveQuotaForOrigin frees the OriginInfo at GroupInfo::LockedRemoveOriginInfo, while CanonicalQuotaObject::mOriginInfo still holds a raw pointer to it. The freed pointer is immediately dereferenced at line 211. The only guard against self-deletion is a MOZ_ASSERT that is compiled out in release builds.

Affected Code

File: dom/quota/CanonicalQuotaObject.cpp, lines 197–211

for (const auto& lock : locks) {
  MOZ_ASSERT(!(lock->GetPersistenceType() == groupInfo->mPersistenceType &&
               lock->Origin() == mOriginInfo->mOrigin),
             "Deleted itself!");                          // DEBUG-only!

  quotaManager->LockedRemoveQuotaForOrigin(lock->OriginMetadata());  // <-- FREE
}

// We unlocked and relocked several times so we need to recompute all the
// essential variables and recheck the group limit.

AssertNoUnderflow(aSize, mSize);
const uint64_t increase = aSize - mSize;

if (!mOriginInfo->LockedUpdateUsagesForEviction(mClientType, increase)) {  // <-- USE

File: dom/quota/CanonicalQuotaObject.h, line 79

OriginInfo* mOriginInfo;   // Raw pointer — no strong reference

File: dom/quota/GroupInfo.cpp, line 75 — where the free occurs

mOriginInfos.RemoveElementAt(foundIt);  // Drops last RefPtr → OriginInfo destroyed

The DirectoryLock check in QuotaManager::CollectOriginsForEviction is supposed to exclude origins with active locks, but it fails when the OriginScope of the lock held during OpenDatabaseOp::DoDatabaseWork does not match the origin being written via the SQLite VFS layer. The MOZ_ASSERT(!originInfo->mCanonicalQuotaObjects.Count()) at line 2121 would catch this — but it too is DEBUG-only.

Correct Pattern

// Option 1: Hold a strong reference before eviction
RefPtr<OriginInfo> pinnedOriginInfo = mOriginInfo;
for (const auto& lock : locks) {
  quotaManager->LockedRemoveQuotaForOrigin(lock->OriginMetadata());
}
// pinnedOriginInfo keeps the object alive even if removed from mOriginInfos

// Option 2: Skip self-eviction at runtime (not just in MOZ_ASSERT)
for (const auto& lock : locks) {
  if (lock->GetPersistenceType() == mOriginInfo->mGroupInfo->mPersistenceType &&
      lock->Origin() == mOriginInfo->mOrigin) {
    continue;  // Never evict ourselves
  }
  quotaManager->LockedRemoveQuotaForOrigin(lock->OriginMetadata());
}

Exploit Chain

  1. Web content opens many IndexedDB databases in rapid succession and writes blobs to each (indexedDB.open() + store.put(blob, key)).
  2. Content process sends PBackgroundIDBFactory::OpenDatabase IPC to the parent.
  3. Parent's OpenDatabaseOp::DoDatabaseWork runs on the QuotaManager IO thread and calls CreateStorageConnection, which commits a SQLite transaction.
  4. SQLite's WAL write invokes QuotaWrite → CanonicalQuotaObject::MaybeUpdateSize → LockedMaybeUpdateSize.
  5. The 500 KB temporary-storage limit is exceeded. LockedCollectOriginsForEviction dispatches to PBackground, which runs CollectOriginsForEviction.
  6. The DirectoryLock scope check at ActorsParent.cpp:2114 fails to protect the current origin; it is selected for eviction.
  7. Back on the IO thread, the eviction loop calls LockedRemoveQuotaForOrigin for each origin. One of them is this origin.
  8. GroupInfo::LockedRemoveOriginInfo removes the last RefPtr<OriginInfo> from mOriginInfos → OriginInfo freed.
  9. Line 211 dereferences mOriginInfo (dangling raw pointer) → UAF.
  10. OriginInfo::LockedUpdateUsagesForEviction reads mUsage, mClientUsages, and dereferences mGroupInfo (a pointer inside freed memory), then writes to mClientUsages, mUsage, and mGroupInfo->mUsage — all inside or through freed memory.

IPC Path

  • Protocol: PBackgroundIDBFactory / PBackgroundIDBFactoryRequest
  • Child → Parent: PBackgroundIDBFactory::OpenDatabase — standard, unmodified IndexedDB API call from untrusted web content.
  • Parent handler: mozilla::dom::indexedDB::OpenDatabaseOp::DoDatabaseWork on the QuotaManager IO thread.
  • No compromised child or IPC fuzzing is required — this is reachable from vanilla JavaScript.

Steps to Reproduce

  1. Set pref dom.quotaManager.temporaryStorage.fixedLimit = 500 (simulates a nearly-full disk; in the wild this condition occurs naturally when free disk space is low).
  2. Load the testcase HTML, which rapidly opens ~30 IndexedDB databases per iteration and writes 50 KB blobs to each.
  3. Parent process crashes within ~10 seconds.

Security Impact

Severity: High (sec-high)

  • Process: Parent (chrome-privileged) — direct sandbox escape primitive.
  • Trigger: Pure web content via the standard IndexedDB API. No user interaction, no compromised renderer, no IPC fuzzing.
  • Primitive: UAF with both read and write. LockedUpdateUsagesForEviction reads pointer fields (mGroupInfo, mGroupInfo->mGroupInfoPair) from the freed 200-byte chunk and writes through them (mGroupInfo->mUsage = newGroupUsage). If an attacker reclaims the freed slot with controlled data, this becomes an arbitrary-address write in the parent process.
  • Determinism: Single-threaded — both free and use occur on the same thread (QuotaManager IO) inside the same call frame. Not a race.
  • Precondition: Low temporary-storage limit. Occurs naturally on machines with low free disk space, and can be forced via the dom.quotaManager.temporaryStorage.fixedLimit pref in testing.

ASAN Report

==558974==ERROR: AddressSanitizer: heap-use-after-free on address 0x7c7e4c065b00 at pc 0x7b6e2b6ccc00 bp 0x7b6ddafaa050 sp 0x7b6ddafaa048
READ of size 8 at 0x7c7e4c065b00 thread T39
    #0 0x7b6e2b6ccbff in mozilla::dom::quota::OriginInfo::LockedUpdateUsagesForEviction(mozilla::dom::quota::Client::Type, unsigned long) /firefox/dom/quota/OriginInfo.cpp:279:23
    #1 0x7b6e2b64ddf9 in mozilla::dom::quota::CanonicalQuotaObject::LockedMaybeUpdateSize(long, bool) /firefox/dom/quota/CanonicalQuotaObject.cpp:211:21
    #2 0x7b6e2b64d654 in mozilla::dom::quota::CanonicalQuotaObject::MaybeUpdateSize(long, bool) /firefox/dom/quota/CanonicalQuotaObject.cpp:72:10
    #3 0x7b6e2250baff in (anonymous namespace)::QuotaWrite(sqlite3_file*, void const*, int, long long) /firefox/storage/QuotaVFS.cpp:125:26
    #4 0x7b6e47088d0f in walWriteOneFrame /firefox/third_party/sqlite3/src/sqlite3.c:70724:8
    ...
    #22 0x7b6e2bbed4e3 in mozilla::dom::indexedDB::(anonymous namespace)::OpenDatabaseOp::DoDatabaseWork() /firefox/dom/indexedDB/ActorsParent.cpp:15533:3
    #23 0x7b6e2bbe00e3 in mozilla::dom::indexedDB::(anonymous namespace)::FactoryOp::Run() /firefox/dom/indexedDB/ActorsParent.cpp:15308:7

0x7c7e4c065b00 is located 192 bytes inside of 200-byte region [0x7c7e4c065a40,0x7c7e4c065b08)
freed by thread T39 here:
    #0 0x572add4d86f6 in __interceptor_free _asan_rtl_:3
    ...
    #14 0x7b6e2b6c5db2 in mozilla::dom::quota::GroupInfo::LockedRemoveOriginInfo(nsTSubstring<char> const&) /firefox/dom/quota/GroupInfo.cpp:75:18
    #15 0x7b6e2b6429aa in mozilla::dom::quota::QuotaManager::LockedRemoveQuotaForOrigin(mozilla::dom::quota::OriginMetadata const&) /firefox/dom/quota/ActorsParent.cpp:7893:16
    #16 0x7b6e2b64dd33 in mozilla::dom::quota::CanonicalQuotaObject::LockedMaybeUpdateSize(long, bool) /firefox/dom/quota/CanonicalQuotaObject.cpp:202:19
    #17 0x7b6e2b64d654 in mozilla::dom::quota::CanonicalQuotaObject::MaybeUpdateSize(long, bool) /firefox/dom/quota/CanonicalQuotaObject.cpp:72:10
    #18 0x7b6e2250baff in (anonymous namespace)::QuotaWrite(sqlite3_file*, void const*, int, long long) /firefox/storage/QuotaVFS.cpp:125:26
    ...
    #37 0x7b6e2bbed4e3 in mozilla::dom::indexedDB::(anonymous namespace)::OpenDatabaseOp::DoDatabaseWork() /firefox/dom/indexedDB/ActorsParent.cpp:15533:3

previously allocated by thread T39 here:
    ...
    #4 0x7b6e2b5e1bc4 in mozilla::dom::quota::QuotaManager::InitQuotaForOrigin(mozilla::dom::quota::FullOriginMetadata const&, bool) /firefox/dom/quota/ActorsParent.cpp:2656:34
    ...
    #12 0x7b6e2b629695 in mozilla::dom::quota::QuotaManager::EnsureTemporaryOriginIsInitializedInternal(mozilla::dom::quota::OriginMetadata const&, bool) /firefox/dom/quota/ActorsParent.cpp:6624:10

SUMMARY: AddressSanitizer: heap-use-after-free (/firefox/obj-x86_64-pc-linux-gnu/dist/bin/libxul.so+0x1de9dbff)

Suggested Fix

Two complementary fixes are recommended:

1. Pin the OriginInfo with a strong reference before the eviction loop in CanonicalQuotaObject::LockedMaybeUpdateSize:

// Hold a strong ref so eviction cannot destroy our OriginInfo mid-flight.
RefPtr<OriginInfo> kungFuDeathGrip = mOriginInfo;

for (const auto& lock : locks) {
  // Promote the DEBUG-only assert to a runtime skip:
  if (lock->GetPersistenceType() ==
          kungFuDeathGrip->mGroupInfo->mPersistenceType &&
      lock->Origin() == kungFuDeathGrip->mOrigin) {
    NS_WARNING("Attempted to evict the origin currently being written");
    continue;
  }
  quotaManager->LockedRemoveQuotaForOrigin(lock->OriginMetadata());
}

2. Fix the root cause in CollectOriginsForEviction — promote the DEBUG-only assertion at ActorsParent.cpp:2121 to a runtime check so that origins with live CanonicalQuotaObjects are never selected for eviction:

if (!match) {
  if (originInfo->mCanonicalQuotaObjects.Count()) {
    // Origin has open files — must not be evicted.
    continue;
  }
  aInactiveOriginInfos.InsertElementSorted(
      originInfo, OriginInfoAccessTimeComparator());
}
Attached file Crash stack trace —
Attached file Testcase: test.html —
Group: core-security → dom-core-security

Unable to reproduce bug 2025940 using build mozilla-central 20260324214622-1f2552c4d19d. 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

Root cause

mDirectoryLocks is PBackground-thread-only and not protected by mQuotaMutex (QuotaManager.h:1111). LockedCollectOriginsForEviction drops the mutex and dispatches CollectOriginsHelper to the tail of the PBackground event queue (NS_DISPATCH_NORMAL, ActorsParent.cpp:7853). Any UnregisterDirectoryLock already queued runs first and removes the writing origin's lock from mDirectoryLocks before CollectOriginsForEviction snapshots it. The match check returns false, and the only remaining guard — MOZ_ASSERT(!originInfo->mCanonicalQuotaObjects.Count()) — is compiled out in release.

Back on the IO thread, LockedRemoveQuotaForOrigin drops the last RefPtr<OriginInfo> in GroupInfo::mOriginInfos, freeing the object that CanonicalQuotaObject::mOriginInfo (raw pointer) still points to. Next line dereferences it.

Fix

  1. ActorsParent.cpp — promote the debug-only assert to a runtime continue. Safe: GetInactiveOriginInfos runs under mQuotaMutex (line 2164), and mCanonicalQuotaObjects is only mutated under that same mutex.
  2. CanonicalQuotaObject.cpp — defense in depth: pin OriginInfo with a stack RefPtr before the first mutex drop, capture persistence type + origin string while still valid, and skip self in both eviction loops (DeleteOriginDirectory and LockedRemoveQuotaForOrigin). Keeps MOZ_ASSERT_UNREACHABLE so regressions surface in debug.

Reproduction

Couldn't reproduce locally (nor could bugmon, comment 5) — the race depends on PBackground event queue ordering. The code path is unambiguous from the ASAN trace though: free and use are both on T39, same call frame, at the exact lines patched.

Builds clean on ASAN, original testcase runs without regression.

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.

The trigger example involves a testing prefererence, and the window between the use and the free is limited it sounds like, so I'm going to reduce this to sec-moderate. It would still be good to fix if it isn't too tricky.

Severity: -- → S3
Keywords: sec-high → sec-moderate
Status: UNCONFIRMED → NEW
Ever confirmed: true
Assignee: nobody → hsingh
Status: NEW → ASSIGNED
Attached file (secure) —
Pushed by hsingh@mozilla.com: https://github.com/mozilla-firefox/firefox/commit/df676c60d753 https://hg.mozilla.org/integration/autoland/rev/dd1925e2f74b skip selecting current origin for eviction under storage pressure.r=dom-storage-reviewers,asuth

https://hg-edge.mozilla.org/mozilla-central/rev/dd1925e2f74b

Please add Beta and ESR140 uplift requests for this when you get a chance.

Group: dom-core-security → core-security-release
Status: ASSIGNED → RESOLVED
Closed: 7 months ago
Flags: needinfo?(hsingh)
Resolution: --- → FIXED
Target Milestone: --- → 152 Branch

firefox-beta Uplift Approval Request

  • User impact if declined/Reason for urgency: As explained in the bug, if we dont' make the fix, firefox parent process could lead to UAF and observe unknown side-effects.
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing: NA
  • Risk associated with taking this patch: low
  • Explanation of risk level: Low risk to cherry-pick this patch to upstream branches.
  • String changes made/needed?: NA
  • Is Android affected?: yes
Attachment #9575684 - Flags: approval-mozilla-beta?
Attached file (secure) —

firefox-esr140 Uplift Approval Request

  • User impact if declined/Reason for urgency: As explained in the bug, if we dont' make the fix, firefox parent process could lead to UAF and observe unknown side-effects.
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: yes
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing: NA
  • Risk associated with taking this patch: low
  • Explanation of risk level: Low risk to cherry-pick this patch to upstream branches.
  • String changes made/needed?: NA
  • Is Android affected?: yes
Attachment #9575685 - Flags: approval-mozilla-esr140?
Attached file (secure) —
Attachment #9575684 - Flags: approval-mozilla-beta? → approval-mozilla-beta+
Attachment #9575685 - Flags: approval-mozilla-esr140? → approval-mozilla-esr140+
QA Whiteboard: [sec] [uplift] [qa-triage-done-c152/b151]
Flags: needinfo?(hsingh)
Whiteboard: [adv-main151+r][adv-main151+r][adv-esr115.36+r][adv-esr115.36+r][adv-esr140.11+r][adv-esr140.11+r]
Whiteboard: [adv-main151+r][adv-main151+r][adv-esr115.36+r][adv-esr115.36+r][adv-esr140.11+r][adv-esr140.11+r] → [adv-main151+r][adv-esr140.11+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: