Prevent XXE in Python (defusedxml, lxml)
To prevent XXE in Python, use the defusedxml package in place of the standard-library XML modules — it rejects DTDs and entities outright — and when you need lxml, build an XMLParser with resolve_entities=False, no_network=True and load_dtd=False before parsing untrusted input.
Python's standard-library XML modules have historically been vulnerable to entity attacks, and several (xml.sax, xml.dom.minidom, xml.dom.pulldom) still process external entities. The maintained recommendation is defusedxml, a drop-in replacement that blocks DTDs, external entities and entity-expansion bombs. For lxml, configure the parser explicitly.
Secure parser configuration
defusedxml (standard library replacement)
# pip install defusedxml
from defusedxml.ElementTree import parse, fromstring
tree = parse("data.xml") # raises EntitiesForbidden / DTDForbidden
root = fromstring(untrusted_bytes) # on malicious inputdefusedxml mirrors xml.etree, xml.sax, xml.dom.minidom etc. with safe behaviour.
lxml (hardened parser)
from lxml import etree
parser = etree.XMLParser(
resolve_entities=False, # do not substitute entities
no_network=True, # block http(s)/ftp fetches
load_dtd=False, # do not load external DTDs
dtd_validation=False,
)
tree = etree.parse("data.xml", parser)resolve_entities=False is the key setting; no_network stops SSRF/OOB.
xml.etree.ElementTree (stdlib)
# ElementTree does not expand external general entities and raises on
# undefined entities, but prefer defusedxml for defence against DTD/bomb edge
# cases:
from defusedxml.ElementTree import parse
tree = parse("data.xml")Common pitfalls that re-introduce XXE
- Using xml.sax / xml.dom.minidom on untrusted input without defusedxml.
- Forgetting that lxml's default parser will resolve local-file entities.
- Leaving no_network at its default so OOB/SSRF entities still fetch.
- Calling tree.xinclude() on untrusted documents.
Verifying the fix
Parse a classic file-read payload and a blind OOB payload. defusedxml raises EntitiesForbidden/DTDForbidden; the hardened lxml parser returns empty entity values and makes no network request. Confirm no outbound connection is attempted during parsing.