Closed Bug 2058615 Opened 3 months ago Closed 3 months ago

Type confusion in [@ JS::FinishLoadingImportedModuleFailed] via doubly-delivered LoadRequestedModules rejection callback in ModuleLoaderBase

Categories

(Core :: JavaScript Engine, defect, P1)

defect

Tracking

()

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

People

(Reporter: bugmon, Assigned: allstars.chh)

References

(Blocks 2 open bugs)

Details

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

Attachments

(5 files, 4 external files, 2 obsolete files)

The module loader's rejection callback for JS::LoadRequestedModules can be delivered twice for the same dynamic-import ModuleLoadRequest, and the second delivery dereferences an undefined JS::Value as a JSObject*.

When js::LoadRequestedModules fails by returning false (here: AutoCheckRecursionLimit failure at js/src/vm/Modules.cpp:1616 during a nested InnerModuleLoading descent over previously recorded [[LoadedModules]] edges, which no host frame absorbs), ModuleLoaderBase::StartFetchingModuleDependencies invokes the rejection handler directly as a fallback (ModuleLoaderBase.cpp:1385). This consumes the single AddRef taken at line 1335 and rejects the dynamic-import promise, but never deactivates the engine-side GraphLoadingStateRecordObject: its isLoading flag stays true and it stays alive as the payload of a sibling dependency request parked in a pending fetch's mWaiting list. The first rejection then runs ModuleErrored -> LoadFinished -> ProcessDynamicImport, whose guard checks only IsErrored() (ModuleLoadRequest.cpp:71-73) and not mErroredLoadingImports (set at ModuleLoadRequest.h:112-116, read only in an assert at ModuleLoadRequest.cpp:152), so FinishLoadingImportedModule runs a second time and its trailing ClearImport() (ModuleLoaderBase.cpp:333, ModuleLoadRequest.cpp:184-188) sets the request's mPayload to UndefinedValue.

When the still-pending sibling fetch later fails, OnFetchFailed (ModuleLoaderBase.cpp:892) calls JS::FinishLoadingImportedModuleFailedWithPendingException on the live state object; ContinueModuleLoading sees isLoading == true (Modules.cpp:1735) and synchronously invokes the rejected callback again for the already-finished request (workers use the synchronous callback variant of LoadRequestedModules, ModuleLoaderBase.cpp:1377-1380). OnLoadRequestedModulesRejected (ModuleLoaderBase.cpp:1461-1463) passes the now-undefined mPayload to JS::FinishLoadingImportedModuleFailed, which executes &payloadArg.toObject() (Modules.cpp:183) with no runtime type check in release builds; XOR-unboxing the undefined tag yields a wild pointer and the subsequent object-header read faults at 0x0007800000000000. The same double delivery also receives the request via a non-owning PrivateValue raw pointer (ModuleLoaderBase.cpp:1437-1438) whose balancing strong reference was already released, and ends with a second aRequest->Release() (ModuleLoaderBase.cpp:1496), i.e. a reference-count underflow on the same path. The trigger is pure web content (a dedicated worker doing dynamic imports of blob and cross-origin HTTP module URLs) with no prefs and no source modifications.

Build Info

Affected Code

File: js/loader/ModuleLoaderBase.cpp, line 1333-1386

  // Wrap the request into a JS::Value, and AddRef() it.
  // The Release() will be called in the resolved/rejected handlers.
  Rooted<Value> hostDefinedVal(cx, PrivateValue(aRequest));
  aRequest->AddRef();
  ...
  } else {
    result = LoadRequestedModules(cx, module, hostDefinedVal,
                                  OnLoadRequestedModulesResolved,
                                  OnLoadRequestedModulesRejected);
  }

  if (!result) {
    LOG(("ScriptLoadRequest (%p): LoadRequestedModules failed", aRequest));
    OnLoadRequestedModulesRejected(cx, aRequest, UndefinedHandleValue);
    // BUG: consumes the one balancing callback, but the
    // GraphLoadingStateRecordObject created inside LoadRequestedModules is
    // left with isLoading == true and can outlive this call via a sibling
    // request parked in a pending fetch's mWaiting list.
  }

File: js/src/vm/Modules.cpp, line 1615-1618

  AutoCheckRecursionLimit recursion(cx);
  if (!recursion.check(cx)) {
    return false;  // raw unwind: state->isLoading() is left true
  }

File: js/loader/ModuleLoaderBase.cpp, line 1667-1676

  if (aRequest->IsErrored()) {   // only !mModuleScript || HasParseError();
                                 // mErroredLoadingImports is never consulted
    LOG(("ScriptLoadRequest (%p): ProcessDynamicImport, request has an error",
         aRequest));
    // The error is already processed in OnLoadRequestedModulesRejected.
    return;
  }

  LOG(("ScriptLoadRequest (%p): ProcessDynamicImport", aRequest));
  FinishLoadingImportedModule(cx, aRequest);  // trailing ClearImport() sets
                                              // mPayload = UndefinedValue()

File: js/src/vm/Modules.cpp, line 1735-1757

  // Step 1. If state.[[IsLoading]] is false, return unused.
  if (!state->isLoading()) {
    return true;
  }
  ...
  // Step 3.a. Set state.[[IsLoading]] to false.
  state->setIsLoading(false);

  // Step 3.b. Perform ! Call(state.[[PromiseCapability]].[[Reject]], ...)
  RootedValue hostDefined(cx, state->hostDefined());
  return state->rejected(cx, hostDefined, error);  // second delivery for the
                                                   // same, finished request

File: js/loader/ModuleLoaderBase.cpp, line 1443-1496

bool ModuleLoaderBase::OnLoadRequestedModulesRejected(
    JSContext* aCx, ModuleLoadRequest* aRequest, Handle<Value> error) {
  ...
  if (aRequest->IsDynamicImport()) {
    ...
    Rooted<Value> payload(aCx, aRequest->mPayload);  // undefined after
                                                     // ClearImport()
    if (!error.isUndefined()) {
      FinishLoadingImportedModuleFailed(aCx, payload, error);  // line 1463:
                                                               // crash site
    }
    ...
  }
  ...
  // Decrease the reference 'AddRef'ed when converting the hostDefined.
  aRequest->Release();  // line 1496: second Release for a single AddRef
  return true;
}

File: js/src/vm/Modules.cpp, line 173-189

JS_PUBLIC_API bool JS::FinishLoadingImportedModuleFailed(
    JSContext* cx, Handle<Value> payloadArg, Handle<Value> error) {
  ...
  // Step 2. If payload is a GraphLoadingState Record, then
  JSObject* payload = &payloadArg.toObject();  // undefined Value unboxed as
                                               // JSObject* (no release-mode
                                               // type check)
  if (payload->is<GraphLoadingStateRecordObject>()) {  // header read faults
                                                       // at 0x0007800000000000

Failure of LoadRequestedModules via raw false return triggers a fallback rejection that does not deactivate the GraphLoadingStateRecordObject; ProcessDynamicImport then clears the request's payload despite the load having errored; a later ContinueModuleLoading on the still-loading state re-delivers the rejection callback, which dereferences the cleared (undefined) payload as an object.

Exploit Chain

  1. Attacker page creates a dedicated worker from a blob URL; all remaining steps run automatically in the worker with no user interaction.
  2. The worker builds a 400-deep chain of blob module scripts a1 -> ... -> a400 -> miss (an HTTP module URL that returns 404), plus a module k containing import slow; import a1;, where slow is an HTTP module URL that returns 404 only after 14 seconds.
  3. First import(k): every chain module compiles and records its [[LoadedModules]] edges, the miss 404 rejects the load (module statuses stay New, edges persist), and the slow fetch remains pending in ModuleLoaderBase::mFetchingModules.
  4. From deeply recursed JS (an adaptive sweep toward the stack ceiling), the worker calls import(k) again: the fetched-module-map hit resumes synchronously; StartFetchingModuleDependencies AddRefs the request (ModuleLoaderBase.cpp:1335) and calls the synchronous-callback variant of JS::LoadRequestedModules, creating GraphLoadingStateRecordObject S with hostDefined = PrivateValue(request); HostLoadImportedModule for slow parks a child request whose payload is S in the pending fetch's mWaiting list, keeping S alive.
  5. The engine-only InnerModuleLoading descent over the 400 recorded [[LoadedModules]] edges trips AutoCheckRecursionLimit (Modules.cpp:1616) and unwinds via raw return false with no host frame in between, so js::LoadRequestedModules returns false while S.isLoading remains true.
  6. The if (!result) fallback (ModuleLoaderBase.cpp:1385) delivers the rejection callback the first time: the dynamic-import promise is rejected, mErroredLoadingImports is set, ModuleErrored runs, and the single AddRef is Released — S is never deactivated.
  7. ModuleErrored -> LoadFinished -> ProcessDynamicImport: the guard checks only IsErrored() (mModuleScript is valid and has no parse error) and ignores mErroredLoadingImports, so FinishLoadingImportedModule runs again and its trailing ClearImport() sets the request's mPayload to undefined (ModuleLoadRequest.cpp:184-188).
  8. About 14 seconds later the slow fetch fails: OnFetchComplete -> ResumeWaitingRequests -> OnFetchFailed(child) -> JS::FinishLoadingImportedModuleFailedWithPendingException(S) -> ContinueModuleLoading sees S.isLoading == true and synchronously invokes S.rejected a second time with the raw request pointer.
  9. OnLoadRequestedModulesRejected (ModuleLoaderBase.cpp:1461-1463) passes the now-undefined mPayload to JS::FinishLoadingImportedModuleFailed, which unboxes it with &payloadArg.toObject() (Modules.cpp:183); the object-header read through the resulting wild pointer faults at 0x0007800000000000 in the content-process worker thread. Had the read not faulted, the same path ends with a second aRequest->Release() (ModuleLoaderBase.cpp:1496) against a single AddRef — a reference-count underflow on the doubly-delivered path.

Steps to Reproduce

  1. Build Firefox with the ASAN fuzzing mozconfig (mozconfig.linux.asan.fuzzing) from an unmodified tree.
  2. Start the auxiliary HTTP server: python3 external_services/mod_server.py (listens on 127.0.0.1:8765; serves /js?fail=1 as 404 and /js?delay=N&fail=1 as 404 after N ms, with Access-Control-Allow-Origin: *).
  3. Load testcase.html over HTTP from any origin (the module fetches to 127.0.0.1:8765 are cross-origin and CORS-allowed). No prefs and no source modifications are required.
  4. Wait ~14-16 seconds after load; the worker thread of the content process crashes with the SEGV shown below.

Security Impact

  • Severity: High
  • Attacker capability: From unprivileged web content, with no prefs and no user interaction beyond loading the page, an attacker can force the module loader's rejection callback to run a second time on a request whose import state has already been torn down. The demonstrated result is a type confusion in the content process: an undefined JS::Value is unboxed as JSObject* and dereferenced (in this run, a read at a fixed non-canonical address). The same doubly-delivered path holds the request only as a non-owning raw PrivateValue pointer whose balancing strong reference was released at the first delivery, and ends with a second aRequest->Release() (ModuleLoaderBase.cpp:1496) against a single AddRef (ModuleLoaderBase.cpp:1335) — an unbalanced-refcount condition on a refcounted object in the same code path. Exploitation beyond the demonstrated content-process crash was not shown in this run.
  • Preconditions: None beyond normal browsing: victim loads an attacker page over HTTP(S). The attacker needs a server that serves a delayed 404 module response (~14 s) to keep a fetch pending; the recursion-limit trigger is an automated in-page sweep. Reproduced deterministically on the first attempt.

ASAN Report

==42717==ERROR: AddressSanitizer: SEGV on unknown address (pc 0x7686b8b2fdc2 bp 0x768603b712f0 sp 0x768603b71260 T20)
==42717==The signal is caused by a READ memory access.
==42717==Hint: this fault was caused by a dereference of a high value address (see register values below).
    #0 0x7686b8b2fdc2 in js::gc::HeaderWord::get() const /firefox/js/src/gc/Cell.h:113:23
    #1 0x7686b8b2fdc2 in js::gc::CellWithTenuredGCPointer<js::gc::Cell, js::Shape>::headerPtr() const /firefox/js/src/gc/Cell.h:876:60
    #2 0x7686b8b2fdc2 in JSObject::shape() const /firefox/js/src/vm/JSObject.h:100:37
    #3 0x7686b8b2fdc2 in JSObject::getClass() const /firefox/js/src/vm/JSObject.h:121:44
    #4 0x7686b8b2fdc2 in bool JSObject::is<js::GraphLoadingStateRecordObject>() const /firefox/js/src/vm/JSObject.h:530:12
    #5 0x7686b8b2fdc2 in JS::FinishLoadingImportedModuleFailed(JSContext*, JS::Handle<JS::Value>, JS::Handle<JS::Value>) /firefox/js/src/vm/Modules.cpp:184:16
    #6 0x7686a8c39de4 in JS::loader::ModuleLoaderBase::OnLoadRequestedModulesRejected(JSContext*, JS::loader::ModuleLoadRequest*, JS::Handle<JS::Value>) /firefox/js/loader/ModuleLoaderBase.cpp:1463:7
    #7 0x7686a8c39973 in JS::loader::ModuleLoaderBase::OnLoadRequestedModulesRejected(JSContext*, JS::Handle<JS::Value>, JS::Handle<JS::Value>) /firefox/js/loader/ModuleLoaderBase.cpp:1439:10
    #8 0x7686b6d08fba in js::GraphLoadingStateRecordObject::rejected(JSContext*, JS::Handle<JS::Value>, JS::Handle<JS::Value>) /firefox/js/src/builtin/ModuleObject.cpp:1786:10
    #9 0x7686b8b2fb9e in ContinueModuleLoading(JSContext*, JS::Handle<js::GraphLoadingStateRecordObject*>, JS::Handle<js::ModuleObject*>, js::ImportPhase, JS::Handle<JS::Value>) /firefox/js/src/vm/Modules.cpp:1757:17
    #10 0x7686b8b2fe7d in JS::FinishLoadingImportedModuleFailed(JSContext*, JS::Handle<JS::Value>, JS::Handle<JS::Value>) /firefox/js/src/vm/Modules.cpp:187:12
    #11 0x7686b8b2f89a in JS::FinishLoadingImportedModuleFailedWithPendingException(JSContext*, JS::Handle<JS::Value>) /firefox/js/src/vm/Modules.cpp:218:10
    #12 0x7686a8c30867 in JS::loader::ModuleLoaderBase::OnFetchFailed(JS::loader::ModuleLoadRequest*) /firefox/js/loader/ModuleLoaderBase.cpp:892:7
    #13 0x7686a8c349ab in JS::loader::ModuleLoaderBase::ResumeWaitingRequest(JS::loader::ModuleLoadRequest*, bool) /firefox/js/loader/ModuleLoaderBase.cpp:723:5
    #14 0x7686a8c349ab in JS::loader::ModuleLoaderBase::ResumeWaitingRequests(JS::loader::ModuleLoaderBase::LoadingRequest*, bool) /firefox/js/loader/ModuleLoaderBase.cpp:710:5
    #15 0x7686a8c34fe1 in JS::loader::ModuleLoaderBase::OnFetchComplete(JS::loader::ModuleLoadRequest*, nsresult) /firefox/js/loader/ModuleLoaderBase.cpp:812:3
    #16 0x7686b311e12a in JS::loader::ModuleLoadRequest::OnFetchComplete(nsresult) dist/include/js/loader/ModuleLoadRequest.h:96:21
    #17 0x7686b311e12a in mozilla::dom::workerinternals::loader::ScriptExecutorRunnable::ProcessModuleScript(JSContext*, mozilla::dom::WorkerPrivate*) /firefox/dom/workers/ScriptLoader.cpp:1745:18
    #18 0x7686b311e655 in mozilla::dom::workerinternals::loader::ScriptExecutorRunnable::WorkerRun(JSContext*, mozilla::dom::WorkerPrivate*) /firefox/dom/workers/ScriptLoader.cpp:1792:12
    #19 0x7686b318ff7b in mozilla::dom::WorkerThreadRunnable::Run() /firefox/dom/workers/WorkerRunnable.cpp:438:12
    #20 0x7686a879038a in nsThread::ProcessNextEvent(bool, bool*) /firefox/xpcom/threads/nsThread.cpp:1174:16
    #21 0x7686a8799af9 in NS_ProcessNextEvent(nsIThread*, bool) /firefox/xpcom/threads/nsThreadUtils.cpp:471:10
    #22 0x7686b316f0aa in mozilla::dom::WorkerPrivate::DoRunLoop(JSContext*) /firefox/dom/workers/WorkerPrivate.cpp:4173:7
    #23 0x7686b312f4b1 in mozilla::dom::workerinternals::(anonymous namespace)::WorkerThreadPrimaryRunnable::Run() /firefox/dom/workers/RuntimeService.cpp:2408:42

==42717==Register values:
rax = 0x0000f00000000000  rbx = 0x0000768603b71260  rcx = 0x0000000000000001  rdx = 0x00007756d3b071e0
rdi = 0x0007800000000000  rsi = 0x00007756d3b071e0  rbp = 0x0000768603b712f0  rsp = 0x0000768603b71260
SUMMARY: AddressSanitizer: SEGV (/firefox/obj-firefox-asan/dist/bin/libxul.so+0x250cadc2) (BuildId: f3343165b74dff1cc1c75ae1d9635c98)
==42717==ABORTING
Attached file mod_server.py —
Attached patch iter_1.patch — — Splinter Review
Attached file testcase.html —
Attached file crash_stack.txt —
Attached file README.txt —

This bug was filed automatically by an AI-powered security testing tool. The analysis, testcase, and any suggested patches were generated by an AI model and have NOT been verified by a human.

Please review all details carefully before triaging. The crash is real (confirmed by ASAN), but the root cause analysis and suggested fix may contain errors.

Group: core-security → javascript-core-security

Yoshi, want to take a look at this sec-high?

Flags: needinfo?(allstars.chh)
Assignee: nobody → allstars.chh
Flags: needinfo?(allstars.chh)
Priority: -- → P1
Blocks: sm-security
Severity: -- → S2
Attached file (secure) (obsolete) —

:allstars.chh, please update all release status flags to reflect the affected/unaffected/disabled state correctly. Which branches (beta, release, and/or ESR) are affected by this flaw?

Flags: needinfo?(allstars.chh)

The bug has a release status flag that shows some version of Firefox is affected, thus it will be considered confirmed.

Status: UNCONFIRMED → NEW
Ever confirmed: true
Attachment #9621263 - Attachment is obsolete: true

https://firefox-source-docs.mozilla.org/bug-mgmt/processes/security-approval.html

  • The bug has a sec-high rating, but only affects the content process
    ..

If it meets any of the above criteria, developers do not need to ask for sec-approval.

This bug is content-process only. So I won't ask for sec-approval? for this.

Group: javascript-core-security → core-security-release
Status: NEW → RESOLVED
Closed: 3 months ago
Resolution: --- → FIXED
Target Milestone: --- → 155 Branch

The patch landed in nightly and beta is affected, along with ESR.
:allstars.chh, is this bug important enough to require an uplift?

For more information, please visit BugBot documentation.

Flags: needinfo?(allstars.chh)
Attachment #9624401 - Flags: approval-mozilla-beta?

firefox-beta Uplift Approval Request

  • User impact if declined/Reason for urgency: SEGV on unknown address when repeated loading the same large module grapgh, which may cause over-recursion.
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: no
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Handle over-recursion correctly during module loading.
  • String changes made/needed?: no
  • Is Android affected?: yes
Attachment #9624402 - Flags: approval-mozilla-beta?

firefox-beta Uplift Approval Request

  • User impact if declined/Reason for urgency: SEGV on unknown address when repeated loading the same large module grapgh, which may cause over-recursion.
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: no
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Handle over-recursion correctly during module loading.
    String changes made/needed?: no
  • String changes made/needed?: no
  • Is Android affected?: yes
Attachment #9624404 - Flags: approval-mozilla-release?

firefox-release Uplift Approval Request

  • User impact if declined/Reason for urgency: SEGV on unknown address when repeated loading the same large module grapgh, which may cause over-recursion.
  • Code covered by automated testing?: yes
  • Fix verified in Nightly?: no
  • Needs manual QE testing?: no
  • Steps to reproduce for manual QE testing:
  • Risk associated with taking this patch: low
  • Explanation of risk level: Handle over-recursion correctly during module loading.
    String changes made/needed?: no
  • String changes made/needed?: no
  • Is Android affected?: yes
Flags: needinfo?(allstars.chh)
Attachment #9624401 - Attachment is obsolete: true
Attachment #9624401 - Flags: approval-mozilla-beta?
Attachment #9624402 - Flags: approval-mozilla-beta? → approval-mozilla-beta+
Attachment #9624404 - Flags: approval-mozilla-release? → approval-mozilla-esr153?
Attachment #9624404 - Flags: approval-mozilla-esr153? → approval-mozilla-esr153+
QA Whiteboard: [sec] [uplift] [qa-triage-done-c155/b154]
Whiteboard: [adv-main154+r][adv-esr53.1+r]
Whiteboard: [adv-main154+r][adv-esr53.1+r] → [adv-main154+r][adv-esr153.1+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: