Rules / Java
SHIELD-JAVA-006
XXE via DocumentBuilderFactory
What it detects
DocumentBuilderFactory created without disabling external entities is vulnerable to XXE.
How to fix
Call setFeature to disable doctype declarations and external general and parameter entities.
Vulnerable — Shield flags thisXmlReportParser.java
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import java.io.InputStream;
public class XmlReportParser {
public Document parse(InputStream untrustedXml) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(untrustedXml);
}
}Fixed — scans cleanXmlReportParser.java
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import java.io.InputStream;
public class XmlReportParser {
public Document parse(InputStream untrustedXml) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(untrustedXml);
}
}Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-JAVA-006, the fixed one does not.