CA5359:请勿禁用证书验证

属性
规则 ID CA5359
标题 请勿禁用证书验证
类别 安全性
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用

原因

赋值给 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;
    }
}