为什么DocumentBuilder下面的非验证SSCCE试图读取DTD文件?
public class FooMain {
private static String XML_INSTANCE = "<?xml version=\"1.0\"?> "+
"<!DOCTYPE note SYSTEM \"does-not-exist.dtd\"> "+
"<a/> ";
public static void main(String args[]) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(XML_INSTANCE.getBytes("UTF-8"));
Document doc = builder.parse(is);
}
}
代码爆炸:
[java] Exception in thread "main" java.io.FileNotFoundException: /lhome/minimal-for-SO/does-not-exist.dtd (No such file or directory)
[java] at java.io.FileInputStream.open(Native Method)
[java] at java.io.FileInputStream.<init>(FileInputStream.java:146)
[java] at java.io.FileInputStream.<init>(FileInputStream.java:101)
[java] at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
[java] at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
[java] at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
[java] at org.apache.xerces.impl.XMLEntityManager.startEntity(Unknown Source)
[java] at org.apache.xerces.impl.XMLEntityManager.startDTDEntity(Unknown Source)
[java] at org.apache.xerces.impl.XMLDTDScannerImpl.setInputSource(Unknown Source)
[java] at org.apache.xerces.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(Unknown Source)
[java] at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
[java] at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
[java] at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
[java] at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
[java] at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
[java] at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
[java] at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)
[java] at FooMain.main(FooMain.java:35)
鉴于构建器是非验证的,如果找不到文件(如果没有完全跳过搜索DTD文件),我预计至少不会崩溃。那么什么阻止文档被解析会导致构建器无法验证,因此无需访问DTD?
答案 0 :(得分:6)
为了忽略DTD指令和引用,您必须设置更多标志:
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
如果您正在构建Web应用程序,我建议您全局解决DTD实体,因为它具有潜在的安全性。
例如:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///dev/random" >]><foo>&xxe;</foo>
会导致服务器崩溃,同时尝试将/ dev / random中的内容插入&amp; xxe。