首页 > 解决方案 > 如何通过网桥证书手动(以编程方式)验证服务器是否受信任?

问题描述

我需要验证服务器在机器根证书存储中是否受信任,但需要适应可以使用网桥 CA 的场景。

根据 MSDN,这种使用 TCPClient,然后打开套接字的方法似乎是检查 SSL 流证书的最首选方法。

当我的函数命中ValidateServerCertificate函数时,我打算检查链对象以确定根证书是否存储在计算机上的受信任根证书存储中。很容易。

当我需要遵循用于交叉签署多个 PKI 树的“桥接证书”时,就会出现复杂性(并且缺乏知识)。我不确定桥接证书是否会出现在本地商店、连锁店或其他地方(如果有的话)。

此外,我不确定如何遵循可能发生的分支逻辑,因为桥可以发生在树的任何级别。

欢迎提出建议、方向或流程图

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace sockittome
{ 
    class Program
    {
        static void Main(string[] args)
        {

            string machineName = "pesecpolicy.bankofamerica.com";

            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(machineName, 443); 

            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                null
                );
            // The server name must match the name on the server certificate.
            try
            {
                sslStream.AuthenticateAsClient(machineName);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
                return;
            }

        }

        // The following method is invoked by the RemoteCertificateValidationDelegate.
        public static bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
            // How do I verify the root certificate is installed? 
            // What is the simple way (check certificate hash in the computer store)?
            // What is the complete way (look for bridge certificates ?????)          

            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

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

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
    }
}

标签: .net-coretcpclienttls1.2pkica

解决方案


推荐阅读