Security Warnings for Python ElementTree and minidom
Python’s standard XML processing libraries, including
xml.etree.ElementTree and xml.dom.minidom, are
inherently vulnerable to malicious XML payloads when parsing untrusted
data. According to the official Python documentation, these built-in
parsers are not secured against maliciously constructed inputs, exposing
applications to severe Denial of Service (DoS) attacks, memory
exhaustion, and related vulnerabilities.
Core Vulnerabilities
The standard library modules use underlying parsers that lack default protections against common XML entity-based attacks. The primary security risks include:
1. XML Entity Expansion (Billion Laughs Attack)
An attacker defines nested XML entities where each entity references multiple instances of another entity. When the parser resolves these entities, the payload grows exponentially in memory. Parsing a payload of only a few kilobytes can rapidly consume gigabytes of RAM, causing the Python process to crash or become completely unresponsive.
2. Quadratic Blowup Attack
Similar to the Billion Laughs attack, the quadratic blowup attack relies on entity expansion but avoids deep nesting. Instead, an attacker defines a single, extremely large entity and references it thousands of times inside the XML body. The parser expands these references linearly, leading to severe CPU and memory exhaustion.
3. DTD Retrieval and Resource Starvation
If an XML document contains external Document Type Definitions (DTDs) or excessive declaration loops, the parser may spend excessive CPU cycles or attempt network connections to process the definitions, leading to thread blocking and service degradation.
Vulnerability Scope by Module
Both standard modules share underlying C-based parser dependencies (typically Expat), leading to identical vulnerability profiles for untrusted input:
xml.etree.ElementTree: Vulnerable to XML Entity Expansion and Quadratic Blowup.xml.dom.minidom: Vulnerable to XML Entity Expansion and Quadratic Blowup.
Neither module validates the resource limits of parsed entities by default, making them unsafe for web services, API endpoints, or file upload handlers that accept XML from third parties.
Recommended Mitigations
To safely parse XML data from untrusted sources in Python, implement the following alternatives:
- Use
defusedxml: Thedefusedxmlpackage is a drop-in replacement specifically designed to neutralize entity expansion, quadratic blowup, and external entity resolution across all standard Python XML parsers. - Configure
lxmlsecurely: If using the third-partylxmllibrary, explicitly disable external entity resolution and network access by settingresolve_entities=Falseandno_network=Truewithin the parser configuration.