XML parsing vulnerable to XXE (TransformerFactory)
Bug Pattern: XXE_DTD_TRANSFORM_FACTORY
Attack
XML External Entity (XXE) attacks can occur when an XML parser supports XML entities while processing XML received from an untrusted source.
Risk 1: Expose local file content (XXE: XML eXternal Entity)
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd" > ]>
<foo>&xxe;</foo>
Risk 2: Denial of service (XEE: Xml Entity Expansion)
<?xml version="1.0"?>
<!DOCTYPE lolz [
<!ENTITY lol "lol">
<!ELEMENT lolz (#PCDATA)>
<!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
<!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
[...]
<!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
]>
<lolz>&lol9;</lolz>
Solution
In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code.
Vulnerable Code:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(input, result);
The following snippets show two available solutions. You can set one feature or both.
Solution using “Secure processing” mode:
This setting will protect you against remote file access but not denial of service.
TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "all");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "all");
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(input, result);
Solution disabling DTD:
This setting will protect you against remote file access but not denial of service.
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(input, result);
References
CWE-611: Improper Restriction of XML External Entity Reference (‘XXE’)
CERT: IDS10-J. Prevent XML external entity attacks
OWASP.org: XML External Entity (XXE) Processing
WS-Attacks.org: XML Entity Expansion
WS-Attacks.org: XML External Entity DOS
WS-Attacks.org: XML Entity Reference Attack
Identifying Xml eXternal Entity vulnerability (XXE)