Skip to content

Commit 3607a57

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

4 files changed

Lines changed: 162 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: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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\Test\Mock\MockConnection;
17+
use CodeIgniter\Test\Mock\MockResult;
18+
19+
/**
20+
* Mock connection that records the raw SQL passed to simpleQuery().
21+
*
22+
* PostgreHandler uses simpleQuery() when no bindings are needed, so the
23+
* queries are not bound and must be captured as they are sent to the database.
24+
*
25+
* @internal
26+
*/
27+
final class PostgreHandlerMockConnection extends MockConnection
28+
{
29+
/**
30+
* @var list<string>
31+
*/
32+
public array $executed = [];
33+
34+
public function simpleQuery(string $sql): MockResult
35+
{
36+
$this->executed[] = $sql;
37+
38+
return new MockResult($this->connID, $this->resultID);
39+
}
40+
}
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
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 Config\Session as SessionConfig;
20+
use PHPUnit\Framework\Attributes\Group;
21+
22+
/**
23+
* @internal
24+
*/
25+
#[Group('Others')]
26+
final class PostgreHandlerMockTest extends CIUnitTestCase
27+
{
28+
private const IP_ADDRESS = "192.168.1.1' OR '1'='1";
29+
private const SESSION_ID = "sess'id; DROP TABLE users; --";
30+
31+
private function createHandler(bool $matchIP, MockConnection $mockDb): PostgreHandler
32+
{
33+
$config = new SessionConfig();
34+
$config->driver = PostgreHandler::class;
35+
$config->savePath = 'ci_sessions';
36+
$config->matchIP = $matchIP;
37+
38+
$handler = new PostgreHandler($config, self::IP_ADDRESS);
39+
$this->setPrivateProperty($handler, 'db', $mockDb);
40+
41+
return $handler;
42+
}
43+
44+
private function createMockDb(): PostgreHandlerMockConnection
45+
{
46+
return new PostgreHandlerMockConnection(['DBDriver' => 'Postgre']);
47+
}
48+
49+
public function testLockAndReleaseSessionWithoutMatchIP(): void
50+
{
51+
$db = $this->createMockDb();
52+
$handler = $this->createHandler(false, $db);
53+
54+
$queryCount = 0;
55+
$listener = static function () use (&$queryCount): void {
56+
$queryCount++;
57+
};
58+
Events::on('DBQuery', $listener);
59+
60+
$lockSession = self::getPrivateMethodInvoker($handler, 'lockSession');
61+
$releaseLock = self::getPrivateMethodInvoker($handler, 'releaseLock');
62+
63+
$this->assertTrue($lockSession(self::SESSION_ID));
64+
$this->assertSame(
65+
"hashtext('sess''id; DROP TABLE users; --')",
66+
self::getPrivateProperty($handler, 'lock'),
67+
);
68+
69+
$this->assertTrue($releaseLock());
70+
$this->assertFalse(self::getPrivateProperty($handler, 'lock'));
71+
72+
Events::removeListener('DBQuery', $listener);
73+
74+
$this->assertSame(0, $queryCount);
75+
$this->assertSame([
76+
"SELECT pg_advisory_lock(hashtext('sess''id; DROP TABLE users; --'))",
77+
"SELECT pg_advisory_unlock(hashtext('sess''id; DROP TABLE users; --'))",
78+
], $db->executed);
79+
80+
$this->assertStringNotContainsString(self::SESSION_ID, $db->executed[0]);
81+
$this->assertStringNotContainsString(self::SESSION_ID, $db->executed[1]);
82+
}
83+
84+
public function testLockAndReleaseSessionWithMatchIP(): void
85+
{
86+
$db = $this->createMockDb();
87+
$handler = $this->createHandler(true, $db);
88+
89+
$queryCount = 0;
90+
$listener = static function () use (&$queryCount): void {
91+
$queryCount++;
92+
};
93+
Events::on('DBQuery', $listener);
94+
95+
$lockSession = self::getPrivateMethodInvoker($handler, 'lockSession');
96+
$releaseLock = self::getPrivateMethodInvoker($handler, 'releaseLock');
97+
98+
$this->assertTrue($lockSession(self::SESSION_ID));
99+
$this->assertSame(
100+
"hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1')",
101+
self::getPrivateProperty($handler, 'lock'),
102+
);
103+
104+
$this->assertTrue($releaseLock());
105+
$this->assertFalse(self::getPrivateProperty($handler, 'lock'));
106+
107+
Events::removeListener('DBQuery', $listener);
108+
109+
$this->assertSame(0, $queryCount);
110+
$this->assertSame([
111+
"SELECT pg_advisory_lock(hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1'))",
112+
"SELECT pg_advisory_unlock(hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1'))",
113+
], $db->executed);
114+
115+
$this->assertStringNotContainsString(self::SESSION_ID, $db->executed[0]);
116+
$this->assertStringNotContainsString(self::IP_ADDRESS, $db->executed[0]);
117+
}
118+
}

0 commit comments

Comments
 (0)