Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/Packet.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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) {
Expand Down
24 changes: 24 additions & 0 deletions tests/Unit/PacketTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Loading