19

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

我在 MSDN 上遵循了本教程,但是,它需要使用makecert.exe为服务器和客户端使用创建一个证书,所以我找到了一个示例,它创建了很好的证书:

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();
        }
    }
}

编辑:

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

更新:

根据答案,我已将证书制造商更改为:

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);

现在我得到了例外:

RemoteCertificateChainErrors 异常:根据验证程序,远程证书无效

这是发生在这里:

  // 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;
            }  
4

6 回答 6

12

答案可以在SslStream.AuthenticateAsClient 方法备注部分找到:

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

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

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

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

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

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

  • 如果您指定一个输出文件到 makecert,它会将证书导出为 .cer,但这种格式仅包含公钥,而不包含服务器建立 SSL 连接所需的私钥。最简单的方法是从服务器代码中的 Windows 证书存储区读取证书。(您也可以将其以另一种格式从存储中导出,该格式允许存储私钥,如此处所述使用私钥导出证书并在服务器代码中读取该文件)。

您可以在此处找到有关使用的 makecert 选项的详细信息证书创建工具 (Makecert.exe)

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

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

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

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

serverCertificate = X509Certificate.CreateFromCertFile(certificate);

在服务器代码中:

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。

于 2012-09-04T09:05:49.373 回答
5

服务器证书的 CN 必须与服务器的域名完全相同。我想,在您的情况下,通用名称必须是“localhost”(不带引号)。

重要提示:当然,正如您可能在其他答案中读到的那样,永远不要CN="localhost"在生产中使用。

于 2012-08-27T10:51:37.610 回答
4

首先,不要创建主题为“CN=localhost”或同等主题的证书。它永远不会在生产中使用,所以不要这样做。始终将其发送到您计算机的主机名,例如 CN="mycomputer",并在连接时使用主机名而不是 localhost。您可以使用“主题备用名称”扩展名指定多个名称,但makecert似乎不支持它。

其次,在颁发服务器 SSL 证书时,需要将“服务器身份验证”OID 添加到证书的增强型密钥使用 (EKU) 扩展中。在您的示例中添加-eku 1.3.6.1.5.5.7.3.1参数。makecert如果要进行客户端证书身份验证,请使用 1.3.6.1.5.5.7.3.2 的“客户端身份验证”OID。

最后,makecert 创建的默认证书使用 MD5 作为其哈希算法。MD5 被认为是不安全的,虽然它不会影响您的测试,但请养成使用 SHA1 的习惯。添加-a sha1makecert上面的参数以强制 SHA1。默认密钥大小也应该从 1024 位增加到 2048 位,但你明白了。

于 2012-09-01T12:21:36.630 回答
1

要使其与 WCF 一起使用,必须首先创建一个自签名的根颁发机构证书,然后使用它为 localhost 创建证书。

我认为这也可能适用于您的项目,请查看这篇文章如何:创建临时证书以在开发期间使用以获取详细信息。

于 2012-08-30T07:23:12.637 回答
1

你有没有尝试过:?

为完整的域名创建证书,例如example.net(最好使用example.netexample.comexample.org任何故意不是真实名称的名称)或将在实时使用中使用的名称(如果这是单个站点并且您知道它将是什么)。

更新您的主机文件,使其使用 127.0.0.1 作为该名称。

于 2012-09-01T10:58:33.470 回答
1

关于您的更新:

SslStream 构造函数之一允许您提供RemoteCertificateValidationCallback 委托。您应该能够在您提供的方法中放置一个断点,以查看您得到的实际错误是什么。检查发送的SslPolicyErrors值。

于 2012-09-02T21:40:51.000 回答