使用 Xerces 2 防止 XXE(外部 XML 实体)注入

mag*_*ggn 4 java xml xerces2-j

我正在尝试实现 XML 验证,以防止 XXE 注入。OWASP-Page上显示的代码与本机 JDK8 完美配合。

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(fSchema);
    Validator validator = schema.newValidator();

    validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
    validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

    validator.validate(new StreamSource(fXml));
Run Code Online (Sandbox Code Playgroud)

问题是我在 Wildfly10 上使用此代码,其中内部使用 Xerces2 (xercesImpl-2.11.0.SP4) 并且无法识别所需的 XMLConstants。

Exception in thread "main" org.xml.sax.SAXNotRecognizedException: Property 'http://javax.xml.XMLConstants/property/accessExternalDTD' is not recognized.
Run Code Online (Sandbox Code Playgroud)

该问题在具有给定 Maven 依赖项的单元测试中很容易重现

<!-- https://mvnrepository.com/artifact/xerces/xercesImpl -->
<dependency>
    <groupId>xerces</groupId>
    <artifactId>xercesImpl</artifactId>
    <version>2.11.0.SP4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

尽管可以使用参数在 Wildfly10 上停用 Xerces2

-jaxpmodule“javax.xml.jaxp-provider”

这不是我想做的。

有人知道如何正确配置 Xerxces2 以防止 XXE 注入...

小智 5

为了避免在 fortify 中进行 XXE(外部 XML 实体)注入:

在逻辑部分设置以下代码行以避免 XXE 注入。

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);
Run Code Online (Sandbox Code Playgroud)