CA5374:请勿使用 XslTransform

属性
规则 ID CA5374
标题 请勿使用 XslTransform
类别 安全性
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用

原因

实例化 System.Xml.Xsl.XslTransform,它不会限制潜在的危险外部引用或阻止脚本。

规则说明

对不受信任的输入进行操作时,XslTransform 易受攻击。 攻击可能会执行任意代码。

如何解决冲突

XslTransform 替换为 System.Xml.Xsl.XslCompiledTransform。 有关更多指南,请参阅 [/dotnet/standard/data/xml/migrating-from-the-xsltransform-class]。

何时禁止显示警告

XslTransform 对象、XSLT 样式表和 XML 源数据都来自受信任的源。

抑制警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

#pragma warning disable CA5374
// The code that's violating the rule is on this line.
#pragma warning restore CA5374

若要对文件、文件夹或项目禁用该规则,请在配置文件中将其严重性设置为 none

[*.{cs,vb}]
dotnet_diagnostic.CA5374.severity = none

有关详细信息,请参阅如何禁止显示代码分析警告

伪代码示例

冲突

目前,下面的伪代码示例演示了此规则可检测的情况。

using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace TestForXslTransform
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new XslTransform object.
            XslTransform xslt = new XslTransform();

            // Load the stylesheet.
            xslt.Load("https://server/favorite.xsl");

            // Create a new XPathDocument and load the XML data to be transformed.
            XPathDocument mydata = new XPathDocument("inputdata.xml");

            // Create an XmlTextWriter which outputs to the console.
            XmlWriter writer = new XmlTextWriter(Console.Out);

            // Transform the data and send the output to the console.
            xslt.Transform(mydata, null, writer, null);
        }
    }
}

解决方案

using System.Xml;
using System.Xml.Xsl;

namespace TestForXslTransform
{
    class Program
    {
        static void Main(string[] args)
        {
            // Default XsltSettings constructor disables the XSLT document() function
            // and embedded script blocks.
            XsltSettings settings = new XsltSettings();

            // Execute the transform.
            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load("https://server/favorite.xsl", settings, new XmlUrlResolver());
            xslt.Transform("inputdata.xml", "outputdata.html");
        }
    }
}