如何在 C# 中通过客户端识别我的服务器名称以进行服务器身份验证

2024-02-22

我最近一直在尝试用 C# 制作 SSL 加密的服务器/客户端。

我已关注this http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx然而,MSDN 上的教程需要使用以下命令为服务器和客户端使用创建证书生成证书文件所以我找到了一个例子,它创建了很好的证书:

makecert -sr LocalMachine -ss My -n "CN=Test" -sky Exchange -sk 123456 c:/Test.cer

但现在的问题是服务器启动并等待客户端,当客户端连接时它使用机器名称据我所知,在这种情况下是我的 IP:

127.0.0.1

,然后它需要服务器名称其中必须匹配服务器名称证书上(Test.cer)。我尝试了多种组合(例如“Test”“LocalMachine”,“127.0.0.1”但似乎无法让客户端给出服务器名称匹配从而允许连接。我得到的错误是:

证书错误:RemoteCertificateNameMismatch、RemoteCertificateChainErrors 异常:根据验证程序,远程证书无效

这是我使用的代码,它与 MSDN 示例的不同之处仅在于我在应用程序中分配了服务器的证书路径以及客户端的计算机名称和服务器名称:

SslTcpServer.cs

using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace Examples.System.Net
{
    public sealed class SslTcpServer
    {
        static X509Certificate serverCertificate = null;
        // The certificate parameter specifies the name of the file  
        // containing the machine certificate. 
        public static void RunServer(string certificate)
        {
            serverCertificate = X509Certificate.CreateFromCertFile(certificate);
            // Create a TCP/IP (IPv4) socket and listen for incoming connections.
            TcpListener listener = new TcpListener(IPAddress.Any, 8080);
            listener.Start();
            while (true)
            {
                Console.WriteLine("Waiting for a client to connect...");
                // Application blocks while waiting for an incoming connection. 
                // Type CNTL-C to terminate the server.
                TcpClient client = listener.AcceptTcpClient();
                ProcessClient(client);
            }
        }
        static void ProcessClient(TcpClient client)
        {
            // A client has connected. Create the  
            // SslStream using the client's network stream.
            SslStream sslStream = new SslStream(
                client.GetStream(), false);
            // Authenticate the server but don't require the client to authenticate. 
            try
            {
                sslStream.AuthenticateAsServer(serverCertificate,
                    false, SslProtocols.Tls, true);
                // Display the properties and settings for the authenticated stream.
                DisplaySecurityLevel(sslStream);
                DisplaySecurityServices(sslStream);
                DisplayCertificateInformation(sslStream);
                DisplayStreamProperties(sslStream);

                // Set timeouts for the read and write to 5 seconds.
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                // Read a message from the client.   
                Console.WriteLine("Waiting for client message...");
                string messageData = ReadMessage(sslStream);
                Console.WriteLine("Received: {0}", messageData);

                // Write a message to the client. 
                byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>");
                Console.WriteLine("Sending hello message.");
                sslStream.Write(message);
            }
            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.");
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                // The client stream will be closed with the sslStream 
                // because we specified this behavior when creating 
                // the sslStream.
                sslStream.Close();
                client.Close();
            }
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the client. 
            // The client signals the end of the message using the 
            // "<EOF>" marker.
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                // Read the client's test message.
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8 
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                // Check for EOF or an empty message. 
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }
        static void DisplaySecurityLevel(SslStream stream)
        {
            Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
            Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
            Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
            Console.WriteLine("Protocol: {0}", stream.SslProtocol);
        }
        static void DisplaySecurityServices(SslStream stream)
        {
            Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
            Console.WriteLine("IsSigned: {0}", stream.IsSigned);
            Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
        }
        static void DisplayStreamProperties(SslStream stream)
        {
            Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
            Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
        }
        static void DisplayCertificateInformation(SslStream stream)
        {
            Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

            X509Certificate localCertificate = stream.LocalCertificate;
            if (stream.LocalCertificate != null)
            {
                Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                    localCertificate.Subject,
                    localCertificate.GetEffectiveDateString(),
                    localCertificate.GetExpirationDateString());
            }
            else
            {
                Console.WriteLine("Local certificate is null.");
            }
            // Display the properties of the client's certificate.
            X509Certificate remoteCertificate = stream.RemoteCertificate;
            if (stream.RemoteCertificate != null)
            {
                Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                    remoteCertificate.Subject,
                    remoteCertificate.GetEffectiveDateString(),
                    remoteCertificate.GetExpirationDateString());
            }
            else
            {
                Console.WriteLine("Remote certificate is null.");
            }
        }
        public static void Main(string[] args)
        {
            string certificate = "c:/Test.cer";
            SslTcpServer.RunServer(certificate);
        }
    }
}

SslTcpClient.cs

using System;
using System.Collections;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace Examples.System.Net
{
    public class SslTcpClient
    {
        private static Hashtable certificateErrors = new Hashtable();

        // The following method is invoked by the RemoteCertificateValidationDelegate. 
        public static bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

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

            // Do not allow this client to communicate with unauthenticated servers. 
            return false;
        }
        public static void RunClient(string machineName, string serverName)
        {
            // Create a TCP/IP client socket. 
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(machineName, 8080);
            Console.WriteLine("Client connected.");
            // 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(serverName);
            }
            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;
            }
            // Encode a test message into a byte array. 
            // Signal the end of the message using the "<EOF>".
            byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
            // Send hello message to the server. 
            sslStream.Write(messsage);
            sslStream.Flush();
            // Read message from the server. 
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);
            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server. 
            // The end of the message is signaled using the 
            // "<EOF>" marker.
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8 
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                // Check for EOF. 
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }
        public static void Main(string[] args)
        {
            string serverCertificateName = null;
            string machineName = null;
            /*
            // User can specify the machine name and server name. 
            // Server name must match the name on the server's certificate. 
            machineName = args[0];
            if (args.Length < 2)
            {
                serverCertificateName = machineName;
            }
            else
            {
                serverCertificateName = args[1];
            }*/
            machineName = "127.0.0.1";
            serverCertificateName = "David-PC";// tried Test, LocalMachine and 127.0.0.1
            SslTcpClient.RunClient(machineName, serverCertificateName);
            Console.ReadKey();
        }
    }
}

EDIT:

服务器接受客户端连接和所有内容,但在等待客户端发送消息时超时。 (由于证书中的服务器名称与我在客户端中提供的服务器名称不同,客户端不会与服务器进行身份验证)这就是我的想法,只是为了澄清

UPDATE:

根据答案,我已将证书制作者更改为:

makecert -sr LocalMachine -ss My -n "CN=localhost" -sky Exchange -sk 123456 c:/Test.cer 在我的客户中我有:

        machineName = "127.0.0.1";
        serverCertificateName = "localhost";// tried Test, LocalMachine and 127.0.0.1
        SslTcpClient.RunClient(machineName, serverCertificateName);

现在我得到了例外:

远程证书链错误 异常:根据验证程序,远程证书无效

这是发生在这里:

  // The server name must match the name on the server certificate. 
            try
            {
                sslStream.AuthenticateAsClient(serverName);
            }
            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. "+ e.Message);
                client.Close();
                return;
            }  

答案可以在以下位置找到SslStream.AuthenticateAsClient 方法 http://msdn.microsoft.com/en-us/library/ms145060.aspx备注部分:

为 targetHost 指定的值必须与服务器证书上的名称匹配。

如果您为服务器使用主题为“CN=localhost”的证书,则必须使用“localhost”作为 targetHost 参数调用 AuthenticateAsClient,才能在客户端成功对其进行身份验证。如果您要使用“CN=David-PC”作为证书主题,则必须使用“David-PC”作为 targetHost 调用 AuthenticateAsClient。 SslStream 通过将要连接的服务器名称(以及传递给 AuthenticateAsClient 的名称)与从服务器收到的证书中的主题进行匹配来检查服务器身份。实践是,运行服务器的计算机名称与证书主题的名称相匹配,并且在客户端中,您将与用于打开连接的主机名相同的主机名传递给 AuthenticateAsClient(在本例中为 TcpClient)。

然而,要在服务器和客户端之间成功建立 SSL 连接,还有其他条件:传递给 AuthenticateAsServer 的证书必须具有私钥,它必须在客户端计算机上受信任,并且不得具有与建立 SSL 会话的使用相关的任何密钥使用限制。

现在与您的代码示例相关,您的问题与证书的生成和使用有关。

  • 您没有为您的证书提供颁发者,因此它无法被信任 - 这是 RemoteCertificateChainErrors 异常的原因。我建议创建一个用于开发目的的自签名证书,并指定 makecert 的 -r 选项。

  • 要获得信任,证书必须是自签名的并放置在 Windows 证书存储中的受信任位置,或者必须通过签名链链接到已受信任的证书颁发机构。因此,不要使用 -ss My 选项将证书放置在个人存储中,而是使用 -ss root 将其放置在受信任的根证书颁发机构中,并且它将在您的计算机上受到信任(从代码中我假设您的客户端正在运行与服务器在同一台计算机上,并且证书也是在其上生成的)。

  • 如果您为 makecert 指定输出文件,它会将证书导出为 .cer,但此格式仅包含公钥,而不包含服务器建立 SSL 连接所需的私钥。最简单的方法是从服务器代码中的 Windows 证书存储中读取证书。 (您还可以以另一种格式从商店导出它,该格式允许存储私钥,如此处所述使用私钥导出证书 http://technet.microsoft.com/en-us/library/cc737187%28v=ws.10%29.aspx并在服务器代码中读取该文件)。

您可以在此处找到有关使用的 makecert 选项的详细信息证书创建工具(Makecert.exe) http://msdn.microsoft.com/en-us/library/bfsktky3.aspx

总之,您的代码需要进行以下更改才能运行(使用最新的代码更新进行测试):

  • 使用以下命令生成证书:

makecert -sr LocalMachine -ss root -r -n "CN=localhost" -sky 交换 -sk 123456

  • 从 Windows 证书存储中读取证书而不是文件(为了简化本示例),因此替换

serverCertificate = X509Certificate.CreateFromCertFile(证书);

在服务器代码中:

X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, "CN=localhost", false);
store.Close();

if (certificates.Count == 0)
{
    Console.WriteLine("Server certificate not found...");
    return;
}
else
{
    serverCertificate = certificates[0];
}

如果稍后更改代码,请记住将“CN=localhost”替换为您打算使用的证书主题(在这种情况下,应与传递给 makecert 的 -n 选项的值相同)。还可以考虑在服务器证书的主题中使用运行服务器的计算机名称而不是 localhost。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 C# 中通过客户端识别我的服务器名称以进行服务器身份验证 的相关文章

随机推荐