配置的XML解析器不会阻止也不限制外部实体的解析。这可以将解析器暴露给XML外部实体攻击

时间:2016-11-21 07:57:52

标签: java security serialization deserialization transform

我们对代码进行了安全审核,他们提到我们的代码容易受到外部实体(XXE)攻击。

解释 - XML外部实体攻击受益于XML功能,可在处理时动态构建文档。 XML实体允许从给定资源动态包含数据。外部实体允许XML文档包含来自外部URI的数据。除非另外配置,否则外部实体强制XML解析器访问由URI指定的资源,例如本地机器或远程系统上的文件。此行为将应用程序公开给XML外部实体(XXE)攻击,这些攻击可用于执行本地系统的拒绝服务,未经授权访问本地计算机上的文件,扫描远程计算机以及执行远程系统的拒绝服务。以下XML文档显示了XXE攻击的示例。

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///dev/random" >]><foo>&xxe;</foo>

如果XML解析器尝试用/ dev / random文件的内容替换实体,则此示例可能会使服务器(在UNIX系统上)崩溃。

建议 - 应安全地配置XML unmarshaller,以便它不允许外部实体作为传入XML文档的一部分。要避免XXE注入,请不要使用直接处理XML源的unmarshal方法,如java.io.File,java.io.Reader或java.io.InputStream。使用安全配置的解析器解析文档,并使用采用安全

的unmarshal方法

解析器作为XML源,如以下示例所示:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(<XML Source>);
Model model = (Model) u.unmarshal(document);

编写的代码位于发现XXE攻击的位置 -

1- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
2- DocumentBuilder db = dbf.newDocumentBuilder();
3- InputSource is = new InputSource();
4- is.setCharacterStream(new StringReader(xml));
5-
6- Document doc = db.parse(is);
7- NodeList nodes = doc.getElementsByTagName(elementsByTagName);
8-
9- return nodes;

我在第6行遇到XXE攻击。 请帮助我如何解决上述问题。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:0)

有关补救的详细说明和选项,建议您查看OWASP XEE Cheat Sheet

我们提出了类似的问题并通过禁用DOCTYPES(上面链接的第一个建议)解决了这个问题,因为我们并不需要它们:

ind1

答案 1 :(得分:0)

对于javax.xml.parsers.DocumentBuilderFactory,以下设置足以防止XXE攻击

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

// Disallow the DTDs (doctypes) entirely.
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);   

// Or do the following:
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);