diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index 6623106d9e5e..f501846d0be3 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -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. diff --git a/docs/helpers/security_helper.md b/docs/helpers/security_helper.md index a79d78c12e27..9fed2f6a59f1 100644 --- a/docs/helpers/security_helper.md +++ b/docs/helpers/security_helper.md @@ -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 `#i', - '#`]+)).*?\>#i', - ], - '\\2', - $str, - ); + if (! str_contains(strtolower($str), strtolower(']*+'; + $value = '(?:"[^"]*+(?:"|\z)|\'[^\']*+(?:\'|\z)|' . $unquoted . ')'; + $assignment = '(?:' . $whitespace . '*+=' . $whitespace . '*+(?:' . $value . ')?)?'; + $attribute = $name . $assignment; + + $tagPattern = '#]|\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('assertSame('http://example.com/spacer.gif', strip_image_tags('http://example.com/spacer.gif')); $this->assertSame('http://example.com/spacer.gif', strip_image_tags('Who needs CSS when you have a spacer.gif?')); + $this->assertSame('http://example.com/spacer.gif', strip_image_tags('test')); + $this->assertSame('http://example.com/spacer.gif', strip_image_tags('test')); + $this->assertSame('http://example.com/spacer.gif', strip_image_tags('')); + $this->assertSame('http://example.com/test.png', strip_image_tags('')); + $this->assertSame('http://example.com/test.jpg', strip_image_tags('test\'s photo')); + $this->assertSame('http://example.com/test.jpg', strip_image_tags('\'test')); + + // Empty src or tags without src should be stripped + $this->assertSame('', strip_image_tags('')); + $this->assertSame('', strip_image_tags('')); + $this->assertSame('', strip_image_tags('')); + $this->assertSame('', strip_image_tags('no image')); + $this->assertSame('Hello World', strip_image_tags('Hello World')); + $this->assertSame('Hello World', strip_image_tags('Hello World')); + $this->assertSame('Hello World', strip_image_tags('Hello World')); + + // Multiline img tag + $this->assertSame('http://example.com/test.png', strip_image_tags("")); + + // Intervening text between multiple img tags must not be swallowed + $this->assertSame('Text1 Text2 bar.jpg Text3', strip_image_tags('Text1 foo Text2 Text3')); + $this->assertSame('Start 1.jpg Middle 2.jpg End', strip_image_tags('Start Middle End')); + + // Attribute injection and quote handling + $this->assertSame('test', strip_image_tags('')); + $this->assertSame('test', strip_image_tags('')); + $this->assertSame('test', strip_image_tags('')); + $this->assertSame('test', strip_image_tags('')); + + // Nested img tag bypass + $this->assertSame('x', strip_image_tags('g src=x onerror=alert(1)>')); + $this->assertSame('x', strip_image_tags('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('')); + $this->assertSame('http://example.com/real.gif', strip_image_tags('')); + $this->assertSame('http://example.com/real.gif', strip_image_tags('')); + } + + public function testStripImageTagsGreaterThanSignInsideQuotedAttribute(): void + { + $this->assertSame('photo.jpg', strip_image_tags('><svg onload=alert(1)>')); + $this->assertSame('photo.jpg', strip_image_tags("><svg onload=alert(1)>")); + $this->assertSame('photo.jpg', strip_image_tags('><svg onload=alert(1)>')); + $this->assertSame('', strip_image_tags('><svg onload=alert(1)>')); + $this->assertSame('Before photo.jpg After', strip_image_tags('Before a>b After')); + } + + public function testStripImageTagsNestedTags(): void + { + $this->assertSame('x', strip_image_tags('g src=x onerror=alert(1)>')); + $this->assertSame('x', strip_image_tags('g>g src=x onerror=alert(1)>')); + $this->assertStringNotContainsString('g src=x onerror=alert(1)>')); + $this->assertStringNotContainsString('onerror', strip_image_tags('g src=x onerror=alert(1)>')); + } + + public function testStripImageTagsIgnoresDataSrcAttribute(): void + { + $this->assertSame('real.gif', strip_image_tags('')); + $this->assertSame('real.gif', strip_image_tags('')); + $this->assertSame('', strip_image_tags('')); + } + + public function testStripImageTagsWithoutSrcAttribute(): void + { + $this->assertSame('', strip_image_tags('')); + $this->assertSame('', strip_image_tags('test')); + $this->assertSame('', strip_image_tags('test')); + } + + public function testStripImageTagsIsCaseInsensitive(): void + { + $this->assertSame('photo.jpg', strip_image_tags('')); + } + + 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 = ''; + $result = strip_image_tags($input); + + $this->assertStringNotContainsString('assertStringContainsString('<img', $result); + + $result = strip_image_tags('Hello a>b World'); + + $this->assertSame('Hello <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('' + . str_repeat('g>', 25) + . 'g src=x onerror=alert(1)>'; + + $output = strip_image_tags($input); + + $this->assertStringNotContainsString('assertStringContainsString('<img', $output); } public function testEncodePhpTags(): void