From 51720cdb613a78b77ca942f1f02d783eeca0721a Mon Sep 17 00:00:00 2001 From: Malek Kadri <93520204+malekkadri@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:43:50 +0100 Subject: [PATCH 1/2] fix: reject incomplete SSH packet fields --- src/Packet.php | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/Packet.php b/src/Packet.php index ab3098a..15d515a 100644 --- a/src/Packet.php +++ b/src/Packet.php @@ -29,7 +29,15 @@ public function __construct( */ public function extractString(string $data, int &$offset): array { + if (strlen($data) - $offset < 4) { + throw new \UnexpectedValueException('Incomplete SSH string length'); + } + $length = unpack('N', substr($data, $offset, 4))[1]; + if ($length > strlen($data) - $offset - 4) { + throw new \UnexpectedValueException('Incomplete SSH string data'); + } + $string = substr($data, $offset + 4, $length); $offset += 4 + $length; @@ -61,8 +69,13 @@ public function extractFormat(string $format): array $specifiers = $matches[1] ?? []; foreach ($specifiers as $spec) { - if ($this->offset >= strlen($this->message)) { - return $values; + $remaining = strlen($this->message) - $this->offset; + if ($remaining === 0) { + throw new \UnexpectedValueException("Missing SSH field for %{$spec}"); + } + + if ($spec === 'u' && $remaining < 4) { + throw new \UnexpectedValueException('Incomplete SSH uint32 field'); } match ($spec) { From 0cbacc19ad4cff2399ccd1c7735d0b0ad27ff99c Mon Sep 17 00:00:00 2001 From: Malek Kadri <93520204+malekkadri@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:45:20 +0100 Subject: [PATCH 2/2] test: cover truncated SSH field parsing --- tests/Unit/PacketTest.php | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/Unit/PacketTest.php b/tests/Unit/PacketTest.php index 42eb7f6..477b0ff 100644 --- a/tests/Unit/PacketTest.php +++ b/tests/Unit/PacketTest.php @@ -82,3 +82,27 @@ ->and($int1)->toBe(420) ->and($bool)->toBeTrue(); }); + +test('rejects incomplete SSH fields', function (string $format, string $message) { + $packet = new Packet(chr(MessageType::CHANNEL_OPEN->value).$message); + + expect(fn () => $packet->extractFormat($format)) + ->toThrow(\UnexpectedValueException::class); +})->with([ + 'missing uint32' => ['%u', ''], + 'partial uint32' => ['%u', "\x00\x00\x01"], + 'partial string length' => ['%s', "\x00\x00"], + 'declared string exceeds available data' => ['%s', pack('N', 5).'abc'], + 'partial uint32 after valid string' => ['%s%u', pack('N', 1).'a'."\x00\x01"], + 'missing boolean after valid string' => ['%s%b', pack('N', 1).'a'], +]); + +test('does not advance the offset for an incomplete SSH string', function () { + $packet = new Packet(chr(MessageType::CHANNEL_OPEN->value)); + $offset = 0; + + expect(fn () => $packet->extractString(pack('N', 5).'abc', $offset)) + ->toThrow(\UnexpectedValueException::class); + + expect($offset)->toBe(0); +});