如何解决“对XML外部实体引用('XXE')的不当限制”

时间:2019-05-21 10:53:42

标签: java security xml-parsing unmarshalling veracode

我正在尝试修复veracode在我的Web应用程序中列出的所有漏洞。我被这个我实际上不知道的特定漏洞所困扰。 '对XML外部实体的不当限制 参考'。可以,请帮助我,并解释有关代码的问题以及解决该问题的方法?

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

1 个答案:

答案 0 :(得分:0)

这是获取解决方案的良好参考:https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java

例如,在您的情况下,您只需将这两个属性添加到XMLInputFactory和流阅读器中即可:

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

这应该有助于Veracode扫描