C#idiomatic C#
ca3061fundamentals/code-analysis/quality-rules

Code analysis

CA3061: Do not add schema by URL

Provides information about code analysis rule CA3061, including causes, how to fix violations, and when to suppress it.

CA3061 Security enabled by default in .NET 10: No
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

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.

csharp
#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.

ini
[*.{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.

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

Solution

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