I have a method like below. I've set the FEATURE_SECURE_PROCESSING to true.
public String getString(org.w3c.dom.Node node) throws TransformerException {
StringWriter writer = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(node), new StreamResult(writer));
return writer.toString();
}
When I run my unit test below, I can list the files under project directory, meaning it is vulnerable to XXE attacks.
@Test
public void test() throws Exception {
String dir = new File("").getAbsolutePath();
String xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE test[" +
"<!ENTITY problemEntity SYSTEM \"" + dir + "\">" +
"]>" +
"<Response>" +
"&problemEntity;" +
"</Response>";
org.w3c.dom.Element node = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes()))
.getDocumentElement();
String name = getString(node);
System.out.println(name);
}
How can I secure the TransformerFactory to such attacks?