Objects that parse or handle XML data can lead to XML External Entity (XXE) attacks when not configured properly. Improper restriction of XML external entity processing can lead to server-side request forgery and information disclosure.
1public DocumentBuilder createDocumentBuilderNoncompliant(InputStream inputStream) throws Exception {
2 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
3 factory.setValidating(true);
4 factory.setIgnoringElementContentWhitespace(true);
5 // Noncompliant: not configured to handle external entities.
6 DocumentBuilder builder = factory.newDocumentBuilder();
7 builder.parse(inputStream);
8 return builder;
9}
1public DocumentBuilder createDocumentBuilderCompliant(InputStream inputStream) throws Exception {
2 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
3 factory.setValidating(true);
4 factory.setIgnoringElementContentWhitespace(true);
5 // Compliant: configured to disable external entities.
6 factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
7 DocumentBuilder builder = factory.newDocumentBuilder();
8 builder.parse(inputStream);
9 return builder;
10}