XElement.Parse && XDocument.Parse 在 c# 中容易受到 XML 注入

XElement.Parse && XDocument.Parse are vulnerable to XML injection in c#

以下代码被 fortify 检测为 XML 注入。请有人帮我解决这个问题。

LockUserXml(string xml)
{
   var doc = XDocument.Parse(xml);
   ..
   ..
}

LocalUserXml(XmlElement root, ExportXmlParameter param)
{
   XElement rootElement = XElement.Parse(root.OuterXml);
   ..
   ..
   ..
}

来自Microsoft doc

How to fix XML violations

  • Don't write raw XML. Instead, use methods or properties that XML-encode their input.

  • Or, XML-encode input before writing raw XML.

  • Or, validate user input by using sanitizers for primitive type conversion and XML encoding

你可以做的是使用 Load 而不是 Parse 配置 reader 设置(参见 XmlReaderSettings)如下:

LockUserXml(string xml)
{
   var xmlReader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings() { XmlResolver = null });
   var doc = XDocument.Load(xmlReader);
   ..
   ..
}

另见 How to prevent XXE attack ( XmlDocument in .net)