C# SSLStream读取函数引发IOException异常

4
我正在尝试创建自己的HTTPS代理服务器。但是当我尝试从sslstream对象读取数据时,出现了异常。以下是异常信息:

类型为“System.IO.IOException”的未经处理的异常发生在System.dll中。

其他信息:无法从传输连接读取数据:连接方在一段时间后没有正确响应或已建立的连接失败,因为连接的主机没有正确响应。

以下是我的代码:
    public Server()
    {
        m_portnumber = 4434;
        m_tcplistener = new TcpListener(IPAddress.Any, m_portnumber);
        m_cert = createCertificate();
    }
    public void start()
    {
        m_tcplistener.Start();
        while (true)
        {
            TcpClient client = m_tcplistener.AcceptTcpClient();
            ClientHandler(client);
        }
    }

    private void ClientHandler(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(m_cert,
                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);
        }
        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 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();
    }
    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.");
        }
    }
    private static void DisplayUsage()
    {
        Console.WriteLine("To start the server specify:");
        Console.WriteLine("serverSync certificateFile.cer");
        Environment.Exit(1);
    }

    private X509Certificate createCertificate()
    {
        byte[] c = Certificate.CreateSelfSignCertificatePfx(
                   "CN=localhost", //host name
                    DateTime.Parse("2015-01-01"), //not valid before
                    DateTime.Parse("2020-01-01"), //not valid after
                    "sslpass"); //password to encrypt key file
        using (BinaryWriter binWriter = new BinaryWriter(File.Open(@"cert.pfx", FileMode.Create)))
        {
            binWriter.Write(c);
        }
        return new X509Certificate2(@"cert.pfx", "sslpass");
    }
}

1
问题出现在这一行:bytes = sslStream.Read(buffer, 0, buffer.Length); - michal_h
当然会发生。你设置了读取超时,MSDN说:“如果读取操作在此属性指定的时间内未完成,则读取操作会引发 IOException。”你期望会发生什么? - Dark Falcon
实际上客户端给我发送了URL,我需要通过我的方式与服务器建立连接。那么我应该做什么? - michal_h
我确信它永远不会停留在EOF的那一行,它总是在之前抛出异常。 - michal_h
哇 - 这太棒了 - 非常感谢你,伙计! - michal_h
显示剩余2条评论
2个回答

3
这不是SSL错误,而是TCP错误。你正在连接的IP/端口对没有在监听。这是一种主动拒绝,所以并不像是你到达了IP并告诉你没有端口那样。这是一个超时,可能意味着无效的IP或目标防火墙正在忽略你(有意)。
我首先怀疑的是m_portnumber = 4434;这行代码。这是一个不寻常的端口号。确定它不是打错了吗?你是否想要HTTPS通常的端口(443)?如果你真的需要4434,请检查网络连接。确保IP正确解析、可达,目标正在监听并且防火墙允许你进入。

1
即使我使用端口号443,我仍然得到相同的异常。 - michal_h

0

我猜以上代码是从https://learn.microsoft.com/en-us/dotnet/api/system.net.security.sslstream?view=net-5.0中获取的。

在一个Windows机器(Win10 1809)上遇到了与ReadMessage(SslStream sslStream)类似的问题。

这里有两件事需要注意:

  1. sslStream.Read将读取身份验证网络流中的所有内容,包括头和正文。因此,您有责任解析两者并退出循环。

  2. 在我的情况下,机器花费了很长时间(超过5秒)从流中读取。所以我不得不删除时间读取超时。这是它

    sslStream.ReadTimeout = 5000; \\ 默认情况下为无限


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接