Insecure XML parser

Insecure XML parser

Description

Check which parser and settings handle untrusted XML. Access to external resources and entity expansion depend on the library version and any changes to the default parser.

Potential impact

The parser may expose readable files or contact internal services if network references are enabled. Large inputs and excessive entity expansion can exhaust CPU and memory.

Remediation

Disable unnecessary external entity resolution and DTD loading. Limit input size and parsing resources, handle parse errors at the request boundary, and keep Python, the parser and its underlying libraries patched.

Examples

lxml

Before

python
# XML parsing with the default lxml parser
from lxml import etree

def unsafe_parse(xml_string):
    root = etree.fromstring(xml_string)
    return root

xml_data = """<?xml version="1.0"?>
<!DOCTYPE root [
<!ELEMENT root ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<root>&xxe;</root>"""
root = unsafe_parse(xml_data)

After

python
# XML parsing without entity expansion
from lxml import etree

def safe_parse(xml_string):
    parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True)
    root = etree.fromstring(xml_string, parser=parser)
    return root

xml_data = """<?xml version="1.0"?>
<!DOCTYPE root [
<!ELEMENT root ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<root>&xxe;</root>"""
root = safe_parse(xml_data)

Since lxml 5.0, XMLParser defaults to resolve_entities="internal". Check older versions and customized default parsers separately. The second example explicitly disables entity substitution, external DTD loading and network access in lxml. It uses the maintained lxml API in place of defusedxml.lxml.

ElementTree

Before

python
# XML parsing with standard ElementTree
import xml.etree.ElementTree as ET

def unsafe_parse(xml_string):
    root = ET.fromstring(xml_string)
    return root

xml_data = """<?xml version="1.0"?>
<!DOCTYPE root [
<!ELEMENT root ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<root>&xxe;</root>"""
root = unsafe_parse(xml_data)

After

python
# Safe XML parsing with defusedxml
from defusedxml.ElementTree import fromstring

def safe_parse(xml_string):
    root = fromstring(xml_string)
    return root

xml_data = """<?xml version="1.0"?>
<!DOCTYPE root [
<!ELEMENT root ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<root>&xxe;</root>"""
root = safe_parse(xml_data)

Standard ElementTree raises a parse error for the external entity shown here. By default, defusedxml.ElementTree rejects the declaration itself with EntitiesForbidden. Handle both kinds of error at the request boundary.

References