XML parsing vulnerable to XXE (XPathExpression)

Bug Pattern: XXE_XPATH

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)

  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <!DOCTYPE foo [
  3. <!ENTITY xxe SYSTEM "file:///etc/passwd" > ]>
  4. <foo>&xxe;</foo>

Risk 2: Denial of service (XEE: Xml Entity Expansion)

  1. <?xml version="1.0"?>
  2. <!DOCTYPE lolz [
  3. <!ENTITY lol "lol">
  4. <!ELEMENT lolz (#PCDATA)>
  5. <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
  6. <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
  7. <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
  8. [...]
  9. <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
  10. ]>
  11. <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:

  1. DocumentBuilder builder = df.newDocumentBuilder();
  2. XPathFactory xPathFactory = XPathFactory.newInstance();
  3. XPath xpath = xPathFactory.newXPath();
  4. XPathExpression xPathExpr = xpath.compile("/somepath/text()");
  5. xPathExpr.evaluate(new InputSource(inputStream));

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 Denial of Service attack and remote file access.

  1. DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
  2. df.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
  3. DocumentBuilder builder = df.newDocumentBuilder();
  4. [...]
  5. xPathExpr.evaluate( builder.parse(inputStream) );

Solution disabling DTD:

By disabling DTD, almost all XXE attacks will be prevented.

  1. DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
  2. spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
  3. DocumentBuilder builder = df.newDocumentBuilder();
  4. [...]
  5. xPathExpr.evaluate( builder.parse(inputStream) );

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)
XML External Entity (XXE) Prevention Cheat Sheet_Prevention_Cheat_Sheet#XPathExpression)