CA5374:請勿使用 XslTransform

屬性
規則識別碼 CA5374
標題 請勿使用 XslTransform
類別 安全性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

具現化 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");
        }
    }
}