Skip to content

Commit fdfb299

Browse files
committed
fix(Security): improve regex and quote handling in strip_image_tags()
1 parent c431aa1 commit fdfb299

3 files changed

Lines changed: 179 additions & 8 deletions

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+
- **Security:** Fixed a bug in `strip_image_tags()` where an invalid PCRE character class caused attribute injection and improper quote handling, and ensured tags without `src` are stripped.
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/Helpers/security_helper.php‎

Lines changed: 72 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -86,17 +86,81 @@ function sanitize_filename(string $filename, bool $relativePath = false): string
8686
if (! function_exists('strip_image_tags')) {
8787
/**
8888
* Strip Image Tags
89+
*
90+
* Replaces every `<img ...>` tag with the value of its `src` attribute
91+
* (or removes it when there is none). A `>` inside a quoted attribute
92+
* value does not end the tag. If PCRE fails, the image tags are removed
93+
* without regular expressions, so unfiltered input is never returned.
8994
*/
9095
function strip_image_tags(string $str): string
9196
{
92-
return preg_replace(
93-
[
94-
'#<img[\s/]+.*?src\s*=\s*(["\'])([^\\1]+?)\\1.*?\>#i',
95-
'#<img[\s/]+.*?src\s*=\s*?(([^\s"\'=<>`]+)).*?\>#i',
96-
],
97-
'\\2',
98-
$str,
99-
);
97+
if (! str_contains(strtolower($str), '<img')) {
98+
return $str;
99+
}
100+
101+
// The tag body: quoted values (which may contain ">") or any non-">" char.
102+
$tagPattern = '#<img(?=[\s/>])((?:"[^"]*"|\'[^\']*\'|[^>])*+)>#i';
103+
$attrPattern = '#[\s/]+([^\s"\'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s"\'<>`]+)))?#';
104+
105+
$replaceTag = static function (array $matches) use ($attrPattern): string {
106+
if (preg_match_all($attrPattern, $matches[1], $attributes, PREG_SET_ORDER) === false) {
107+
return '';
108+
}
109+
110+
foreach ($attributes as $attribute) {
111+
if (strtolower($attribute[1]) === 'src') {
112+
return ($attribute[2] ?? '') . ($attribute[3] ?? '') . ($attribute[4] ?? '');
113+
}
114+
}
115+
116+
return '';
117+
};
118+
119+
// Regex-free removal of image tags, used only when PCRE fails.
120+
$removeTags = static function (string $input): string {
121+
$output = '';
122+
$length = strlen($input);
123+
$offset = 0;
124+
125+
while (($pos = stripos($input, '<img', $offset)) !== false) {
126+
$output .= substr($input, $offset, $pos - $offset);
127+
$end = $pos + 4;
128+
$quote = '';
129+
130+
for (; $end < $length; $end++) {
131+
$char = $input[$end];
132+
133+
if ($quote !== '') {
134+
if ($char === $quote) {
135+
$quote = '';
136+
}
137+
} elseif ($char === '"' || $char === "'") {
138+
$quote = $char;
139+
} elseif ($char === '>') {
140+
break;
141+
}
142+
}
143+
144+
$offset = $end + 1;
145+
}
146+
147+
return $output . substr($input, $offset);
148+
};
149+
150+
$iterations = 0;
151+
152+
do {
153+
if (++$iterations > 25) {
154+
$str = $removeTags($str);
155+
break;
156+
}
157+
158+
$original = $str;
159+
$result = preg_replace_callback($tagPattern, $replaceTag, $str);
160+
$str = $result ?? $removeTags($str);
161+
} while ($str !== $original && str_contains(strtolower($str), '<img'));
162+
163+
return $str;
100164
}
101165
}
102166

‎tests/system/Helpers/SecurityHelperTest.php‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,112 @@ public function testStripImageTags(): void
208208
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('http://example.com/spacer.gif'));
209209

210210
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('<img src="http://example.com/spacer.gif" alt="Who needs CSS when you have a spacer.gif?" />'));
211+
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('<img src=\'http://example.com/spacer.gif\' alt="test" />'));
212+
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('<img src=http://example.com/spacer.gif alt="test" />'));
213+
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('<img src = "http://example.com/spacer.gif" />'));
214+
$this->assertSame('http://example.com/test.png', strip_image_tags('<img class="my-class" id="my-img" src="http://example.com/test.png">'));
215+
$this->assertSame('http://example.com/test.jpg', strip_image_tags('<img alt="test\'s photo" src="http://example.com/test.jpg">'));
216+
$this->assertSame('http://example.com/test.jpg', strip_image_tags('<img alt=\'test "quoted" photo\' src=\'http://example.com/test.jpg\'>'));
217+
218+
// Empty src or tags without src should be stripped
219+
$this->assertSame('', strip_image_tags('<img src="" onerror="alert(1)">'));
220+
$this->assertSame('', strip_image_tags('<img src=\'\' onerror=\'alert(1)\'>'));
221+
$this->assertSame('', strip_image_tags('<img onerror="alert(1)">'));
222+
$this->assertSame('', strip_image_tags('<img alt="no image">'));
223+
$this->assertSame('Hello World', strip_image_tags('Hello <img> World'));
224+
$this->assertSame('Hello World', strip_image_tags('Hello <img/> World'));
225+
$this->assertSame('Hello World', strip_image_tags('Hello <img > World'));
226+
227+
// Multiline img tag
228+
$this->assertSame('http://example.com/test.png', strip_image_tags("<img\n class=\"foo\"\n src=\"http://example.com/test.png\"\n alt=\"bar\">"));
229+
230+
// Intervening text between multiple img tags must not be swallowed
231+
$this->assertSame('Text1 Text2 bar.jpg Text3', strip_image_tags('Text1 <img alt="foo"> Text2 <img src="bar.jpg"> Text3'));
232+
$this->assertSame('Start 1.jpg Middle 2.jpg End', strip_image_tags('Start <img src="1.jpg"> Middle <img src="2.jpg"> End'));
233+
234+
// Attribute injection and quote handling
235+
$this->assertSame('test', strip_image_tags('<img src="test" onmouseover="alert(1)">'));
236+
$this->assertSame('test', strip_image_tags('<img src=\'test\' onmouseover=\'alert(1)\'>'));
237+
$this->assertSame('test', strip_image_tags('<img src=\'test\' onmouseover="alert(1)">'));
238+
$this->assertSame('test', strip_image_tags('<img src="test" onmouseover=\'alert(1)\'>'));
239+
240+
// Nested img tag bypass
241+
$this->assertSame('x', strip_image_tags('<im<img>g src=x onerror=alert(1)>'));
242+
$this->assertSame('x', strip_image_tags('<im<im<img>g>g src=x onerror=alert(1)>'));
243+
244+
// Only actual src attribute should be matched, not attributes ending with src (e.g. data-src)
245+
$this->assertSame('', strip_image_tags('<img data-src="http://example.com/fake.gif">'));
246+
$this->assertSame('http://example.com/real.gif', strip_image_tags('<img data-src="http://example.com/fake.gif" src="http://example.com/real.gif">'));
247+
$this->assertSame('http://example.com/real.gif', strip_image_tags('<img src="http://example.com/real.gif" data-src="http://example.com/fake.gif">'));
248+
}
249+
250+
public function testStripImageTagsGreaterThanSignInsideQuotedAttribute(): void
251+
{
252+
$this->assertSame('photo.jpg', strip_image_tags('<img alt="><svg onload=alert(1)>" src="photo.jpg">'));
253+
$this->assertSame('photo.jpg', strip_image_tags("<img alt='><svg onload=alert(1)>' src='photo.jpg'>"));
254+
$this->assertSame('photo.jpg', strip_image_tags('<img src="photo.jpg" alt="><svg onload=alert(1)>">'));
255+
$this->assertSame('', strip_image_tags('<img alt="><svg onload=alert(1)>">'));
256+
$this->assertSame('Before photo.jpg After', strip_image_tags('Before <img alt="a>b" src="photo.jpg"> After'));
257+
}
258+
259+
public function testStripImageTagsNestedTags(): void
260+
{
261+
$this->assertSame('x', strip_image_tags('<im<img>g src=x onerror=alert(1)>'));
262+
$this->assertSame('x', strip_image_tags('<im<im<img>g>g src=x onerror=alert(1)>'));
263+
$this->assertStringNotContainsString('<img', strip_image_tags('<im<img>g src=x onerror=alert(1)>'));
264+
$this->assertStringNotContainsString('onerror', strip_image_tags('<im<img>g src=x onerror=alert(1)>'));
265+
}
266+
267+
public function testStripImageTagsIgnoresDataSrcAttribute(): void
268+
{
269+
$this->assertSame('real.gif', strip_image_tags('<img data-src="fake.gif" src="real.gif">'));
270+
$this->assertSame('real.gif', strip_image_tags('<img src="real.gif" data-src="fake.gif">'));
271+
$this->assertSame('', strip_image_tags('<img data-src="fake.gif">'));
272+
}
273+
274+
public function testStripImageTagsWithoutSrcAttribute(): void
275+
{
276+
$this->assertSame('', strip_image_tags('<img>'));
277+
$this->assertSame('', strip_image_tags('<img alt="test">'));
278+
$this->assertSame('', strip_image_tags('<IMG ALT="test">'));
279+
}
280+
281+
public function testStripImageTagsIsCaseInsensitive(): void
282+
{
283+
$this->assertSame('photo.jpg', strip_image_tags('<IMG SRC="photo.jpg">'));
284+
}
285+
286+
public function testStripImageTagsFallbackWhenPcreFails(): void
287+
{
288+
$oldBacktrack = ini_get('pcre.backtrack_limit');
289+
$oldJit = ini_get('pcre.jit');
290+
291+
try {
292+
// Force PCRE failure: JIT does not honour backtrack_limit.
293+
ini_set('pcre.jit', '0');
294+
ini_set('pcre.backtrack_limit', '1');
295+
296+
// Make sure PCRE really fails for this input, so the fallback is exercised.
297+
// This also keeps the test independent of the test order: a pattern
298+
// already compiled and JIT-cached by earlier tests still honours
299+
// backtrack_limit once JIT is disabled, and the assertion below turns
300+
// any silent PCRE success into an explicit failure.
301+
$input = '<img src="photo.jpg" onerror="alert(1)">';
302+
preg_match('#<img(?=[\s/>])((?:"[^"]*"|\'[^\']*\'|[^>])*+)>#i', $input);
303+
$this->assertNotSame(PREG_NO_ERROR, preg_last_error(), 'PCRE was expected to fail with backtrack_limit=1.');
304+
305+
$result = strip_image_tags($input);
306+
307+
$this->assertStringNotContainsString('<img', $result);
308+
$this->assertStringNotContainsString('onerror', $result);
309+
310+
$result = strip_image_tags('Hello <img alt="a>b" onerror=alert(1)> World');
311+
312+
$this->assertSame('Hello World', $result);
313+
} finally {
314+
ini_set('pcre.backtrack_limit', (string) $oldBacktrack);
315+
ini_set('pcre.jit', (string) $oldJit);
316+
}
211317
}
212318

213319
public function testEncodePhpTags(): void

0 commit comments

Comments
 (0)