CS.X509.VALIDATION
已禁用证书验证
证书可以帮助验证服务器的身份。客户端应验证服务器证书,以确保将请求发送到预期服务器。CS.X509.VALIDATION 检查器会标记其中 ServicePointManager.ServerCertificateValidationCallback 属性始终返回 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)
{
return true; // Any certificate will pass validation
}
}
修正代码示例
复制
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;
}
}