Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Twig/FileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,13 @@ public function findTemplate(string $name): string
$templatePaths = App::path('templates');
if (file_exists($name)) {
$name = str_replace('//', '/', $name);
$namePath = realpath($name);
// Check both app template paths and all plugins,
// as template from element() end up here too.
// We also need to protect against `{% include var_name %}`
// where var_name is request data.
foreach ($templatePaths as $templatePath) {
if (str_starts_with($name, $templatePath)) {
if ($namePath !== false && str_starts_with($namePath, $templatePath)) {
return $name;
}
}
Expand Down
25 changes: 25 additions & 0 deletions tests/TestCase/View/TwigViewTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ protected function setUp(): void
Configure::write('App.encoding', 'UTF-8');

$this->view = new AppView();
if (file_exists(TMP . 'secret.txt')) {
unlink(TMP . 'secret.txt');
}
}

/**
Expand Down Expand Up @@ -260,6 +263,10 @@ public function testThrowSyntaxError(): void
public function testTemplatePathRestriction(): void
{
$path = TMP . 'secret.txt';
if (!is_dir(TMP)) {
mkdir(TMP, 0777, true);
}

file_put_contents($path, 'SECRET DATA from /tmp/secret.txt');
$view = new AppView();
$view->set('item', $path);
Expand All @@ -268,6 +275,24 @@ public function testTemplatePathRestriction(): void
$view->render('template_path_restriction');
}

public function testTemplatePathRestrictionRelativePath(): void
{
$path = TMP . 'secret.txt';
if (!is_dir(TMP)) {
mkdir(TMP, 0777, true);
}

$base = ROOT;
$slashes = substr_count($base, DIRECTORY_SEPARATOR);
$includePath = ROOT . str_repeat('/..', $slashes) . TMP . 'secret.txt';
file_put_contents($path, 'SECRET DATA from /tmp/secret.txt');
$view = new AppView();
$view->set('item', $includePath);
$this->expectException(LoaderError::class);
$this->expectExceptionMessage('Could not find template');
$view->render('template_path_restriction');
}

public function testHelperFunction(): void
{
$view = new AppView(null, null, null, [
Expand Down
Loading