XML External Entity Injection(xml外链实体注入)
xml 外联实体
参考博客:http://blog.csdn.net/cristianojason/article/details/51000438
例如:
源文件
<?xml version="1.0" encoding="GBK"?> <!DOCTYPE root[ <!ENTITY titlue "我是title1"> <!ENTITY titlue2 "我是title2"> ]> <root1> <title value="&titlue;"> &titlue; </title> <title2> <value><a>&titlue2;</a></value> </title2> </root1>
解析后的结果:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE root> <root1> <title value="我是title1">我是title1</title> <title2> <value> <a>我是title2</a> </value> </title2> </root1>
危害:如果外链的是一个网页, 或者其他程序,又或者外联一下攻击性的东西, 导致的后果可想而知。
解决方案:
禁止外链实体:
public static XmlDocument GetXmlDocumentIgnoreDtd(string xmlContent) { var xmlDoc = new XmlDocument { XmlResolver = null }; var settings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; // 禁止外联实体,防止注入 byte[] array = Encoding.UTF8.GetBytes(xmlContent); using (var stream = new MemoryStream(array)) { var reader = XmlReader.Create(stream, settings); xmlDoc.Load(reader); } return xmlDoc; }
注:如果导入的xml中存在外联实体,则会抛出异常,因为该方法不允许外链实体,如果想导入外联实体则需要修改DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null