CA3061: Do not add schema by URL

Property Value
Rule ID CA3061
Title Do not add schema by URL
Category Security
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

Overload of XmlSchemaCollection.Add(String, String) is using XmlUrlResolver to specify external XML schema in the form of an URI. If the URI String is tainted, it may lead to parsing of a malicious XML schema, which allows for the inclusion of XML bombs and malicious external entities. This could allow a malicious attacker to perform a denial of service, information disclosure, or server-side request forgery attack.

Rule description

Do not use the unsafe overload of the Add method because it may cause dangerous external references.

How to fix violations

  • Do not use XmlSchemaCollection.Add(String, String).

When to suppress warnings

Suppress this rule if you are sure your XML does not resolve dangerous external references.

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 CA3061
// The code that's violating the rule is on this line.
#pragma warning restore CA3061

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

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

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

Pseudo-code examples

Violation

The following pseudo-code sample illustrates the pattern detected by this rule. The second parameter's type is string.

using System;
using System.Xml.Schema;
...
XmlSchemaCollection xsc = new XmlSchemaCollection();
xsc.Add("urn: bookstore - schema", "books.xsd");

Solution

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
...
XmlSchemaCollection xsc = new XmlSchemaCollection();
xsc.Add("urn: bookstore - schema", new XmlTextReader(new FileStream(""xmlFilename"", FileMode.Open)));