Configure Java XML parser to prevent XXE

After enabling XML eXternal Entity (XXE), you can create a malicious XML as shown below and read the contents of any file on your computer. It ’s no surprise that XXE attacks are part of OWASP ’s top ten vulnerabilities. The JavaXML library is particularly vulnerable to XXE injection attacks because most XML parsers have external entities enabled by default.

<?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>

As shown below, a simple implementation of DefaultHandler and Java SAX parser implements parsing of the XML file and displays the content of the passwd file. The Java SAX parser case is the main example here, but other parsers (such as DocumentBuilder and DOM4J) have similar default behavior.

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));
    }
};

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); 
...

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

from: https://dev.to//brianverm/configure-your-java-xml-parsers-to-prevent-xxe-213c

Published 0 original articles · liked 0 · visits 648

Guess you like

Origin blog.csdn.net/cunxiedian8614/article/details/105691141