TLS - TCP-клиент аутентифицируется на SslStream.AuthenticateAsClient (servername), но сервер не подключается ни к одному клиенту, все на локальной машине C # - PullRequest
0 голосов
/ 14 марта 2019

Я довольно новичок в сетевом программировании, и мне нужна помощь с подключением клиента TCP через TLS. Мне дали проект, который уже был закодирован, и он сопровождался предоставленным сертификатом и открытым ключом. Я установил сертификат pfx на своем локальном компьютере и закодировал нового прослушивателя / сервера TCP и клиента TCP, указывающего на локальный хост, как показано ниже:

Клиент

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

Сервер

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

Моя проблема в том, что клиент работает правильно и даже проходит аутентификацию на

sslStream.AuthenticateAsClient (имя_сервер);

но сервер не устанавливает соединение с

TcpClient client = listener.AcceptTcpClient (); ProcessClient (клиент);

Я что-то упускаю или делаю что-то не так? Кроме того, стоит ли начинать все заново, получать новый сертификат и т. Д.?

1 Ответ

0 голосов
/ 25 марта 2019

На стороне сервера вы слушаете порт 8080, а на стороне клиента вы подключаетесь к порту 5997. Чтобы быть более точным ваш сервер размещает [YourIP]: 8080 и ваш клиент пытается подключиться к [YourIP]: 5997


Более того Tls и SSL обычно используются на порту 443 . Порты клиента и сервера должны быть одинаковыми, чтобы они могли соединяться друг с другом.


Я также не уверен, что c # распознает 'localhost' как 'YourIP' лучше открыть ваш cmd (если вы используете windows). Введите "ipconfig", нажмите enter и lookup и используйте свой IPv4-адрес .
...