英文:
TransformerFactory still vulnerable to XXE attacks
问题
我已经设置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\"?>" +
"<!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以防止此类攻击?
英文:
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?
答案1
得分: 1
你正在向TransformerFactory
提供一个DOMSource
,因此在TransformerFactory
存在之前已经处理了DTD。你需要在解析XML文档时应用任何控制,这是在创建DOM节点时发生的。
英文:
You're supplying a DOMSource
to the TransformerFactory
, so the DTD was processed before the TransformerFactory
came into existence. You need to apply any controls at the point the XML document is parsed, which is when the DOM Node gets created.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论