TransformerFactory 的 XML EER 限制不当

Improper Restriction of XML EER for TransformerFactory

“TransformerFactory”的 Veracode 漏洞“XML 外部实体引用的不当限制”,有几种解决方案,我发现最相关的是:。但是在尝试了这些解决方案后,none 成功了。下面是代码:

import net.sf.saxon.TransformerFactoryImpl;
.....
 TransformerFactory genericFactory = TransformerFactoryImpl.newInstance();
 genericFactory.setFeature("http://javax.xml.XMLConstants/property/accessExternalDTD", false);  
 genericFactory.setFeature(Constants.FEATURE_SECURE_PROCESSING,true);

错误是:

javax.xml.transform.TransformerConfigurationException: Unsupported TransformerFactory feature: http://javax.xml.XMLConstants/property/accessExternalDTD

目前我是运行Java8上的应用,相关的jar是: saxon9.jar, xalan-2.7.2.jar

我尝试了几种组合,例如:

//1
 TransformerFactory genericFactory = javax.xml.transform.TransformerFactory.newInstance();
 genericFactory.setFeature("http://javax.xml.XMLConstants/property/accessExternalDTD", false);  
//2
 TransformerFactory genericFactory = com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newInstance();
 genericFactory.setFeature("http://javax.xml.XMLConstants/property/accessExternalDTD", false);

但是得到同样的错误。如何解决这个错误?

根据 OWASP 在描述如何防止 XML eXternal Entity injection (XXE), when using Java and TransformerFactory the recommended approach 时如下:

TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

请注意,它们是配置属性,而不是功能。

请考虑复习 TransformerFactory 中为 setAttribute 方法提供的 documentation,我认为它可以提供帮助:

Access to external DTDs in the source file is restricted to the protocols specified by the XMLConstants.ACCESS_EXTERNAL_DTD property. If access is denied during transformation due to the restriction of this property, TransformerException will be thrown by Transformer.transform(Source, Result).

Access to external DTDs in the stylesheet is restricted to the protocols specified by the XMLConstants.ACCESS_EXTERNAL_DTD property. If access is denied during the creation of a new transformer due to the restriction of this property, TransformerConfigurationException will be thrown by the newTransformer(Source) method.

Access to external reference set by the stylesheet processing instruction, Import and Include element is restricted to the protocols specified by the XMLConstants.ACCESS_EXTERNAL_STYLESHEET property. If access is denied during the creation of a new transformer due to the restriction of this property, TransformerConfigurationException will be thrown by the newTransformer(Source) method.