Compare commits

...

2 Commits

Author SHA1 Message Date
Vladyslav Vildanov 8ee8993eb7 Fixed CRLF command injection / smuggling in AbstractAggregateConnection::write() (#1719) 2026-09-11 07:58:18 -07:00
Sergey Sannikov 3ffaf10e99 Return NAN for RESP3 NaN double payloads (#1718)
parseDouble() fell through to a float cast for ',nan', and
(float) 'nan' evaluates to 0.0 in PHP, so a NaN score silently became
a valid zero. Return NAN instead. The RESP3 specification also notes
that Redis before 7.2 may emit any libc representation of NaN
('-nan', 'NAN', 'nan(char-sequence)') and that clients should handle
them, so those spellings are accepted as well.

The TDigest RESP3 tests asserted 0 or null for empty sketches, which
only passed because of the collapsed 0.0 (null == 0.0 loosely); their
RESP2 counterparts already assert the string 'nan' for the same
replies. They now assert NaN.

Note for reviewers: json_encode() throws on NAN, so consumers who
serialize raw replies must handle it; the previous behavior hid NaN
behind a plausible-looking 0.0 instead.
2026-09-10 15:29:52 -07:00
20 changed files with 129 additions and 415 deletions
+3 -3
View File
@@ -1,11 +1,11 @@
## Changelog
## Unlreleads
### Added
## Unreleased
### Changed
- Changed RESP3 double parsing to return `NAN` for NaN payloads instead of `0.0`
### Fixed
- Fixed CRLF command injection / smuggling in `AbstractAggregateConnection::write()` (CVE GHSA-w6f5-v2h6-g786, CWE-93)
- Fixed RESP3 double parsing returning positive `INF` for `-inf` payloads (#1716)
- Fixed `client_info` connection parameter being ignored (#1722)
## v3.6.0 (2026-08-14)
### Added
-45
View File
@@ -12,9 +12,6 @@
namespace Predis\Command;
use Predis\ClientConfiguration;
use UnexpectedValueException;
/**
* Base class for Redis commands.
*/
@@ -155,46 +152,4 @@ abstract class Command implements CommandInterface
return $buffer;
}
/**
* {@inheritDoc}
*/
public static function deserializeCommand(string $serializedCommand): CommandInterface
{
if ($serializedCommand[0] !== '*') {
throw new UnexpectedValueException('Invalid serializing format');
}
$commandArray = explode("\r\n", $serializedCommand);
$commandId = $commandArray[2];
$classPath = __NAMESPACE__ . '\Redis\\';
// Check if given command is a module command.
if (count($commandIdArray = explode('.', $commandId)) > 1) {
// Fetch module configuration to resolve namespace.
$moduleConfiguration = array_filter(
ClientConfiguration::getModules(),
static function ($module) use ($commandIdArray) {
return $module['commandPrefix'] === $commandIdArray[0];
}
);
$commandClass = strtoupper($commandIdArray[0] . $commandIdArray[1]);
$classPath .= array_shift($moduleConfiguration)['name'] . '\\' . $commandClass;
} else {
$classPath .= $commandIdArray[0];
}
$command = new $classPath();
$arguments = [];
for ($i = 4, $iMax = count($commandArray); $i < $iMax; $i++) {
$arguments[] = $commandArray[$i];
++$i;
}
$command->setArguments($arguments);
return $command;
}
}
-8
View File
@@ -92,12 +92,4 @@ interface CommandInterface
* @return string
*/
public function serializeCommand(): string;
/**
* Creates command object from given serialized representation.
*
* @param string $serializedCommand
* @return static
*/
public static function deserializeCommand(string $serializedCommand): CommandInterface;
}
-42
View File
@@ -12,9 +12,6 @@
namespace Predis\Command;
use Predis\ClientConfiguration;
use UnexpectedValueException;
/**
* Class representing a generic Redis command.
*
@@ -152,43 +149,4 @@ final class RawCommand implements CommandInterface
return $buffer;
}
public static function deserializeCommand(string $serializedCommand): CommandInterface
{
if ($serializedCommand[0] !== '*') {
throw new UnexpectedValueException('Invalid serializing format');
}
$commandArray = explode("\r\n", $serializedCommand);
$commandId = $commandArray[2];
$classPath = __NAMESPACE__ . '\Redis\\';
// Check if given command is a module command.
if (count($commandIdArray = explode('.', $commandId)) > 1) {
// Fetch module configuration to resolve namespace.
$moduleConfiguration = array_filter(
ClientConfiguration::getModules(),
static function ($module) use ($commandIdArray) {
return $module['commandPrefix'] === $commandIdArray[0];
}
);
$commandClass = strtoupper($commandIdArray[0] . $commandIdArray[1]);
$classPath .= array_shift($moduleConfiguration)['name'] . '\\' . $commandClass;
} else {
$classPath .= $commandIdArray[0];
}
$command = new $classPath();
$arguments = [];
for ($i = 4, $iMax = count($commandArray); $i < $iMax; $i++) {
$arguments[] = $commandArray[$i];
++$i;
}
$command->setArguments($arguments);
return $command;
}
}
+8 -15
View File
@@ -12,8 +12,8 @@
namespace Predis\Connection;
use Predis\Command\Command;
use Predis\Command\CommandInterface;
use Predis\NotSupportedException;
abstract class AbstractAggregateConnection implements AggregateConnectionInterface
{
@@ -77,19 +77,12 @@ abstract class AbstractAggregateConnection implements AggregateConnectionInterfa
*/
public function write(string $buffer): void
{
$rawCommands = [];
$explodedBuffer = explode("\r\n", trim($buffer));
while (!empty($explodedBuffer)) {
$argsLen = (int) explode('*', $explodedBuffer[0])[1];
$cmdLen = ($argsLen * 2) + 1;
$rawCommands[] = array_splice($explodedBuffer, 0, $cmdLen);
}
foreach ($rawCommands as $command) {
$command = implode("\r\n", $command) . "\r\n";
$commandObj = Command::deserializeCommand($command);
$this->getConnectionByCommand($commandObj)->write($command);
}
// Refuse raw buffers: re-splitting them on "\r\n" ignored RESP length
// prefixes and let CRLF-smuggled commands be routed to a node
// (CVE GHSA-w6f5-v2h6-g786). Pipelines write each command individually.
throw new NotSupportedException(
'Aggregate connections cannot write a raw command buffer; '
. 'route each command through writeRequest() instead.'
);
}
}
@@ -71,6 +71,10 @@ class Resp3Strategy extends Resp2Strategy
return -INF;
}
if (preg_match('/^-?nan(\(.*\))?$/i', $string) === 1) {
return NAN;
}
return (float) $string;
}
-104
View File
@@ -12,23 +12,8 @@
namespace Predis\Command;
use Predis\Command\Redis\BloomFilter\BFADD;
use Predis\Command\Redis\CountMinSketch\CMSINFO;
use Predis\Command\Redis\CuckooFilter\CFADD;
use Predis\Command\Redis\GET;
use Predis\Command\Redis\Json\JSONSET;
use Predis\Command\Redis\MGET;
use Predis\Command\Redis\Search\FTAGGREGATE;
use Predis\Command\Redis\Search\FTEXPLAIN;
use Predis\Command\Redis\Search\FTSEARCH;
use Predis\Command\Redis\Search\FTSPELLCHECK;
use Predis\Command\Redis\TDigest\TDIGESTADD;
use Predis\Command\Redis\TimeSeries\TSGET;
use Predis\Command\Redis\TopK\TOPKQUERY;
use Predis\Command\Redis\ZADD;
use PredisTestCase;
use stdClass;
use UnexpectedValueException;
class CommandTest extends PredisTestCase
{
@@ -194,93 +179,4 @@ class CommandTest extends PredisTestCase
$command->serializeCommand()
);
}
/**
* @dataProvider deserializeCommandProvider
* @group disconnected
*/
public function testDeserializeCommand(string $class, array $arguments): void
{
$command = new $class();
$command->setArguments($arguments);
$deserializedCommand = Command::deserializeCommand($command->serializeCommand());
$this->assertInstanceOf($class, $deserializedCommand);
$this->assertEquals($command->getArguments(), $deserializedCommand->getArguments());
}
/**
* @group disconnected
* @return void
*/
public function testDeserializeCommandThrowsException(): void
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Invalid serializing format');
Command::deserializeCommand('foobar');
}
public function deserializeCommandProvider(): array
{
return [
'GET' => [
GET::class,
['arg1'],
],
'MGET' => [
MGET::class,
['arg1', 'arg2', 'arg3'],
],
'ZADD' => [
ZADD::class,
['key', 'value', 'key1', 'value1'],
],
'JSONSET' => [
JSONSET::class,
['key', '$', '{"key":"value"}'],
],
'BFADD' => [
BFADD::class,
['key', 'value'],
],
'CFADD' => [
CFADD::class,
['key', 'value'],
],
'CMSINFO' => [
CMSINFO::class,
['key', 'value'],
],
'FTSEARCH' => [
FTSEARCH::class,
['key', 'value', 'DIALECT', '2'],
],
'FTAGGREGATE' => [
FTAGGREGATE::class,
['key', 'value', 'DIALECT', '2'],
],
'FTSPELLCHECK' => [
FTSPELLCHECK::class,
['key', 'value', 'DIALECT', '2'],
],
'FTEXPLAIN' => [
FTEXPLAIN::class,
['key', 'value', 'DIALECT', '2'],
],
'TDIGESTADD' => [
TDIGESTADD::class,
['key', 'value'],
],
'TSGET' => [
TSGET::class,
['key'],
],
'TOPKQUERY' => [
TOPKQUERY::class,
['key'],
],
];
}
}
-89
View File
@@ -12,19 +12,7 @@
namespace Predis\Command;
use Predis\Command\Redis\BloomFilter\BFADD;
use Predis\Command\Redis\CountMinSketch\CMSINFO;
use Predis\Command\Redis\CuckooFilter\CFADD;
use Predis\Command\Redis\GET;
use Predis\Command\Redis\Json\JSONSET;
use Predis\Command\Redis\MGET;
use Predis\Command\Redis\Search\FTSEARCH;
use Predis\Command\Redis\TDigest\TDIGESTADD;
use Predis\Command\Redis\TimeSeries\TSGET;
use Predis\Command\Redis\TopK\TOPKQUERY;
use Predis\Command\Redis\ZADD;
use PredisTestCase;
use UnexpectedValueException;
class RawCommandTest extends PredisTestCase
{
@@ -163,81 +151,4 @@ class RawCommandTest extends PredisTestCase
$command->serializeCommand()
);
}
/**
* @dataProvider deserializeCommandProvider
* @group disconnected
*/
public function testDeserializeCommand(string $class, array $arguments): void
{
$command = new $class();
$command->setArguments($arguments);
$deserializedCommand = RawCommand::deserializeCommand($command->serializeCommand());
$this->assertInstanceOf($class, $deserializedCommand);
$this->assertEquals($command->getArguments(), $deserializedCommand->getArguments());
}
/**
* @group disconnected
* @return void
*/
public function testDeserializeCommandThrowsException(): void
{
$this->expectException(UnexpectedValueException::class);
$this->expectExceptionMessage('Invalid serializing format');
RawCommand::deserializeCommand('foobar');
}
public function deserializeCommandProvider(): array
{
return [
'GET' => [
GET::class,
['arg1'],
],
'MGET' => [
MGET::class,
['arg1', 'arg2', 'arg3'],
],
'ZADD' => [
ZADD::class,
['key', 'value', 'key1', 'value1'],
],
'JSONSET' => [
JSONSET::class,
['key', '$', '{"key":"value"}'],
],
'BFADD' => [
BFADD::class,
['key', 'value'],
],
'CFADD' => [
CFADD::class,
['key', 'value'],
],
'CMSINFO' => [
CMSINFO::class,
['key', 'value'],
],
'FTSEARCH' => [
FTSEARCH::class,
['key', 'value'],
],
'TDIGESTADD' => [
TDIGESTADD::class,
['key', 'value'],
],
'TSGET' => [
TSGET::class,
['key'],
],
'TOPKQUERY' => [
TOPKQUERY::class,
['key'],
],
];
}
}
@@ -118,7 +118,11 @@ class TDIGESTBYRANK_Test extends PredisCommandTestCase
$actualResponse = $redis->tdigestbyrank('key', 0, 1, 2, 3, 4, 5, 6);
$this->assertEquals($expectedResponse, $actualResponse);
$this->assertEquals([null, null], $redis->tdigestbyrank('empty_key', 0, 1));
$emptyResponse = $redis->tdigestbyrank('empty_key', 0, 1);
$this->assertCount(2, $emptyResponse);
foreach ($emptyResponse as $value) {
$this->assertNan($value);
}
}
/**
@@ -118,7 +118,11 @@ class TDIGESTBYREVRANK_Test extends PredisCommandTestCase
$actualResponse = $redis->tdigestbyrevrank('key', 0, 1, 2, 3, 4, 5, 6);
$this->assertEquals($expectedResponse, $actualResponse);
$this->assertEquals([null, null], $redis->tdigestbyrevrank('empty_key', 0, 1));
$emptyResponse = $redis->tdigestbyrevrank('empty_key', 0, 1);
$this->assertCount(2, $emptyResponse);
foreach ($emptyResponse as $value) {
$this->assertNan($value);
}
}
/**
@@ -118,7 +118,11 @@ class TDIGESTCDF_Test extends PredisCommandTestCase
$actualResponse = $redis->tdigestcdf('key', 0, 1, 2, 3, 4);
$this->assertSameWithPrecision($expectedResponse, $actualResponse, 5);
$this->assertSame([0.0, 0.0], $redis->tdigestcdf('empty_key', 0, 1));
$emptyResponse = $redis->tdigestcdf('empty_key', 0, 1);
$this->assertCount(2, $emptyResponse);
foreach ($emptyResponse as $value) {
$this->assertNan($value);
}
}
/**
@@ -116,7 +116,7 @@ class TDIGESTMAX_Test extends PredisCommandTestCase
$actualResponse = $redis->tdigestmax('key');
$this->assertEquals('5', $actualResponse);
$this->assertEquals(0, $redis->tdigestmax('empty_key'));
$this->assertNan($redis->tdigestmax('empty_key'));
}
/**
@@ -116,7 +116,7 @@ class TDIGESTMIN_Test extends PredisCommandTestCase
$actualResponse = $redis->tdigestmin('key');
$this->assertEquals('1', $actualResponse);
$this->assertEquals(0, $redis->tdigestmin('empty_key'));
$this->assertNan($redis->tdigestmin('empty_key'));
}
/**
@@ -118,7 +118,11 @@ class TDIGESTQUANTILE_Test extends PredisCommandTestCase
$this->assertEquals([1.0, 2.0, 3.0, 3.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 5.0], $quantileResponse);
$redis->tdigestcreate('empty_key');
$this->assertEquals([null, null], $redis->tdigestquantile('empty_key', 0.0, 0.1));
$emptyResponse = $redis->tdigestquantile('empty_key', 0.0, 0.1);
$this->assertCount(2, $emptyResponse);
foreach ($emptyResponse as $value) {
$this->assertNan($value);
}
}
/**
@@ -129,10 +129,11 @@ class TDIGESTRESET_Test extends PredisCommandTestCase
$this->assertEquals('OK', $actualResponse);
$this->assertSame(500, $info['Compression']);
$this->assertEquals(
[null, null, null, null, null, null],
$redis->tdigestbyrank('key', 0, 1, 2, 3, 4, 5)
);
$resetResponse = $redis->tdigestbyrank('key', 0, 1, 2, 3, 4, 5);
$this->assertCount(6, $resetResponse);
foreach ($resetResponse as $value) {
$this->assertNan($value);
}
}
/**
@@ -474,46 +474,31 @@ class PredisClusterTest extends PredisTestCase
}
/**
* Regression guard for CVE GHSA-w6f5-v2h6-g786 (CWE-93): an aggregate connection
* must refuse a raw, already-serialized command buffer instead of re-splitting it
* on "\r\n". The old parser ignored RESP bulk-length prefixes, so CRLF sequences
* smuggled into a value or key were parsed as extra commands and routed to a node.
*
* @group disconnected
*/
public function testWrite(): void
public function testWriteRejectsRawCommandBuffer(): void
{
$command1 = new GET();
$command1->setArguments(['arg1']);
$command2 = new GET();
$command2->setArguments(['arg2']);
$command3 = new GET();
$command3->setArguments(['arg3']);
// A single GET whose key carries a smuggled FLUSHDB payload; the old code
// would have re-parsed and routed the FLUSHDB, this must route nothing.
$command = new GET();
$command->setArguments(["slug:PAD\r\n*1\r\n\$7\r\nFLUSHDB"]);
$connection1 = $this->getMockConnection('tcp://127.0.0.1:7001');
$connection2 = $this->getMockConnection('tcp://127.0.0.1:7002');
$connection3 = $this->getMockConnection('tcp://127.0.0.1:7003');
$connection1
->expects($this->exactly(3))
->method('write')
->withConsecutive(
[$command1->serializeCommand()],
[$command2->serializeCommand()],
[$command3->serializeCommand()]
);
$connection2
->expects($this->never())
->method('write');
$connection3
->expects($this->never())
->method('write');
$cluster = new PredisCluster(new Parameters());
$cluster->add($connection1);
$cluster->add($connection2);
$cluster->add($connection3);
$cluster->write($command1->serializeCommand() . $command2->serializeCommand() . $command3->serializeCommand());
$this->expectException('Predis\NotSupportedException');
$this->expectExceptionMessage('Aggregate connections cannot write a raw command buffer');
$cluster->write($command->serializeCommand());
}
}
@@ -1634,46 +1634,33 @@ class RedisClusterTest extends PredisTestCase
}
/**
* Regression guard for CVE GHSA-w6f5-v2h6-g786 (CWE-93): an aggregate connection
* must refuse a raw, already-serialized command buffer instead of re-splitting it
* on "\r\n". The old parser ignored RESP bulk-length prefixes, so CRLF sequences
* smuggled into a value or key were parsed as extra commands and routed to a node.
*
* @group disconnected
*/
public function testWrite(): void
public function testWriteRejectsRawCommandBuffer(): void
{
$command1 = new Command\Redis\GET();
$command1->setArguments(['arg1']);
$command2 = new Command\Redis\GET();
$command2->setArguments(['arg2']);
$command3 = new Command\Redis\GET();
$command3->setArguments(['arg3']);
// A single GET whose key carries a smuggled FLUSHDB payload; the old code
// would have re-parsed and routed the FLUSHDB, this must route nothing.
$command = new Command\Redis\GET();
$command->setArguments(["slug:PAD\r\n*1\r\n\$7\r\nFLUSHDB"]);
$factory = $this->getMockBuilder(FactoryInterface::class)->getMock();
$connection1 = $this->getMockConnection('tcp://127.0.0.1:7001');
$connection2 = $this->getMockConnection('tcp://127.0.0.1:7002');
$connection3 = $this->getMockConnection('tcp://127.0.0.1:7003');
$connection1
->expects($this->once())
->method('write')
->with($command3->serializeCommand());
$connection2
->expects($this->once())
->method('write')
->with($command2->serializeCommand());
$connection3
->expects($this->once())
->method('write')
->with($command1->serializeCommand());
->expects($this->never())
->method('write');
$cluster = new RedisCluster($factory, new Parameters());
$cluster->add($connection1);
$cluster->add($connection2);
$cluster->add($connection3);
$cluster->write($command1->serializeCommand() . $command2->serializeCommand() . $command3->serializeCommand());
$this->expectException('Predis\NotSupportedException');
$this->expectExceptionMessage('Aggregate connections cannot write a raw command buffer');
$cluster->write($command->serializeCommand());
}
}
@@ -1459,41 +1459,40 @@ repl_backlog_histlen:12978
}
/**
* Regression guard for CVE GHSA-w6f5-v2h6-g786 (CWE-93): an aggregate connection
* must refuse a raw, already-serialized command buffer instead of re-splitting it
* on "\r\n". The old parser ignored RESP bulk-length prefixes, so CRLF sequences
* smuggled into a value or key were parsed as extra commands and routed to a node.
*
* @group disconnected
*/
public function testWrite(): void
public function testWriteRejectsRawCommandBuffer(): void
{
$command1 = new Command\Redis\Json\JSONGET();
$command1->setArguments(['arg1']);
$command2 = new Command\Redis\Json\JSONGET();
$command2->setArguments(['arg2']);
$command3 = new Command\Redis\Json\JSONGET();
$command3->setArguments(['arg3']);
// A single command whose key carries a smuggled FLUSHDB payload; the old code
// would have re-parsed and routed the FLUSHDB, this must route nothing.
$command = new Command\Redis\Json\JSONGET();
$command->setArguments(["slug:PAD\r\n*1\r\n\$7\r\nFLUSHDB"]);
$master = $this->getMockConnection('tcp://127.0.0.1:6379?role=master');
$slave1 = $this->getMockConnection('tcp://127.0.0.1:6380?role=slave');
$slave1
$master
->expects($this->never())
->method('write');
$master
->expects($this->exactly(3))
->method('write')
->withConsecutive(
[$command1->serializeCommand()],
[$command2->serializeCommand()],
[$command3->serializeCommand()]
);
$slave1
->expects($this->never())
->method('write');
$replication = new MasterSlaveReplication();
$replication->add($master);
$replication->add($slave1);
$replication->write($command1->serializeCommand() . $command2->serializeCommand() . $command3->serializeCommand());
$this->expectException('Predis\NotSupportedException');
$this->expectExceptionMessage('Aggregate connections cannot write a raw command buffer');
$replication->write($command->serializeCommand());
}
/**
@@ -1975,18 +1975,19 @@ class SentinelReplicationTest extends PredisTestCase
}
/**
* Regression guard for CVE GHSA-w6f5-v2h6-g786 (CWE-93): an aggregate connection
* must refuse a raw, already-serialized command buffer instead of re-splitting it
* on "\r\n". The old parser ignored RESP bulk-length prefixes, so CRLF sequences
* smuggled into a value or key were parsed as extra commands and routed to a node.
*
* @group disconnected
*/
public function testWrite(): void
public function testWriteRejectsRawCommandBuffer(): void
{
$command1 = new Command\Redis\Search\FTSEARCH();
$command1->setArguments(['arg1', '*']);
$command2 = new Command\Redis\Search\FTSEARCH();
$command2->setArguments(['arg2', '*']);
$command3 = new Command\Redis\Search\FTSEARCH();
$command3->setArguments(['arg3', '*']);
// A single command whose argument carries a smuggled FLUSHDB payload; the old
// code would have re-parsed and routed the FLUSHDB, this must route nothing.
$command = new Command\Redis\Search\FTSEARCH();
$command->setArguments(["idx:PAD\r\n*1\r\n\$7\r\nFLUSHDB", '*']);
$sentinel = $this->getMockSentinelConnection('tcp://127.0.0.1:5381?role=sentinel');
$master = $this->getMockConnection('tcp://127.0.0.1:6379?role=master');
@@ -1995,29 +1996,22 @@ class SentinelReplicationTest extends PredisTestCase
$factory = new Connection\Factory();
$master
->expects($this->exactly(3))
->method('isConnected')
->willReturn(true);
->expects($this->never())
->method('write');
$slave
->expects($this->never())
->method('write');
$master
->expects($this->exactly(3))
->method('write')
->withConsecutive(
[$command1->serializeCommand()],
[$command2->serializeCommand()],
[$command3->serializeCommand()]
);
$replication = new SentinelReplication('svc', [$sentinel], $factory, $strategy);
$replication->add($master);
$replication->add($slave);
$replication->write($command1->serializeCommand() . $command2->serializeCommand() . $command3->serializeCommand());
$this->expectException('Predis\NotSupportedException');
$this->expectExceptionMessage('Aggregate connections cannot write a raw command buffer');
$replication->write($command->serializeCommand());
}
public function connectionsProvider(): array
@@ -67,6 +67,19 @@ class Resp3StrategyTest extends PredisTestCase
$this->assertSame($expectedValue, $actualResponse);
}
/**
* @dataProvider nanProvider
* @group disconnected
* @param string $data
* @return void
*/
public function testParseDataReturnsFloatNanOnNanValue(string $data): void
{
$actualResponse = $this->strategy->parseData($data);
$this->assertNan($actualResponse);
}
/**
* @dataProvider booleanProvider
* @group disconnected
@@ -171,6 +184,16 @@ class Resp3StrategyTest extends PredisTestCase
];
}
public function nanProvider(): array
{
return [
'canonical nan' => [",nan\r\n"],
'negative nan' => [",-nan\r\n"],
'uppercase nan' => [",NAN\r\n"],
'nan with payload' => [",nan(ind)\r\n"],
];
}
public function booleanProvider(): array
{
return [