Closed Bug 2054635 Opened 4 months ago Closed 4 months ago

Heap use-after-free in [@ nsINode::GetParentNode] via xmlns markup injection in nsContentUtils::CreateContextualFragment and synchronous customized built-in upgrade

Categories

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

defect

Tracking

()

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

People

(Reporter: bugmon, Assigned: keithamus)

References

Details

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

Attachments

(6 files, 6 external files, 1 obsolete file)

nsContentUtils::CreateContextualFragment builds the XML fragment-parsing context string by concatenating the raw, unescaped value of xmlns attributes from the context node's ancestor chain into synthesized 'notacustomelement' tags. An attacker-controlled xmlns attribute value containing '"/><p xmlns="..." is="evil-is"/><notacustomelement q="' therefore injects arbitrary extra elements into the parser context, defeating the code's explicit invariant that context elements can never trigger custom element constructors.

The injected element is a customized built-in (<p is="evil-is">). nsXMLContentSink::CreateElement passes FROM_PARSER_NETWORK, so nsContentUtils::NewXULOrHTMLElement takes the synchronous path and runs CustomElementRegistry::Upgrade — executing the author's constructor mid-parse. Unlike DoCustomElementCreate (which throws if the constructed element already has a parent), the Upgrade path performs no post-constructor parent check. The constructor appends this to a detached holder div. Back in nsXMLContentSink::HandleStartElement, parent->AppendChildTo splices the already-parented element into the synthesized context element CTX: nsINode::InsertChildBefore's "no existing parent" invariant is a debug-only MOZ_ASSERT, and Element::BindToTree sees hadParent==true, so it reassigns mParent = CTX WITHOUT NS_ADDREF.

After parsing, CTX is kept alive only by its two legitimate children's owning mParent references. Content JS removes both siblings, dropping CTX's refcount to zero; the cycle collector's FreeSnowWhite destroys CTX while the injected element's raw mParent still points at it. Any ancestor walk (here Node.contains() -> nsINode::IsInclusiveDescendantOf -> GetParentNode) then reads the freed 136-byte DOM-arena allocation. The dangling pointer targets a small, easily reallocatable DOM allocation and is reachable from many raw-pointer consumers (parentNode wrapping, removal writes, ancestor walks), making this an exploitable use-after-free triggerable from ordinary web content with no special configuration.

Build Info

Affected Code

File: dom/base/nsContentUtils.cpp, line 6852-6866

        if (name->NamespaceEquals(kNameSpaceID_XMLNS)) {
          info.mValue->ToString(uriStr);

          // really want something like nsXMLContentSerializer::SerializeAttr
          tagName.AppendLiteral(" xmlns");  // space important
          if (name->GetPrefix()) {
            tagName.Append(char16_t(':'));
            name->LocalName()->ToString(nameStr);
            tagName.Append(nameStr);
          } else {
            setDefaultNamespace = true;
          }
          tagName.AppendLiteral(R"(=")");
          tagName.Append(uriStr);   // <-- raw attacker value, no escaping of '"' '<' '>' '/'
          tagName.Append('"');
        }

File: parser/htmlparser/nsParser.cpp, line 576-580

  for (theIndex = 0; theIndex < theCount; theIndex++) {
    theContext.Append('<');
    theContext.Append(aTagStack[theCount - theIndex - 1]);  // injected markup becomes real tags
    theContext.Append('>');
  }

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) {   // true: XML sink passes FROM_PARSER_NETWORK
        // 4.3. "...Upgrade result using definition."
        CustomElementRegistry::Upgrade(*aResult, definition, rv);
        // NOTE: no check that the constructor left *aResult unparented
        // (contrast DoCustomElementCreate, which throws on element->GetParentNode())
        if (rv.MaybeSetPendingException(cx)) {
          aes.ReportException();
        }
      }

File: dom/base/nsINode.cpp, line 2149

  MOZ_ASSERT(!aKid->GetParentNode(), "Inserting node that already has parent");
  // debug-only: compiled out in release/ASAN-opt builds, so the
  // already-parented element is spliced into a second parent's child list

File: dom/base/Element.cpp, line 2931-2951

  const bool hadParent = !!GetParentNode();
  ...
  // Now set the parent.
  mParent = &aParent;
  if (!hadParent && aParent.IsContent()) {
    SetParentIsContent(true);
    NS_ADDREF(mParent);   // skipped: hadParent==true, so mParent = CTX is an unowned raw pointer
  }

File: dom/base/nsINode.cpp, line 173-177

bool nsINode::IsInclusiveDescendantOf(const nsINode* aNode) const {
  MOZ_ASSERT(aNode, "is descendant of null node");
  for (const nsINode* node : InclusiveAncestors(*this)) {  // walks raw mParent; reads freed CTX
    if (node == aNode) {
      return true;
    }

Four cooperating defects form the chain: (1) unescaped xmlns value concatenated into the synthesized context tag; (2) synchronous customized-built-in Upgrade with no post-constructor parent check; (3) debug-only 'no existing parent' invariant in InsertChildBefore; (4) BindToTree skipping the parent AddRef when the node already had a parent.

Exploit Chain

  1. Attacker page (XHTML) defines a customized built-in element 'evil-is' (extends <p>) whose constructor appends this to a detached holder div.
  2. Attacker sets an xmlns attribute on a div to 'x"/><p xmlns="http://www.w3.org/1999/xhtml" is="evil-is"/><notacustomelement q="y' and calls Range.createContextualFragment on a range inside that div.
  3. nsContentUtils::CreateContextualFragment concatenates the raw xmlns value into the synthesized context tag; nsParser::ParseFragment wraps it in angle brackets, so expat parses an injected self-closed <p is="evil-is"/> as a child of the synthesized context element CTX.
  4. nsXMLContentSink::CreateElement passes FROM_PARSER_NETWORK, so nsContentUtils::NewXULOrHTMLElement runs CustomElementRegistry::Upgrade synchronously; the author constructor executes mid-parse and parents the new element E into the detached holder. The Upgrade path never checks that E is still unparented.
  5. Back in nsXMLContentSink::HandleStartElement, parent->AppendChildTo(E) runs; InsertChildBefore's no-existing-parent invariant is debug-only, and Element::BindToTree sees hadParent==true and sets E.mParent = CTX without NS_ADDREF — E now holds an unowned raw pointer to CTX.
  6. JS removes CTX's two legitimate children (the synthesized 'notacustomelement' siblings), releasing CTX's only owning references; CTX's refcount reaches zero and the cycle collector's FreeSnowWhite frees the 136-byte HTMLUnknownElement.
  7. JS calls HOLDER.contains(E): nsINode::IsInclusiveDescendantOf walks E's ancestor chain through raw GetParentNode() pointers and reads the freed CTX (ASAN: heap-use-after-free READ of size 8).
  8. For exploitation, the attacker instead reclaims the freed 136-byte DOM-arena slot with controlled data before the ancestor walk (or before parentNode wrapping / E.remove(), which perform writes and virtual-call-adjacent accesses through the dangling pointer), converting the UAF into control over a fake nsINode and ultimately arbitrary code execution in the content process.

Steps to Reproduce

  1. Build Firefox with the ASAN fuzzing mozconfig (mozconfig.linux.asan.fuzzing).
  2. Serve testcase.xhtml (the provided XHTML testcase) over HTTP and load it in the ASAN build; prefs browser.dom.window.dump.enabled=true and devtools.console.stdout.content=true are used only for log output and are not required for the crash.
  3. The page defines the 'evil-is' customized built-in, injects markup via the xmlns attribute value, calls Range.createContextualFragment, removes the two sibling context elements, then repeatedly calls HOLDER.contains(E) while churning allocations to trigger cycle-collector FreeSnowWhite.
  4. Within ~10-20 seconds ASAN reports heap-use-after-free READ of size 8 in nsINode::GetParentNode (inlined into nsINode::Contains), with the freed object allocated at NS_NewHTMLUnknownElement under nsXMLFragmentContentSink::CreateElement and freed by nsCycleCollector::FreeSnowWhite.

Security Impact

  • Severity: High
  • Attacker capability: A web page, with no user interaction and default settings, obtains a dangling pointer from a live DOM element to a freed 136-byte DOM-arena allocation. The freed slot can be reclaimed with attacker-controlled data, after which many raw-pointer consumers (ancestor walks, parentNode wrapping, node removal writes) operate on a fake nsINode, providing a strong primitive for arbitrary code execution in the content process.
  • Preconditions: None beyond loading an attacker-controlled XHTML page in a default-configuration Firefox. No prefs, patches, or unusual user interaction required; custom elements and Range.createContextualFragment are standard web APIs.

ASAN Report

==11521==ERROR: AddressSanitizer: heap-use-after-free on address 0x7587e2107480 at pc 0x74b7ba03cbce bp 0x7ffdb69fce50 sp 0x7ffdb69fce48
READ of size 8 at 0x7587e2107480 thread T0 (WebCOOP+COEP Co)
    #0 0x74b7ba03cbcd in nsINode::GetParentNode() const /firefox/dom/base/nsINode.h:1411:57
    #1 0x74b7ba03cbcd in mozilla::dom::InclusiveAncestors::operator++() /firefox/obj-firefox-asan/dom/base/./../../../dom/base/AncestorIterator.h:69:1
    #2 0x74b7ba03cbcd in nsINode::IsInclusiveDescendantOf(nsINode const*) const /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsINode.cpp:175:22
    #3 0x74b7ba03cbcd in nsINode::Contains(nsINode const*) const /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsINode.cpp:3669:18
    #4 0x74b7baa3c705 in mozilla::dom::Node_Binding::contains(JSContext*, JS::Handle<JSObject*>, void*, JSJitMethodCallArgs const&) /firefox/obj-firefox-asan/dom/bindings/./NodeBinding.cpp:1396:36
    #5 0x74b7bc097b86 in bool mozilla::dom::binding_detail::GenericMethod<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:3215:13
    #6 0x3fecbb444834  (<unknown module>)

0x7587e2107480 is located 48 bytes inside of 136-byte region [0x7587e2107450,0x7587e21074d8)
freed by thread T0 (WebCOOP+COEP Co) here:
    #0 0x59e6764a6746 in __interceptor_free _asan_rtl_:3
    #1 0x74b7b9cf96c6 in nsNodeInfoManager::Free(void*) /firefox/dom/base/nsNodeInfoManager.h:116:27
    #2 0x74b7b9cf96c6 in nsIContent::Destroy() /firefox/obj-firefox-asan/dom/base/./../../../dom/base/FragmentOrElement.cpp:133:1
    #3 0x74b7b62a9b53 in SnowWhiteKiller::~SnowWhiteKiller() /firefox/obj-firefox-asan/xpcom/base/./../../../xpcom/base/nsCycleCollector.cpp:2664:7
    #4 0x74b7b62901b1 in nsCycleCollector::FreeSnowWhite(bool) /firefox/obj-firefox-asan/xpcom/base/./../../../xpcom/base/nsCycleCollector.cpp:2855:3
    #5 0x74b7b6a0805f in XPCJSContext::AfterProcessTask(unsigned int) /firefox/obj-firefox-asan/js/xpconnect/src/./../../../../js/xpconnect/src/XPCJSContext.cpp:1532:28
    #6 0x74b7b64902c1 in nsThread::ProcessNextEvent(bool, bool*) /firefox/obj-firefox-asan/xpcom/threads/./../../../xpcom/threads/nsThread.cpp:1235:24
    [...]

previously allocated by thread T0 (WebCOOP+COEP Co) here:
    #0 0x59e6764a69e4 in __interceptor_malloc _asan_rtl_:3
    #1 0x74b7b9ae12c5 in mozilla::dom::DOMArena::Allocate(unsigned long) /firefox/obj-firefox-asan/dist/include/mozilla/dom/DOMArena.h:44:17
    #2 0x74b7b9ae12c5 in nsNodeInfoManager::Allocate(unsigned long) /firefox/obj-firefox-asan/dom/base/nsNodeInfoManager.cpp:283:20
    #3 0x74b7bd6e7a27 in NS_NewHTMLUnknownElement(already_AddRefed<mozilla::dom::NodeInfo>, mozilla::dom::FromParser) /firefox/obj-firefox-asan/dom/html/./../../../dom/html/HTMLUnknownElement.cpp:11:1
    #4 0x74b7bd5ee27c in CreateHTMLElement(unsigned int, already_AddRefed<mozilla::dom::NodeInfo>, mozilla::dom::FromParser) /firefox/obj-firefox-asan/dom/html/./../../../dom/html/HTMLElementFactory.cpp:72:41
    #5 0x74b7b97c1be2 in nsContentUtils::NewXULOrHTMLElement(...) /firefox/dom/base/nsContentUtils.cpp:12211:18
    #6 0x74b7bd5ee148 in NS_NewHTMLElement(...) /firefox/obj-firefox-asan/dom/html/./../../../dom/html/HTMLElementFactory.cpp:56:10
    #7 0x74b7ba0d6fbe in NS_NewElement(...) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsNameSpaceManager.cpp:208:12
    #9 0x74b7c151adf8 in nsXMLContentSink::CreateElement(...) /firefox/obj-firefox-asan/dom/xml/./../../../dom/xml/nsXMLContentSink.cpp:529:10
    #10 0x74b7c15268e3 in nsXMLFragmentContentSink::CreateElement(...) /firefox/obj-firefox-asan/dom/xml/./../../../dom/xml/nsXMLFragmentContentSink.cpp:167:35
    #11 0x74b7c151f6d0 in nsXMLContentSink::HandleStartElement(...) /firefox/obj-firefox-asan/dom/xml/./../../../dom/xml/nsXMLContentSink.cpp:1011:12
    #14 0x74b7b6e754a3 in nsExpatDriver::HandleStartElement(...) /firefox/obj-firefox-asan/parser/htmlparser/./../../../parser/htmlparser/nsExpatDriver.cpp:479:32
    [rlbox-sandboxed expat frames: w2c_rlbox_doContent/doProlog/prologProcessor/callProcessor/XML_Parse_0]
    #22 0x74b7b6e7ec1a in nsExpatDriver::ParseChunk(...) /firefox/obj-firefox-asan/parser/htmlparser/./../../../parser/htmlparser/nsExpatDriver.cpp:1240:14
    #25 0x74b7b6e8bc52 in nsParser::ResumeParse(bool, bool, bool) /firefox/obj-firefox-asan/parser/htmlparser/./../../../parser/htmlparser/nsParser.cpp:706:48
    #26 0x74b7b6e8c70f in nsParser::Parse(...) /firefox/obj-firefox-asan/parser/htmlparser/./../../../parser/htmlparser/nsParser.cpp:560:10
    #27 0x74b7b6e8cb2e in nsParser::ParseFragment(...) /firefox/obj-firefox-asan/parser/htmlparser/./../../../parser/htmlparser/nsParser.cpp:590:12
    #28 0x74b7b978099e in nsContentUtils::ParseFragmentXML(...) /firefox/dom/base/nsContentUtils.cpp:7265:37
    #29 0x74b7b977efe7 in nsContentUtils::CreateContextualFragment(...) /firefox/dom/base/nsContentUtils.cpp:6886:9
    #30 0x74b7b9b07352 in nsRange::CreateContextualFragment(...) /firefox/obj-firefox-asan/dom/base/./../../../dom/base/nsRange.cpp:2777:10
    #31 0x74b7baf14d3b in mozilla::dom::Range_Binding::createContextualFragment(...) /firefox/obj-firefox-asan/dom/bindings/./RangeBinding.cpp:1308:83
    [... JS engine frames ...]

SUMMARY: AddressSanitizer: heap-use-after-free (/firefox/obj-firefox-asan/dist/bin/libxul.so+0x18947bcd) (BuildId: 58e09999d32b069c4f064daeff51cf86)
==11521==ABORTING
Attached file verifier_verdict-0.md —
Attached file verifier-1.jsonl —
Attached file verifier-0.jsonl —
Attached file patch.jsonl —
Attached file analyzer.jsonl —
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)
Attached file (secure) —
Attached file (secure) —
Group: dom-core-security → core-security-release
Status: ASSIGNED → RESOLVED
Closed: 4 months ago
Resolution: --- → FIXED
Target Milestone: --- → 155 Branch

Please add uplift requests for Beta and ESR115, ESR140, and ESR153

Attached file (secure) —
Attachment #9613874 - Flags: approval-mozilla-beta?

firefox-beta Uplift Approval Request

  • User impact if declined/Reason for urgency: sec-high issue
  • 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: Corrects an oversight, aligning to the spec, while also preventing sec-high issue.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attached file (secure) (obsolete) —
Attachment #9613875 - Flags: approval-mozilla-release?

firefox-release Uplift Approval Request

  • User impact if declined/Reason for urgency: sec-high issue
  • 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: Corrects an oversight, aligning to the spec, while also preventing sec-high issue.
  • String changes made/needed?: N/A
  • Is Android affected?: yes

firefox-esr115 Uplift Approval Request

  • User impact if declined/Reason for urgency: sec-high issue
  • 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: Corrects an oversight, aligning to the spec, while also preventing sec-high issue.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attachment #9613876 - Flags: approval-mozilla-esr115?
Attached file (secure) —

firefox-esr140 Uplift Approval Request

  • User impact if declined/Reason for urgency: sec-high issue
  • 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: Corrects an oversight, aligning to the spec, while also preventing sec-high issue.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attachment #9613877 - Flags: approval-mozilla-esr140?
Attached file (secure) —

firefox-esr153 Uplift Approval Request

  • User impact if declined/Reason for urgency: sec-high issue
  • 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: Corrects an oversight, aligning to the spec, while also preventing sec-high issue.
  • String changes made/needed?: N/A
  • Is Android affected?: yes
Attachment #9613878 - Flags: approval-mozilla-esr153?
Attached file (secure) —
Flags: needinfo?(mozilla)
Attachment #9613874 - Flags: approval-mozilla-beta? → approval-mozilla-beta+
Duplicate of this bug: 2054716
Attachment #9613877 - Flags: approval-mozilla-esr140? → approval-mozilla-esr140+
Attachment #9613878 - Flags: approval-mozilla-esr153? → approval-mozilla-esr153+
Attachment #9613876 - Flags: approval-mozilla-esr115? → approval-mozilla-esr115+

Comment on attachment 9613875 [details]
(secure)

-> 154

Attachment #9613875 - Flags: approval-mozilla-release? → approval-mozilla-release-
QA Whiteboard: [sec] [uplift] [qa-triage-done-c155/b154]
See Also: → 2058665
Blocks: 2060799
Attachment #9613875 - Attachment is obsolete: true
Whiteboard: [adv-main151+r][adv-esr115.36+r][adv-esr140.11+r][adv-esr115.39+]
Whiteboard: [adv-main151+r][adv-esr115.36+r][adv-esr140.11+r][adv-esr115.39+] → [adv-main154+r][adv-esr53.1+r][adv-esr140.14+r][adv-esr115.39+]
Whiteboard: [adv-main154+r][adv-esr53.1+r][adv-esr140.14+r][adv-esr115.39+] → [adv-main154+r][adv-esr153.1+r][adv-esr140.14+r][adv-esr115.39+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: