TExcelTAD

XML External Entities (XXE)

XML has a feature most developers never use and many parsers used to enable by default: a document can declare entities in its DOCTYPE, and an external entity's value is loaded from a URI, a local file or a URL, when the parser meets the reference. An application that parses XML from users (SOAP and XML APIs, SAML assertions, office documents and SVG images, which are ZIP archives or XML underneath, RSS imports) with such a parser lets the user write <!ENTITY x SYSTEM "file:///etc/passwd"> and get the file's contents back in the parsed result. XXE (CWE-611) gives file disclosure, SSRF through http:// entities, and denial of service through recursive entity expansion. Modern parsers are mostly safe by default, so the real lesson is to know which settings turn the danger back on. This lesson shows both behaviours with Python's own parsers on a file that exists only in the example's virtual file system.

Definitions

  • Internal entity: <!ENTITY company "TAD Market">, expanded wherever &company; appears.
  • External general entity: <!ENTITY x SYSTEM "file:///path"> or SYSTEM "http://host/…", its replacement text read from the URI.
  • External parameter entity: <!ENTITY % p SYSTEM "…"> used inside the DTD itself; the basis of blind, out-of-band XXE (data sent to an attacker's server inside a URL).
  • Entity expansion bomb ("billion laughs"): nested internal entities, each expanding to ten copies of the previous, a few hundred bytes growing to gigabytes.
  • defusedxml: a Python package that wraps the standard library parsers and refuses DTDs with entities, external references and expansion bombs, raising an exception instead. The same idea exists in other ecosystems as parser flags (Java's XMLConstants.FEATURE_SECURE_PROCESSING and disallow-doctype-decl, .NET's DtdProcessing.Prohibit, libxml2 without XML_PARSE_NOENT).

Python's parsers, safe and unsafe

The example writes a "secret" file into Pyodide's in-memory file system (it lives only inside this run), then parses the same hostile document three ways: with ElementTree (the default most code uses), with a SAX parser in its default configuration, and with a SAX parser where a developer turned on external entities, for example to support a legacy feature.

python · try it yourself
import io, xml.sax
import xml.etree.ElementTree as ET
from xml.sax.handler import feature_external_ges

with open("/tmp/lab-secret.txt", "w") as f:
    f.write("DB_PASSWORD=lab-only-not-real")

hostile = """<?xml version="1.0"?>
<!DOCTYPE order [ <!ENTITY xxe SYSTEM "file:///tmp/lab-secret.txt"> ]>
<order><note>&xxe;</note></order>"""

try:
    print("ElementTree:      ", repr(ET.fromstring(hostile).find("note").text))
except ET.ParseError as e:
    print("ElementTree:       ParseError:", e)

class Notes(xml.sax.ContentHandler):
    def __init__(self):
        super().__init__(); self.text = ""
    def characters(self, content):
        self.text += content

for label, external in [("SAX default:      ", False), ("SAX external on:  ", True)]:
    h, p = Notes(), xml.sax.make_parser()
    p.setContentHandler(h)
    p.setFeature(feature_external_ges, external)
    p.parse(io.StringIO(hostile))
    print(label, repr(h.text))
ElementTree:       ParseError: undefined entity &xxe;: line 3, column 13
SAX default:       ''
SAX external on:   'DB_PASSWORD=lab-only-not-real'

ElementTree refused the document outright: the external entity is never fetched, so &xxe; counts as undefined. The SAX parser in its default configuration also skipped the external entity and returned an empty note. One setFeature(feature_external_ges, True) later, the parser opened the file and the secret appeared in the parsed data, which an application would then store, echo back in an error message or a confirmation page, and hand to the attacker. On a real server the same line reads /etc/passwd, cloud credentials files or application configuration.

The defusedxml idea, without the package

defusedxml is not part of Pyodide, so here is its principle in a few lines: inspect the DOCTYPE with the parser's own events and refuse documents that declare entities at all, before anything is expanded. Real code should use the package itself (defusedxml.ElementTree.fromstring), which also covers external DTDs and the other parsers.

python · try it yourself
import xml.parsers.expat

class EntitiesForbidden(ValueError):
    pass

def safe_parse(text):
    p = xml.parsers.expat.ParserCreate()
    def no_entities(name, is_parameter, value, base, system_id, public_id, notation):
        raise EntitiesForbidden(f"entity {name!r} declared ({'external' if system_id else 'internal'})")
    p.EntityDeclHandler = no_entities
    elements = []
    p.StartElementHandler = lambda name, attrs: elements.append(name)
    p.Parse(text, True)
    return elements

docs = {
    "plain order": "<order><item sku='T-1'/></order>",
    "external entity": '<!DOCTYPE o [<!ENTITY x SYSTEM "file:///tmp/lab-secret.txt">]><o>&x;</o>',
    "expansion bomb": '<!DOCTYPE b [<!ENTITY a "lol"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">]><b>&b;</b>',
}
for name, doc in docs.items():
    try:
        print(f"{name:16} parsed: {safe_parse(doc)}")
    except EntitiesForbidden as e:
        print(f"{name:16} refused: {e}")
plain order      parsed: ['order', 'item']
external entity  refused: entity 'x' declared (external)
expansion bomb   refused: entity 'a' declared (internal)

The bomb here has only two levels (it would expand to 30 characters); a real one nests ten levels for a billion copies. Refusing entity declarations stops both families at the first declaration. (Recent expat versions also limit expansion amplification on their own, another reason to keep parsers updated.)

How XXE is detected

  • Testing (in scope): every input that is XML or becomes XML: Content-Type: application/xml or text/xml bodies (try switching a JSON endpoint to XML too; some frameworks accept both), SOAP, SAML responses, file uploads of SVG, DOCX/XLSX (unzip, add a DOCTYPE to [Content_Types].xml or word/document.xml), RSS and sitemap imports. Use a harmless local file of the lab target (/etc/hostname) or an http:// entity pointing at your own lab listener for blind cases.
  • Code review: parser construction with DTD processing or external entities enabled: resolve_entities=True / no_network=False in lxml, setFeature(feature_external_ges, True) in Python SAX, DocumentBuilderFactory without secure-processing features in Java, XmlResolver set in .NET, LIBXML_NOENT in PHP.
  • Logs and egress: XML bodies containing <!DOCTYPE or <!ENTITY, parser errors about entities, and application servers making outbound requests or reading unexpected files right after XML requests.

How it is fixed

  1. Disable DTDs entirely where they aren't needed (almost always): defusedxml in Python, disallow-doctype-decl in Java, DtdProcessing.Prohibit in .NET.
  2. If DTDs are needed, disable external entities and external DTD loading, and limit entity expansion.
  3. Prefer JSON or a schema-validated format where you design the API; keep XML libraries patched.
  4. Run parsers with least privilege and without egress, so a missed configuration can't read secrets or reach internal hosts.

Pitfalls

  • One safe parser, one unsafe one: the main API uses a hardened parser, but the SVG thumbnailer or the DOCX importer uses a library default.
  • XSLT and XInclude: transformations and xi:include can read files too; disable them for untrusted input.
  • Assuming "the library is new, so it's safe": some still resolve entities when a flag is set for unrelated reasons (validation against a DTD).

Practice

1. A Java service uses DocumentBuilderFactory.newInstance() with default settings to parse uploaded XML. What do you recommend?

Set factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true), plus FEATURE_SECURE_PROCESSING, and disable external general and parameter entities and external DTD loading; then add a test that a document with an external entity is rejected.

2. Why are SVG uploads an XXE risk even if the site never "uses XML"?

SVG is XML. A server that parses uploaded SVGs (to read dimensions, sanitise, or rasterise them) runs an XML parser on attacker input, with whatever entity settings that library uses.

Test yourself

What does an external entity let an attacker do against a misconfigured parser?

  1. Run SQL
  2. Make the parser read a local file or URL and include it in the parsed data
  3. Change the XML version
  4. Nothing

In the example, which configuration disclosed the secret file?

  1. ElementTree default
  2. SAX default
  3. SAX with feature_external_ges turned on
  4. All three

What is the simplest robust fix for XXE?

  1. Escape ampersands
  2. Disallow DTDs (e.g. defusedxml, disallow-doctype-decl)
  3. Use HTTPS
  4. Validate with a regex

What is a 'billion laughs' document?

  1. A joke file
  2. Nested internal entities that expand exponentially: a denial-of-service attack on the parser
  3. An external DTD
  4. An XSLT stylesheet