SSLStream读取无效数据+ KB3147458 SSLStream错误(?)

时间:2016-04-17 12:39:18

标签: c# .net sslstream

我遇到SSLStream在远程客户端没有发送任何内容时返回一些数据的问题。当服务器正在侦听新命令时,我遇到此问题。 如果服务器未收到新请求,则由于SSLStream的读取超时,ReadMessage()函数应捕获IOException。当第二次执行sslStream.Read()时,会发生问题,它似乎读取了客户端未发送的5个字节。所以问题发生在这个序列中:

- > ReadMessage() - > sslstream.Read() - >按预期捕获超时异常

- > ReadMessage() - > sslstream.Read() - >超时异常未被捕获,即使客户端没有发送任何内容,也会读取5个字节

- > ReadMessage() - > sslstream.Read() - >按预期捕获超时异常

- > ReadMessage() - > sslstream.Read() - >超时异常未捕获,即使客户端没有发送任何内容,也会读取5个字节...

依旧......

    public void ClientHandle(object obj)
    {
        nRetry = MAX_RETRIES;

        // Open connection with the client
        if (Open() == OPEN_SUCCESS)
        {
            String request = ReadMessage();
            String response = null;

            // while loop for the incoming commands from client
            while (!String.IsNullOrEmpty(request))
            {
                Console.WriteLine("[{0}] {1}", RemoteIPAddress, request);

                response = Execute(request);

                // If QUIT was received, close the connection with the client
                if (response.Equals(QUIT_RESPONSE))
                {
                    // Closing connection
                    Console.WriteLine("[{0}] {1}", RemoteIPAddress, response);

                    // Send QUIT_RESPONSE then return and close this thread
                    SendMessage(response);
                    break;
                }

                // If another command was received, send the response to the client
                if (!response.StartsWith("TIMEOUT"))
                {
                    // Reset nRetry
                    nRetry = MAX_RETRIES;

                    if (!SendMessage(response))
                    {
                        // Couldn't send message
                        Close();
                        break;
                    }
                }


                // Wait for new input request from client
                request = ReadMessage();

                // If nothing was received, SslStream timeout occurred
                if (String.IsNullOrEmpty(request))
                {
                    request = "TIMEOUT";
                    nRetry--;

                    if (nRetry == 0)
                    {
                        // Close everything
                        Console.WriteLine("Client is unreachable. Closing client connection.");
                        Close();
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }

            Console.WriteLine("Stopped");
        }
    }



    public String ReadMessage()
    {
        if (tcpClient != null)
        {
            int bytes = -1;
            byte[] buffer = new byte[MESSAGE_SIZE];

            try
            {
                bytes = sslStream.Read(buffer, 0, MESSAGE_SIZE);
            }
            catch (ObjectDisposedException)
            {
                // Streams were disposed
                return String.Empty;
            }
            catch (IOException)
            {
                return String.Empty;
            }
            catch (Exception)
            {
                // Some other exception occured
                return String.Empty;
            }

            if (bytes != MESSAGE_SIZE)
            {
                return String.Empty;
            }

            // Return string read from the stream
            return Encoding.Unicode.GetString(buffer, 0, MESSAGE_SIZE).Replace("\0", String.Empty);
        }

        return String.Empty;
    }


    public bool SendMessage(String message)
    {
        if (tcpClient != null)
        {
            byte[] data = CreateMessage(message);

            try
            {
                // Write command message to the stream and send it
                sslStream.Write(data, 0, MESSAGE_SIZE);
                sslStream.Flush();
            }
            catch (ObjectDisposedException)
            {
                // Streamers were disposed
                return false;
            }
            catch (IOException)
            {
                // Error while trying to access streams or connection timedout
                return false;
            }
            catch (Exception)
            {
                return false;
            }

            // Data sent successfully
            return true;
        }

        return false;
    }

   private byte[] CreateMessage(String message)
    {
        byte[] data = new byte[MESSAGE_SIZE];

        byte[] messageBytes = Encoding.Unicode.GetBytes(message);

        // Can't exceed MESSAGE_SIZE parameter (max message size in bytes)
        if (messageBytes.Length >= MESSAGE_SIZE)
        {
            throw new ArgumentOutOfRangeException("message", String.Format("Message string can't be longer than {0} bytes", MESSAGE_SIZE));
        }

        for (int i = 0; i < messageBytes.Length; i++)
        {
            data[i] = messageBytes[i];
        }
        for (int i = messageBytes.Length; i < MESSAGE_SIZE; i++)
        {
            data[i] = messageBytes[messageBytes.Length - 1];
        }

        return data;
    }

客户端也使用完全相同的ReadMessage(),SendMessage()和CreateMessage()函数向服务器发送消息。 MESSAGE_SIZE常量也相同,设置为2048。

2 个答案:

答案 0 :(得分:2)

问题是我在超时后重新使用了SSLStream。所以我只是通过删除nRetry变量并设置更长的超时来解决问题。相关的MSDN文章说SSLStream将在超时异常(https://msdn.microsoft.com/en-us/library/system.net.security.sslstream(v=vs.110).aspx)之后返回垃圾:

  

SslStream假定当从内部流抛出一个IOException时,超时以及任何其他IOException将被其调用者视为致命错误。超时后重用SslStream实例将返回垃圾。应用程序应关闭SslStream并在这些情况下抛出异常。

另一个问题是Windows更新KB3147458(Windows 10月4日的更新)更改了Read函数的行为。看起来SSLStream实现中的某些内容发生了变化,现在它每次返回2个部分,1个字节和其余字节的数据。实际上,MSDN文档并没有说Read()函数会在一个步骤中返回所有请求的字节,并且提供的示例使用do-while循环来读取确切的字节数。所以我认为Read()函数不能保证一次读取确切的请求字节数,可能需要更多的读取迭代。

SSLstream正常运行,因此它不会被破坏。您只需要注意并使用do-while循环并检查是否正确读取了所有字节。

我更改了此处显示的代码,以解决我遇到的错误。

    public String ReadMessage()
    {
        if (tcpClient != null)
        {
            int bytes = -1, offset = 0;
            byte[] buffer = new byte[MESSAGE_SIZE];

            try
            {
                // perform multiple read iterations 
                // and check the number of bytes received
                while (offset < MESSAGE_SIZE)
                {
                    bytes = sslStream.Read(buffer, offset, MESSAGE_SIZE - offset);
                    offset += bytes;

                    if (bytes == 0)
                    {
                        return String.Empty;
                    }
                }
            }
            catch (Exception)
            {
                // Some exception occured
                return String.Empty;
            }

            if (offset != MESSAGE_SIZE)
            {
                return String.Empty;
            }

            // Return string read from the stream
            return Encoding.Unicode.GetString(buffer, 0, MESSAGE_SIZE).Replace("\0", String.Empty);
        }

        return String.Empty;
    }

答案 1 :(得分:1)

关于SslStream在超时后在Read()上返回五个字节,这是因为SslStream类没有正常处理来自底层流的任何IOException,并且如前所述。

  

SslStream假定当从内部流抛出一个IOException时,超时以及任何其他IOException将被其调用者视为致命错误。超时后重用SslStream实例将返回垃圾。应用程序应关闭SslStream并在这些情况下抛出异常。

https://msdn.microsoft.com/en-us/library/system.net.security.sslstream(v=vs.110).aspx

但是,您可以通过创建位于Tcp NetworkStream和SslStream之间的包装类来解决问题,该类捕获并抑制无害的超时异常,(似乎)不会丢失功能。

完整的代码在我的答案中,在类似的帖子中,https://stackoverflow.com/a/48231248/8915494

关于Read()方法只返回每个Read()上的部分有效负载,你的答案已经正确地修复了这个问题。虽然这是SslStream的“最近”行为,但遗憾的是,所有网络和所有代码都需要创建某种形式的缓冲区来存储片段,直到您拥有完整的数据包为止。例如,如果您的数据超过1500字节(大多数以太网适配器的最大数据包大小,假设以太网传输),您很可能会收到多个部分的数据,并且必须自己重新组装。

希望这会有所帮助