| 屬性 | 值 |
|---|---|
| 規則識別碼 | CA5386 |
| 職稱 | 避免將 SecurityProtocolType 值寫入程式碼 |
| 類別 | 安全性 |
| 修正是造成中斷還是不中斷 | 不中斷 |
| 在 .NET 10 中預設啟用 | 否 |
| 適用語言 | C# 與 Visual Basic |
原因
符合下列任一條件時,此規則將會被觸發:
- 已引用安全但硬编码的System.Net.SecurityProtocolType值。
- 表示安全通訊協定版本的整數值已指派給 SecurityProtocolType 變數。
安全值為:
- Tls12
- Tls13
規則描述
傳輸層安全性協定 (TLS) 用於保護電腦之間的通訊,最常見於超文字傳輸協定安全 (HTTPS)。 通訊協定版本 TLS 1.0 和 TLS 1.1 已遭取代,而 TLS 1.2 和 TLS 1.3 是最新版本。 在未來,TLS 1.2 和 TLS 1.3 可能已遭取代。 為了確保您的應用程式保持安全,請避免硬式編碼通訊協定版本,並至少以 .NET Framework v4.7.1 為目標。 如需詳細資訊,請參閱 使用 .NET Framework 的傳輸層安全性 (TLS) 最佳做法。
如何修正違規
請勿硬式編碼 TLS 通訊協定版本。
隱藏警告的時機
如果您的應用程式以 .NET Framework v4.6.2 或更早版本為目標,而且可能會在具有不安全預設值的計算機上執行,您可以隱藏此警告。
隱藏警告
如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。
#pragma warning disable CA5386
// The code that's violating the rule is on this line.
#pragma warning restore CA5386
若要停用檔案、資料夾或專案的規則,請在組態檔中將其嚴重性設為 none。
[*.{cs,vb}]
dotnet_diagnostic.CA5386.severity = none
如需詳細資訊,請參閱 如何隱藏程式代碼分析警告。
虛擬程式代碼範例
列舉名稱違規
using System;
using System.Net;
public class ExampleClass
{
public void ExampleMethod()
{
// CA5386 violation
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
}
Imports System
Imports System.Net
Public Class TestClass
Public Sub ExampleMethod()
' CA5386 violation
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
End Sub
End Class
整數值違規
using System;
using System.Net;
public class ExampleClass
{
public void ExampleMethod()
{
// CA5386 violation
ServicePointManager.SecurityProtocol = (SecurityProtocolType) 3072; // TLS 1.2
}
}
Imports System
Imports System.Net
Public Class TestClass
Public Sub ExampleMethod()
' CA5386 violation
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType) ' TLS 1.2
End Sub
End Class
解決方案
using System;
using System.Net;
public class TestClass
{
public void TestMethod()
{
// Let the operating system decide what TLS protocol version to use.
// See https://learn.microsoft.com/dotnet/framework/network-programming/tls
}
}
Imports System
Imports System.Net
Public Class TestClass
Public Sub ExampleMethod()
' Let the operating system decide what TLS protocol version to use.
' See https://learn.microsoft.com/dotnet/framework/network-programming/tls
End Sub
End Class