Skip to content

Commit a74bff5

Browse files
committed
fix: reject problematic default upload names on Windows
1 parent 3ad5144 commit a74bff5

6 files changed

Lines changed: 189 additions & 24 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,15 @@ Release Date: Unreleased
88

99
## Message Changes
1010

11+
- Added the `HTTP.invalidFileName` language string.
12+
1113
## Changes
1214

1315
## Deprecations
1416

1517
## Bugs Fixed
1618

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.
1720
- **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.
1821
- **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.
1922

‎docs/libraries/uploaded_files.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,6 +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.
451452

452453
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()`.
453454

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

464-
By default, the client-provided filename is sanitized and used.
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.
465466

466467
#### with New Filename
467468

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

505506
- the file has already been moved
506507
- 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
507509
- the file move operation fails (e.g., improper permissions)
508510

509511
### Store Files

‎system/HTTP/Exceptions/HTTPException.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,14 @@ public static function forInvalidFile(?string $path = null)
207207
return new static(lang('HTTP.invalidFile'));
208208
}
209209

210+
/**
211+
* For Uploaded file move
212+
*/
213+
public static function forInvalidFileName(): static
214+
{
215+
return new static(lang('HTTP.invalidFileName'));
216+
}
217+
210218
/**
211219
* For Uploaded file move
212220
*

‎system/HTTP/Files/UploadedFile.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,11 @@ public function move(string $targetPath, ?string $name = null, bool $overwrite =
141141
if ($name === null) {
142142
helper('security');
143143
$name = sanitize_filename($this->getName());
144+
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+
}
144149
}
145150
$destination = $overwrite ? $targetPath . $name : $this->getDestination($targetPath . $name);
146151

‎system/Language/en/HTTP.php‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,10 @@
6363
'disallowedAction' => 'The action you requested is not allowed.',
6464

6565
// Uploaded file moving
66-
'alreadyMoved' => 'The uploaded file has already been moved.',
67-
'invalidFile' => 'The original file is not a valid file.',
68-
'moveFailed' => 'Could not move file "{0}" to "{1}". Reason: {2}',
66+
'alreadyMoved' => 'The uploaded file has already been moved.',
67+
'invalidFile' => 'The original file is not a valid file.',
68+
'invalidFileName' => 'The uploaded filename is invalid.',
69+
'moveFailed' => 'Could not move file "{0}" to "{1}". Reason: {2}',
6970

7071
'uploadErrOk' => 'The file uploaded with success.',
7172
'uploadErrIniSize' => 'The file "%s" exceeds your upload_max_filesize ini directive.',

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

Lines changed: 166 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use CodeIgniter\Test\CIUnitTestCase;
1818
use org\bovigo\vfs\vfsStream;
1919
use org\bovigo\vfs\vfsStreamDirectory;
20+
use PHPUnit\Framework\Attributes\DataProvider;
2021
use PHPUnit\Framework\Attributes\Group;
2122

2223
/**
@@ -68,14 +69,14 @@ public function testMove(): void
6869
'name' => $finalFilename . '.txt',
6970
'type' => 'text/plain',
7071
'size' => 124,
71-
'tmp_name' => '/tmp/fileA.txt',
72+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
7273
'error' => 0,
7374
],
7475
'userfile2' => [
7576
'name' => 'fileA.txt',
7677
'type' => 'text/csv',
7778
'size' => 248,
78-
'tmp_name' => '/tmp/fileB.txt',
79+
'tmp_name' => sys_get_temp_dir() . '/fileB.txt',
7980
'error' => 0,
8081
],
8182
]);
@@ -108,7 +109,7 @@ public function testMoveSanitizesClientNameByDefault(): void
108109
'name' => '../../public/shell.php',
109110
'type' => 'text/plain',
110111
'size' => 124,
111-
'tmp_name' => '/tmp/fileA.txt',
112+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
112113
'error' => 0,
113114
],
114115
]);
@@ -133,6 +134,141 @@ public function testMoveSanitizesClientNameByDefault(): void
133134
$this->assertFalse($this->root->hasChild('public/shell.php'));
134135
}
135136

137+
/**
138+
* On Windows these names may resolve to a different file or an NTFS stream.
139+
*/
140+
#[DataProvider('provideMoveRejectsUnsafeDefaultNameOnWindows')]
141+
public function testMoveRejectsUnsafeDefaultNameOnWindows(string $clientName): void
142+
{
143+
is_windows(true);
144+
145+
service('superglobals')->setFilesArray([
146+
'userfile' => [
147+
'name' => $clientName,
148+
'type' => 'text/plain',
149+
'size' => 124,
150+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
151+
'error' => 0,
152+
],
153+
]);
154+
155+
$file = (new FileCollection())->getFile('userfile');
156+
$this->assertInstanceOf(UploadedFile::class, $file);
157+
158+
try {
159+
$file->move($this->destination);
160+
$this->fail('HTTPException was not thrown.');
161+
} catch (HTTPException $e) {
162+
$this->assertSame(lang('HTTP.invalidFileName'), $e->getMessage());
163+
}
164+
165+
$this->assertFalse($file->hasMoved());
166+
$this->assertSame($clientName, $file->getName());
167+
$this->assertSame([], array_values(array_diff(scandir($this->destination), ['.', '..', 'index.html'])));
168+
}
169+
170+
/**
171+
* @return iterable<string, array{string}>
172+
*/
173+
public static function provideMoveRejectsUnsafeDefaultNameOnWindows(): iterable
174+
{
175+
yield 'single period' => ['shell.php.'];
176+
177+
yield 'double period' => ['shell.php..'];
178+
179+
yield 'triple period' => ['shell.php...'];
180+
181+
yield 'space then periods' => ['shell.php ..'];
182+
183+
yield 'period then space' => ['shell.php. '];
184+
185+
yield 'trailing space' => ['shell.php '];
186+
187+
yield 'periods only' => ['..'];
188+
189+
yield 'NTFS stream' => ['shell.php:stream'];
190+
191+
yield 'NTFS stream in text file' => ['notes.txt:metadata'];
192+
}
193+
194+
#[DataProvider('provideMoveKeepsWindowsUnsafeDefaultNameOutsideWindows')]
195+
public function testMoveKeepsWindowsUnsafeDefaultNameOutsideWindows(string $clientName): void
196+
{
197+
is_windows(false);
198+
199+
service('superglobals')->setFilesArray([
200+
'userfile' => [
201+
'name' => $clientName,
202+
'type' => 'text/plain',
203+
'size' => 124,
204+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
205+
'error' => 0,
206+
],
207+
]);
208+
209+
$file = (new FileCollection())->getFile('userfile');
210+
$this->assertInstanceOf(UploadedFile::class, $file);
211+
212+
$this->assertTrue($file->move($this->destination));
213+
$this->assertSame($clientName, $file->getName());
214+
$this->assertTrue($this->root->hasChild('destination/' . $clientName));
215+
}
216+
217+
/**
218+
* A trailing space is not covered here: vfsStream trims trailing whitespace from paths.
219+
*
220+
* @return iterable<string, array{string}>
221+
*/
222+
public static function provideMoveKeepsWindowsUnsafeDefaultNameOutsideWindows(): iterable
223+
{
224+
yield 'trailing periods' => ['notes.txt..'];
225+
226+
yield 'colon' => ['meeting 10:30.txt'];
227+
}
228+
229+
public function testMoveAcceptsDefaultNameWithInnerPeriodsAndSpaces(): void
230+
{
231+
is_windows(true);
232+
233+
service('superglobals')->setFilesArray([
234+
'userfile' => [
235+
'name' => 'my file.v1..final.txt',
236+
'type' => 'text/plain',
237+
'size' => 124,
238+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
239+
'error' => 0,
240+
],
241+
]);
242+
243+
$file = (new FileCollection())->getFile('userfile');
244+
$this->assertInstanceOf(UploadedFile::class, $file);
245+
246+
$this->assertTrue($file->move($this->destination));
247+
$this->assertSame('my file.v1..final.txt', $file->getName());
248+
$this->assertTrue($this->root->hasChild('destination/my file.v1..final.txt'));
249+
}
250+
251+
public function testMoveDoesNotRejectCallerSuppliedName(): void
252+
{
253+
is_windows(true);
254+
255+
service('superglobals')->setFilesArray([
256+
'userfile' => [
257+
'name' => 'shell.php..',
258+
'type' => 'text/plain',
259+
'size' => 124,
260+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
261+
'error' => 0,
262+
],
263+
]);
264+
265+
$file = (new FileCollection())->getFile('userfile');
266+
$this->assertInstanceOf(UploadedFile::class, $file);
267+
268+
$this->assertTrue($file->move($this->destination, 'avatar.txt'));
269+
$this->assertSame('avatar.txt', $file->getName());
270+
}
271+
136272
public function testMoveOverwriting(): void
137273
{
138274
$finalFilename = 'file_with_delimiters_underscore';
@@ -141,21 +277,21 @@ public function testMoveOverwriting(): void
141277
'name' => $finalFilename . '.txt',
142278
'type' => 'text/plain',
143279
'size' => 124,
144-
'tmp_name' => '/tmp/fileA.txt',
280+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
145281
'error' => 0,
146282
],
147283
'userfile2' => [
148284
'name' => $finalFilename . '.txt',
149285
'type' => 'text/csv',
150286
'size' => 248,
151-
'tmp_name' => '/tmp/fileB.txt',
287+
'tmp_name' => sys_get_temp_dir() . '/fileB.txt',
152288
'error' => 0,
153289
],
154290
'userfile3' => [
155291
'name' => $finalFilename . '.txt',
156292
'type' => 'text/csv',
157293
'size' => 248,
158-
'tmp_name' => '/tmp/fileC.txt',
294+
'tmp_name' => sys_get_temp_dir() . '/fileC.txt',
159295
'error' => 0,
160296
],
161297
]);
@@ -191,7 +327,7 @@ public function testMoved(): void
191327
'name' => $finalFilename . '.txt',
192328
'type' => 'text/plain',
193329
'size' => 124,
194-
'tmp_name' => '/tmp/fileA.txt',
330+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
195331
'error' => 0,
196332
],
197333
]);
@@ -224,7 +360,7 @@ public function testStore(): void
224360
'name' => $finalFilename . '.txt',
225361
'type' => 'text/plain',
226362
'size' => 124,
227-
'tmp_name' => '/tmp/fileA.txt',
363+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
228364
'error' => 0,
229365
],
230366
]);
@@ -233,19 +369,29 @@ public function testStore(): void
233369

234370
$this->assertTrue($collection->hasFile('userfile1'));
235371

236-
$destination = $this->destination;
237-
// Create the destination if not exists
238-
if (! is_dir($destination)) {
239-
mkdir($destination, 0777, true);
240-
}
241-
242372
$file = $collection->getFile('userfile1');
243373

244374
$this->assertInstanceOf(UploadedFile::class, $file);
245375

246-
$path = $file->store($destination, $file->getName());
376+
$folderName = 'file-moving-test-' . bin2hex(random_bytes(4));
377+
$directory = WRITEPATH . 'uploads/' . $folderName;
247378

248-
$this->assertSame($destination . '/fileA.txt', $path);
379+
try {
380+
$path = $file->store($folderName, $file->getName());
381+
382+
$this->assertSame($folderName . '/fileA.txt', $path);
383+
$this->assertFileExists($directory . '/fileA.txt');
384+
} finally {
385+
if (is_file($directory . '/fileA.txt')) {
386+
unlink($directory . '/fileA.txt');
387+
}
388+
if (is_file($directory . '/index.html')) {
389+
unlink($directory . '/index.html');
390+
}
391+
if (is_dir($directory)) {
392+
rmdir($directory);
393+
}
394+
}
249395
}
250396

251397
public function testAlreadyMoved(): void
@@ -256,7 +402,7 @@ public function testAlreadyMoved(): void
256402
'name' => $finalFilename . '.txt',
257403
'type' => 'text/plain',
258404
'size' => 124,
259-
'tmp_name' => '/tmp/fileA.txt',
405+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
260406
'error' => 0,
261407
],
262408
]);
@@ -286,7 +432,7 @@ public function testInvalidFile(): void
286432
'name' => 'someFile.txt',
287433
'type' => 'text/plain',
288434
'size' => 124,
289-
'tmp_name' => '/tmp/myTempFile.txt',
435+
'tmp_name' => sys_get_temp_dir() . '/myTempFile.txt',
290436
'error' => UPLOAD_ERR_INI_SIZE,
291437
],
292438
]);
@@ -308,7 +454,7 @@ public function testFailedMoveBecauseOfWarning(): void
308454
'name' => 'someFile.txt',
309455
'type' => 'text/plain',
310456
'size' => 124,
311-
'tmp_name' => '/tmp/myTempFile.txt',
457+
'tmp_name' => sys_get_temp_dir() . '/myTempFile.txt',
312458
'error' => 0,
313459
],
314460
]);
@@ -335,7 +481,7 @@ public function testFailedMoveBecauseOfFalseReturned(): void
335481
'name' => 'fileA.txt',
336482
'type' => 'text/plain',
337483
'size' => 124,
338-
'tmp_name' => '/tmp/fileA.txt',
484+
'tmp_name' => sys_get_temp_dir() . '/fileA.txt',
339485
'error' => 0,
340486
],
341487
]);

0 commit comments

Comments
 (0)