Skip to content

Commit 9f3374f

Browse files
authored
Merge commit from fork
* fix: reject trailing-dot and embedded PHP upload filenames * apply review suggestions
1 parent 641ee5b commit 9f3374f

6 files changed

Lines changed: 175 additions & 0 deletions

File tree

‎system/Validation/StrictRules/FileRules.php‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,10 @@ public function is_image(?string $blank, string $params): bool
149149
if ($this->hasInvalidImageClientExtension($file)) {
150150
return false;
151151
}
152+
153+
if ($this->hasUnsafeClientFilename($file)) {
154+
return false;
155+
}
152156
}
153157

154158
return true;
@@ -183,6 +187,10 @@ public function mime_in(?string $blank, string $params): bool
183187
if ($this->hasMismatchedClientExtension($file)) {
184188
return false;
185189
}
190+
191+
if ($this->hasUnsafeClientFilename($file)) {
192+
return false;
193+
}
186194
}
187195

188196
return true;
@@ -220,6 +228,10 @@ public function ext_in(?string $blank, string $params): bool
220228
if ($file->guessExtension() !== $clientExtension) {
221229
return false;
222230
}
231+
232+
if ($this->hasUnsafeClientFilename($file)) {
233+
return false;
234+
}
223235
}
224236

225237
return true;
@@ -346,4 +358,35 @@ private function hasMismatchedClientExtension(UploadedFile $file): bool
346358

347359
return $file->guessExtension() !== $clientExtension;
348360
}
361+
362+
/**
363+
* Reject trailing-dot names and names with a PHP extension before the final extension.
364+
*/
365+
private function hasUnsafeClientFilename(UploadedFile $file): bool
366+
{
367+
helper('security');
368+
369+
// Check the name that UploadedFile::move() uses when no name is supplied.
370+
$filename = sanitize_filename($file->getClientName());
371+
$parts = explode('.', strtolower(rtrim($filename, ' ')));
372+
373+
if (count($parts) === 1) {
374+
return false;
375+
}
376+
377+
if (array_pop($parts) === '') {
378+
return true;
379+
}
380+
381+
// Some server configurations select a PHP handler from an earlier extension.
382+
array_shift($parts);
383+
384+
foreach ($parts as $part) {
385+
if (preg_match('/^php[0-9]*$/', $part) === 1 || in_array($part, ['pht', 'phtml', 'phar', 'phps'], true)) {
386+
return true;
387+
}
388+
}
389+
390+
return false;
391+
}
349392
}

‎tests/system/Validation/StrictRules/FileRulesTest.php‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use CodeIgniter\Exceptions\InvalidArgumentException;
1717
use CodeIgniter\Test\CIUnitTestCase;
1818
use CodeIgniter\Validation\Validation;
19+
use PHPUnit\Framework\Attributes\DataProvider;
1920
use PHPUnit\Framework\Attributes\Group;
2021
use Tests\Support\Validation\TestRules;
2122

@@ -525,6 +526,92 @@ public function testExtensionFailsForExtensionlessClientFilename(): void
525526
}
526527
}
527528

529+
#[DataProvider('provideFileRulesRejectUnsafeClientFilename')]
530+
public function testFileRulesRejectUnsafeClientFilename(string $name, string $rule): void
531+
{
532+
$payload = $this->createGifPhpPayload();
533+
534+
try {
535+
$this->setUploadedAvatar($payload, $name);
536+
537+
$this->validation->setRules(['avatar' => $rule]);
538+
$this->assertFalse($this->validation->run([]));
539+
} finally {
540+
unlink($payload);
541+
}
542+
}
543+
544+
/**
545+
* @return iterable<string, array{string, string}>
546+
*/
547+
public static function provideFileRulesRejectUnsafeClientFilename(): iterable
548+
{
549+
$names = [
550+
'shell.php.',
551+
'shell.php..',
552+
'shell.php. ',
553+
'shell.gif.',
554+
'shell.gif. ',
555+
'shell.php.gif',
556+
'shell.PHP.gif',
557+
'shell.p$hp.gif',
558+
'shell.php;.gif',
559+
'shell.PH#P.gif',
560+
'shell.p%20hp.gif',
561+
"shell.p\x01hp.gif",
562+
'shell.php8.gif',
563+
'shell.pht.gif',
564+
'shell.phtml.gif',
565+
'shell.phar.gif',
566+
'shell.phar&.gif',
567+
'shell.phps.gif',
568+
'.php.gif',
569+
'.phar.gif',
570+
'.phps.gif',
571+
];
572+
573+
$rules = [
574+
'is_image[avatar]',
575+
'mime_in[avatar,image/gif]',
576+
'ext_in[avatar,gif]',
577+
];
578+
579+
foreach ($names as $name) {
580+
foreach ($rules as $rule) {
581+
yield json_encode($name) . ' ' . $rule => [$name, $rule];
582+
}
583+
}
584+
}
585+
586+
#[DataProvider('provideFileRulesAllowSafeDottedClientFilename')]
587+
public function testFileRulesAllowSafeDottedClientFilename(string $name, string $rule): void
588+
{
589+
$payload = $this->createGifPayload();
590+
591+
try {
592+
$this->setUploadedAvatar($payload, $name);
593+
594+
$this->validation->setRules(['avatar' => $rule]);
595+
$this->assertTrue($this->validation->run([]));
596+
} finally {
597+
unlink($payload);
598+
}
599+
}
600+
601+
/**
602+
* @return iterable<string, array{string, string}>
603+
*/
604+
public static function provideFileRulesAllowSafeDottedClientFilename(): iterable
605+
{
606+
foreach (['family.vacation.gif', 'family.va$ca%20tion.gif', 'php.gif', 'p$hp.gif'] as $name) {
607+
yield $name . ' is_image[avatar]' => [$name, 'is_image[avatar]'];
608+
609+
yield $name . ' mime_in[avatar,image/gif]' => [$name, 'mime_in[avatar,image/gif]'];
610+
611+
yield $name . ' ext_in[avatar,gif]' => [$name, 'ext_in[avatar,gif]'];
612+
}
613+
}
614+
528615
private function createGifPayload(): string
529616
{
530617
$payload = tempnam(sys_get_temp_dir(), 'ci4-upload-poc-');
@@ -538,6 +625,15 @@ private function createGifPayload(): string
538625
return $payload;
539626
}
540627

628+
private function createGifPhpPayload(): string
629+
{
630+
$payload = $this->createGifPayload();
631+
632+
file_put_contents($payload, "\n<?php echo 'payload'; ?>\n", FILE_APPEND);
633+
634+
return $payload;
635+
}
636+
541637
private function createPhpPayload(): string
542638
{
543639
$payload = tempnam(sys_get_temp_dir(), 'ci4-upload-poc-');

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ Release Date: Unreleased
1414
SECURITY
1515
********
1616

17+
- **Validation:** The ``is_image`` and ``mime_in`` file upload rules now reject client filenames ending in dots while
18+
continuing to accept genuinely extensionless uploads. These rules and ``ext_in`` also reject filenames with a PHP
19+
handler extension before the final extension, such as ``shell.php.gif``, including extensions revealed by filename
20+
sanitization. These checks also reject innocent filenames such as ``logo.php.gif``. See
21+
:doc:`Upgrading from 4.7.4 to 4.7.5 </installation/upgrade_475>` for migration instructions.
22+
Previously, a GIF/PHP polyglot with one of these names could pass validation. Applications that save uploads with
23+
client-provided names in executable public directories may be affected. Use a generated filename or disable script
24+
execution in the upload directory. See the `Security advisory GHSA-4hwf-v4mp-hf6c <https://github.com/codeigniter4/CodeIgniter4/security/advisories/GHSA-4hwf-v4mp-hf6c>`_
25+
for more information.
1726
- **View Parser:** Fixed a stored XSS vulnerability where a substituted value containing
1827
Parser syntax (e.g., ``{text|raw}`` or ``{!text!}``) was interpreted by a later
1928
substitution pass, allowing user-supplied data to bypass auto-escaping of other

‎user_guide_src/source/installation/upgrade_475.rst‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,22 @@ on placeholders within built-in plugin output must render those fragments explic
6464
Custom plugins that transform template code retain their existing behavior and are
6565
responsible for keeping untrusted data separate from Parser syntax.
6666

67+
File Upload Validation
68+
======================
69+
70+
The ``is_image``, ``mime_in``, and ``ext_in`` rules now reject client filenames
71+
with a PHP handler extension before the final extension, including extensions
72+
revealed by ``sanitize_filename()`` (for example, ``shell.p$hp.gif`` becomes
73+
``shell.php.gif``). Filenames ending in dots, including dots followed by spaces,
74+
are also rejected.
75+
76+
These checks apply regardless of the file's contents or the intended meaning of
77+
its name. For example, both ``shell.php.gif`` and an innocent PHP logo named
78+
``logo.php.gif`` fail validation, even if the latter contains only a GIF image.
79+
Rename such files before uploading, for example to ``logo-php.gif``. Choosing a
80+
generated filename when saving the file does not bypass these validation checks,
81+
which run against the client filename before the file is saved.
82+
6783
*********************
6884
Breaking Enhancements
6985
*********************

‎user_guide_src/source/libraries/uploaded_files.rst‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,8 @@ In PHP versions below 8.1, this returns ``null``
328328

329329
.. literalinclude:: uploaded_files/023.php
330330

331+
.. _uploaded-files-moving-files:
332+
331333
Moving Files
332334
============
333335

@@ -341,6 +343,11 @@ Moving Files
341343
``$fileName`` is NOT sanitized, so if you pass one, generate it yourself or sanitize it with
342344
:php:func:`sanitize_filename`.
343345

346+
Sanitizing a client-provided filename does not make it safe to keep in a web-accessible directory where scripts can
347+
execute. Some web servers select a handler from any extension in a filename, including an extension before the final
348+
one. Keep uploads outside the public directory with ``store()`` when possible. If they must be public, disable script
349+
execution in the upload directory and pass ``$file->getRandomName()`` as the second argument to ``move()``.
350+
344351
with Original Filename
345352
----------------------
346353

‎user_guide_src/source/libraries/validation.rst‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,3 +1117,7 @@ is_image Yes Fails if the file cannot be determined to be
11171117
======================= ========== ============================================= ===================================================
11181118

11191119
The file validation rules apply for both single and multiple file uploads.
1120+
1121+
The ``is_image``, ``mime_in``, and ``ext_in`` rules check the uploaded file and its client filename, but they cannot
1122+
guarantee that a web server will not execute a file saved under that name. See :ref:`uploaded-files-moving-files` for
1123+
safe storage practices.

0 commit comments

Comments
 (0)