如何针对 XXE 全局配置 XML 解析器?
How do I globally configure XML parsers against XXE?
在Java中解析XML变得非常简单。大多数代码最终调用 DocumentBuilderFactory.newInstance()
,其中 returns 是一个易受 XXE kind of attacks by default.
攻击的 XML 解析器
OWASP 文档详细解释了如何配置从 DocumentBuilderFactory
返回的 XML 解析器以防止此类攻击,但我如何将其设置为默认值?
我的问题是我正在使用像 JDOM2 这样的库和其他处理 XML 的代码,我无法轻易更改所有这些代码。我如何使安全解析器成为默认解析器?
我看到 DocumentBuilderFactory
支持 javax.xml.parsers.DocumentBuilderFactory
但它对 Web 应用程序有何作用?
您可以尝试编写自定义的 DocumentBuilderFactory
并为 javax.xml.parsers.DocumentBuilderFactory
设置系统 属性
所以DocumentBuilderFactory.newInstance()
将return您的自定义class
查看文档 DocumentsBuilderFactory#newInstance
[编辑] 现在这可能会导致 Web 容器出现问题,例如 Tomcat,它不支持每个 webapp 的系统属性。这里的解决办法是给容器设置属性,把自定义工厂放在服务器的class路径下。这样,所有网络应用程序都会使用它 - 这可能是您想要的重要安全功能。
见http://web-in-security.blogspot.fr/2014/11/detecting-and-exploiting-xxe-in-saml.html or https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Prevention_Cheat_Sheet
但是下面的代码提供了很好的保护
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
dbf.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
dbf.setExpandEntityReferences(false);
不确定 XMLConstants.FEATURE_SECURE_PROCESSING 的效果。它通常在 dbf.setFeature 中记录,但并非在所有版本的 Xerces 中都可用
在Java中解析XML变得非常简单。大多数代码最终调用 DocumentBuilderFactory.newInstance()
,其中 returns 是一个易受 XXE kind of attacks by default.
OWASP 文档详细解释了如何配置从 DocumentBuilderFactory
返回的 XML 解析器以防止此类攻击,但我如何将其设置为默认值?
我的问题是我正在使用像 JDOM2 这样的库和其他处理 XML 的代码,我无法轻易更改所有这些代码。我如何使安全解析器成为默认解析器?
我看到 DocumentBuilderFactory
支持 javax.xml.parsers.DocumentBuilderFactory
但它对 Web 应用程序有何作用?
您可以尝试编写自定义的 DocumentBuilderFactory
并为 javax.xml.parsers.DocumentBuilderFactory
所以DocumentBuilderFactory.newInstance()
将return您的自定义class
查看文档 DocumentsBuilderFactory#newInstance
[编辑] 现在这可能会导致 Web 容器出现问题,例如 Tomcat,它不支持每个 webapp 的系统属性。这里的解决办法是给容器设置属性,把自定义工厂放在服务器的class路径下。这样,所有网络应用程序都会使用它 - 这可能是您想要的重要安全功能。
见http://web-in-security.blogspot.fr/2014/11/detecting-and-exploiting-xxe-in-saml.html or https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Prevention_Cheat_Sheet
但是下面的代码提供了很好的保护
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
dbf.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
dbf.setExpandEntityReferences(false);
不确定 XMLConstants.FEATURE_SECURE_PROCESSING 的效果。它通常在 dbf.setFeature 中记录,但并非在所有版本的 Xerces 中都可用