From 592d21c3aaee5bf29965a617d2f602ff3b47e8e8 Mon Sep 17 00:00:00 2001 From: Serge Camille Date: Fri, 21 Aug 2020 21:27:56 +0200 Subject: [PATCH] Add some response length checks in connection Open() I don't know what the correct expected connection response size is, so I just added checks for the minimal index access by the current code. This change will just change NullReferenceExceptions into WrongNumberOfBytesException when the PLC response with not enough data for a connection attempt. --- S7.Net/PlcAsynchronous.cs | 5 +++++ S7.Net/PlcSynchronous.cs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/S7.Net/PlcAsynchronous.cs b/S7.Net/PlcAsynchronous.cs index 26cf05c..868ddb1 100644 --- a/S7.Net/PlcAsynchronous.cs +++ b/S7.Net/PlcAsynchronous.cs @@ -39,11 +39,16 @@ namespace S7.Net var s7data = await COTP.TSDU.ReadAsync(stream); if (s7data == null) throw new WrongNumberOfBytesException("No data received in response to Communication Setup"); + if (s7data.Length < 2) + throw new WrongNumberOfBytesException("Not enough data received in response to Communication Setup"); //Check for S7 Ack Data if (s7data[1] != 0x03) throw new InvalidDataException("Error reading Communication Setup response", s7data, 1, 0x03); + if (s7data.Length < 20) + throw new WrongNumberOfBytesException("Not enough data received in response to Communication Setup"); + MaxPDUSize = (short)(s7data[18] * 256 + s7data[19]); } diff --git a/S7.Net/PlcSynchronous.cs b/S7.Net/PlcSynchronous.cs index 34fa143..7cb37f4 100644 --- a/S7.Net/PlcSynchronous.cs +++ b/S7.Net/PlcSynchronous.cs @@ -34,11 +34,16 @@ namespace S7.Net var s7data = COTP.TSDU.Read(stream); if (s7data == null) throw new WrongNumberOfBytesException("No data received in response to Communication Setup"); + if (s7data.Length < 2) + throw new WrongNumberOfBytesException("Not enough data received in response to Communication Setup"); //Check for S7 Ack Data if (s7data[1] != 0x03) throw new InvalidDataException("Error reading Communication Setup response", s7data, 1, 0x03); + if (s7data.Length < 20) + throw new WrongNumberOfBytesException("Not enough data received in response to Communication Setup"); + MaxPDUSize = (short)(s7data[18] * 256 + s7data[19]); } catch (Exception exc)