XXE – Java secure coding

Java applications using XML libraries are particularly vulnerable to XXE because the default settings for most Java XML parsers is to have XXE enabled. To use these parsers safely, you have to explicitly disable XXE in the parser you use. The following describes how to disable XXE in the most commonly used XML parsers for Java.

JAXP DocumentBuilderFactory


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);

try {
   dbf.setFeature("http://apache.org/xml/features/allow-java-encodings", true);
}
catch (ParserConfigurationException e) {
   System.err.println("could not set parser feature");
}

 

SAXParserFactory

import javax.xml.parsers.SAXParser;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
SAXParser parser = /* created from SAXParserFactory */;
XMLReader reader = parser.getXMLReader();
try {
   reader.setFeature("http://xml.org/sax/features/allow-java-encodings", true);
}
catch (SAXException e) {
   System.err.println("could not set parser feature");
}

 

XMLReader

To protect a Java XMLReader from XXE, do this:

XMLReader spf = XMLReaderFactory.createXMLReader();
spf.setFeature(“http://xml.org/sax/features/external-general-entities”, false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
spf.setFeature(“http://apache.org/xml/features/nonvalidating/load-external-dtd”,false);

more libraries and references:
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#Java

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *