如何修复java中的“禁用XML外部实体(XXE)处理”漏洞

che*_*too 13 java xml owasp sonarqube

我针对 sonarqube 运行了我的 java 代码,我得到了“禁用 XML 外部实体 (XXE) 处理”作为漏洞。我花了一些时间在谷歌上解决这个问题。我一直在尝试很多方法,但没有任何方法对我有用。我不知道我错过了什么

我的代码:

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        docFactory.setFeature(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        docFactory.setFeature(XMLInputFactory.SUPPORT_DTD, false);

        docFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        docFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        docFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document doc = docBuilder.parse(filepath);
Run Code Online (Sandbox Code Playgroud)

我正在使用 java 1.8,任何帮助表示赞赏。谢谢

cho*_*omp 15

我最终添加了以下所有属性以避免声纳抱怨这个漏洞:

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        //REDHAT
        //https://www.blackhat.com/docs/us-15/materials/us-15-Wang-FileCry-The-New-Age-Of-XXE-java-wp.pdf
        factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

        //OWASP
        //https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        // Disable external DTDs as well
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
        factory.setXIncludeAware(false);
        factory.setExpandEntityReferences(false);

        DocumentBuilder builder = factory.newDocumentBuilder();
Run Code Online (Sandbox Code Playgroud)


Lin*_*ine 6

Java 9+ 解决方案:

对我来说,更改DocumentBuilderFactory.newInstance()DocumentBuilderFactory.newDefaultInstance()足以消除此警告。

  • 在没有附加信息的情况下,这听起来更像是一种击败 Sonar 检查的方法(例如,它不知道此方法,因此它不标记它),而不是解决潜在的漏洞。基本上,看起来你也做了同样的事情,但是是在声纳的背后。(再一次,没有附加信息)。 (4认同)

小智 5

只需设置这两个属性就足够了:

factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
Run Code Online (Sandbox Code Playgroud)