Setting FEATURE_SECURE_PROCESSING
may or may not help, depending on what implementation TransformerFactory.getInstance()
actually returns.
For example in Java 7 with no additional XML libraries on classpath setting transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
does not help.
You can fix this by providing a Source
other than StreamSource
(which factory would need to parse using some settings that you do not control).
For example you can use StAXSource
like this:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // does not help in Java 7
Transformer transformer = transformerFactory.newTransformer();
// StreamSource is insecure by default:
// Source source = new StreamSource(new StringReader(xxeXml));
// Source configured to be secure:
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLEventReader xmlEventReader = xif.createXMLEventReader(new StringReader(xxeXml));
Source source = new StAXSource(xmlEventReader);
transformer.transform(
source,
new StreamResult(new ByteArrayOutputStream()));
Note the actual TrasformerFactory
may not actually support StAXSource
, so you need to test your code with the classpath as it would be on production. For example Saxon 9 (old one, I know) does not support StAXSource
and the only clean way of "fixing" it that I know is to provide custom net.sf.saxon.Configuration
instance.