分享方式:


CA5359:請勿停用憑證驗證

屬性
規則識別碼 CA5359
標題 請勿停用憑證驗證
類別 安全性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

指定給 ServicePointManager.ServerCertificateValidationCallback 的回呼一律會傳 true回 。

檔案描述

憑證可協助驗證伺服器的身分識別。 用戶端應該驗證伺服器憑證,以確保要求會傳送至預定的伺服器。 ServicePointManager.ServerCertificateValidationCallback如果一律傳true回 ,則根據預設,任何憑證都會通過所有傳出 HTTPS 要求的驗證。

如何修正違規

隱藏警告的時機

如果附加多個委派,則只會遵守上一個委派 ServerCertificateValidationCallback的值,因此可以放心地隱藏來自其他委派的警告。 不過,您可能想要完全移除未使用的委派。

隱藏警告

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

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

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

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

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

虛擬程式代碼範例

違規

using System.Net;

class ExampleClass
{
    public void ExampleMethod()
    {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => { return true; };
    }
}

解決方案

using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

class ExampleClass
{
    public void ExampleMethod()
    {
        ServicePointManager.ServerCertificateValidationCallback += SelfSignedForLocalhost;
    }

    private static bool SelfSignedForLocalhost(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;
        }

        // For HTTPS requests to this specific host, we expect this specific certificate.
        // In practice, you'd want this to be configurable and allow for multiple certificates per host, to enable
        // seamless certificate rotations.
        return sender is HttpWebRequest httpWebRequest
                && httpWebRequest.RequestUri.Host == "localhost"
                && certificate is X509Certificate2 x509Certificate2
                && x509Certificate2.Thumbprint == "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                && sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors;
    }
}