Getting Veracode vulnerability "Improper Restriction of XML External Entity Reference" for "TransformerFactory", There are several solution for this and the most relevant I found is: solution. But after trying these solution none of them worked. Below is the code:
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);
The error is:
javax.xml.transform.TransformerConfigurationException: Unsupported TransformerFactory feature: http://javax.xml.XMLConstants/property/accessExternalDTD
Currently I am running the application on Java 8 and the relevant jars are: saxon9.jar, xalan-2.7.2.jar
I tried several combination for these like:
//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);
But getting the same error. How to solve this error?
According to OWASP when describing how to prevent XML eXternal Entity injection (XXE), when using Java and TransformerFactory
the recommended approach is the following:
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
Please, note they are configuring attributes, not features.
Please, consider review as well the documentation provided for the setAttribute
method in TransformerFactory
, I think it can be of help:
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 byTransformer.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 thenewTransformer(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 thenewTransformer(Source)
method.