Skip to content

Commit f5e463b

Browse files
michalsngr8man
andauthored
Merge commit from fork
Co-authored-by: Bogdan <matolq@gmail.com>
1 parent ecbf044 commit f5e463b

7 files changed

Lines changed: 141 additions & 16 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2951,11 +2951,7 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri
29512951
);
29522952

29532953
// convert binds in where
2954-
foreach ($this->QBWhere as $key => $where) {
2955-
foreach ($this->binds as $field => $bind) {
2956-
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
2957-
}
2958-
}
2954+
$this->convertWhereBindsForBatch();
29592955

29602956
$sql .= ' ' . $this->compileWhereHaving('QBWhere');
29612957

@@ -2981,6 +2977,35 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri
29812977
return str_replace('{:_table_:}', $data, $sql);
29822978
}
29832979

2980+
/**
2981+
* Escapes and substitutes the WHERE binds into the QBWhere conditions
2982+
* for batch delete queries.
2983+
*
2984+
* The bound values respect their escape flag and are escaped the same way
2985+
* as a regular query (see Query::matchNamedBinds()), instead of being
2986+
* injected into the SQL as raw, unescaped values.
2987+
*
2988+
* @used-by _deleteBatch()
2989+
*/
2990+
protected function convertWhereBindsForBatch(): void
2991+
{
2992+
$replacers = [];
2993+
2994+
foreach ($this->binds as $field => $bind) {
2995+
$escapedValue = $bind[1] ? $this->db->escape($bind[0]) : $bind[0];
2996+
2997+
if (is_array($bind[0])) {
2998+
$escapedValue = '(' . implode(',', $escapedValue) . ')';
2999+
}
3000+
3001+
$replacers[':' . $field . ':'] = (string) $escapedValue;
3002+
}
3003+
3004+
foreach ($this->QBWhere as $key => $where) {
3005+
$this->QBWhere[$key]['condition'] = strtr($where['condition'], $replacers);
3006+
}
3007+
}
3008+
29843009
/**
29853010
* Increments a numeric column by the specified value.
29863011
*

‎system/Database/OCI8/Builder.php‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -457,11 +457,7 @@ protected function _deleteBatch(string $table, array $keys, array $values): stri
457457
);
458458

459459
// convert binds in where
460-
foreach ($this->QBWhere as $key => $where) {
461-
foreach ($this->binds as $field => $bind) {
462-
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
463-
}
464-
}
460+
$this->convertWhereBindsForBatch();
465461

466462
$sql .= ' ' . str_replace(
467463
'WHERE ',

‎system/Database/Postgre/Builder.php‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -597,11 +597,7 @@ static function ($key, $value) use ($table, $alias, $that): RawSql|string {
597597
);
598598

599599
// convert binds in where
600-
foreach ($this->QBWhere as $key => $where) {
601-
foreach ($this->binds as $field => $bind) {
602-
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
603-
}
604-
}
600+
$this->convertWhereBindsForBatch();
605601

606602
$sql .= ' ' . str_replace(
607603
'WHERE ',

‎tests/system/Database/Builder/DeleteTest.php‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313

1414
namespace CodeIgniter\Database\Builder;
1515

16+
use CodeIgniter\Database\BaseBuilder;
1617
use CodeIgniter\Test\CIUnitTestCase;
1718
use CodeIgniter\Test\Mock\MockConnection;
19+
use CodeIgniter\Test\Mock\MockQuery;
1820
use PHPUnit\Framework\Attributes\Group;
1921

2022
/**
@@ -90,4 +92,81 @@ public function testGetCompiledDeleteWithLimit(): void
9092
EOL;
9193
$this->assertSame($expectedSQL, $sql);
9294
}
95+
96+
public function testDeleteBatchEscapesWhereBinds(): void
97+
{
98+
$db = new MockConnection([]);
99+
$builder = new BaseBuilder('jobs', $db);
100+
101+
$data = [
102+
['id' => 1, 'name' => 'Derek J'],
103+
['id' => 2, 'name' => 'Ahmadinejad'],
104+
];
105+
106+
// A user-controlled value that would break out of the query if it
107+
// were substituted into the SQL unescaped.
108+
$malicious = "anything' OR '1'='1";
109+
110+
$db->shouldReturn('execute', new class () {});
111+
$builder->setData($data, null, 'data')
112+
->onConstraint(['id' => 'id'])
113+
->where('jobs.name', $malicious)
114+
->deleteBatch();
115+
116+
$query = $db->getLastQuery();
117+
$this->assertInstanceOf(MockQuery::class, $query);
118+
119+
// The bound value must be escaped and quoted as a single string literal:
120+
// it is wrapped in single quotes and the inner quotes are doubled, so it
121+
// cannot break out of the literal and inject SQL.
122+
$this->assertStringContainsString("'anything'' OR ''1''", $query->getQuery());
123+
$this->assertStringNotContainsString("= anything' OR '1'='1", $query->getQuery());
124+
}
125+
126+
public function testDeleteBatchEscapesMultipleWhereBinds(): void
127+
{
128+
$db = new MockConnection([]);
129+
$builder = new BaseBuilder('jobs', $db);
130+
131+
$data = [
132+
['id' => 1, 'name' => 'Derek J'],
133+
['id' => 2, 'name' => 'Ahmadinejad'],
134+
];
135+
136+
$db->shouldReturn('execute', new class () {});
137+
$builder->setData($data, null, 'data')
138+
->onConstraint(['id' => 'id'])
139+
->where('jobs.name', "anything' OR '1'='1")
140+
->where('jobs.id', 1)
141+
->deleteBatch();
142+
143+
$query = $db->getLastQuery();
144+
$this->assertInstanceOf(MockQuery::class, $query);
145+
146+
$this->assertStringContainsString('"jobs"."name" = \'anything\'\' OR \'\'1\'\' = \'\'1\'', $query->getQuery());
147+
$this->assertStringContainsString('"jobs"."id" = 1', $query->getQuery());
148+
}
149+
150+
public function testDeleteBatchEscapesWhereInBinds(): void
151+
{
152+
$db = new MockConnection([]);
153+
$builder = new BaseBuilder('jobs', $db);
154+
155+
$data = [
156+
['id' => 1, 'name' => 'Derek J'],
157+
['id' => 2, 'name' => 'Ahmadinejad'],
158+
];
159+
160+
$db->shouldReturn('execute', new class () {});
161+
$builder->setData($data, null, 'data')
162+
->onConstraint(['id' => 'id'])
163+
->whereIn('jobs.name', ["anything' OR '1'='1", 'Ahmadinejad'])
164+
->deleteBatch();
165+
166+
$query = $db->getLastQuery();
167+
$this->assertInstanceOf(MockQuery::class, $query);
168+
169+
$this->assertStringContainsString("IN ('anything'' OR ''1''=''1','Ahmadinejad')", $query->getQuery());
170+
$this->assertStringNotContainsString("IN anything' OR '1'='1", $query->getQuery());
171+
}
93172
}

‎tests/system/Database/Live/DeleteTest.php‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,25 @@ public function testDeleteBatch(): void
100100
$this->dontSeeInDatabase('user', ['email' => 'ahmadinejad@world.com', 'name' => 'Ahmadinejad']);
101101
}
102102

103+
public function testDeleteBatchPreventsSQLInjectionInWhere(): void
104+
{
105+
if ($this->db->DBDriver === 'SQLite3') {
106+
$this->markTestSkipped('SQLite3 driver does not support WHERE for batch deletes.');
107+
}
108+
109+
$data = [
110+
['userid' => 1, 'username' => 'Derek J'],
111+
];
112+
113+
$this->db->table('user')
114+
->setData($data, null, 'data')
115+
->onConstraint(['id' => 'userid'])
116+
->where('user.name', "nobody' OR 1=1 --")
117+
->deleteBatch();
118+
119+
$this->seeInDatabase('user', ['email' => 'derek@world.com', 'name' => 'Derek Jones']);
120+
}
121+
103122
public function testDeleteBatchConstraintsDate(): void
104123
{
105124
$table = 'type_test';

‎user_guide_src/source/changelogs/v4.7.4.rst‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@ SECURITY
2121
See the `Security advisory GHSA-7wmf-pw8j-mc78 <https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-7wmf-pw8j-mc78>`_
2222
for more information.
2323

24+
- **Query Builder:** Fixed a SQL injection vulnerability in ``deleteBatch()``.
25+
When ``deleteBatch()`` was used together with ``where()`` conditions, the
26+
bound values from the WHERE clause were substituted into the generated SQL
27+
with their escape flag ignored, so they were never escaped or quoted. The
28+
WHERE binds are now escaped in the same way as a regular ``delete()``.
29+
30+
See the `Security advisory GHSA-c9w5-rwh3-7pm9 <https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-c9w5-rwh3-7pm9>`_
31+
for more information.
32+
2433
********
2534
BREAKING
2635
********

‎user_guide_src/source/database/query_builder.rst‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1230,7 +1230,8 @@ Generates a batch **DELETE** statement based on a set of data.
12301230

12311231
This method may be especially useful when deleting data in a table with a composite primary key.
12321232

1233-
.. note:: SQLite3 does not support the use of ``where()``.
1233+
.. note:: The SQLite3 driver does not support additional Query Builder WHERE
1234+
conditions for ``deleteBatch()``.
12341235

12351236
Delete from a Query
12361237
^^^^^^^^^^^^^^^^^^^

0 commit comments

Comments
 (0)