DEV Community

Cover image for Configure your Java XML-parsers to prevent XXE

Configure your Java XML-parsers to prevent XXE

With XML eXternal Entity (XXE) enabled, it is possible to create a malicious XML, as seen below, and read the content of an arbitrary file on the machine. It’s not a surprise that XXE attacks are part of the OWASP Top 10 vulnerabilities.Java XML libraries are particularly vulnerable to XXE injection because most XML parsers have external entities by default enabled.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE bar [
       <!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<song>
   <artist>&xxe;</artist>
   <title>Bohemian Rhapsody</title>
   <album>A Night at the Opera</album>
</song>
Enter fullscreen mode Exit fullscreen mode

A naive implementation of the DefaultHandler and the Java SAX parser, like that seen below, parses this XML file and reveal the content of the passwd file. The Java SAX parser case is used as the main example here but other parsers, like DocumentBuilder and DOM4J, have similar default behaviour.

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler = new DefaultHandler() {

    public void startElement(String uri, String localName,String qName,Attributes attributes) throws SAXException {
        System.out.println(qName);
    }

    public void characters(char ch[], int start, int length) throws SAXException {
        System.out.println(new String(ch, start, length));
    }
};

Enter fullscreen mode Exit fullscreen mode

Changing the default settings to disallow external entities and doctypes for xerces1 or xerces2, respectively, prevents these kinds of attacks.

...
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

factory.setFeature("https://xml.org/sax/features/external-general-entities", false);
saxParser.getXMLReader().setFeature("https://xml.org/sax/features/external-general-entities", false);
factory.setFeature("https://apache.org/xml/features/disallow-doctype-decl", true); 
...
Enter fullscreen mode Exit fullscreen mode

For more hands-on information about preventing malicious XXE injection, please take a look at the OWASP XXE Cheatsheet

This was just 1 of 10 Java security best practices. Take a look at the full 10 and the easy printable one-pager available

Top comments (0)