XXE and XML Parser Security: Safe Settings for Untrusted Files
Explain external entities, DTD handling, network access, entity expansion and defensive parsing.
DTD Processing: The Primary Control
The Document Type Definition (DTD) is the section where entities are declared. If you disable DTD processing entirely, external entities cannot be declared and therefore cannot be resolved. This is the single most effective defensive setting.
Disabling DTDs per parser
| Parser/Language | Setting |
|---|---|
| Python (lxml) | parser = etree.XMLParser(load_dtd=False) |
| Java (DocumentBuilderFactory) | factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) |
| .NET (XmlReader) | settings.DtdProcessing = DtdProcessing.Prohibit |
| PHP (DOMDocument) | libxml_disable_entity_loader(true) before loading |
| C (libxml2) | xmlCtxtUseOptions(ctxt, XML_PARSE_NOENT) must be omitted; set XML_PARSE_DTDLOAD to 0 |
Verification: Parse a document containing <!DOCTYPE root [<!ENTITY test "value">]> and a reference to &test;. If DTDs are disabled, the parser rejects the file or leaves &test; unresolved rather than substituting "value".
What you lose
- Validation against an external DTD schema.
- Internal general entity shortcuts (
<!ENTITY name "replacement">). - Conditional sections (
IGNORE/INCLUDE) defined in the DTD.
If you do not need these features, disable DTDs. The W3C specification notes that a non-validating parser "need not" read external DTDs (§5.1), so refusing to load them does not violate the standard.
Network Access: Blocking Outbound Requests
If DTD processing must remain enabled, block the parser from making network requests. External entities often use SYSTEM identifiers pointing to URLs. When network access is blocked, those entities resolve to empty or trigger a recoverable error.
Disabling network access
- Python (lxml):
parser = etree.XMLParser(no_network=True) - Java:
factory.setFeature("http://apache.org/xml/features/network-access", false) - libxml2:
xmlCtxtUseOptions(ctxt, XML_PARSE_NONET) - PHP:
libxml_disable_entity_loader(true)also blocks network loading
Limitation: Blocking network access does not block file:// URI resolution. A SYSTEM "file:///etc/passwd" entity still reads the local filesystem. To prevent local file reads, you must disable DTDs entirely or configure the parser to reject file:// and data:// schemes explicitly. Not all parsers expose scheme-level filtering.
Verification: Create a test file referencing http://example.com/test.dtd. If the parser throws a network-related error or returns an empty entity, network access is blocked. If it retrieves the remote content, the setting is not active.
Entity Expansion: The Billion Laughs Attack
An entity does not need to reference an external file to cause harm. Recursive entity definitions can expand exponentially in memory. A file under 1 KB can expand to gigabytes of text, exhausting RAM and crashing the process. This is a denial-of-service vector, not a data leak.
Defensive limits
Set hard caps on entity expansion depth and total entity count:
| Parser | Parameter | Typical safe limit |
|---|---|---|
| Python (lxml) | huge_tree=False (default) |
Rejects entities exceeding ~10,000 expansions |
| Java | factory.setFeature("http://apache.org/xml/features/entity-expansion-limit", 1000) |
1,000 expansions |
| .NET | reader.Settings.MaxCharactersFromEntities = 1024 |
1,024 characters from entities |
| libxml2 | Omit XML_PARSE_HUGE (limits active by default) |
Limits active |
Do not enable huge_tree or XML_PARSE_HUGE unless parsing documents that legitimately exceed 100 MB and you have verified no untrusted content is present. Even then, prefer a streaming parser that never holds the entire expanded document in memory.
Verification: Construct a test file with 10 levels of nested entity expansion (the "billion laughs" pattern). Parse it. If the parser rejects the file or raises a resource-limit error, the cap is active. If the process hangs or crashes with an out-of-memory error, the cap is missing.
Minimal Safe Configuration
Combine all three layers into a single parser configuration.
Python with lxml:
from lxml import etree
parser = etree.XMLParser(
load_dtd=False,
no_network=True,
huge_tree=False
)
try:
tree = etree.parse("untrusted.xml", parser)
except etree.XMLSyntaxError as e:
print(f"Parser rejected file: {e}")
Java:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://apache.org/xml/features/network-access", false);
factory.setFeature("http://apache.org/xml/features/entity-expansion-limit", 1000);
DocumentBuilder builder = factory.newDocumentBuilder();
What this configuration cannot recover
- Previously parsed files: If a file containing an XXE payload was parsed before these settings were applied, data may already be exfiltrated. These settings prevent future occurrences only.
- Internal entities used for text reuse: If the file uses
<!ENTITY company "Acme Corp">and references&company;, disabling DTDs leaves the reference unresolved, producing a parse error. You must either accept that loss or implement a whitelist of known entity names. - Schema validation: Disabling DTDs prevents validation against a DTD schema. Use XML Schema (XSD) or RELAX NG instead; those formats are not vulnerable to XXE.
When DTDs Cannot Be Disabled
If your application validates against a known DTD (for example, SOAP message processing), you cannot disable DTDs entirely. In that case:
- Whitelist DTD locations: Configure the parser to load DTDs only from a specific directory or URL you control. Reject any file referencing an external DTD outside that whitelist.
- Strip the DTD before parsing: Remove the
<!DOCTYPE ... >block using a pre-processing step. This is fragile—attackers can obfuscate the declaration—but works for simple, well-formed inputs. - Use a separate validation pass: Parse the file with DTDs disabled first, extract a known identifier such as a schema location, then re-parse with DTDs enabled only for that specific schema.
None of these approaches are as safe as disabling DTDs entirely. The W3C specification's entity resolution machinery is powerful enough that even whitelisted DTDs can be exploited if the attacker controls part of an entity value.
Audit Your Current Configuration
Check the XML parsing code in your application now and verify three points:
- Is DTD processing explicitly disabled, not relying on defaults?
- Is network access explicitly disabled?
- Is entity expansion limited to a reasonable number (for example, 1,000)?
If any of these settings are missing or left at defaults, treat that as a high-severity finding. The file you parse next could be the one that leaks production data.