how to fix 'Disable XML external entity (XXE) processing' vulnerabilities in java
我针对sonarqube运行了Java代码,并获得"禁用XML外部实体(XXE)处理"作为漏洞。我花了一些时间在Google上解决了这个问题。我一直在尝试很多方法,但是没有任何工作对我有用。我不知道我在想什么
我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 | 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); |
我正在使用Java 1.8,希望能提供任何帮助。谢谢
我最终添加了以下所有属性,以避免Sonar抱怨此漏洞:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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(); |
Java 9解决方案:
对我来说,将
只需设置这两个属性就足够了:
1 2 | factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); |
我通过添加以下代码段解决了此问题:
1 2 3 4 5 6 | saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); saxParserFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); saxParserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); saxParserFactory.setXIncludeAware(false); |