CA5398:避免以硬式編碼方式寫入 SslProtocols 值

屬性
規則識別碼 CA5398
標題 避免以硬式編碼方式寫入 SslProtocols 值
類別 安全性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

當符合下列任一條件時,就會引發此規則:

保管庫值為:

  • Tls12
  • Tls13

檔案描述

傳輸層安全性 (TLS) 最常使用超文字傳輸通訊協定安全 (HTTPS) 保護電腦之間的通訊。 通訊協定版本 TLS 1.0 和 TLS 1.1 已遭取代,而 TLS 1.2 和 TLS 1.3 是最新版本。 在未來,TLS 1.2 和 TLS 1.3 可能已遭取代。 若要確保應用程式保持安全,請避免將通訊協定版本硬式編碼。 如需詳細資訊,請參閱 使用 .NET Framework 的傳輸層安全性 (TLS) 最佳做法。

如何修正違規

請勿硬式編碼 TLS 通訊協定版本。

隱藏警告的時機

如果您需要連線到無法升級為使用未來 TLS 通訊協定版本的舊版服務,則隱藏警告是安全的。

隱藏警告

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

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

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

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

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

虛擬程式碼範例

列舉名稱違規

using System;
using System.Security.Authentication;

public class ExampleClass
{
    public void ExampleMethod()
    {
        // CA5398 violation
        SslProtocols sslProtocols = SslProtocols.Tls12;
    }
}
Imports System
Imports System.Security.Authentication

Public Class TestClass
    Public Function ExampleMethod() As SslProtocols
        ' CA5398 violation
        Return SslProtocols.Tls12
    End Function
End Class

整數值違規

using System;
using System.Security.Authentication;

public class ExampleClass
{
    public SslProtocols ExampleMethod()
    {
        // CA5398 violation
        return (SslProtocols) 3072;    // TLS 1.2
    }
}
Imports System
Imports System.Security.Authentication

Public Class TestClass
    Public Function ExampleMethod() As SslProtocols
        ' CA5398 violation
        Return CType(3072, SslProtocols)   ' TLS 1.2
    End Function
End Class

解決方案

using System;
using System.Security.Authentication;

public class TestClass
{
    public void Method()
    {
        // Let the operating system decide what TLS protocol version to use.
        // See https://learn.microsoft.com/dotnet/framework/network-programming/tls
        SslProtocols sslProtocols = SslProtocols.None;
    }
}
Imports System
Imports System.Security.Authentication

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
        Dim sslProtocols As SslProtocols = SslProtocols.None
    End Sub
End Class

CA5364:請勿使用已取代的安全性通訊協定

CA5386:避免將 SecurityProtocolType 值寫入程式碼

CA5397:請勿使用已過時的 SslProtocols 通訊協定