Heap use-after-free read in [@ nsINode::GetPreviousSibling] via unguarded root-element append in nsXMLContentSink::SetDocElement
Categories
(Core :: XML, defect)
Tracking
()
People
(Reporter: bugmon, Assigned: ltenenbaum)
References
Details
(5 keywords, Whiteboard: [adv-main154+r][adv-esr153.1+r][adv-esr140.14+r][adv-esr115.39+r])
Attachments
(6 files, 5 external files)
nsXMLContentSink::SetDocElement (dom/xml/nsXMLContentSink.cpp:957) appends the document element to the document with the low-level mDocument->AppendChildTo() without checking whether the element already has a parent. When the root element of an XML document is a customized built-in custom element (<html is="x-r">), nsXMLContentSink::CreateElement synchronously upgrades it via CustomElementRegistry::Upgrade (dom/base/nsContentUtils.cpp:12196), and that path performs no post-construction validation of the element's state — unlike the autonomous-element path DoCustomElementCreate (nsContentUtils.cpp:12028-12033), which throws NotSupportedError if the constructor left the element with a parent, and unlike the sink's own non-root path (nsXMLContentSink.cpp:1033-1035), which calls content->Remove() before appending. An author constructor that appends this to a detached element therefore hands SetDocElement an already-parented node.
The MOZ_ASSERT(!aKid->GetParentNode()) in nsINode::InsertChildBefore (dom/base/nsINode.cpp:2149) is compiled out in non-debug builds, so nsINode::AppendChildToChildList (nsINode.cpp:2265-2282) links the node into the document's child list while its sibling fields still participate in the detached keeper's list, cross-linking the two lists; Element::BindToTree (dom/base/Element.cpp:2948) then overwrites mParent without unlinking from the old parent. A subsequent appendChild on the keeper consults the corrupted last-child pointer (GetLastChild() returns mFirstChild->mPreviousOrLastSibling, nsINode.cpp:1172-1174) and splices new nodes into the document's sibling chain, leaving the root element's mPreviousOrLastSibling pointing at a comment node that document.replaceChildren() subsequently orphans. After the cycle collector frees that node (snow-white deletion), reading root.previousSibling dereferences the freed node's mNextSibling field (nsINode.cpp:2209), which ASAN reports as a heap-use-after-free read. The same dangling pointer is also written through by later child-list mutations (nsINode.cpp:2273), so the corruption is not limited to reads.
The bug is reachable from ordinary web content: the attacker page loads a same-origin XML document whose prolog is still being parsed when the page registers the custom element definition. The testcase uses content.sink.* prefs to make the parser yield during the prolog; over the network the same window exists whenever the document is delivered in chunks, which an attacker serving their own resource controls. fuzzing.enabled is used only for FuzzingFunctions.garbageCollect to deterministically trigger the GC/CC that frees the orphaned node.
Build Info
- Branch: main
- Revision: 91d6cd2d1476bca635bb96f82ca34eda283b5460
- Timestamp: 2026-07-22T16:05:43+00:00
Affected Code
File: dom/xml/nsXMLContentSink.cpp, line 956-961
IgnoredErrorResult rv;
mDocument->AppendChildTo(mDocElement, NotifyForDocElement(), rv); // no check that mDocElement is unparented
if (rv.Failed()) {
// If we return false here, the caller will bail out because it won't
// find a parent content node to append to, which is fine.
return false;
File: dom/xml/nsXMLContentSink.cpp, line 1030-1037
if (!SetDocElement(nameSpaceID, localName, content) && appendContent) {
NS_ENSURE_TRUE(parent, NS_ERROR_UNEXPECTED);
if (MOZ_UNLIKELY(content->GetParentNode())) { // non-root path guards against a constructor that parented the element
content->Remove();
}
parent->AppendChildTo(content, false, IgnoreErrors());
}
File: dom/base/nsContentUtils.cpp, line 12184-12206
// 4. "If definition is non-null, and definition's name is not equal to its
// local name (i.e., definition represents a customized built-in
// element):"
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); // no post-construction validation of parent/children
if (rv.MaybeSetPendingException(cx)) {
aes.ReportException();
}
} else {
nsContentUtils::EnqueueUpgradeReaction(*aResult, definition);
}
return NS_OK;
}
File: dom/base/nsContentUtils.cpp, line 12028-12033
// contrast: the autonomous-element path rejects a constructor that mutated the element
if (aDoc != element->OwnerDoc() || element->GetParentNode() ||
element->HasChildren() || element->GetAttrCount() ||
element->NodeInfo()->NameAtom() != localName) {
aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return;
}
File: dom/base/nsINode.cpp, line 2143-2170
MOZ_ASSERT(!aKid->GetParentNode(), "Inserting node that already has parent"); // compiled out in --disable-debug builds
...
if (!aBeforeThis) {
AppendChildToChildList(aKid);
} else {
InsertChildToChildList(aKid, aBeforeThis);
}
File: dom/base/nsINode.cpp, line 2265-2282
void nsINode::AppendChildToChildList(nsIContent* aKid) {
MOZ_ASSERT(aKid);
MOZ_ASSERT(!aKid->mNextSibling);
RemoveFromCache(this);
if (mFirstChild) {
nsIContent* lastChild = GetLastChild();
lastChild->mNextSibling = aKid; // writes through mFirstChild->mPreviousOrLastSibling
aKid->mPreviousOrLastSibling = lastChild; // overwrites the kid's link into its old list
} else {
mFirstChild = aKid;
}
// Maintain link to the last child
mFirstChild->mPreviousOrLastSibling = aKid;
++mChildCount;
}
File: dom/base/nsINode.cpp, line 2206-2212
nsIContent* nsINode::GetPreviousSibling() const {
// Do not expose circular linked list
if (mPreviousOrLastSibling && !mPreviousOrLastSibling->mNextSibling) { // UAF read: mPreviousOrLastSibling points at a freed node
return nullptr;
}
return mPreviousOrLastSibling;
}
File: dom/base/Element.cpp, line 2929-2952
MOZ_ASSERT(!GetParentNode() || &aParent == GetParentNode(),
"Already have a parent. Unbind first!"); // compiled out
const bool hadParent = !!GetParentNode();
...
// Now set the parent.
mParent = &aParent; // silently overwrites the keeper parent
if (!hadParent && aParent.IsContent()) { // skipped because hadParent is true
SetParentIsContent(true);
NS_ADDREF(mParent);
}
SetDocElement appends the root element without the already-has-parent guard that the non-root path in HandleStartElement has. The customized built-in upgrade path runs the author constructor synchronously with no post-construction check, unlike DoCustomElementCreate. With the InsertChildBefore assertion compiled out, AppendChildToChildList cross-links the two child lists and GetPreviousSibling later dereferences the stale sibling pointer.
Exploit Chain
- Attacker page creates a same-origin XML (application/xhtml+xml) document whose prolog contains many comments before the root element <html xmlns="..." is="x-r">, and loads it in an iframe. Parsing of the prolog yields back to the event loop (in the testcase via content.sink.* deflect prefs; in the wild via chunked network delivery of the attacker's own resource).
- While the iframe document is still in readyState 'loading' with no documentElement, the parent page registers a customized built-in definition 'x-r' (extends 'html') in the iframe's window. Its constructor calls super() and then appends
thisto a detached <div> (the 'keeper'), which is legal because the customized built-in upgrade path (nsContentUtils.cpp:12196) performs no post-construction validation. - The parser reaches the root element; nsXMLContentSink::CreateElement synchronously upgrades it, so the element returned to the sink already has the keeper as parent. SetDocElement (nsXMLContentSink.cpp:957) appends it to the document anyway; the InsertChildBefore assertion is compiled out, AppendChildToChildList links it into the document's child list while its sibling fields still belong to the keeper's list, and BindToTree overwrites mParent. The keeper's and document's child lists are now cross-linked; in particular the root's mPreviousOrLastSibling serves as the keeper's last-child marker while the root sits in the document's list.
- After load, the page appends a DocumentFragment containing two comment nodes (F1, F2) to the keeper. AppendChildToChildList consults the corrupted GetLastChild() (mFirstChild->mPreviousOrLastSibling), so F1/F2 are spliced into the document's sibling chain, and the root's mPreviousOrLastSibling is left pointing at F2 as a raw, never-repaired pointer.
- document.replaceChildren() removes the document's children, dropping ownership of F1/F2. They have no JS wrappers, so after a GC the cycle collector's snow-white deletion frees them (nsCycleCollector.cpp FreeSnowWhite, nsIContent::Destroy).
- Reading root.previousSibling calls nsINode::GetPreviousSibling (nsINode.cpp:2209), which dereferences the freed F2 node's mNextSibling field — a use-after-free read of DOM-arena heap memory. The same dangling pointer is written through by any further child-list mutation on the keeper (nsINode.cpp:2273), giving a write primitive into memory that the attacker can attempt to reallocate.
Steps to Reproduce
- Build Firefox with the ASAN fuzzing mozconfig (/app/mozconfigs/mozconfig.linux.asan.fuzzing; ASAN, --enable-fuzzing, --disable-debug).
- Run testcase.html via browser_evaluator with prefs: fuzzing.enabled=true, content.sink.perf_deflect_count=2, content.sink.interactive_deflect_count=2, content.sink.perf_parse_time=1000, content.sink.interactive_parse_time=1000, content.notify.interval=1000. fuzzing.enabled is needed only for FuzzingFunctions.garbageCollect; the content.sink prefs make the XML parser yield during the comment prolog so the definition can be registered before the root element is parsed, standing in for chunked network delivery.
- The content process crashes with an ASAN heap-use-after-free read in nsINode::GetPreviousSibling within a few seconds (first or second garbageCollect iteration).
Security Impact
- Severity: High
- Attacker capability: Web content corrupts DOM sibling-list pointers in the content process: a document-element node retains a raw pointer to a freed comment node. Demonstrated impact is a use-after-free read (root.previousSibling reads the freed node's mNextSibling, nsINode.cpp:2209); the same corrupted pointer feeds child-list mutation code that writes through it (nsINode.cpp:2273), and BindToTree's skipped refcount adjustment additionally produces an unbalanced release when the element is unbound. The freed allocation is a 128-byte DOM-arena block the attacker can attempt to reclaim with controlled data, making this a plausible content-process exploitation primitive.
- Preconditions: Victim loads an attacker-controlled page (no user interaction beyond navigation). The attacker's same-origin XML subresource must still be mid-parse (prolog) when the custom element definition is registered; the attacker controls this window by chunking delivery of their own resource. The testcase reproduces the window with content.sink.* parser-yield prefs and uses fuzzing.enabled only to force GC deterministically; garbage collection and cycle collection occur without it during normal browsing.
ASAN Report
==22293==ERROR: AddressSanitizer: heap-use-after-free on address 0x764f63ba6cc8 at pc 0x758f3c1051c4 bp 0x7fffe3fb5360 sp 0x7fffe3fb5358
READ of size 8 at 0x764f63ba6cc8 thread T0 (WebCOOP+COEP Co)
#0 0x758f3c1051c3 in nsCOMPtr<nsIContent>::operator bool() const /firefox/xpcom/base/nsCOMPtr.h:762:45
#1 0x758f3c1051c3 in nsINode::GetPreviousSibling() const /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsINode.cpp:2208:34
#2 0x758f3cb79c1e in mozilla::dom::Node_Binding::get_previousSibling(JSContext*, JS::Handle<JSObject*>, void*, JSJitGetterCallArgs) /firefox/obj-firefox-asan/dom/bindings/./NodeBinding.cpp:596:60
#3 0x758f3e1b3811 in bool mozilla::dom::binding_detail::GenericGetter<mozilla::dom::binding_detail::NormalThisPolicy, mozilla::dom::binding_detail::ThrowExceptions>(JSContext*, unsigned int, JS::Value*) /firefox/obj-firefox-asan/dom/bindings/./../../../dom/bindings/BindingUtils.cpp:3085:13
#4 0x758f483eb355 in CallJSNative(JSContext*, bool (*)(JSContext*, unsigned int, JS::Value*), js::CallReason, JS::CallArgs const&) /firefox/js/src/vm/Interpreter.cpp:498:13
#5 0x758f483eb355 in js::InternalCallOrConstruct(JSContext*, JS::CallArgs const&, js::MaybeConstruct, js::CallReason) /firefox/js/src/vm/Interpreter.cpp:594:12
#6 0x758f483ecd8e in InternalCall(JSContext*, js::AnyInvokeArgs const&, js::CallReason) /firefox/js/src/vm/Interpreter.cpp:661:10
#8 0x758f483ee8cb in js::CallGetter(JSContext*, JS::Handle<JS::Value>, JS::Handle<JS::Value>, JS::MutableHandle<JS::Value>) /firefox/js/src/vm/Interpreter.cpp:815:10
#16 0x758f48400dcb in js::Interpret(JSContext*, js::RunState&) /firefox/js/src/vm/Interpreter.cpp:2935:12
#25 0x758f3c06f12c in mozilla::dom::CallbackTimeoutHandler::Call(char const*) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/TimeoutHandler.cpp:167:29
#26 0x758f3ba09a5d in nsGlobalWindowInner::RunTimeoutHandler(mozilla::dom::Timeout*) /firefox/dom/base/nsGlobalWindowInner.cpp:6607:38
#27 0x758f3c0696bc in mozilla::dom::TimeoutManager::RunTimeout(mozilla::TimeStamp const&, mozilla::TimeStamp const&, bool) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/TimeoutManager.cpp:955:39
[...]
0x764f63ba6cc8 is located 72 bytes inside of 128-byte region [0x764f63ba6c80,0x764f63ba6d00)
freed by thread T0 (WebCOOP+COEP Co) here:
#0 0x5a0e300f0916 in __interceptor_free _asan_rtl_:3
#1 0x758f3be14226 in nsNodeInfoManager::Free(void*) /firefox/dom/base/nsNodeInfoManager.h:116:27
#2 0x758f3be14226 in nsIContent::Destroy() /firefox/obj-firefox-asan/dom/base/./../../../dom/base/FragmentOrElement.cpp:133:1
#3 0x758f383b5e73 in SnowWhiteKiller::~SnowWhiteKiller() /firefox/obj-firefox-asan/xpcom/base/./../../../xpcom/base/nsCycleCollector.cpp:2663:7
#4 0x758f3839c4d1 in nsCycleCollector::FreeSnowWhite(bool) /firefox/obj-firefox-asan/xpcom/base/./../../../xpcom/base/nsCycleCollector.cpp:2854:3
#5 0x758f38b156ff in XPCJSContext::AfterProcessTask(unsigned int) /firefox/obj-firefox-asan/js/xpconnect/src/./../../../../js/xpconnect/src/XPCJSContext.cpp:1531:28
[...]
previously allocated by thread T0 (WebCOOP+COEP Co) here:
#0 0x5a0e300f0bb4 in __interceptor_malloc _asan_rtl_:3
#1 0x758f3bbf6945 in mozilla::dom::DOMArena::Allocate(unsigned long) /firefox/obj-firefox-asan/dist/include/mozilla/dom/DOMArena.h:44:17
#2 0x758f3bbf6945 in nsNodeInfoManager::Allocate(unsigned long) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsNodeInfoManager.cpp:283:20
#3 0x758f433a3069 in nsXMLContentSink::HandleComment(char16_t const*) /firefox/obj-firefox-asan/dom/xml/./../../../dom/xml/nsXMLContentSink.cpp:1173:29
#4 0x758f38f859a0 in nsExpatDriver::HandleComment(char16_t const*) /firefox/obj-firefox-asan/parser/htmlparser/./../../../parser/htmlparser/nsExpatDriver.cpp:594:26
[...]
#17 0x758f38f9b564 in nsParser::ParseFragment(nsTSubstring<char16_t> const&, nsTArray<nsTString<char16_t>>&) /firefox/obj-firefox-asan/parser/htmlparser/./../../../parser/htmlparser/nsParser.cpp:609:14
#18 0x758f3b896c3e in nsContentUtils::ParseFragmentXML(...) /firefox/dom/base/nsContentUtils.cpp:7294:37
#19 0x758f3b8950a7 in nsContentUtils::CreateContextualFragment(...) /firefox/dom/base/nsContentUtils.cpp:6903:9
#20 0x758f3bc1cb15 in nsRange::CreateContextualFragment(...) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsRange.cpp:2777:10
[...]
SUMMARY: AddressSanitizer: heap-use-after-free (/firefox/obj-firefox-asan/dist/bin/libxul.so+0x188941c3) (BuildId: 60c9a7b2e158d29006421169013c39a5)
==22293==ABORTING
| Reporter | ||
Comment 1•3 months ago
|
||
| Reporter | ||
Comment 2•3 months ago
|
||
| Reporter | ||
Comment 3•3 months ago
|
||
| Reporter | ||
Comment 4•3 months ago
|
||
| Reporter | ||
Comment 5•3 months ago
|
||
| Reporter | ||
Comment 6•3 months ago
|
||
Comment 7•3 months ago
|
||
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.
Updated•3 months ago
|
Comment 8•3 months ago
|
||
Hey Leo, this can be also related with other Form/Parser bugs ...
| Assignee | ||
Comment 9•3 months ago
|
||
I assume bug 2054635 is related, based on the patch (although it seems I can't even put it in "See Also" without having access ☹)
| Assignee | ||
Comment 10•3 months ago
|
||
Updated•3 months ago
|
Comment 11•3 months ago
|
||
Comment 12•3 months ago
|
||
Comment 13•3 months ago
|
||
The patch landed in nightly and beta is affected, along with ESR.
:ltenenbaum, is this bug important enough to require an uplift?
- If yes, please nominate the patch for beta and ESR approvals.
- See https://wiki.mozilla.org/Release_Management/Requesting_an_Uplift for documentation on how to request an uplift.
- If no, please set
status-firefox154and the ESR status flag(s) towontfix.
For more information, please visit BugBot documentation.
Updated•3 months ago
|
| Assignee | ||
Comment 14•3 months ago
|
||
Original Revision: https://phabricator.services.mozilla.com/D315092
Updated•3 months ago
|
| Assignee | ||
Comment 15•3 months ago
|
||
Original Revision: https://phabricator.services.mozilla.com/D315092
Updated•3 months ago
|
| Assignee | ||
Comment 16•3 months ago
|
||
Original Revision: https://phabricator.services.mozilla.com/D315092
Updated•3 months ago
|
| Assignee | ||
Comment 17•3 months ago
|
||
Original Revision: https://phabricator.services.mozilla.com/D315092
Updated•3 months ago
|
Comment 18•3 months ago
|
||
firefox-esr153 Uplift Approval Request
- User impact if declined/Reason for urgency: Use-after-free security bug
- Code covered by automated testing?: yes
- Fix verified in Nightly?: yes
- Needs manual QE testing?: no
- Steps to reproduce for manual QE testing:
- Risk associated with taking this patch: low
- Explanation of risk level: Small change, just fixes handling of this unusual case
- String changes made/needed?: N/A
- Is Android affected?: yes
Comment 19•3 months ago
|
||
firefox-beta Uplift Approval Request
- User impact if declined/Reason for urgency: Use-after-free security bug
- Code covered by automated testing?: yes
- Fix verified in Nightly?: yes
- Needs manual QE testing?: no
- Steps to reproduce for manual QE testing:
- Risk associated with taking this patch: low
- Explanation of risk level: Small change, just fixes handling of this unusual case
- String changes made/needed?: N/A
- Is Android affected?: yes
Comment 20•3 months ago
|
||
firefox-esr140 Uplift Approval Request
- User impact if declined/Reason for urgency: Use-after-free security bug
- Code covered by automated testing?: yes
- Fix verified in Nightly?: yes
- Needs manual QE testing?: no
- Steps to reproduce for manual QE testing:
- Risk associated with taking this patch: low
- Explanation of risk level: Small change, just fixes handling of this unusual case
- String changes made/needed?: N/A
- Is Android affected?: yes
Comment 21•3 months ago
|
||
firefox-esr115 Uplift Approval Request
- User impact if declined/Reason for urgency: Use-after-free security bug
- Code covered by automated testing?: yes
- Fix verified in Nightly?: yes
- Needs manual QE testing?: no
- Steps to reproduce for manual QE testing:
- Risk associated with taking this patch: low
- Explanation of risk level: Small change, just fixes handling of this unusual case
- String changes made/needed?: N/A
- Is Android affected?: yes
| Assignee | ||
Updated•3 months ago
|
Updated•3 months ago
|
Updated•3 months ago
|
Comment 22•3 months ago
|
||
| uplift | ||
Updated•3 months ago
|
Updated•3 months ago
|
Comment 23•3 months ago
|
||
| uplift | ||
Updated•3 months ago
|
Updated•3 months ago
|
Comment 24•3 months ago
|
||
| uplift | ||
Updated•3 months ago
|
Updated•3 months ago
|
Comment 25•3 months ago
|
||
| uplift | ||
Updated•3 months ago
|
Updated•3 months ago
|
Updated•3 months ago
|
Updated•3 months ago
|
Updated•26 days ago
|
Description
•