Repository navigation
Description
Summary
When a reply line arrives in two parts and the second part comes after read_timeout, phpredis takes the first part as the whole line. The command returns a wrong value, the connection stays open, and the rest of the line is read as the reply to the next command on that connection.
On 6.3.0 the same thing happens when one line is longer than the reader's line buffer (about 4 KB). The bytes past the buffer become the next reply. Against a real server, a Lua script that returns redis.error_reply(ARGV[1]) is enough for the caller to choose what the next command returns.
Commit 6e13625 (#2899) added a CRLF check to redis_sock_gets() and fixes the command specific readers. It is not in a release yet. redis_read_reply_type() still reads the INT, BULK and MULTIBULK header with redis_sock_get_line() and only checks for NULL (library.c:4592 on develop), so rawCommand(), eval() and the other replies that go through the generic reader are still affected on develop.
Versions
- phpredis 6.3.0 from pecl
- phpredis develop at bac0015, built from git (it reports 6.3.0RC1)
- the same develop build with the change proposed below
- PHP 8.4.18 CLI, Alpine Linux, Redis 7.4.11 for the real server test
Results
The script is at the end. It needs no Redis server: it starts a small fake server that writes fixed bytes and pauses 1.5 s in the middle of a line, with read_timeout set to 1 s.
| Case | 6.3.0 | develop | develop with the fix below |
|---|---|---|---|
A. rawCommand, :123 cut after :1 |
returns 1 |
returns 1 |
exception, disconnected |
B. rawCommand, 3 element array, a length line cut |
returns ["aa","2"], then get('k2') returns 'cc' |
same as 6.3.0 | exception, disconnected |
C. incr, :123 cut after :1 |
returns false, next command gets a protocol error |
exception, disconnected | exception, disconnected |
D. get, error line of 4094 bytes followed by +INJECTED |
next get returns '+INJECTED' |
exception, disconnected | exception, disconnected |
| Control, same replies sent whole | correct | correct | correct |
In case B the second get gets no error at all. It returns the last element of the previous reply as if it were the value of k2.
Full output
6.3.0:
phpredis 6.3.0, PHP 8.4.18
--- A_generic_int
rawCommand ["X-INT"] -> returned 1 [1.0s, connected=true]
get ["k"] -> RedisException: protocol error, got '2' as reply type byte [0.5s, connected=true]
--- B_generic_multibulk
rawCommand ["X-ARR"] -> returned ["aa","2"] [1.5s, connected=true]
get ["k1"] -> RedisException: protocol error, got 'b' as reply type byte [0.0s, connected=true]
get ["k2"] -> returned 'cc' [0.0s, connected=true]
--- C_specific_int
incr ["n"] -> returned false [1.0s, connected=true]
get ["k"] -> RedisException: protocol error, got '2' as reply type byte [0.5s, connected=true]
--- D_long_error_line
get ["k1"] -> returned false [0.0s, connected=true, lastError=4091 bytes]
get ["k2"] -> returned '+INJECTED' [0.0s, connected=true, lastError=4091 bytes]
--- Z_control
rawCommand ["X-INT"] -> returned 123 [0.0s, connected=true]
incr ["n"] -> returned 123 [0.0s, connected=true]
get ["k"] -> returned 'v1' [0.0s, connected=true]
develop bac0015:
phpredis 6.3.0RC1, PHP 8.4.18
--- A_generic_int
rawCommand ["X-INT"] -> returned 1 [1.0s, connected=true]
get ["k"] -> RedisException: protocol error, got '2' as reply type byte [0.5s, connected=true]
--- B_generic_multibulk
rawCommand ["X-ARR"] -> returned ["aa","2"] [1.5s, connected=true]
get ["k1"] -> RedisException: protocol error, got 'b' as reply type byte [0.0s, connected=true]
get ["k2"] -> returned 'cc' [0.0s, connected=true]
--- C_specific_int
incr ["n"] -> RedisException: read error on connection to 127.0.0.1:35639 [1.0s, connected=false]
get ["k"] -> RedisException: read error on connection to 127.0.0.1:35639 [0.5s, connected=false]
--- D_long_error_line
get ["k1"] -> RedisException: read error on connection to 127.0.0.1:33813 [0.0s, connected=false]
get ["k2"] -> RedisException: read error on connection to 127.0.0.1:33813 [0.0s, connected=false]
--- Z_control
rawCommand ["X-INT"] -> returned 123 [0.0s, connected=true]
incr ["n"] -> returned 123 [0.0s, connected=true]
get ["k"] -> returned 'v1' [0.0s, connected=true]
develop bac0015 with the fix below:
phpredis 6.3.0RC1, PHP 8.4.18
--- A_generic_int
rawCommand ["X-INT"] -> RedisException: read error on connection to 127.0.0.1:41389 [1.0s, connected=false]
get ["k"] -> RedisException: read error on connection to 127.0.0.1:41389 [0.5s, connected=false]
--- B_generic_multibulk
rawCommand ["X-ARR"] -> RedisException: protocol error, couldn't parse MULTI-BULK response [1.0s, connected=false]
get ["k1"] -> RedisException: read error on connection to 127.0.0.1:35091 [0.5s, connected=false]
get ["k2"] -> RedisException: Redis server 127.0.0.1:35091 went away [0.0s, connected=false, lastError=18 bytes]
--- C_specific_int
incr ["n"] -> RedisException: read error on connection to 127.0.0.1:44729 [1.0s, connected=false]
get ["k"] -> RedisException: read error on connection to 127.0.0.1:44729 [0.5s, connected=false]
--- D_long_error_line
get ["k1"] -> RedisException: read error on connection to 127.0.0.1:38811 [0.0s, connected=false]
get ["k2"] -> RedisException: read error on connection to 127.0.0.1:38811 [0.0s, connected=false]
--- Z_control
rawCommand ["X-INT"] -> returned 123 [0.0s, connected=true]
incr ["n"] -> returned 123 [0.0s, connected=true]
get ["k"] -> returned 'v1' [0.0s, connected=true]
6.3.0 with 6e13625 and the fix below gives the same output as the line above.
The fake server accepts one connection only, so after phpredis disconnects, the next command cannot reconnect. That is the test server, not phpredis.
When the wrong reply reaches another request
This depends on how the connection is reused. We checked it with PHP's built in web server and two requests: the first one runs case B and then get('a'), get('b'), the second one runs get('c'), get('d').
connect(): the damage stays in the first request (get('b')returns"cc"). The socket is closed at the end of the request and the second request is clean.pconnect()with default settings: phpredis sendsECHOwhen it takes the socket from its pool. The check read a stale reply, closed the socket and opened a new one, so the second request was clean.pconnect()withredis.pconnect.echo_check_liveness=0orredis.pconnect.pooling_enabled=0: the second request got the first request's replies (get('c')returned"v-a",get('d')returned"v-b").
So in a normal request with connect(), any later command in the same request can get a wrong value. In long running PHP (Swoole, RoadRunner, queue workers) where one Redis object, or a pool of them, serves many requests, nothing runs the ECHO check between requests and the next user of the connection gets the leftover replies. We found this in a Swoole application with a connection pool.
Output of the two request test (6.3.0)
Default settings:
--- connect
request 1:
rawCommand X-ARR -> ["aa","2"]
get a -> RedisException: protocol error, got 'b' as reply type byte
get b -> "cc"
request 2:
get c -> "v-c"
get d -> "v-d"
--- pconnect
request 1:
rawCommand X-ARR -> ["aa","2"]
get a -> RedisException: protocol error, got 'b' as reply type byte
get b -> "cc"
request 2:
get c -> "v-c"
get d -> "v-d"
--- fake server log
conn#1 accepted
conn#1 <- X-ARR
conn#1 <- GET a
conn#1 <- GET b
conn#1 closed
conn#2 accepted
conn#2 <- GET c
conn#2 <- GET d
conn#2 closed
conn#3 accepted
conn#3 <- X-ARR
conn#3 <- GET a
conn#3 <- GET b
conn#3 <- ECHO phpredis:6abe5c1305939:00000000
conn#4 accepted
conn#3 closed
conn#4 <- GET c
conn#4 <- GET d
With -d redis.pconnect.echo_check_liveness=0 (-d redis.pconnect.pooling_enabled=0 gives the same result):
--- connect
request 1:
rawCommand X-ARR -> ["aa","2"]
get a -> RedisException: protocol error, got 'b' as reply type byte
get b -> "cc"
request 2:
get c -> "v-c"
get d -> "v-d"
--- pconnect
request 1:
rawCommand X-ARR -> ["aa","2"]
get a -> RedisException: protocol error, got 'b' as reply type byte
get b -> "cc"
request 2:
get c -> "v-a"
get d -> "v-b"
--- fake server log
conn#1 accepted
conn#1 <- X-ARR
conn#1 <- GET a
conn#1 <- GET b
conn#1 closed
conn#2 accepted
conn#2 <- GET c
conn#2 <- GET d
conn#2 closed
conn#3 accepted
conn#3 <- X-ARR
conn#3 <- GET a
conn#3 <- GET b
conn#3 <- GET c
conn#3 <- GET d
Cause
In redis_read_reply_type():
/* Read up to our newline */
if (redis_sock_get_line(redis_sock, inbuf, sizeof(inbuf), &nread) == NULL) {
return -1;
}When read_timeout expires in the middle of a line, redis_sock_get_line() returns what was read so far instead of NULL, so the check passes and strtol() parses the partial number (:1 gives 1, $1 gives 1). On 6.3.0 redis_sock_gets() had the same gap, which 6e13625 closed. This caller was not changed.
Suggested fix
Read the header with redis_sock_gets(), like the other readers:
--- a/library.c
+++ b/library.c
@@ redis_read_reply_type(RedisSock *redis_sock, REDIS_REPLY_TYPE *reply_type,
// Buffer to hold size information
char inbuf[255];
- /* Read up to our newline */
- if (redis_sock_get_line(redis_sock, inbuf, sizeof(inbuf), &nread) == NULL) {
+ /* Read up to our newline. redis_sock_gets() fails a line that does
+ * not end in CRLF, drops the connection and throws, so the rest of
+ * the line is never read as the next reply. */
+ if (redis_sock_gets(redis_sock, inbuf, sizeof(inbuf), &nread) < 0) {
return -1;
}redis_sock_gets() removes the trailing \r\n, so strtol() parses the same text as before. The patch applies to develop and, together with 6e13625, to 6.3.0. With it every case above throws and closes the connection, and the control case is unchanged.
Cost: for 200 EVAL calls on one connection, strace -c counted 921 system calls on 6.3.0, 921 on 6.3.0 with 6e13625 and this change, and 922 on develop with this change. When the reply is already buffered, the extra redis_check_eof() in redis_sock_gets() returns without a system call.
It would also help to have a 6.3.x release with 6e13625 and this change. Every released version is affected today.
Reproduction
phpredis-repro.php (no server needed): php phpredis-repro.php
<?php
/*
* Reply line cut short by a read timeout or by the line buffer size.
* No Redis server needed: each case starts a small fake server (this same
* file, run with "serve <case>") that writes fixed bytes, with a 1.5 s pause
* in the middle of a line where noted. Client read_timeout is 1 s.
*
* php phpredis-repro.php
*/
const READ_TIMEOUT = 1.0;
const PAUSE_SEC = 1.5;
/* For each case: the commands the client sends, and for each command the
* bytes the server writes back. null means pause. */
function cases(): array {
return [
// Generic reader (rawCommand, eval): ":123\r\n" cut after ":1"
'A_generic_int' => [
'cmds' => [['rawCommand', ['X-INT']], ['get', ['k']]],
'reply' => [[':1', null, "23\r\n"], ["\$2\r\nv1\r\n"]],
],
// Generic reader: *3 [aa, bbbbbbbbbbbb, cc] with "$12" cut after "$1"
'B_generic_multibulk' => [
'cmds' => [['rawCommand', ['X-ARR']], ['get', ['k1']], ['get', ['k2']]],
'reply' => [["*3\r\n\$2\r\naa\r\n\$1", null, "2\r\nbbbbbbbbbbbb\r\n\$2\r\ncc\r\n"],
["\$2\r\nv1\r\n"], ["\$2\r\nv2\r\n"]],
],
// Command specific reader (INCR): ":123\r\n" cut after ":1"
'C_specific_int' => [
'cmds' => [['incr', ['n']], ['get', ['k']]],
'reply' => [[':1', null, "23\r\n"], ["\$2\r\nv1\r\n"]],
],
// One error line longer than the line buffer, no pause:
// 4094 bytes, then "+INJECTED"
'D_long_error_line' => [
'cmds' => [['get', ['k1']], ['get', ['k2']]],
'reply' => [['-ERR ' . str_repeat('x', 4089) . "+INJECTED\r\n"], ["\$2\r\nv2\r\n"]],
],
// Control: whole replies, no pause
'Z_control' => [
'cmds' => [['rawCommand', ['X-INT']], ['incr', ['n']], ['get', ['k']]],
'reply' => [[":123\r\n"], [":123\r\n"], ["\$2\r\nv1\r\n"]],
],
];
}
/* Fake server (child process) */
if (($argv[1] ?? '') === 'serve') {
$srv = stream_socket_server('tcp://127.0.0.1:0');
echo substr(strrchr(stream_socket_get_name($srv, false), ':'), 1), "\n";
fflush(STDOUT);
$c = stream_socket_accept($srv, 10);
foreach (cases()[$argv[2]]['reply'] as $parts) {
readCommand($c);
foreach ($parts as $p) {
if ($p === null) {
usleep((int) (PAUSE_SEC * 1e6));
continue;
}
fwrite($c, $p);
fflush($c);
}
}
while (fgets($c) !== false) {
// keep the socket open until the client closes it
}
exit(0);
}
/* Reads one RESP array command */
function readCommand($c): void {
$hdr = fgets($c);
if ($hdr === false || $hdr[0] !== '*') {
return;
}
for ($i = 0, $n = (int) substr($hdr, 1); $i < $n; $i++) {
$len = (int) substr(fgets($c), 1);
fread($c, $len + 2);
}
}
function show(mixed $v): string {
return is_array($v) ? json_encode($v) : var_export($v, true);
}
/* Client */
echo 'phpredis ', phpversion('redis'), ', PHP ', PHP_VERSION, "\n";
foreach (array_keys(cases()) as $name) {
$proc = proc_open([PHP_BINARY, __FILE__, 'serve', $name], [1 => ['pipe', 'w']], $pipes);
$port = (int) fgets($pipes[1]);
$r = new Redis();
$r->connect('127.0.0.1', $port, 1.0, null, 0, READ_TIMEOUT);
echo "--- $name\n";
foreach (cases()[$name]['cmds'] as [$m, $args]) {
$t = microtime(true);
try {
$out = 'returned ' . show($r->$m(...$args));
} catch (Throwable $e) {
$out = get_class($e) . ': ' . trim(substr($e->getMessage(), 0, 70));
}
$err = $r->getLastError();
printf(" %-10s %-9s -> %s [%.1fs, connected=%s%s]\n",
$m, json_encode($args), $out, microtime(true) - $t,
var_export($r->isConnected(), true),
$err === null ? '' : ', lastError=' . strlen($err) . ' bytes');
}
$r->close();
proc_terminate($proc, 9);
proc_close($proc);
}phpredis-real-redis.php (long error line against a real server): php phpredis-real-redis.php 127.0.0.1 6379
<?php
/*
* Long error line against a real Redis server (tested with 7.4.11).
* The error text comes from a script argument, so whoever controls the
* argument controls the bytes past the reader's line buffer.
*
* php phpredis-real-redis.php [host] [port]
*/
$host = $argv[1] ?? '127.0.0.1';
$port = (int) ($argv[2] ?? 6379);
$r = new Redis();
$r->connect($host, $port, 1.0, null, 0, 1.0);
$r->set('repro:k2', 'v2');
foreach (range(4080, 4095) as $k) {
$msg = str_repeat('x', $k) . '+INJECTED';
try {
$a = var_export($r->eval('return redis.error_reply(ARGV[1])', [$msg], 0), true);
} catch (Throwable $e) {
$a = get_class($e) . ' (' . strlen($e->getMessage()) . ' bytes)';
}
try {
$b = var_export($r->get('repro:k2'), true);
} catch (Throwable $e) {
$b = get_class($e) . ': ' . addcslashes(trim(substr($e->getMessage(), 0, 60)), "\0..\37");
}
printf("k=%d eval -> %s | GET repro:k2 -> %s\n", $k, $a, $b);
$r->close();
$r->connect($host, $port, 1.0, null, 0, 1.0);
}
$r->del('repro:k2');6.3.0, Redis 7.4.11 (Redis adds ERR in front of the message):
k=4080 eval -> false | GET repro:k2 -> 'v2'
k=4081 eval -> false | GET repro:k2 -> RedisException: protocol error, got '\n' as reply type byte
k=4082 eval -> false | GET repro:k2 -> false
k=4083 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'D' as reply type byte
k=4084 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'E' as reply type byte
k=4085 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'T' as reply type byte
k=4086 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'C' as reply type byte
k=4087 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'E' as reply type byte
k=4088 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'J' as reply type byte
k=4089 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'N' as reply type byte
k=4090 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'I' as reply type byte
k=4091 eval -> false | GET repro:k2 -> '+INJECTED'
k=4092 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'x' as reply type byte
k=4093 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'x' as reply type byte
k=4094 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'x' as reply type byte
k=4095 eval -> false | GET repro:k2 -> RedisException: protocol error, got 'x' as reply type byte
On develop every eval above 4080 throws and GET returns 'v2'.
Two request test: sh run.sh
fake.php:
<?php
// Fake RESP server on 127.0.0.1:7777. Serves several connections and logs
// every command it receives with the number of its connection.
// X-ARR -> *3 [aa, bbbbbbbbbbbb, cc], "$12" cut after "$1" by a 1.5 s pause
// GET k -> "v-k"
// ECHO x -> x
function reply(string $cmd, array $args): array {
switch (strtoupper($cmd)) {
case 'X-ARR':
return ["*3\r\n\$2\r\naa\r\n\$1", null, "2\r\nbbbbbbbbbbbb\r\n\$2\r\ncc\r\n"];
case 'GET':
return ['$' . strlen('v-' . $args[0]) . "\r\nv-{$args[0]}\r\n"];
case 'ECHO':
return ['$' . strlen($args[0]) . "\r\n{$args[0]}\r\n"];
case 'PING':
return ["+PONG\r\n"];
default:
return ["+OK\r\n"];
}
}
$srv = stream_socket_server('tcp://127.0.0.1:7777');
$conns = [];
$bufs = [];
$ids = [];
$next = 1;
while (true) {
$r = array_merge([$srv], $conns);
$w = $e = null;
if (stream_select($r, $w, $e, null) < 1) {
continue;
}
foreach ($r as $s) {
if ($s === $srv) {
$c = stream_socket_accept($srv);
$k = (int) $c;
$conns[$k] = $c;
$bufs[$k] = '';
$ids[$k] = $next++;
echo "conn#{$ids[$k]} accepted\n";
continue;
}
$k = (int) $s;
$d = fread($s, 65536);
if ($d === '' || $d === false) {
echo "conn#{$ids[$k]} closed\n";
fclose($s);
unset($conns[$k]);
continue;
}
$bufs[$k] .= $d;
// Parse every complete RESP array command in the buffer
while (preg_match('/^\*(\d+)\r\n/', $bufs[$k], $m)) {
$pos = strlen($m[0]);
$args = [];
for ($i = 0; $i < (int) $m[1]; $i++) {
if (!preg_match('/\G\$(\d+)\r\n/', $bufs[$k], $mm, 0, $pos)) {
break 2;
}
$pos += strlen($mm[0]);
$len = (int) $mm[1];
if (strlen($bufs[$k]) < $pos + $len + 2) {
break 2;
}
$args[] = substr($bufs[$k], $pos, $len);
$pos += $len + 2;
}
$bufs[$k] = substr($bufs[$k], $pos);
$cmd = array_shift($args);
echo "conn#{$ids[$k]} <- {$cmd} " . implode(' ', $args) . "\n";
foreach (reply($cmd, $args) as $p) {
if ($p === null) {
usleep(1500000);
continue;
}
fwrite($s, $p);
}
}
}
}web/index.php:
<?php
// One web request. ?mode=connect|pconnect ?bad=1 sends the cut reply first ?keys=a,b
$r = new Redis();
$_GET['mode'] === 'pconnect'
? $r->pconnect('127.0.0.1', 7777, 1.0, null, 0, 1.0)
: $r->connect('127.0.0.1', 7777, 1.0, null, 0, 1.0);
$out = [];
$run = function (string $label, callable $f) use (&$out) {
try {
$out[] = $label . ' -> ' . json_encode($f());
} catch (Throwable $e) {
$out[] = $label . ' -> ' . get_class($e) . ': ' . trim($e->getMessage());
}
};
if ($_GET['bad'] === '1') {
$run('rawCommand X-ARR', fn() => $r->rawCommand('X-ARR'));
}
foreach (explode(',', $_GET['keys']) as $k) {
$run("get $k", fn() => $r->get($k));
}
echo implode("\n", $out), "\n";run.sh:
#!/bin/sh
# Two web requests on PHP's built-in server, first with connect(), then with
# pconnect(). Extra arguments are passed to the web server, for example
# sh run.sh -d redis.pconnect.echo_check_liveness=0
DIR=$(cd "$(dirname "$0")" && pwd)
php "$DIR/fake.php" > /tmp/fake.log 2>&1 &
php "$@" -S 127.0.0.1:8080 -t "$DIR/web" > /tmp/web.log 2>&1 &
sleep 1
get() { php -r 'echo file_get_contents("http://127.0.0.1:8080/?" . $argv[1]);' "$1"; }
for m in connect pconnect; do
echo "--- $m"
echo "request 1:"; get "mode=$m&bad=1&keys=a,b"
echo "request 2:"; get "mode=$m&bad=0&keys=c,d"
done
echo "--- fake server log"; cat /tmp/fake.log
kill %1 %2 2>/dev/null
Activity
EJ-Research commentedon Oct 1, 2026
I opened #2941 with the change suggested above (redis_read_reply_type() reads the header with redis_sock_gets()).