Search code examples
javasecurityxml-parsingunmarshallingveracode

How to resolve 'Improper Restriction of XML External Entity Reference ('XXE')'


I am trying to fix all of the vulnerabilities that veracode has listed out in my web application. I am stuck on this particular vulnerability which I actually have no idea about. 'Improper Restriction of XML External Entity Reference'. Cal any please help me and explain on the issue with the code and a way by which we can solve this?

    Object objec = null;

    try {
        JAXBContext jContext = JAXBContext.newInstance(context);
        Unmarshaller unmarshaller = jContext.createUnmarshaller();
        InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
        objec = unmarshaller.unmarshal(inputStream);  //Vulnerability reported in this line

    } catch (JAXBException e) {
        e.printStackTrace();
    }

    return objec;
}

Solution

  • This is a good reference for getting a solution: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java

    For example, in your case, you would just add these 2 properties to a XMLInputFactory and a stream reader:

            final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
            // These 2 properties are the key
            xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
            // Your stream reader for the xml string
            final XMLStreamReader xmlStreamReader = xmlInputFactory
                    .createXMLStreamReader(new StringReader(yourXMLStringGoesHere));
            final NsIgnoringXmlReader nsIgnoringXmlReader = new NsIgnoringXmlReader(xmlStreamReader);
            // Done with unmarshalling the XML safely
            final YourObject obj = (YourObject) unmarshaller.unmarshal(nsIgnoringXmlReader);
    

    This should help with the Veracode scan