XSLT parsing vulnerable to XXE (TransformerFactory)

Bug Pattern: XXE_XSLT_TRANSFORM_FACTORY

Attack

XSLT External Entity (XXE) attacks can occur when an XSLT parser supports external entities while processing XSLT received from an untrusted source.

Risk: Expose local file content (XXE: XML eXternal Entity)

  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2. <xsl:template match="/">
  3. <xsl:value-of select="document('/etc/passwd')">
  4. </xsl:value-of></xsl:template>
  5. </xsl:stylesheet>

Solution

In order to avoid exposing dangerous feature of the XML parser, you can do the following change to the code.

Vulnerable Code:

  1. Transformer transformer = TransformerFactory.newInstance().newTransformer();
  2. 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.

  1. TransformerFactory factory = TransformerFactory.newInstance();
  2. factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "all");
  3. factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "all");
  4. Transformer transformer = factory.newTransformer();
  5. transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  6. transformer.transform(input, result);

Solution disabling DTD:

This setting will protect you against remote file access but not denial of service.

  1. TransformerFactory factory = TransformerFactory.newInstance();
  2. factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
  3. Transformer transformer = factory.newTransformer();
  4. transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  5. 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)