Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changelogs/v4.7.7.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Release Date: Unreleased
- **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.
- **Images:** Fixed a bug in `ImageMagickHandler::save()` where saving without an extension or with an unsupported extension threw an `ImagickException` instead of falling back to the image's format.
- **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.
- **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.
- **Session:** Fixed a bug where `BaseHandler::destroyCookie()` did not send the `SameSite` attribute in the `Set-Cookie` header, which could prevent browsers from properly clearing the session cookie.
- **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.

Expand Down
5 changes: 4 additions & 1 deletion docs/helpers/security_helper.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ For more info, please see the [Security Library](../libraries/security.md) docum

- **Return type**: `string`

This is a security function that will strip image tags from a string. It leaves the image URL as plain text.
This function replaces image tags with their `src` values and removes tags without `src`. It does not sanitize HTML or escape the returned values. Use appropriate escaping when displaying the result as text.

!!! note "Note"
If tag replacement fails or the iteration limit is reached, any remaining `<img` prefixes are escaped as `&lt;img`, so the result may contain escaped tag text.

Example:

Expand Down
74 changes: 65 additions & 9 deletions system/Helpers/security_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,18 +85,74 @@ function sanitize_filename(string $filename, bool $relativePath = false): string

if (! function_exists('strip_image_tags')) {
/**
* Strip Image Tags
* Replaces image tags with their raw src values.
*
* If tag replacement fails or the iteration limit is reached, remaining
* "<img" prefixes are escaped as "&lt;img".
*
* This function does not sanitize HTML. Escape the result appropriately
* when displaying it as text.
*/
function strip_image_tags(string $str): string
{
return preg_replace(
[
'#<img[\s/]+.*?src\s*=\s*(["\'])([^\\1]+?)\\1.*?\>#i',
'#<img[\s/]+.*?src\s*=\s*?(([^\s"\'=<>`]+)).*?\>#i',
],
'\\2',
$str,
);
if (! str_contains(strtolower($str), strtolower('<img'))) {
return $str;
}

// HTML whitespace excludes vertical tabs. Names may start with "="
// and contain quotes; quoted values begin only after an assignment.
$whitespace = '[\t\n\f\r ]';
$separators = '[\t\n\f\r /]';
$name = '[^\t\n\f\r />][^\t\n\f\r />=]*+';
$unquoted = '[^\t\n\f\r >"\'][^\t\n\f\r >]*+';
$value = '(?:"[^"]*+(?:"|\z)|\'[^\']*+(?:\'|\z)|' . $unquoted . ')';
$assignment = '(?:' . $whitespace . '*+=' . $whitespace . '*+(?:' . $value . ')?)?';
$attribute = $name . $assignment;

$tagPattern = '#<img(?=[\t\n\f\r />]|\z)((?:' . $separators . '++|' . $attribute . ')*+)(>|\z)#i';

// Skip complete non-src attributes, then capture the first src value.
// Possessive repetition prevents searching inside earlier attributes.
$nameEnd = '(?=[\t\n\f\r />=]|\z)';
$srcPattern = '#\A(?:' . $separators . '*+(?!src' . $nameEnd . ')' . $attribute . ')*+'
. $separators . '*+src' . $nameEnd
. '(?:' . $whitespace . '*+=' . $whitespace . '*+'
. '(?|"([^"]*+)"|\'([^\']*+)\'|(' . $unquoted . '))?)?#i';

$replace = static function (array $tag) use ($srcPattern): string {
// Browsers discard a tag that reaches EOF before its closing ">".
if ($tag[2] === '') {
return '';
}

if (preg_match($srcPattern, $tag[1], $src) !== 1) {
return '';
}

return $src[1] ?? '';
};

// Removing a tag may join surrounding text into another image tag.
for ($remaining = 10; $remaining > 0; $remaining--) {
$result = preg_replace_callback($tagPattern, $replace, $str);

if ($result === null) {
break;
}

if ($result === $str) {
return $result;
}

$str = $result;

if ($remaining > 1 && ! str_contains(strtolower($str), strtolower('<img'))) {
return $str;
}
}

// Tag replacement failed or the iteration limit was reached.
return str_ireplace('<img', '&lt;img', $str);
}
Comment thread
michalsn marked this conversation as resolved.
Resolved
}

Expand Down
116 changes: 116 additions & 0 deletions tests/system/Helpers/SecurityHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,122 @@ public function testStripImageTags(): void
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('http://example.com/spacer.gif'));

$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?" />'));
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('<img src=\'http://example.com/spacer.gif\' alt="test" />'));
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('<img src=http://example.com/spacer.gif alt="test" />'));
$this->assertSame('http://example.com/spacer.gif', strip_image_tags('<img src = "http://example.com/spacer.gif" />'));
$this->assertSame('http://example.com/test.png', strip_image_tags('<img class="my-class" id="my-img" src="http://example.com/test.png">'));
$this->assertSame('http://example.com/test.jpg', strip_image_tags('<img alt="test\'s photo" src="http://example.com/test.jpg">'));
$this->assertSame('http://example.com/test.jpg', strip_image_tags('<img alt=\'test "quoted" photo\' src=\'http://example.com/test.jpg\'>'));

// Empty src or tags without src should be stripped
$this->assertSame('', strip_image_tags('<img src="" onerror="alert(1)">'));
Comment thread
paulbalandan marked this conversation as resolved.
Resolved
$this->assertSame('', strip_image_tags('<img src=\'\' onerror=\'alert(1)\'>'));
$this->assertSame('', strip_image_tags('<img onerror="alert(1)">'));
$this->assertSame('', strip_image_tags('<img alt="no image">'));
$this->assertSame('Hello World', strip_image_tags('Hello <img> World'));
$this->assertSame('Hello World', strip_image_tags('Hello <img/> World'));
$this->assertSame('Hello World', strip_image_tags('Hello <img > World'));

// Multiline img tag
$this->assertSame('http://example.com/test.png', strip_image_tags("<img\n class=\"foo\"\n src=\"http://example.com/test.png\"\n alt=\"bar\">"));

// Intervening text between multiple img tags must not be swallowed
$this->assertSame('Text1 Text2 bar.jpg Text3', strip_image_tags('Text1 <img alt="foo"> Text2 <img src="bar.jpg"> Text3'));
$this->assertSame('Start 1.jpg Middle 2.jpg End', strip_image_tags('Start <img src="1.jpg"> Middle <img src="2.jpg"> End'));

// Attribute injection and quote handling
$this->assertSame('test', strip_image_tags('<img src="test" onmouseover="alert(1)">'));
$this->assertSame('test', strip_image_tags('<img src=\'test\' onmouseover=\'alert(1)\'>'));
$this->assertSame('test', strip_image_tags('<img src=\'test\' onmouseover="alert(1)">'));
$this->assertSame('test', strip_image_tags('<img src="test" onmouseover=\'alert(1)\'>'));

// Nested img tag bypass
$this->assertSame('x', strip_image_tags('<im<img>g src=x onerror=alert(1)>'));
$this->assertSame('x', strip_image_tags('<im<im<img>g>g src=x onerror=alert(1)>'));

// Only actual src attribute should be matched, not attributes ending with src (e.g. data-src)
$this->assertSame('', strip_image_tags('<img data-src="http://example.com/fake.gif">'));
$this->assertSame('http://example.com/real.gif', strip_image_tags('<img data-src="http://example.com/fake.gif" src="http://example.com/real.gif">'));
$this->assertSame('http://example.com/real.gif', strip_image_tags('<img src="http://example.com/real.gif" data-src="http://example.com/fake.gif">'));
}

public function testStripImageTagsGreaterThanSignInsideQuotedAttribute(): void
{
$this->assertSame('photo.jpg', strip_image_tags('<img alt="><svg onload=alert(1)>" src="photo.jpg">'));
$this->assertSame('photo.jpg', strip_image_tags("<img alt='><svg onload=alert(1)>' src='photo.jpg'>"));
$this->assertSame('photo.jpg', strip_image_tags('<img src="photo.jpg" alt="><svg onload=alert(1)>">'));
$this->assertSame('', strip_image_tags('<img alt="><svg onload=alert(1)>">'));
$this->assertSame('Before photo.jpg After', strip_image_tags('Before <img alt="a>b" src="photo.jpg"> After'));
}

public function testStripImageTagsNestedTags(): void
{
$this->assertSame('x', strip_image_tags('<im<img>g src=x onerror=alert(1)>'));
$this->assertSame('x', strip_image_tags('<im<im<img>g>g src=x onerror=alert(1)>'));
$this->assertStringNotContainsString('<img', strip_image_tags('<im<img>g src=x onerror=alert(1)>'));
$this->assertStringNotContainsString('onerror', strip_image_tags('<im<img>g src=x onerror=alert(1)>'));
}

public function testStripImageTagsIgnoresDataSrcAttribute(): void
{
$this->assertSame('real.gif', strip_image_tags('<img data-src="fake.gif" src="real.gif">'));
$this->assertSame('real.gif', strip_image_tags('<img src="real.gif" data-src="fake.gif">'));
$this->assertSame('', strip_image_tags('<img data-src="fake.gif">'));
}

public function testStripImageTagsWithoutSrcAttribute(): void
{
$this->assertSame('', strip_image_tags('<img>'));
$this->assertSame('', strip_image_tags('<img alt="test">'));
$this->assertSame('', strip_image_tags('<IMG ALT="test">'));
}

public function testStripImageTagsIsCaseInsensitive(): void
{
$this->assertSame('photo.jpg', strip_image_tags('<IMG SRC="photo.jpg">'));
}

public function testStripImageTagsFallbackWhenPcreFails(): void
{
$oldBacktrack = ini_get('pcre.backtrack_limit');
$oldJit = ini_get('pcre.jit');

try {
// Force PCRE failure: JIT does not honour backtrack_limit.
ini_set('pcre.jit', '0');
ini_set('pcre.backtrack_limit', '1');

// Make sure PCRE really fails for this input, so the fallback is exercised.
// This also keeps the test independent of the test order: a pattern
// already compiled and JIT-cached by earlier tests still honours
// backtrack_limit once JIT is disabled, and the assertion below turns
// any silent PCRE success into an explicit failure.
$input = '<img src="photo.jpg" onerror="alert(1)">';
$result = strip_image_tags($input);

$this->assertStringNotContainsString('<img', $result);
$this->assertStringContainsString('&lt;img', $result);

$result = strip_image_tags('Hello <img alt="a>b" onerror=alert(1)> World');

$this->assertSame('Hello &lt;img alt="a>b" onerror=alert(1)> World', $result);
} finally {
ini_set('pcre.backtrack_limit', (string) $oldBacktrack);
ini_set('pcre.jit', (string) $oldJit);
}
}

public function testStripImageTagsExceedingIterationLimitEscapesPrefix(): void
{
$input = str_repeat('<im', 26)
. '<img>'
. str_repeat('g>', 25)
. 'g src=x onerror=alert(1)>';

$output = strip_image_tags($input);

$this->assertStringNotContainsString('<img', $output);
$this->assertStringContainsString('&lt;img', $output);
}

public function testEncodePhpTags(): void
Expand Down
Loading