我有一个像下面这样的方法。我已将 FEATURE_SECURE_PROCESSING 设置为 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();
}
当我在下面运行我的单元测试时,我可以列出项目目录下的文件,这意味着它容易受到 XXE 攻击。
@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);
}
如何保护 TransformerFactory 免受此类攻击?