संपादित करें

इसके माध्यम से साझा किया गया


CA5374: Do not use XslTransform

Property Value
Rule ID CA5374
Title Do not use XslTransform
Category Security
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

Instantiating an System.Xml.Xsl.XslTransform, which doesn't restrict potentially dangerous external references or prevent scripts.

Rule description

XslTransform is vulnerable when operating on untrusted input. An attack could execute arbitrary code.

How to fix violations

Replace XslTransform with System.Xml.Xsl.XslCompiledTransform. For more guidance, see Migrating from the XslTransform class.

When to suppress warnings

The XslTransform object, XSLT style sheets, and XML source data are all from trusted sources.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

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

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

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

For more information, see How to suppress code analysis warnings.

Pseudo-code examples

Violation

At present, the following pseudo-code sample illustrates the pattern detected by this rule.

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);
        }
    }
}

Solution

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