Description
Disable entity substitution and external DTD loading when lxml.etree.XMLParser processes untrusted XML. Blocking network access alone still leaves local file references to consider.
Potential impact
Readable files may be exposed, and a network loader may contact internal services. huge_tree=True relaxes parser safety limits and can increase memory use.
Remediation
Set resolve_entities=False, load_dtd=False and no_network=True explicitly. Keep huge_tree at its default of False. If the application does not require XML, consider a simpler format such as JSON.
Examples
Before
from flask import request
from lxml import etree
def bad_parse():
xml_body = request.get_data()
parser = etree.XMLParser(resolve_entities=True, load_dtd=True)
return etree.fromstring(xml_body, parser=parser)
After
from flask import request
from lxml import etree
def safe_parse():
xml_body = request.get_data()
parser = etree.XMLParser(resolve_entities=False, load_dtd=False, no_network=True)
return etree.fromstring(xml_body, parser=parser)
The second example passes this parser to etree.fromstring. Flask’s request.get_data() reads the entire body first, so enforce a request-size limit before reading it.