From 5b1df7e538f442f54b5c7201ab43f30bfedc93d9 Mon Sep 17 00:00:00 2001 From: Wendal Chen Date: Thu, 5 Jul 2018 21:15:41 +0800 Subject: [PATCH] =?UTF-8?q?update:=20=E7=BB=A7=E7=BB=AD=E6=9B=B4=E6=96=B0X?= =?UTF-8?q?mls=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/org/nutz/lang/Xmls.java | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/org/nutz/lang/Xmls.java b/src/org/nutz/lang/Xmls.java index dbe8234df..01a30c23c 100644 --- a/src/org/nutz/lang/Xmls.java +++ b/src/org/nutz/lang/Xmls.java @@ -48,9 +48,40 @@ public abstract class Xmls { * @throws ParserConfigurationException */ public static DocumentBuilder xmls() throws ParserConfigurationException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setExpandEntityReferences(false); - return factory.newDocumentBuilder(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + String FEATURE = null; + + // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented + // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl + + FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; + dbf.setFeature(FEATURE, true); + + // If you can't completely disable DTDs, then at least do the following: + // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities + + // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities + + // JDK7+ - http://xml.org/sax/features/external-general-entities + FEATURE = "http://xml.org/sax/features/external-general-entities"; + dbf.setFeature(FEATURE, false); + + // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities + + // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities + + // JDK7+ - http://xml.org/sax/features/external-parameter-entities + FEATURE = "http://xml.org/sax/features/external-parameter-entities"; + dbf.setFeature(FEATURE, false); + + // Disable external DTDs as well + FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd"; + dbf.setFeature(FEATURE, false); + + // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" + dbf.setXIncludeAware(false); + dbf.setExpandEntityReferences(false); + return dbf.newDocumentBuilder(); } public static Document xml(InputStream ins) {