Closed Bug 2054716 Opened 4 months ago Closed 4 months ago

Use-after-free (dangling last-child pointer) in [@ nsINode::AppendChildToChildList] via synchronous custom element upgrade during XML parsing

Categories

(Core :: DOM: Core & HTML, defect)

defect

Tracking

()

RESOLVED DUPLICATE of bug 2054635

People

(Reporter: bugmon, Assigned: keithamus)

Details

(5 keywords)

Attachments

(5 files)

When the XML content sink parses a customized built-in element (e.g. <button is="my-button"> in an XHTML document), nsContentUtils::NewXULOrHTMLElement synchronously runs CustomElementRegistry::Upgrade, executing the author's constructor before the sink attaches the new element to its parser parent. The constructor can insert the half-created element elsewhere in the DOM (giving it a parent and a next sibling). The sink then unconditionally calls parent->AppendChildTo(content, ...) (nsXMLContentSink.cpp:1033); nsINode::InsertChildBefore guards against an already-parented child only with a debug-only MOZ_ASSERT, so in release builds the element is spliced into a second parent's child list while still linked into the first parent's list.

This corrupts the doubly-linked sibling list invariants. In the testcase, the button (now first child of #target) still holds mNextSibling pointing at a <span> that remains linked as the last child of #stash. When the parser appends the next sibling (<p>) to #target, button->mNextSibling = p releases the span's only strong reference and it is destroyed — but #stash's cached last-child pointer (mFirstChild->mPreviousOrLastSibling, a raw pointer) still points at the freed span. A later stash.appendChild() calls nsINode::GetLastChild(), dereferences the dangling pointer in AppendChildToChildList (nsINode.cpp:2273), reads the stale nsCOMPtr value from freed memory (invoking Release() on an attacker-groomable pointer — a controlled virtual-call primitive) and writes the new child pointer into the freed slot.

This is reachable from ordinary untrusted web content in a default configuration (no prefs, no user interaction beyond loading a page): it only requires an XHTML document, a customized built-in custom element definition, and heap grooming. It provides both a use-after-free write of a controlled pointer and a Release() virtual call through attacker-controlled freed memory, making it a strong candidate for content-process remote code execution.

Build Info

Affected Code

File: dom/base/nsContentUtils.cpp, line 12128-12143

if (definition->IsCustomBuiltIn()) {
  // 4.2. "Set result to the result of creating an element internal..."
  if (nodeInfo->NamespaceEquals(kNameSpaceID_XHTML)) {
    *aResult =
        CreateHTMLElement(*tag, nodeInfo.forget(), aFromParser).take();
  } else {
    NS_IF_ADDREF(*aResult = nsXULElement::Construct(nodeInfo.forget()));
  }
  (*aResult)->SetCustomElementData(MakeUnique<CustomElementData>(typeAtom));
  if (synchronousCustomElements) {
    // 4.3. "If synchronousCustomElements is true, then run this step while
    //       catching any exceptions: Upgrade result using definition."
    CustomElementRegistry::Upgrade(*aResult, definition, rv);  // <-- runs author constructor; script may parent the element and give it siblings
    if (rv.MaybeSetPendingException(cx)) {
      aes.ReportException();
    }
  }

File: dom/xml/nsXMLContentSink.cpp, line 1028-1034

if (NS_OK == result) {
  // Store the element
  if (!SetDocElement(nameSpaceID, localName, content) && appendContent) {
    NS_ENSURE_TRUE(parent, NS_ERROR_UNEXPECTED);

    parent->AppendChildTo(content, false, IgnoreErrors());  // <-- no check that the upgrade constructor already parented `content`
  }
}

File: dom/base/nsINode.cpp, line 2140-2170

void nsINode::InsertChildBefore(
    nsIContent* aKid, nsIContent* aBeforeThis, bool aNotify, ErrorResult& aRv,
    nsINode* aOldParent, MutationEffectOnScript aMutationEffectOnScript) {
  ...
  MOZ_ASSERT(!aKid->GetParentNode(), "Inserting node that already has parent");  // <-- debug-only; no release-mode guard
  ...
  if (!aBeforeThis) {
    AppendChildToChildList(aKid);
  }

File: dom/base/nsINode.cpp, line 2265-2282

void nsINode::AppendChildToChildList(nsIContent* aKid) {
  MOZ_ASSERT(aKid);
  MOZ_ASSERT(!aKid->mNextSibling);  // <-- violated silently in release: button keeps mNextSibling -> span

  RemoveFromCache(this);

  if (mFirstChild) {
    nsIContent* lastChild = GetLastChild();   // <-- returns dangling raw pointer to the freed span
    lastChild->mNextSibling = aKid;           // <-- CRASH: UAF read of stale nsCOMPtr (Release on controlled ptr) + UAF pointer write
    aKid->mPreviousOrLastSibling = lastChild;
  } else {
    mFirstChild = aKid;
  }

  // Maintain link to the last child
  mFirstChild->mPreviousOrLastSibling = aKid;
  ++mChildCount;
}

File: dom/base/nsINode.cpp, line 1172-1174

nsIContent* nsINode::GetLastChild() const {
  return mFirstChild ? mFirstChild->mPreviousOrLastSibling : nullptr;  // <-- raw (weak) pointer; left dangling after the span is destroyed
}

The upgrade runs author script before the parser attaches the element; the sink's low-level append has no release-mode protection against a child that already has a parent or a next sibling; the cached last-child pointer is a raw (weak) pointer that goes stale when the sibling list is corrupted.

Exploit Chain

  1. Attacker serves an XHTML page defining a customized built-in element ('my-button' extending 'button') whose constructor re-enters DOM mutation: it appends this into a stash <div> and then uses insertAdjacentHTML to insert an empty <span> after it.
  2. The XML parser encounters <button is="my-button"> inside #target. nsXMLContentSink::CreateElement -> NS_NewElement -> nsContentUtils::NewXULOrHTMLElement synchronously calls CustomElementRegistry::Upgrade (nsContentUtils.cpp:12140), running the author constructor before the sink attaches the element.
  3. After the constructor, the button is a child of #stash with mNextSibling -> span (the span's only strong reference), and #stash's cached last-child raw pointer (mFirstChild(<a>)->mPreviousOrLastSibling) points at the span.
  4. The sink then calls parent(#target)->AppendChildTo(button) (nsXMLContentSink.cpp:1033). InsertChildBefore's already-has-parent check is debug-only, so AppendChildToChildList splices the button into #target's child list while it is still linked into #stash's list, silently violating MOZ_ASSERT(!aKid->mNextSibling).
  5. The parser appends the next sibling <p> to #target: GetLastChild() returns the button and button->mNextSibling = p releases the span's only strong reference, destroying it. #stash's raw last-child pointer now dangles.
  6. The page applies allocation pressure (ArrayBuffer churn over several timer ticks) so the freed span's memory is recycled/returned to the allocator, allowing the attacker to place controlled data at the stale nsCOMPtr slot.
  7. The page calls stash.appendChild(newTextNode): AppendChildToChildList dereferences the dangling last-child pointer, reads the stale mNextSibling nsCOMPtr from freed memory and calls Release() on it (a virtual call through an attacker-groomable pointer), then writes the new child pointer into the freed slot — combined UAF read/virtual-call and UAF pointer-write primitives suitable for content-process code execution.

Steps to Reproduce

  1. Build Firefox from a clean tree with the ASAN fuzzing mozconfig (mozconfig.linux.asan.fuzzing).
  2. Serve the provided testcase.xhtml over HTTP (must be parsed as XML/XHTML so the nsXMLContentSink path is used); no custom prefs, patches, or servers are required.
  3. Load the page and wait ~8 seconds while the script runs 10 rounds of ArrayBuffer allocation pressure via setTimeout.
  4. On the final round, the script calls stash.appendChild(document.createTextNode('z')), which dereferences the dangling last-child pointer; ASAN reports a heap-buffer-overflow READ of size 8 in nsCOMPtr<nsIContent>::assign_assuming_AddRef inside nsINode::AppendChildToChildList in the content process.

Security Impact

  • Severity: High
  • Attacker capability: An attacker controlling ordinary web content gets a use-after-free on a DOM node: AppendChildToChildList reads a stale nsCOMPtr from attacker-reclaimable freed memory and calls Release() on it (controlled virtual call), then writes a live node pointer into the freed allocation. With standard heap grooming this is a strong primitive for arbitrary code execution in the content process.
  • Preconditions: None beyond loading an attacker-controlled page in a default configuration: the document must be parsed as XHTML/XML and define a customized built-in custom element (both available to web content by default; no prefs, no user interaction, no compromised process required). Reliability depends on heap grooming, but the testcase triggers it deterministically without OOM.

ASAN Report

==7691==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x77227a20be88 at pc 0x7652520e6aeb bp 0x7ffd6e5f8c30 sp 0x7ffd6e5f8c28
READ of size 8 at 0x77227a20be88 thread T0 (WebCOOP+COEP Co)
    #0 0x7652520e6aea in nsCOMPtr<nsIContent>::assign_assuming_AddRef(nsIContent*) /firefox/xpcom/base/nsCOMPtr.h:313:17
    #1 0x7652520e6aea in nsCOMPtr<nsIContent>::assign_with_AddRef(nsIContent*) /firefox/xpcom/base/nsCOMPtr.h:808:3
    #2 0x7652520e6aea in nsCOMPtr<nsIContent>::operator=(nsIContent*) /firefox/xpcom/base/nsCOMPtr.h:586:5
    #3 0x7652520e6aea in nsINode::AppendChildToChildList(nsIContent*) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsINode.cpp:2273:29
    #4 0x7652520e61ba in nsINode::InsertChildBefore(nsIContent*, nsIContent*, bool, mozilla::ErrorResult&, nsINode*, MutationEffectOnScript) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsINode.cpp:2167:5
    #5 0x7652520f0c9c in nsINode::ReplaceOrInsertBefore(bool, nsINode*, nsINode*, MutationEffectOnScript, mozilla::ErrorResult&) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsINode.cpp:3560:5
    #6 0x765252a8392b in nsINode::InsertBeforeInternal(nsINode&, nsINode*, MutationEffectOnScript, mozilla::ErrorResult&) /firefox/dom/base/nsINode.h:2911:12
    #7 0x765252a8392b in nsINode::AppendChildInternal(nsINode&, MutationEffectOnScript, mozilla::ErrorResult&) /firefox/dom/base/nsINode.h:2925:12
    #8 0x765252a8392b in nsINode::AppendChild(nsINode&, mozilla::ErrorResult&) /firefox/dom/base/nsINode.h:2919:12
    #9 0x765252a8392b in mozilla::dom::Node_Binding::appendChild(JSContext*, JS::Handle<JSObject*>, void*, JSJitMethodCallArgs const&) /firefox/obj-firefox-asan/dom/bindings/./NodeBinding.cpp:951:60
    #10 0x7652540e3496 in bool mozilla::dom::binding_detail::GenericMethod<...>(JSContext*, unsigned int, JS::Value*) /firefox/obj-firefox-asan/dom/bindings/./../../../dom/bindings/BindingUtils.cpp:3215:13
    [... JS interpreter frames ...]
    #24 0x765251f9b95c in mozilla::dom::CallbackTimeoutHandler::Call(char const*) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/TimeoutHandler.cpp:167:29
    #25 0x76525193e08d in nsGlobalWindowInner::RunTimeoutHandler(mozilla::dom::Timeout*) /firefox/dom/base/nsGlobalWindowInner.cpp:6604:38
    #26 0x765251f95eec in mozilla::dom::TimeoutManager::RunTimeout(...) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/TimeoutManager.cpp:955:39
    [... event loop frames ...]

0x77227a20be88 is located 1176 bytes after 144-byte region [0x77227a20b960,0x77227a20b9f0)
allocated by thread T0 (WebCOOP+COEP Co) here:
    #0 0x57fec72ce9e4 in __interceptor_malloc _asan_rtl_:3
    #1 0x57fec73240b5 in moz_xmalloc /firefox/obj-firefox-asan/memory/mozalloc/./../../../memory/mozalloc/mozalloc.cpp:48:15
    #2 0x7652517cbed3 in operator new(unsigned long) /firefox/obj-firefox-asan/dist/include/mozilla/cxxalloc.h:33:10
    #3 0x7652517cbed3 in nsContentUtils::ParseFragmentXML(...) /firefox/dom/base/nsContentUtils.cpp:7229:31
    #4 0x7652517ca8f7 in nsContentUtils::CreateContextualFragment(...) /firefox/dom/base/nsContentUtils.cpp:6886:9
    #5 0x765251d17c61 in mozilla::dom::Element::InsertAdjacentHTML(...) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/Element.cpp:5608:39
    [... JS frames ...]
    #19 0x765253bcbf78 in mozilla::dom::CustomElementConstructor::Construct(...) /firefox/obj-firefox-asan/dom/bindings/./CustomElementRegistryBinding.cpp:99:8
    #20 0x765251a9b632 in mozilla::dom::(anonymous namespace)::DoUpgrade(...) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/CustomElementRegistry.cpp:1511:17
    #21 0x765251a9b632 in mozilla::dom::CustomElementRegistry::Upgrade(...) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/CustomElementRegistry.cpp:1599:3
    #22 0x76525180d74e in nsContentUtils::NewXULOrHTMLElement(...) /firefox/dom/base/nsContentUtils.cpp:12140:9
    #23 0x76525566df58 in NS_NewHTMLElement(...) /firefox/obj-firefox-asan/dom/html/./../../../dom/html/HTMLElementFactory.cpp:56:10
    #24 0x7652521228ce in NS_NewElement(...) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsNameSpaceManager.cpp:208:12
    #26 0x7652595a02d7 in nsXMLContentSink::CreateElement(...) /firefox/obj-firefox-asan/dom/xml/./../../../dom/xml/nsXMLContentSink.cpp:526:10
    #27 0x7652595a4c10 in nsXMLContentSink::HandleStartElement(...) /firefox/obj-firefox-asan/dom/xml/./../../../dom/xml/nsXMLContentSink.cpp:1011:12
    #30 0x76524eec0c63 in nsExpatDriver::HandleStartElement(...) /firefox/obj-firefox-asan/parser/htmlparser/./../../../parser/htmlparser/nsExpatDriver.cpp:479:32
    [... expat/rlbox frames ...]

SUMMARY: AddressSanitizer: heap-buffer-overflow (/firefox/obj-firefox-asan/dist/bin/libxul.so+0x189a6aea) (BuildId: 6179a7572e62e98ec2cc8f392240bcf6)
Attached file testcase.xhtml —
Attached file prefs.json —
Attached patch fix.patch — — Splinter Review
Attached file crash_stack.txt —
Attached file prefs.js —
Group: core-security → dom-core-security

Hi Keith, can you take a first look at this? Thanks.

Flags: needinfo?(mozilla)
Assignee: nobody → mozilla
Status: UNCONFIRMED → ASSIGNED
Ever confirmed: true
Flags: needinfo?(mozilla)

We believe this is a duplicate of https://bugzilla.mozilla.org/show_bug.cgi?id=2054635 and we plan to test against nightly to be sure.

Yes. Looks like this is resolved in current nightly. Marking as fixed.

Status: ASSIGNED → RESOLVED
Closed: 4 months ago
Duplicate of bug: 2054635
Resolution: --- → DUPLICATE
Group: dom-core-security
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: