Implement multiple layers of protection to ensure that if one defense fails, others will still protect your application:
// Java - JAXP DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // Completely disable DTDs
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
// PHP
libxml_disable_entity_loader(true); // For PHP < 8.0
// In PHP 8.0+, you must use LIBXML_NONET flag instead
// .NET
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
settings.XmlResolver = null;
// Python - Use defusedxml library
from defusedxml import ElementTree
tree = ElementTree.parse(xml_file)
// Node.js - xml2js
const parser = new xml2js.Parser({
explicitEntities: false,
resolveEntities: false
});
When possible, avoid XML processing entirely by using alternative data formats:
// Instead of XML, use JSON:
{
"user": {
"name": "John Doe",
"email": "john.doe@example.com",
"role": "user"
}
}
Employ specialized security libraries to process XML safely:
// OWASP Enterprise Security API (ESAPI) example
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.codecs.XMLEntityCodec;
String cleanXML = ESAPI.encoder().encodeForXML(untrustedXML);
// Process the cleaned XML
Regularly test your application for XXE vulnerabilities:
Configure Web Application Firewall (WAF) rules to detect and block common XXE attack patterns:
// Example ModSecurity WAF rule to block DOCTYPE declarations
SecRule REQUEST_BODY "
Ensure you're using the latest versions of XML parsers and libraries: