Skip to content

Commit 7b00e71

Browse files
committed
fix(Session): use query binding for session lock in PostgreHandler
1 parent c431aa1 commit 7b00e71

3 files changed

Lines changed: 146 additions & 1 deletion

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Release Date: Unreleased
1919
- **CORS:** Fixed a bug where `Cors::hasResponseHeaders()` matched header substrings via `str_contains()`, causing false positives when existing exposed headers shared a prefix with configured exposed headers.
2020
- **HTTP:** Fixed a bug where `UploadedFile::move()` and `UploadedFile::store()` on Windows could store a file under a different name than `getName()` reported, or write its contents to an NTFS alternate data stream. Filenames ending in a period or space or containing a colon are now rejected, including explicitly supplied names.
2121
- **Security:** Fixed a bug where `Security::__construct()` threw a `TypeError` when the CSRF cookie was an array, causing an HTTP 500 response for affected requests.
22+
- **Session:** Fixed a bug where `PostgreHandler::lockSession()` and `releaseLock()` interpolated unescaped session IDs and IP addresses into SQL queries. They are now escaped with `BaseConnection::escape()` and executed with `simpleQuery()`.
2223
- **Worker Mode:** Fixed a bug where every request that ended with an uncaught exception, including a `404 Page Not Found` without a 404 override, called `exit()` in the exception handler. This ended the worker script, so FrankenPHP booted a new one, and the worker loop skipped its cleanup after the request. The exception handler now returns to the worker loop.
2324

2425
See the repo's [CHANGELOG.md](https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md) for a complete list of bugs fixed.

‎system/Session/Handlers/Database/PostgreHandler.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ public function gc($max_lifetime): false|int
7070
*/
7171
protected function lockSession(string $sessionID): bool
7272
{
73-
$arg = "hashtext('{$sessionID}')" . ($this->matchIP ? ", hashtext('{$this->ipAddress}')" : '');
73+
$arg = 'hashtext(' . $this->db->escape($sessionID) . ')'
74+
. ($this->matchIP ? ', hashtext(' . $this->db->escape($this->ipAddress) . ')' : '');
75+
7476
if ($this->db->simpleQuery("SELECT pg_advisory_lock({$arg})") !== false) {
7577
$this->lock = $arg;
7678

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Session\Handlers\Database;
15+
16+
use CodeIgniter\Events\Events;
17+
use CodeIgniter\Test\CIUnitTestCase;
18+
use CodeIgniter\Test\Mock\MockConnection;
19+
use CodeIgniter\Test\Mock\MockResult;
20+
use Config\Session as SessionConfig;
21+
use PHPUnit\Framework\Attributes\Group;
22+
23+
/**
24+
* @internal
25+
*/
26+
#[Group('Others')]
27+
final class PostgreHandlerMockTest extends CIUnitTestCase
28+
{
29+
private const IP_ADDRESS = "192.168.1.1' OR '1'='1";
30+
private const SESSION_ID = "sess'id; DROP TABLE users; --";
31+
32+
private function createHandler(bool $matchIP, MockConnection $mockDb): PostgreHandler
33+
{
34+
$config = new SessionConfig();
35+
$config->driver = PostgreHandler::class;
36+
$config->savePath = 'ci_sessions';
37+
$config->matchIP = $matchIP;
38+
39+
$handler = new PostgreHandler($config, self::IP_ADDRESS);
40+
$this->setPrivateProperty($handler, 'db', $mockDb);
41+
42+
return $handler;
43+
}
44+
45+
private function createMockDb(): PostgreHandlerMockConnection
46+
{
47+
return new PostgreHandlerMockConnection(['DBDriver' => 'Postgre']);
48+
}
49+
50+
public function testLockAndReleaseSessionWithoutMatchIP(): void
51+
{
52+
$db = $this->createMockDb();
53+
$handler = $this->createHandler(false, $db);
54+
55+
$queryCount = 0;
56+
$listener = static function () use (&$queryCount): void {
57+
$queryCount++;
58+
};
59+
Events::on('DBQuery', $listener);
60+
61+
$lockSession = self::getPrivateMethodInvoker($handler, 'lockSession');
62+
$releaseLock = self::getPrivateMethodInvoker($handler, 'releaseLock');
63+
64+
$this->assertTrue($lockSession(self::SESSION_ID));
65+
$this->assertSame(
66+
"hashtext('sess''id; DROP TABLE users; --')",
67+
self::getPrivateProperty($handler, 'lock'),
68+
);
69+
70+
$this->assertTrue($releaseLock());
71+
$this->assertFalse(self::getPrivateProperty($handler, 'lock'));
72+
73+
Events::removeListener('DBQuery', $listener);
74+
75+
$this->assertSame(0, $queryCount);
76+
$this->assertSame([
77+
"SELECT pg_advisory_lock(hashtext('sess''id; DROP TABLE users; --'))",
78+
"SELECT pg_advisory_unlock(hashtext('sess''id; DROP TABLE users; --'))",
79+
], $db->executed);
80+
81+
$this->assertStringNotContainsString(self::SESSION_ID, $db->executed[0]);
82+
$this->assertStringNotContainsString(self::SESSION_ID, $db->executed[1]);
83+
}
84+
85+
public function testLockAndReleaseSessionWithMatchIP(): void
86+
{
87+
$db = $this->createMockDb();
88+
$handler = $this->createHandler(true, $db);
89+
90+
$queryCount = 0;
91+
$listener = static function () use (&$queryCount): void {
92+
$queryCount++;
93+
};
94+
Events::on('DBQuery', $listener);
95+
96+
$lockSession = self::getPrivateMethodInvoker($handler, 'lockSession');
97+
$releaseLock = self::getPrivateMethodInvoker($handler, 'releaseLock');
98+
99+
$this->assertTrue($lockSession(self::SESSION_ID));
100+
$this->assertSame(
101+
"hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1')",
102+
self::getPrivateProperty($handler, 'lock'),
103+
);
104+
105+
$this->assertTrue($releaseLock());
106+
$this->assertFalse(self::getPrivateProperty($handler, 'lock'));
107+
108+
Events::removeListener('DBQuery', $listener);
109+
110+
$this->assertSame(0, $queryCount);
111+
$this->assertSame([
112+
"SELECT pg_advisory_lock(hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1'))",
113+
"SELECT pg_advisory_unlock(hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1'))",
114+
], $db->executed);
115+
116+
$this->assertStringNotContainsString(self::SESSION_ID, $db->executed[0]);
117+
$this->assertStringNotContainsString(self::IP_ADDRESS, $db->executed[0]);
118+
}
119+
}
120+
121+
/**
122+
* Mock connection that records the raw SQL passed to simpleQuery().
123+
*
124+
* PostgreHandler uses simpleQuery() with escaped values, so the queries are not
125+
* bound and must be captured as they are sent to the database.
126+
*
127+
* @internal
128+
*/
129+
final class PostgreHandlerMockConnection extends MockConnection
130+
{
131+
/**
132+
* @var list<string>
133+
*/
134+
public array $executed = [];
135+
136+
public function simpleQuery(string $sql): MockResult
137+
{
138+
$this->executed[] = $sql;
139+
140+
return new MockResult($this->connID, $this->resultID);
141+
}
142+
}

0 commit comments

Comments
 (0)