简体   繁体   English

TLS-TCP客户端在SslStream.AuthenticateAsClient(servername)上进行身份验证,但是服务器未连接到任何客户端,所有这些都在本地计算机C#上

[英]TLS - TCP Client Authenticates on SslStream.AuthenticateAsClient(servername) but the server is not connecting to any Client, all on local machine C#

i am fairly new to Network Programming and i need help with connecting a TCP Client via TLS. 我是网络编程的新手,我需要帮助通过TLS连接TCP客户端。 I was given a project that was coded already and it came with both the certificate and the public key provided. 我得到了一个已编码的项目,它附带了证书和提供的公钥。 I have installed the pfx certificate on my local machine and have coded a new TCP Listener/Server and TCP Client pointing to local host as below: 我在本地计算机上安装了pfx证书,并编写了一个新的TCP侦听器/服务器和指向本地主机的TCP客户端,如下所示:

The Client 客户端

static void Main(string[] args)
    {
        string server = "localhost";
        TcpClient client = new TcpClient(server, 5997);
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        //client.Connect(server, 5997);//connection without TLS - authenticating properly

        using (SslStream sslStream = new SslStream(client.GetStream(), false,
            new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
        {
            try
            {
                var servername = "myAuthenticatingServerName";//the server name must be the same as the one on the server certificate
                sslStream.AuthenticateAsClient(servername);

                try
                {
                    Console.WriteLine("Client Connected...");

                    // 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.");

                }

                catch (Exception e)
                {
                    Console.WriteLine("Error..... " + e.StackTrace);
                }
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine($"Error: { e.Message}");
                if (e.InnerException != null)
                {
                    Console.WriteLine($"Inner exception: {e.InnerException.Message}");
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                Console.WriteLine("Authentication failed - closing the connection.");
                client.Close();
            }

        }
        client.Close();
        Console.WriteLine($"Connection closed at {DateTime.Now}.");
        Console.ReadLine();
    }

    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
        {
            try
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);
            }
            catch (Exception ex)
            {

                throw ex;
            }


            // 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 bool ValidateServerCertificate(object sender, X509Certificate certificate,
    X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

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

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

The Server 服务器

  public sealed class SslTcpServer
{
    static X509Certificate2 serverCertificate = null;
    // The certificate parameter specifies the name of the file 
    // containing the machine certificate.
    public static void RunServer(X509Certificate2 certificate)
    {
        serverCertificate = 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, clientCertificateRequired: false, enabledSslProtocols: SslProtocols.Tls, checkCertificateRevocation: 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.");
            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 int Main(string[] args)
    {
        RunServer(Certificate.GetCertificate());
        return 0;
    }
}

public class Certificate
{


    public static X509Certificate2 GetCertificate()
    {
        string certificatePath = ConfigurationManager.AppSettings["certificatePath"].ToString();
        var stream = File.OpenRead(certificatePath);
        return new X509Certificate2(ReadStream(stream), "mypassword");
    }

    private static byte[] ReadStream(Stream input)
    {
        byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }
}

My problem is that the client runs properly and even Authenticates on 我的问题是客户端运行正常甚至验证

sslStream.AuthenticateAsClient(servername); sslStream.AuthenticateAsClient(服务器);

but the server does not pick up any connection on 但是服务器没有接通任何连接

TcpClient client = listener.AcceptTcpClient(); TcpClient client = listener.AcceptTcpClient(); ProcessClient(client); ProcessClient(客户端);

Am i missing something, or doing something wrong? 我错过了什么,或做错了什么? Also, is it worth starting afresh, getting a new certificate etc? 是否值得重新开始,获得新证书等?

On the server-side you are listening to port 8080 and on the client-side your are connecting to port 5997. To be more specific your server is hosting [YourIP]:8080 and your client is trying to connect to [YourIP]:5997 在服务器端,您正在侦听端口8080,在客户端,您正在连接到端口5997.更具体地说, 您的服务器正在托管[YourIP]:8080并且您的客户端正在尝试连接到[YourIP]:5997


Moreover Tls and SSL are usually used on the port 443 . 此外, Tls和SSL通常用在端口443上 The client and server ports need to be the same so they can connect to each other. 客户端和服务器端口需要相同,以便它们可以相互连接。


I'm also not sure if c# is recognising 'localhost' as 'YourIP' its better to open up your cmd(in case you are using windows) Type in 'ipconfig' hit enter and lookup and use your IPv4 Address . 也不确定c#是否将'localhost'识别为'YourIP'更好地打开你的cmd(如果你使用的是Windows)输入'ipconfig'点击回车并查找并使用你的IPv4地址

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

相关问题 SslStream.AuthenticateAsClient不起作用 - SslStream.AuthenticateAsClient is not working 在涉及SslStream.AuthenticateAsClient()的客户端证书期间设置“ Windows安全性”对话框所有者 - Setting the “Windows Security” dialog owner during a Client Certificate involving SslStream.AuthenticateAsClient() 使用sslStream的C#Tcp客户端传输文件 - c# Tcp client transfer file with sslStream 使用TLS 1.2将客户端连接到TCP服务器 - Connecting a client to a TCP server using TLS 1.2 避免对SslStream.AuthenticateAsClient的管理员访问权限? - Avoiding administrator access for SslStream.AuthenticateAsClient? SslStream.AuthenticateAsClient()使用未缓存的CRL非常慢 - SslStream.AuthenticateAsClient() VERY slow with uncached CRL sslStream.AuthenticateAsClient在Windows 7上运行,但在Windows 8上失败 - sslStream.AuthenticateAsClient works on windows 7 but fails on windows 8 SslStream.AuthenticateAsClient上的异常(消息格式错误) - Exception on SslStream.AuthenticateAsClient (The message was badly formatted) 如何将C#SSLStream客户端连接到OpenSSL服务器? - How can I connect a C# SSLStream client to an OpenSSL server? C# 客户端服务器 TCP 客户端监听 - C# Client Server TCP Client Listening
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM