XML External Entity injection (XXE) is one of those bugs where the fix is a one-line setting, and the hard part is knowing whether your parser needs it. In Python the answer depends on which library parses the XML, which version it is, and which of its parser classes you picked. "We use the default" is not an answer you can stop at.
This article covers what XXE is in one paragraph, what Python's parsers actually do by default (I ran it, so the output below is real), where a parser you'd call "safe" has still bitten people, a small parser wrapper that rejects the whole feature, and how to prove the fix with a canary file and a regression test.
Only test applications you own or are authorized to test. Every example uses stand-in data: a canary file I planted and a server on 127.0.0.1.
What XXE is
XML lets a document declare its own entities in a document type definition (DTD). An external entity says "replace &x; with whatever lives at this URI", and that URI can be a local file or a URL. If a parser resolves it while reading untrusted input, the document can pull a file off the server or make the server call something it can reach. OWASP's cheat sheet lists three outcomes: exposed local files, server-side request forgery (SSRF), and resource exhaustion. The weakness is CWE-611.
Almost nobody wants this feature. PortSwigger's summary is that these bugs arise because the parser supports dangerous XML features the application doesn't need. So the fix is to turn the features off, not to filter the input.
Where XML hides
You don't need an endpoint that says "XML". PortSwigger's Web Security Academy describes three places it shows up beyond the obvious one:
-
Content type switching. A form or JSON endpoint may also accept
text/xmland parse the body. - File uploads. Formats like SVG and DOCX are XML, so an image or document processor may parse one.
-
XInclude. If user data is placed inside a server-side XML document,
xi:includecan load a file without any DTD.
When you're reviewing code, grep for every XML parse call, and for every library that parses XML for you (office documents, SVG handling, SOAP or SAML clients). Each is a parser with its own defaults.
What Python's parsers do by default
The Python docs say Expat, the parser behind the standard library's xml package, doesn't access local files or create network connections by default. Separately, they warn that Expat versions below 2.7.2 may be vulnerable to billion-laughs style entity expansion, and that Python may bundle or use a system Expat, so you should check pyexpat.EXPAT_VERSION. Mine says expat_2.8.2.
lxml is a different story. Its parser options include resolve_entities, no_network (on by default per the docs) and huge_tree, which the docs say disables security restrictions. The lxml changelog records the history:
-
lxml 5.0.0 (2023-12-29): lxml stopped expanding external entities by default. The new default is
resolve_entities='internal'. -
lxml 6.1.0 (2026-04-17):
iterparseandETCompatXMLParserstill hadresolve_entitiesset toTruewhen you didn't set it, which allowed XXE to local files. That was fixed, and tracked as CVE-2026-41066. NVD and GitHub's advisory (GHSA-vfmq-68hx-4jfw) both describe it, and NVD says versions before 6.1.0 are affected.
So "lxml's default is safe" was true for the main parser for years while two other entry points weren't. That's the pattern to remember: check each parser class you use, not the library.
Here is a script that tests all of it against a canary file and a counting server I run locally. It plants CANARY-7f3a in a temp file, builds a document whose entity points at it, then a second document whose entity points at my local server, and tries each setup:
# xxe_demo.py (excerpt)
FILE_DOC = (
f'<?xml version="1.0"?><!DOCTYPE d [<!ENTITY x SYSTEM "{canary.as_uri()}">]>'
"<d>&x;</d>"
).encode()
show("stdlib ElementTree, file entity", lambda: ET.fromstring(FILE_DOC))
show("lxml default parser, file entity", lambda: etree.fromstring(FILE_DOC))
show("lxml resolve_entities=True, file entity",
lambda: etree.fromstring(FILE_DOC, etree.XMLParser(resolve_entities=True)))
Output (Python 3.14.7, lxml 6.1.3):
stdlib ElementTree, file entity -> ParseError
lxml default parser, file entity -> XMLSyntaxError
lxml resolve_entities=True, file entity -> text='CANARY-7f3a'
lxml resolve_entities=True, no_network=False -> text='from-local-server'
requests that reached my local server: 1
lxml iterparse default, file entity -> XMLSyntaxError
The two defaults I tried refuse (the error text is "undefined entity" for the stdlib and "Entity 'x' not defined" for lxml). Flip one option to resolve_entities=True and the canary comes straight back in the parsed text. Add no_network=False and the parser makes a real request to the server I started. Notice that nothing in the input changed between those runs. The setting did.
The fix: don't accept a DTD at all
OWASP's guidance leads with this: disable DTDs whenever possible, reject DOCTYPE declarations if the parser supports it, keep XInclude off, and treat an unsupported security setting as a configuration failure rather than continuing with partial hardening. An API that takes an order or a config file almost never needs a DTD, so reject it up front. You then have no entities to expand or resolve, whichever parser or version sits behind it.
Here's a standard-library version. A throwaway Expat parser raises as soon as it sees a DOCTYPE, and only then do we build the tree:
# safe_xml.py
import xml.etree.ElementTree as ET
from xml.parsers import expat
MAX_BYTES = 1_000_000
class RejectedXML(ValueError):
pass
def _no_doctype(*_args):
raise RejectedXML("DOCTYPE declarations are not accepted")
def parse_untrusted(data: bytes) -> ET.Element:
"""Parse request XML. No DTD, so no entities to expand, none to resolve."""
if len(data) > MAX_BYTES:
raise RejectedXML("document too large")
gate = expat.ParserCreate()
gate.StartDoctypeDeclHandler = _no_doctype
try:
gate.Parse(data, True)
return ET.fromstring(data)
except expat.ExpatError as exc:
raise RejectedXML(f"not well-formed XML: {exc}") from exc
If you're on lxml, set the options explicitly so a future reader (or a future default) can't change the behavior, and reject the DOCTYPE after parsing:
# lxml_safe.py
from lxml import etree
PARSER = etree.XMLParser(
resolve_entities=False, # never substitute entities
no_network=True, # lxml's default, stated so a reader sees it
load_dtd=False,
dtd_validation=False,
huge_tree=False, # keep libxml2's safety limits on
)
def parse_untrusted(data: bytes):
root = etree.fromstring(data, PARSER)
info = root.getroottree().docinfo
if info.doctype:
raise ValueError("DOCTYPE declarations are not accepted")
return root
I ran both: a normal <order> parses, and the hostile file-entity document raises DOCTYPE declarations are not accepted from the lxml version.
Two cautions from the same cheat sheet. Keep XInclude disabled, since it can load resources independently of DTDs (the stdlib wrapper never calls it, and a test below checks that). And if you use a Java, .NET or C++ parser somewhere else in your stack, don't reuse this Python advice: OWASP's cheat sheet has per-parser settings, and the right ones differ.
Also remember the size cap. Preventing XXE doesn't prevent every XML denial-of-service, as OWASP notes, which is why the wrapper limits the input size too.
Prove it: a canary, a control, and a test that goes red
A parse error isn't proof, and neither is "we set the flag". Proof is a value you planted coming back, or a request you can see arriving.
On a system you own or are authorized to test, the loop is short:
-
Plant a canary. Put a harmless file with a unique string on the test server, for example
/tmp/xxe-canary.txtcontainingCANARY-7f3a. For the network side, run a listener you control that logs requests. -
Send a control first. A normal document to
https://app.example.com/api/orders, so you know what a good response looks like. -
Send the entity. The same document with a DOCTYPE declaring an external entity that points at your canary file (
file:///tmp/xxe-canary.txt) or your listener, and the entity used in a field the response echoes. - Read the evidence. Canary text in the response, or a hit in your listener's log, is proof. A 400 or a parse error is not a finding: it may be the fix working. If the response never echoes anything, the entity can still be resolved, which is what PortSwigger's blind XXE material covers with out-of-band detection. Your listener is how you'd see that.
Do the same through every XML-consuming route you found: the content-type switch, the upload, the XInclude form.
For the fix, make it a test. The suite I wrote plants the same canary, runs a local counting server, and sends seven documents to parse_untrusted: a control, an external file entity, an external network entity, an external DTD, nested internal entities (a tiny billion-laughs shape), an XInclude document that must come back as inert data, and oversized or malformed input. The core assertions:
def test_rejects_external_network_entity(self):
doc = (
'<?xml version="1.0"?><!DOCTYPE d [<!ENTITY x SYSTEM '
f'"http://127.0.0.1:{self.port}/probe">]><d>&x;</d>'
).encode()
with self.assertRaises(RejectedXML):
parse_untrusted(doc)
self.assertEqual(self.hits, []) # the server never saw a request
def test_xinclude_stays_inert_data(self):
doc = (
'<d xmlns:xi="http://www.w3.org/2001/XInclude">'
f'<xi:include parse="text" href="{self.canary.as_uri()}"/></d>'
).encode()
root = parse_untrusted(doc)
self.assertNotIn("CANARY", "".join(root.itertext()))
Result on the fixed code:
Ran 7 tests in 0.526s
OK
Then the check that matters: I pointed the same suite at a stand-in "before" parser, lxml with resolve_entities=True and no_network=False. Five of the seven tests failed. Four of those failed because the hostile document was accepted; the fifth is the size and malformed-input test, since that stand-in has no size cap and raises a different exception type. A test that can't fail proves nothing, so run it against the old behavior at least once.
Put it in CI. A dependency bump or a new parser call can quietly reopen this, and the test turns that into a red build instead of a finding.
A short review checklist
- Every XML parse call is behind one wrapper, and the wrapper rejects DOCTYPE.
-
lxmlis 6.1.0 or newer, anditerparseand any compatibility parser setresolve_entitiesexplicitly. -
pyexpat.EXPAT_VERSIONis 2.7.2 or newer, or you reject DTDs so it doesn't matter. - XInclude is not enabled on untrusted input.
- File uploads that are XML under the hood (SVG, DOCX) go through the same wrapper or a hardened library.
- The regression test uses a canary and a counting listener, and it fails on the old parser.
Try it yourself
Practice on targets built for it. PortSwigger's Web Security Academy has hands-on labs on retrieving files with external entities, XXE to SSRF, XInclude and XXE via image upload. OWASP Juice Shop has two XXE challenges ("XXE Data Access" and "XXE DoS") and runs locally:
docker run --rm -p 127.0.0.1:3000:3000 bkimminich/juice-shop
Then take your own code, find each place that parses XML, and run the canary test against it.
The short version
- XXE exists because a parser supports a feature your app never asked for. Turn it off.
- Python's stdlib parser doesn't resolve external entities by default; lxml's main parser stopped in 5.0.0, and two other lxml entry points only got there in 6.1.0. Check each parser class you use.
- Reject DOCTYPE at the edge and the library's defaults stop mattering.
- Prove both directions: a canary that comes back on the vulnerable setup, and a test that goes red on it.
Further reading
- OWASP: XML External Entity Prevention Cheat Sheet
- PortSwigger Web Security Academy: XML external entity (XXE) injection
- CWE-611: Improper Restriction of XML External Entity Reference
- Python docs: XML security
- lxml: Parsing XML and HTML and the lxml changelog
- GitHub advisory GHSA-vfmq-68hx-4jfw (CVE-2026-41066)
I'm Krishna, a pentester and the founder of Xalgorix, an open-source AI pentester that only reports vulnerabilities it has actually exploited.
๐ If this was useful, follow me for more hands-on web & API security write-ups.
๐ Connect with me on LinkedIn: https://www.linkedin.com/in/xalgord/

Top comments (0)