Skip to main content

XXE in Java and Python: how external entities work and how to switch them off

XML external entity (XXE) injection is an old bug that keeps coming back because XML keeps coming back: SAML assertions, SOAP endpoints, Office documents, SVG uploads, RSS imports, configuration files sent by partners. Any code that parses XML from outside your trust boundary with a permissive parser can be made to read local files or send requests from your server.

This post explains how external entities work, the parser settings that turn them off in Java and Python, and the separate billion laughs problem. For a compact rule-by-rule reference, see our XXE rule page.

How an external entity attack works

XML lets a document declare entities in a DOCTYPE. An internal entity is a shortcut for text. An external entity points at a URI, and a parser that resolves it fetches that URI and inserts the content into the document.

<?xml version="1.0"?>
<!DOCTYPE order [
  <!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<order><note>&xxe;</note></order>

If the application parses this and echoes note back (in a response, an error message or a saved record), the attacker reads /etc/passwd. Swap the URI for http://169.254.169.254/ or an internal hostname and the parser makes a server-side request, which turns XXE into SSRF. When nothing is echoed, attackers use parameter entities and an external DTD they host to exfiltrate data out of band, so "we never return the XML" is not a defense.

The weakness is catalogued as CWE-611. The fix is always the same idea: do not let the parser process DOCTYPEs, or at least never let it resolve external entities or load external DTDs.

XXE in Java

Java has several XML APIs and each has its own switches. Do not assume a factory is safe: the defaults depend on the parser implementation and its configuration, and third-party providers picked up through newInstance() can behave differently. Harden every factory you create.

DocumentBuilderFactory (DOM)

// Vulnerable: default factory parsing request XML
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(request.getInputStream());
// Fixed: refuse any DOCTYPE at all
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
Document doc = dbf.newDocumentBuilder().parse(request.getInputStream());

disallow-doctype-decl is the strongest setting because it rejects the attack at the first line. If you genuinely need DTDs, set http://xml.org/sax/features/external-general-entities and http://xml.org/sax/features/external-parameter-entities to false and http://apache.org/xml/features/nonvalidating/load-external-dtd to false instead. The OWASP XXE Prevention Cheat Sheet notes that setExpandEntityReferences(false) alone is not a substitute for blocking external resources.

SAXParserFactory

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
spf.setNamespaceAware(true);
SAXParser parser = spf.newSAXParser();

XMLInputFactory (StAX)

StAX uses properties, not features:

XMLInputFactory xif = XMLInputFactory.newInstance();
xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
XMLStreamReader reader = xif.createXMLStreamReader(input);

The same rules apply to TransformerFactory, SchemaFactory, XMLReader, dom4j's SAXReader and JDOM's SAXBuilder. A frequent real-world shape is a small XmlUtils.parse(String) helper written once, without hardening, and called from a dozen controllers. Fix the helper and every caller is fixed.

Make hardening unconditional

Hardening inside an if (strictMode) block, or applied to one factory while a second factory elsewhere in the class stays default, is how fixes go missing. Configure the factory where it is created, every time, or build it in one place and inject it.

XXE in Python

Python's situation is better, but it depends on which library you use and which version.

Library External entities by default Notes
xml.etree.ElementTree Not expanded Raises a parse error when an entity occurs
xml.dom.minidom Not expanded Returns the entity unexpanded
xml.sax, xml.dom.pulldom Not processed since Python 3.7.1 Can be switched back on with a feature flag
lxml 5.0 and later Internal only resolve_entities='internal' became the default
lxml before 5.0 Resolved Upgrade, or set resolve_entities=False

The standard-library rows come from the Python XML vulnerabilities table; the lxml change is in the lxml 5.0 changelog. The risk in Python is mostly code that turns protections back on:

# Vulnerable: every lxml protection off
from lxml import etree
parser = etree.XMLParser(resolve_entities=True, load_dtd=True, no_network=False)
doc = etree.fromstring(request.body, parser)

# Vulnerable: sax with external entities re-enabled
import xml.sax
from xml.sax.handler import feature_external_ges
p = xml.sax.make_parser()
p.setFeature(feature_external_ges, True)
# Fixed: defusedxml wraps the stdlib parsers and lxml
from defusedxml.ElementTree import fromstring
doc = fromstring(request.body)

# Or, with lxml directly
parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True)

The Python documentation recommends defusedxml "for any server code that parses untrusted XML data". By default it also refuses entity declarations and external references, which covers the next problem.

Billion laughs: entity expansion without any file access

Even internal entities are dangerous. Ten entities that each reference the previous one ten times expand to a billion copies of a short string:

<!DOCTYPE lolz [
  <!ENTITY lol "lol">
  <!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
  <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
  <!-- ... up to lol9 -->
]>
<lolz>&lol9;</lolz>

This is CWE-776, a denial of service rather than a data leak. In Java, FEATURE_SECURE_PROCESSING applies entity expansion limits, and disallow-doctype-decl prevents the attack outright. In Python, Expat 2.4.1 and newer has protection against billion laughs and quadratic blowup, but the Python docs point out that the Expat version can depend on how Python was built, so check pyexpat.EXPAT_VERSION or use defusedxml.

What Vulkro checks

Vulkro Core reads parser construction and configuration; it never runs the parser. In Java, JAVA-XXE-001 fires when a JAXP factory, dom4j SAXReader or JDOM SAXBuilder parses a request-derived value in a file with no hardening, and JAVA-XXE-002 / JAVA-XXE-003 catch the unhardened helper and the call sites that feed it request data. Hardening inside a conditional branch does not count as hardening. In Python, the lxml check fires on resolve_entities=True, no_network=False or load_dtd=True, and XXE-PY-001 fires on xml.sax with external entity features enabled, staying quiet when the file imports defusedxml. JavaScript, Go and PHP have their own rules. The XXE rule page lists every rule, its severity and its known gaps.

FAQ

Is Java's DocumentBuilderFactory vulnerable to XXE by default?

Treat it as vulnerable until hardened. Set disallow-doctype-decl to true on every factory that parses untrusted XML, plus FEATURE_SECURE_PROCESSING, and do the equivalent for SAX, StAX and transformer factories.

Is Python's ElementTree safe from XXE?

xml.etree.ElementTree does not expand external entities. It is still exposed to entity expansion attacks if your Expat is old, so defusedxml is the safer choice for server code that parses untrusted XML.

What is the difference between XXE and billion laughs?

XXE resolves external entities to read files or make requests. Billion laughs uses nested internal entities to exhaust memory and CPU. Refusing DOCTYPE declarations stops both.

Check your XML parsing code: Start a 14-day trial. Related: SSRF in Node.js, since XXE often ends in a server-side request.