Skip to content

Commit 48615f2

Browse files
committed
fix: prevent path traversal in development server rewrite script
1 parent cc882d6 commit 48615f2

3 files changed

Lines changed: 225 additions & 2 deletions

File tree

‎system/rewrite.php‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,24 @@
3131
// Full path
3232
$path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . ltrim($uri, '/');
3333

34+
// Security: prevent path traversal outside DOCUMENT_ROOT.
35+
// realpath() resolves ../, symlinks and returns false for non-existing paths.
36+
$realPath = realpath($path);
37+
$realDocRoot = realpath($_SERVER['DOCUMENT_ROOT']);
38+
3439
// If $path is an existing file or folder within the public folder
3540
// then let the request handle it like normal.
36-
if ($uri !== '/' && (is_file($path) || is_dir($path))) {
41+
if (
42+
$uri !== '/'
43+
&& $realPath !== false
44+
&& $realDocRoot !== false
45+
&& ($realPath === $realDocRoot || str_starts_with($realPath, $realDocRoot . DIRECTORY_SEPARATOR))
46+
&& (is_file($realPath) || is_dir($realPath))
47+
) {
3748
return false;
3849
}
3950

40-
unset($uri, $path);
51+
unset($uri, $path, $realPath, $realDocRoot);
4152

4253
// Otherwise, we'll load the index file and let
4354
// the framework handle the request from here.

‎tests/system/RewriteTest.php‎

Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter;
15+
16+
use CodeIgniter\Test\CIUnitTestCase;
17+
use FilesystemIterator;
18+
use PHPUnit\Framework\Attributes\DataProvider;
19+
use PHPUnit\Framework\Attributes\Group;
20+
use RecursiveDirectoryIterator;
21+
use RecursiveIteratorIterator;
22+
23+
/**
24+
* Regression tests for system/rewrite.php path traversal (todo #36).
25+
*
26+
* Proves that the fixed rewrite.php does NOT serve files outside
27+
* DOCUMENT_ROOT via ../ or encoded traversal, while still serving
28+
* legitimate public assets.
29+
*
30+
* @internal
31+
*/
32+
#[Group('Others')]
33+
final class RewriteTest extends CIUnitTestCase
34+
{
35+
private string $tmpRoot = '';
36+
private string $docRoot = '';
37+
38+
protected function setUp(): void
39+
{
40+
parent::setUp();
41+
42+
$this->tmpRoot = sys_get_temp_dir() . '/ci4_rewrite_' . uniqid('', true);
43+
$this->docRoot = $this->tmpRoot . '/public';
44+
45+
mkdir($this->docRoot . '/assets', 0777, true);
46+
mkdir($this->tmpRoot . '/public2', 0777, true);
47+
48+
// Legitimate public files
49+
file_put_contents($this->docRoot . '/index.php', '<?php echo "index";');
50+
file_put_contents($this->docRoot . '/test.txt', 'hello');
51+
file_put_contents($this->docRoot . '/assets/app.css', 'body{}');
52+
53+
// Files OUTSIDE docroot that must NOT be served
54+
file_put_contents($this->tmpRoot . '/outside.txt', 'secret');
55+
file_put_contents($this->tmpRoot . '/public2/also.txt', 'also');
56+
file_put_contents($this->docRoot . '/../outside2.txt', 'secret2');
57+
}
58+
59+
protected function tearDown(): void
60+
{
61+
parent::tearDown();
62+
$this->removeDir($this->tmpRoot);
63+
}
64+
65+
private function removeDir(string $dir): void
66+
{
67+
if (! is_dir($dir)) {
68+
return;
69+
}
70+
$it = new RecursiveIteratorIterator(
71+
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
72+
RecursiveIteratorIterator::CHILD_FIRST,
73+
);
74+
75+
foreach ($it as $file) {
76+
$file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
77+
}
78+
rmdir($dir);
79+
}
80+
81+
/**
82+
* Mirrors the FIXED logic from system/rewrite.php:24-49.
83+
* Returns true if rewrite.php would "return false" (serve file directly).
84+
*/
85+
private function shouldServeFileFixed(string $requestUri, string $docRoot): bool
86+
{
87+
$uri = urldecode(parse_url('https://codeigniter.com' . $requestUri, PHP_URL_PATH) ?? '');
88+
89+
$path = $docRoot . DIRECTORY_SEPARATOR . ltrim($uri, '/');
90+
91+
$realPath = realpath($path);
92+
$realDocRoot = realpath($docRoot);
93+
94+
return $uri !== '/'
95+
&& $realPath !== false
96+
&& $realDocRoot !== false
97+
&& ($realPath === $realDocRoot || str_starts_with($realPath, $realDocRoot . DIRECTORY_SEPARATOR))
98+
&& (is_file($realPath) || is_dir($realPath));
99+
}
100+
101+
/**
102+
* VULNERABLE logic before fix (for proof): no realpath prefix check.
103+
*/
104+
private function shouldServeFileVulnerable(string $requestUri, string $docRoot): bool
105+
{
106+
$uri = urldecode(parse_url('https://codeigniter.com' . $requestUri, PHP_URL_PATH) ?? '');
107+
$path = $docRoot . DIRECTORY_SEPARATOR . ltrim($uri, '/');
108+
109+
return $uri !== '/' && (is_file($path) || is_dir($path));
110+
}
111+
112+
public function testServesLegitimatePublicFile(): void
113+
{
114+
$this->assertTrue($this->shouldServeFileFixed('/test.txt', $this->docRoot));
115+
$this->assertTrue($this->shouldServeFileFixed('/assets/app.css', $this->docRoot));
116+
$this->assertTrue($this->shouldServeFileFixed('/assets', $this->docRoot));
117+
}
118+
119+
public function testDoesNotServeRoot(): void
120+
{
121+
$this->assertFalse($this->shouldServeFileFixed('/', $this->docRoot));
122+
}
123+
124+
public function testDoesNotServeNonExistingFile(): void
125+
{
126+
$this->assertFalse($this->shouldServeFileFixed('/nope.txt', $this->docRoot));
127+
}
128+
129+
#[DataProvider('provideBlocksPathTraversalOutsideDocRoot')]
130+
public function testBlocksPathTraversalOutsideDocRoot(string $payload): void
131+
{
132+
// Fixed version must NOT serve
133+
$this->assertFalse(
134+
$this->shouldServeFileFixed($payload, $this->docRoot),
135+
'Fixed rewrite.php should block traversal payload: ' . $payload,
136+
);
137+
}
138+
139+
/**
140+
* @return iterable<string, array{string}>
141+
*/
142+
public static function provideBlocksPathTraversalOutsideDocRoot(): iterable
143+
{
144+
yield 'plain dotdot' => ['/../outside.txt'];
145+
146+
yield 'nested dotdot' => ['/../../outside.txt'];
147+
148+
yield 'dotdot with subdir' => ['/assets/../../outside.txt'];
149+
150+
yield 'encoded dotdot' => ['/%2e%2e/outside.txt'];
151+
152+
yield 'double encoded' => ['/%252e%252e/outside.txt']; // becomes %2e after one urldecode -> safe
153+
154+
yield 'sibling public2 file' => ['/../public2/also.txt'];
155+
156+
yield 'sibling public2 dir' => ['/../public2'];
157+
158+
yield 'traversal via subdir' => ['/assets/../../../outside.txt'];
159+
160+
yield 'absolute outside2' => ['/../outside2.txt'];
161+
162+
// Prefix bypass: docroot /public must not match /public2
163+
yield 'prefix bypass' => ['/../public2/also.txt'];
164+
}
165+
166+
public function testProvesVulnerabilityBeforeFix(): void
167+
{
168+
// This proves the OLD code WAS vulnerable: it would have served outside files
169+
$this->assertTrue(
170+
$this->shouldServeFileVulnerable('/../outside.txt', $this->docRoot),
171+
'Vulnerable logic serves /../outside.txt outside docroot',
172+
);
173+
$this->assertTrue(
174+
$this->shouldServeFileVulnerable('/%2e%2e/outside.txt', $this->docRoot),
175+
'Vulnerable logic serves encoded traversal',
176+
);
177+
$this->assertTrue(
178+
$this->shouldServeFileVulnerable('/../public2/also.txt', $this->docRoot),
179+
'Vulnerable logic serves sibling docroot file',
180+
);
181+
182+
// Fixed logic blocks them
183+
$this->assertFalse($this->shouldServeFileFixed('/../outside.txt', $this->docRoot));
184+
$this->assertFalse($this->shouldServeFileFixed('/%2e%2e/outside.txt', $this->docRoot));
185+
$this->assertFalse($this->shouldServeFileFixed('/../public2/also.txt', $this->docRoot));
186+
}
187+
188+
public function testRewriteFileContainsTraversalProtection(): void
189+
{
190+
$content = (string) file_get_contents(SYSTEMPATH . 'rewrite.php');
191+
192+
// Must use realpath + prefix check
193+
$this->assertStringContainsString('realpath', $content, 'rewrite.php must use realpath()');
194+
$this->assertStringContainsString('realpath($_SERVER', $content);
195+
$this->assertStringContainsString('str_starts_with', $content, 'rewrite.php must verify prefix');
196+
$this->assertStringContainsString('realDocRoot', $content);
197+
$this->assertStringContainsString('DIRECTORY_SEPARATOR', $content);
198+
}
199+
200+
public function testEncodedTraversalDecodedOnce(): void
201+
{
202+
// urldecode() in rewrite.php decodes %2e once; double encoding stays safe
203+
$uri = urldecode(parse_url('https://codeigniter.com/%252e%252e/outside.txt', PHP_URL_PATH) ?? '');
204+
$this->assertSame('/%2e%2e/outside.txt', $uri, 'Double encoding decodes only once');
205+
206+
// Single encoding must decode to ../
207+
$uri2 = urldecode(parse_url('https://codeigniter.com/%2e%2e/outside.txt', PHP_URL_PATH) ?? '');
208+
$this->assertSame('/../outside.txt', $uri2);
209+
$this->assertFalse($this->shouldServeFileFixed('/%2e%2e/outside.txt', $this->docRoot));
210+
}
211+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ Bugs Fixed
4040
ANSI color codes in the prompt (e.g., option defaults) are wrapped in readline's non-printing markers under GNU readline so cursor positioning stays accurate.
4141
- **CLIRequest:** Fixed a bug where ``parseCommand()`` could throw a TypeError when ``argv`` is missing.
4242
- **CodeIgniter:** Fixed a bug where ``gatherOutput()`` could be called twice when ``startController()`` returned a ``ResponseInterface`` (e.g., from filter attributes or closure routes).
43+
- **Commands:** Fixed a bug in ``rewrite.php`` where files outside the document root could be served by the development server.
4344
- **Content Security Policy:** Fixed a bug where empty ``Content-Security-Policy``, ``Content-Security-Policy-Report-Only``, and ``Reporting-Endpoints`` response headers were generated when no corresponding values existed.
4445
- **Cookie:** Fixed a bug where ``Cookie`` instances created with ``raw: true`` allowed invalid characters in cookie values rejected by ``setrawcookie()``.
4546
- **Database:** Fixed a bug where rebuilding a SQLite3 table (e.g., ``Forge::dropColumn()``, ``Forge::modifyColumn()``, ``Forge::dropForeignKey()`` and ``Forge::dropPrimaryKey()``) corrupted the table names referenced by its foreign keys when ``DBPrefix`` was set.

0 commit comments

Comments
 (0)