Skip to content

Commit 8277b44

Browse files
committed
fix: reject unsafe uploaded filenames on Windows
1 parent 76f2433 commit 8277b44

4 files changed

Lines changed: 104 additions & 15 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Release Date: Unreleased
1616

1717
## Bugs Fixed
1818

19-
- **HTTP:** Fixed a bug where `UploadedFile::move()` with the default filename on Windows could store a file under a different name than `getName()` reported, or write its contents to an NTFS alternate data stream. Client filenames ending in a period or space or containing a colon are now rejected in this case.
19+
- **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.
2020
- **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.
2121
- **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.
2222

‎docs/libraries/uploaded_files.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,7 @@ echo $clientPath; // dir/file.txt, or dir/sub_dir/file.txt
448448
Do not let user input directly decide the destination directory. The `$targetPath` argument of `move()` and the `$folderName` argument of `store()` are never sanitized, so an attacker-controlled value containing `../` can move the uploaded file outside the intended directory. Use directories controlled by your application.
449449

450450
Filenames are only sanitized by default: `move()` sanitizes the client-provided name when the `$name` argument is omitted, and `store()` generates a random name when `$fileName` is omitted. A caller-supplied `$name` or `$fileName` is NOT sanitized, so if you pass one, generate it yourself or sanitize it with `sanitize_filename`.
451-
On Windows, sanitizing a client-provided name does not remove trailing periods or spaces or prevent NTFS alternate data streams. Use a generated name if you need to pass an explicit filename.
451+
On Windows, `move()` and `store()` reject names ending in a period or space or containing a colon, whether the name was supplied by the caller or chosen by default. Sanitization alone does not remove these forms. Use a generated name when possible.
452452

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

@@ -462,7 +462,7 @@ Each file can be moved to its new location with the aptly named `move()` method.
462462
$file->move(WRITEPATH . 'uploads');
463463
```
464464

465-
By default, the client-provided filename is sanitized and used. On Windows, an `HTTPException` is thrown if the sanitized name ends with a period or a space, or contains a colon. Such names may be stored under a different filename or in an NTFS alternate data stream. Use a generated filename if the client-provided name is rejected.
465+
By default, the client-provided filename is sanitized and used. On Windows, an `HTTPException` is thrown if the name to be stored ends with a period or a space, or contains a colon. This also applies when you pass a name explicitly. Such names may be stored under a different filename or in an NTFS alternate data stream. Use a generated filename if the client-provided name is rejected.
466466

467467
#### with New Filename
468468

@@ -505,7 +505,7 @@ Moving an uploaded file can fail, with an `HTTPException`, under several circums
505505

506506
- the file has already been moved
507507
- the file did not upload successfully
508-
- on Windows, the `$name` argument is omitted and the sanitized client-provided filename ends with a period or a space, or contains a colon
508+
- on Windows, the filename ends with a period or a space, or contains a colon
509509
- the file move operation fails (e.g., improper permissions)
510510

511511
### Store Files
@@ -538,4 +538,5 @@ Moving an uploaded file can fail, with an `HTTPException`, under several circums
538538

539539
- the file has already been moved
540540
- the file did not upload successfully
541+
- on Windows, the supplied filename ends with a period or a space, or contains a colon
541542
- the file move operation fails (e.g., improper permissions)

‎system/HTTP/Files/UploadedFile.php‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,8 @@ public function __construct(string $path, string $originalName, ?string $mimeTyp
119119
* untrusted input: a value containing "../" can move the file outside the intended
120120
* directory. Use a path controlled by your application.
121121
* @param string|null $name The name to rename the file to. When null, the client-provided name is used and sanitized.
122-
* A caller-supplied name is NOT sanitized.
122+
* A caller-supplied name is NOT sanitized. On Windows, names that may resolve to a
123+
* different file or an NTFS stream are rejected in either case.
123124
* @param bool $overwrite State for indicating whether to overwrite the previously generated file with the same
124125
* name or not.
125126
*
@@ -141,11 +142,11 @@ public function move(string $targetPath, ?string $name = null, bool $overwrite =
141142
if ($name === null) {
142143
helper('security');
143144
$name = sanitize_filename($this->getName());
145+
}
144146

145-
// Windows may store these names under a different filename or in an NTFS stream.
146-
if (is_windows() && (rtrim($name, '. ') !== $name || str_contains($name, ':'))) {
147-
throw HTTPException::forInvalidFileName();
148-
}
147+
// Windows may store these names under a different filename or in an NTFS stream.
148+
if (is_windows() && (rtrim($name, '. ') !== $name || str_contains($name, ':'))) {
149+
throw HTTPException::forInvalidFileName();
149150
}
150151
$destination = $overwrite ? $targetPath . $name : $this->getDestination($targetPath . $name);
151152

@@ -351,6 +352,7 @@ public function isValid(): bool
351352
* it from untrusted input: a value containing "../" can move the file outside the
352353
* uploads directory.
353354
* @param string|null $fileName the name to rename the file to. A caller-supplied name is NOT sanitized.
355+
* On Windows, names that may resolve to a different file or an NTFS stream are rejected.
354356
*
355357
* @return string file full path
356358
*/

‎tests/system/HTTP/Files/FileMovingTest.php‎

Lines changed: 92 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,8 @@ public static function provideMoveRejectsUnsafeDefaultNameOnWindows(): iterable
184184

185185
yield 'trailing space' => ['shell.php '];
186186

187+
yield 'two trailing spaces' => ['shell.php '];
188+
187189
yield 'periods only' => ['..'];
188190

189191
yield 'NTFS stream' => ['shell.php:stream'];
@@ -248,7 +250,7 @@ public function testMoveAcceptsDefaultNameWithInnerPeriodsAndSpaces(): void
248250
$this->assertTrue($this->root->hasChild('destination/my file.v1..final.txt'));
249251
}
250252

251-
public function testMoveDoesNotRejectCallerSuppliedName(): void
253+
public function testMoveAcceptsSafeCallerSuppliedName(): void
252254
{
253255
is_windows(true);
254256

@@ -269,6 +271,34 @@ public function testMoveDoesNotRejectCallerSuppliedName(): void
269271
$this->assertSame('avatar.txt', $file->getName());
270272
}
271273

274+
public function testMoveRejectsUnsafeCallerSuppliedNameOnWindows(): void
275+
{
276+
is_windows(true);
277+
278+
service('superglobals')->setFilesArray([
279+
'userfile' => [
280+
'name' => 'avatar.txt',
281+
'type' => 'text/plain',
282+
'size' => 124,
283+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
284+
'error' => 0,
285+
],
286+
]);
287+
288+
$file = (new FileCollection())->getFile('userfile');
289+
$this->assertInstanceOf(UploadedFile::class, $file);
290+
291+
try {
292+
$file->move($this->destination, 'shell.php..');
293+
$this->fail('HTTPException was not thrown.');
294+
} catch (HTTPException $e) {
295+
$this->assertSame(lang('HTTP.invalidFileName'), $e->getMessage());
296+
}
297+
298+
$this->assertFalse($file->hasMoved());
299+
$this->assertSame('avatar.txt', $file->getName());
300+
}
301+
272302
public function testMoveOverwriting(): void
273303
{
274304
$finalFilename = 'file_with_delimiters_underscore';
@@ -377,13 +407,13 @@ public function testStore(): void
377407
$directory = WRITEPATH . 'uploads/' . $folderName;
378408

379409
try {
380-
$path = $file->store($folderName, $file->getName());
410+
$path = $file->store($folderName, 'stored-file.txt');
381411

382-
$this->assertSame($folderName . '/fileA.txt', $path);
383-
$this->assertFileExists($directory . '/fileA.txt');
412+
$this->assertSame($folderName . '/stored-file.txt', $path);
413+
$this->assertFileExists($directory . '/stored-file.txt');
384414
} finally {
385-
if (is_file($directory . '/fileA.txt')) {
386-
unlink($directory . '/fileA.txt');
415+
if (is_file($directory . '/stored-file.txt')) {
416+
unlink($directory . '/stored-file.txt');
387417
}
388418
if (is_file($directory . '/index.html')) {
389419
unlink($directory . '/index.html');
@@ -394,6 +424,62 @@ public function testStore(): void
394424
}
395425
}
396426

427+
#[DataProvider('provideStoreRejectsUnsafeExplicitNameOnWindows')]
428+
public function testStoreRejectsUnsafeExplicitNameOnWindows(string $clientName): void
429+
{
430+
is_windows(true);
431+
432+
service('superglobals')->setFilesArray([
433+
'userfile' => [
434+
'name' => $clientName,
435+
'type' => 'text/plain',
436+
'size' => 124,
437+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
438+
'error' => 0,
439+
],
440+
]);
441+
442+
$file = (new FileCollection())->getFile('userfile');
443+
$this->assertInstanceOf(UploadedFile::class, $file);
444+
445+
$folderName = 'file-moving-test-' . bin2hex(random_bytes(4));
446+
$directory = WRITEPATH . 'uploads/' . $folderName;
447+
448+
try {
449+
try {
450+
$file->store($folderName, $file->getName());
451+
$this->fail('HTTPException was not thrown.');
452+
} catch (HTTPException $e) {
453+
$this->assertSame(lang('HTTP.invalidFileName'), $e->getMessage());
454+
}
455+
456+
$this->assertFalse($file->hasMoved());
457+
$this->assertSame($clientName, $file->getName());
458+
$this->assertFileDoesNotExist($directory . '/shell.php');
459+
} finally {
460+
foreach (['shell.php..', 'shell.php ', 'shell.php:stream', 'shell.php', 'index.html'] as $name) {
461+
if (is_file($directory . '/' . $name)) {
462+
unlink($directory . '/' . $name);
463+
}
464+
}
465+
if (is_dir($directory)) {
466+
rmdir($directory);
467+
}
468+
}
469+
}
470+
471+
/**
472+
* @return iterable<string, array{string}>
473+
*/
474+
public static function provideStoreRejectsUnsafeExplicitNameOnWindows(): iterable
475+
{
476+
yield 'trailing periods' => ['shell.php..'];
477+
478+
yield 'two trailing spaces' => ['shell.php '];
479+
480+
yield 'NTFS stream' => ['shell.php:stream'];
481+
}
482+
397483
public function testAlreadyMoved(): void
398484
{
399485
$finalFilename = 'fileA';

0 commit comments

Comments
 (0)