繁体   English   中英

使用受信任的根证书颁发机构在HttpClient中进行服务器证书验证

[英]Using Trusted Root Certification Authorities for server certificate validation in HttpClient

我使用创建了自签名证书

openssl req -x509 -newkey rsa:2048 -keyout https-key.pem -out https.pem -days 365

然后我创建了pkcs12使用(我已将CN设置为我服务器的ip地址):

openssl pkcs12 -export -out https.pfx -inkey https-key.pem -in https.pem -password pass:123456

在我的服务器中,使用生成的https.pfx文件进行https。

在我的客户端中,我将生成的证书导入Windows的“ Trusted Root Certification Authorities (当前用户和本地系统)。

当我从客户端向服务器发送HTTP请求时,我得到了

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: A security error occurred
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.Tasks.RendezvousAwaitable`1.GetResult()
   at System.Net.Http.WinHttpHandler.<StartRequest>d__105.MoveNext()
   --- End of inner exception stack trace ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Net.Http.HttpClient.<FinishSendAsyncBuffered>d__58.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task).

在chrome中它说:

Attackers might be trying to steal your information from *** (for example, passwords, messages, or credit cards). NET::ERR_CERT_AUTHORITY_INVALID

.NET Core 2.0的HttpClient是否使用Windows证书存储? 可能导致这个问题的原因。

我建议您创建一个小测试应用程序,您可以将其用作客户端来测试服务器的TLS配置。

您可以使用.NET中的SslStream类连接到TLS端点并执行协商。 它可以返回比随机HRESULT代码更容易理解的错误消息以及来自SChannel的无用错误消息。

测试工具只不过是一个包含以下代码的WinForms应用程序:

public static void q48873455()
{
    const string hostname = "localhost";
    var tcpClient = new TcpClient();
    tcpClient.Connect(hostname, 443);
    var tcpStream = tcpClient.GetStream();

    using (var sslStream = new SslStream(tcpStream, false, ValidateServerCertificate))
    {
        sslStream.AuthenticateAsClient(hostname);
    }
}


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

    Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

    return false;
}

此代码建立到端口443的原始TCP连接,然后使用SslStream执行TLS协商。 在该协商期间,服务器将发送其证书,并且SslStream将调用ValidateServerCertificate()方法,传递它收到的certificate ,并为SslPolicyErrors提供一个值,该值指示SChannel对证书的看法。

SslPolicyErrors值是MSDN上列出的值之一,表示SChannel认为证书不可信的原因(如果有的话)。

我倾向于发现,在尝试找出给定证书不可信的原因时,拥有这样的工具非常有用。

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM