阻止XmlReader扩展XML实体
有没有办法阻止.NET的XmlReader
类在阅读内容时将XML实体扩展为它们的值?
例如,假设以下XML用作输入:
á
让我们假设无法达到扩展aacute实体所需的外部OASIS DTD。 我希望读者按顺序阅读author元素,然后是EntityReference
类型的aacute节点,最后是作者end元素,而不会抛出任何错误。 我怎样才能做到这一点?
更新:我还想阻止扩展字符实体,如á
。
一种方法是使用`XmlTextReader’,如下所示:
using (var reader = new XmlTextReader(@"your url")) { // note this reader.EntityHandling = EntityHandling.ExpandCharEntities; while (reader.Read()) { // here it will be EntityReference with no exceptions } }
如果这不是一个选项 – 你可以对XmlReader
做同样的事情,但是需要一些反思(至少我不知道另一种方式):
using (var reader = XmlReader.Create(@"your url", new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore // or Parse })) { // get internal property which has the same function as above in XmlTextReader reader.GetType().GetProperty("EntityHandling", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(reader, EntityHandling.ExpandCharEntities); while (reader.Read()) { // here it will be EntityReference with no exceptions } }
XML解析很危险。 在某些情况下,它允许CVE和拒绝服务攻击。
例如CVE-2016-3255
此外,它还被Black Hat EU 2013讨论
最感兴趣的文档是MLDTDEntityAttacks ,它为开发人员提供实现和Recomendations。
检索资源 :
]> &windowsfile;
DoS :
]> &a4;
回到你的问题。
正如@Evk写道:通过设置EntityHandling,您可以阻止扩展除CharEntities之外的所有实体。
我不知道除了你自己的XmlReader实现之外的防止扩展CharEntity的解决方案。
我想你也想要防止解析& ' < > "
& ' < > "
仅供参考 XmlTextReader如何以及在何处解析CharEntity
XmlTextReader的
ParseElementContent
& 案件
ParseText
Char实体案例
ParseCharRefInline
该函数最终解析数字字符实体引用(例如
和á
)
ParseNumericCharRefInline
此函数解析命名字符实体引用( & ' < > "
)
ParseNamedCharRef