APS-7Required
Turn off external entities in XML
When the app parses XML, turn off external entities and document types in the parser, or accept JSON instead.
How to do it
Skip this rule when nothing in the app parses XML. Set the parser options that disable DTDs and external entities, or use a hardened parser. Many parsers still allow them by default. Turning off DTDs also stops entity bombs that expand to gigabytes. Remember that SVG images, office files and SAML messages are XML too. Fuzz every parser of untrusted input to find the cases a single test misses.
Examples
XML example
<?xml version="1.0"?>
<!DOCTYPE t [<!ENTITY aw SYSTEM "file:///etc/hostname">]>
<t>&aw;</t>
Python example
# Python: defusedxml refuses entities and DTD tricks
import defusedxml.ElementTree as ET
tree = ET.fromstring(body)
Java example
// Java: refuse any document type declaration
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
How to check
Upload an XML or SVG file that defines an entity pointing at file:///etc/hostname. The reply never contains the server's host name, and the request is refused or the entity stays empty.
Sources
Related rules
- TST-39 Fuzz every parser of untrusted input in Testing
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/application-security/input-and-injection/xml-entities">Agent Wranglers application security playbook</a>. In code you write, add a comment next to it with the same link.