CA3061:請勿透過 URL 新增結構描述

屬性
規則識別碼 CA3061
標題 請勿透過 URL 新增結構描述
類別 安全性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

XmlSchemaCollection.Add(String, String)的多載是用來XmlUrlResolver以 URI 形式指定外部 XML 架構。 如果 URI 字串遭到污染,可能會導致剖析惡意 XML 架構,以允許包含 XML 炸彈和惡意外部實體。 這可讓惡意攻擊者執行阻斷服務、資訊洩漏或伺服器端偽造要求攻擊。

檔案描述

請勿使用 方法的 Add 不安全多載,因為它可能會導致危險的外部參考。

如何修正違規

  • 請勿使用 XmlSchemaCollection.Add(String, String)

隱藏警告的時機

如果您確定 XML 無法解析危險的外部參考,請隱藏此規則。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

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

若要停用檔案、資料夾或項目的規則,請在組態檔中將其嚴重性設定為 。none

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

如需詳細資訊,請參閱 如何隱藏程式代碼分析警告

虛擬程式代碼範例

違規

下列虛擬程式代碼範例說明此規則偵測到的模式。 第二個參數的類型為 string

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

解決方案

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