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

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

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

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

这是获得解决方案的一个很好的参考:https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#java

例如,在您的情况下,您只需将这两个属性添加到 XMLInputFactory 和流 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);

这应该有助于 Veracode 扫描